##// END OF EJS Templates
- Add a new ipconfig() public function for manipulating the internal rc...
fptest -
Show More
@@ -1,3021 +1,3070 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 1846 2006-10-28 07:51:56Z vivainio $"""
4 $Id: Magic.py 1879 2006-11-04 00:34:34Z fptest $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import 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 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt,GetoptError
36 from getopt import getopt,GetoptError
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38
38
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 import IPython
46 import IPython
47 from IPython import Debugger, OInspect, wildcard
47 from IPython import Debugger, OInspect, wildcard
48 from IPython.FakeModule import FakeModule
48 from IPython.FakeModule import FakeModule
49 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.Itpl import Itpl, itpl, printpl,itplns
50 from IPython.PyColorize import Parser
50 from IPython.PyColorize import Parser
51 from IPython.ipstruct import Struct
51 from IPython.ipstruct import Struct
52 from IPython.macro import Macro
52 from IPython.macro import Macro
53 from IPython.genutils import *
53 from IPython.genutils import *
54 from IPython import platutils
54 from IPython import platutils
55
55
56 #***************************************************************************
56 #***************************************************************************
57 # Utility functions
57 # Utility functions
58 def on_off(tag):
58 def on_off(tag):
59 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
60 return ['OFF','ON'][tag]
60 return ['OFF','ON'][tag]
61
61
62 class Bunch: pass
62 class Bunch: pass
63
63
64 #***************************************************************************
64 #***************************************************************************
65 # Main class implementing Magic functionality
65 # Main class implementing Magic functionality
66 class Magic:
66 class Magic:
67 """Magic functions for InteractiveShell.
67 """Magic functions for InteractiveShell.
68
68
69 Shell functions which can be reached as %function_name. All magic
69 Shell functions which can be reached as %function_name. All magic
70 functions should accept a string, which they can parse for their own
70 functions should accept a string, which they can parse for their own
71 needs. This can make some functions easier to type, eg `%cd ../`
71 needs. This can make some functions easier to type, eg `%cd ../`
72 vs. `%cd("../")`
72 vs. `%cd("../")`
73
73
74 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 ALL definitions MUST begin with the prefix magic_. The user won't need it
75 at the command line, but it is is needed in the definition. """
75 at the command line, but it is is needed in the definition. """
76
76
77 # class globals
77 # class globals
78 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
79 'Automagic is ON, % prefix NOT needed for magic functions.']
79 'Automagic is ON, % prefix NOT needed for magic functions.']
80
80
81 #......................................................................
81 #......................................................................
82 # some utility functions
82 # some utility functions
83
83
84 def __init__(self,shell):
84 def __init__(self,shell):
85
85
86 self.options_table = {}
86 self.options_table = {}
87 if profile is None:
87 if profile is None:
88 self.magic_prun = self.profile_missing_notice
88 self.magic_prun = self.profile_missing_notice
89 self.shell = shell
89 self.shell = shell
90
90
91 # namespace for holding state we may need
91 # namespace for holding state we may need
92 self._magic_state = Bunch()
92 self._magic_state = Bunch()
93
93
94 def profile_missing_notice(self, *args, **kwargs):
94 def profile_missing_notice(self, *args, **kwargs):
95 error("""\
95 error("""\
96 The profile module could not be found. If you are a Debian user,
96 The profile module could not be found. If you are a Debian user,
97 it has been removed from the standard Debian package because of its non-free
97 it has been removed from the standard Debian package because of its non-free
98 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98 license. To use profiling, please install"python2.3-profiler" from non-free.""")
99
99
100 def default_option(self,fn,optstr):
100 def default_option(self,fn,optstr):
101 """Make an entry in the options_table for fn, with value optstr"""
101 """Make an entry in the options_table for fn, with value optstr"""
102
102
103 if fn not in self.lsmagic():
103 if fn not in self.lsmagic():
104 error("%s is not a magic function" % fn)
104 error("%s is not a magic function" % fn)
105 self.options_table[fn] = optstr
105 self.options_table[fn] = optstr
106
106
107 def lsmagic(self):
107 def lsmagic(self):
108 """Return a list of currently available magic functions.
108 """Return a list of currently available magic functions.
109
109
110 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 Gives a list of the bare names after mangling (['ls','cd', ...], not
111 ['magic_ls','magic_cd',...]"""
111 ['magic_ls','magic_cd',...]"""
112
112
113 # FIXME. This needs a cleanup, in the way the magics list is built.
113 # FIXME. This needs a cleanup, in the way the magics list is built.
114
114
115 # magics in class definition
115 # magics in class definition
116 class_magic = lambda fn: fn.startswith('magic_') and \
116 class_magic = lambda fn: fn.startswith('magic_') and \
117 callable(Magic.__dict__[fn])
117 callable(Magic.__dict__[fn])
118 # in instance namespace (run-time user additions)
118 # in instance namespace (run-time user additions)
119 inst_magic = lambda fn: fn.startswith('magic_') and \
119 inst_magic = lambda fn: fn.startswith('magic_') and \
120 callable(self.__dict__[fn])
120 callable(self.__dict__[fn])
121 # and bound magics by user (so they can access self):
121 # and bound magics by user (so they can access self):
122 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
123 callable(self.__class__.__dict__[fn])
123 callable(self.__class__.__dict__[fn])
124 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 magics = filter(class_magic,Magic.__dict__.keys()) + \
125 filter(inst_magic,self.__dict__.keys()) + \
125 filter(inst_magic,self.__dict__.keys()) + \
126 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 filter(inst_bound_magic,self.__class__.__dict__.keys())
127 out = []
127 out = []
128 for fn in magics:
128 for fn in magics:
129 out.append(fn.replace('magic_','',1))
129 out.append(fn.replace('magic_','',1))
130 out.sort()
130 out.sort()
131 return out
131 return out
132
132
133 def extract_input_slices(self,slices,raw=False):
133 def extract_input_slices(self,slices,raw=False):
134 """Return as a string a set of input history slices.
134 """Return as a string a set of input history slices.
135
135
136 Inputs:
136 Inputs:
137
137
138 - slices: the set of slices is given as a list of strings (like
138 - slices: the set of slices is given as a list of strings (like
139 ['1','4:8','9'], since this function is for use by magic functions
139 ['1','4:8','9'], since this function is for use by magic functions
140 which get their arguments as strings.
140 which get their arguments as strings.
141
141
142 Optional inputs:
142 Optional inputs:
143
143
144 - raw(False): by default, the processed input is used. If this is
144 - raw(False): by default, the processed input is used. If this is
145 true, the raw input history is used instead.
145 true, the raw input history is used instead.
146
146
147 Note that slices can be called with two notations:
147 Note that slices can be called with two notations:
148
148
149 N:M -> standard python form, means including items N...(M-1).
149 N:M -> standard python form, means including items N...(M-1).
150
150
151 N-M -> include items N..M (closed endpoint)."""
151 N-M -> include items N..M (closed endpoint)."""
152
152
153 if raw:
153 if raw:
154 hist = self.shell.input_hist_raw
154 hist = self.shell.input_hist_raw
155 else:
155 else:
156 hist = self.shell.input_hist
156 hist = self.shell.input_hist
157
157
158 cmds = []
158 cmds = []
159 for chunk in slices:
159 for chunk in slices:
160 if ':' in chunk:
160 if ':' in chunk:
161 ini,fin = map(int,chunk.split(':'))
161 ini,fin = map(int,chunk.split(':'))
162 elif '-' in chunk:
162 elif '-' in chunk:
163 ini,fin = map(int,chunk.split('-'))
163 ini,fin = map(int,chunk.split('-'))
164 fin += 1
164 fin += 1
165 else:
165 else:
166 ini = int(chunk)
166 ini = int(chunk)
167 fin = ini+1
167 fin = ini+1
168 cmds.append(hist[ini:fin])
168 cmds.append(hist[ini:fin])
169 return cmds
169 return cmds
170
170
171 def _ofind(self, oname, namespaces=None):
171 def _ofind(self, oname, namespaces=None):
172 """Find an object in the available namespaces.
172 """Find an object in the available namespaces.
173
173
174 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
174 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
175
175
176 Has special code to detect magic functions.
176 Has special code to detect magic functions.
177 """
177 """
178
178
179 oname = oname.strip()
179 oname = oname.strip()
180
180
181 alias_ns = None
181 alias_ns = None
182 if namespaces is None:
182 if namespaces is None:
183 # Namespaces to search in:
183 # Namespaces to search in:
184 # Put them in a list. The order is important so that we
184 # Put them in a list. The order is important so that we
185 # find things in the same order that Python finds them.
185 # find things in the same order that Python finds them.
186 namespaces = [ ('Interactive', self.shell.user_ns),
186 namespaces = [ ('Interactive', self.shell.user_ns),
187 ('IPython internal', self.shell.internal_ns),
187 ('IPython internal', self.shell.internal_ns),
188 ('Python builtin', __builtin__.__dict__),
188 ('Python builtin', __builtin__.__dict__),
189 ('Alias', self.shell.alias_table),
189 ('Alias', self.shell.alias_table),
190 ]
190 ]
191 alias_ns = self.shell.alias_table
191 alias_ns = self.shell.alias_table
192
192
193 # initialize results to 'null'
193 # initialize results to 'null'
194 found = 0; obj = None; ospace = None; ds = None;
194 found = 0; obj = None; ospace = None; ds = None;
195 ismagic = 0; isalias = 0; parent = None
195 ismagic = 0; isalias = 0; parent = None
196
196
197 # Look for the given name by splitting it in parts. If the head is
197 # Look for the given name by splitting it in parts. If the head is
198 # found, then we look for all the remaining parts as members, and only
198 # found, then we look for all the remaining parts as members, and only
199 # declare success if we can find them all.
199 # declare success if we can find them all.
200 oname_parts = oname.split('.')
200 oname_parts = oname.split('.')
201 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
201 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
202 for nsname,ns in namespaces:
202 for nsname,ns in namespaces:
203 try:
203 try:
204 obj = ns[oname_head]
204 obj = ns[oname_head]
205 except KeyError:
205 except KeyError:
206 continue
206 continue
207 else:
207 else:
208 for part in oname_rest:
208 for part in oname_rest:
209 try:
209 try:
210 parent = obj
210 parent = obj
211 obj = getattr(obj,part)
211 obj = getattr(obj,part)
212 except:
212 except:
213 # Blanket except b/c some badly implemented objects
213 # Blanket except b/c some badly implemented objects
214 # allow __getattr__ to raise exceptions other than
214 # allow __getattr__ to raise exceptions other than
215 # AttributeError, which then crashes IPython.
215 # AttributeError, which then crashes IPython.
216 break
216 break
217 else:
217 else:
218 # If we finish the for loop (no break), we got all members
218 # If we finish the for loop (no break), we got all members
219 found = 1
219 found = 1
220 ospace = nsname
220 ospace = nsname
221 if ns == alias_ns:
221 if ns == alias_ns:
222 isalias = 1
222 isalias = 1
223 break # namespace loop
223 break # namespace loop
224
224
225 # Try to see if it's magic
225 # Try to see if it's magic
226 if not found:
226 if not found:
227 if oname.startswith(self.shell.ESC_MAGIC):
227 if oname.startswith(self.shell.ESC_MAGIC):
228 oname = oname[1:]
228 oname = oname[1:]
229 obj = getattr(self,'magic_'+oname,None)
229 obj = getattr(self,'magic_'+oname,None)
230 if obj is not None:
230 if obj is not None:
231 found = 1
231 found = 1
232 ospace = 'IPython internal'
232 ospace = 'IPython internal'
233 ismagic = 1
233 ismagic = 1
234
234
235 # Last try: special-case some literals like '', [], {}, etc:
235 # Last try: special-case some literals like '', [], {}, etc:
236 if not found and oname_head in ["''",'""','[]','{}','()']:
236 if not found and oname_head in ["''",'""','[]','{}','()']:
237 obj = eval(oname_head)
237 obj = eval(oname_head)
238 found = 1
238 found = 1
239 ospace = 'Interactive'
239 ospace = 'Interactive'
240
240
241 return {'found':found, 'obj':obj, 'namespace':ospace,
241 return {'found':found, 'obj':obj, 'namespace':ospace,
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
243
243
244 def arg_err(self,func):
244 def arg_err(self,func):
245 """Print docstring if incorrect arguments were passed"""
245 """Print docstring if incorrect arguments were passed"""
246 print 'Error in arguments:'
246 print 'Error in arguments:'
247 print OInspect.getdoc(func)
247 print OInspect.getdoc(func)
248
248
249 def format_latex(self,strng):
249 def format_latex(self,strng):
250 """Format a string for latex inclusion."""
250 """Format a string for latex inclusion."""
251
251
252 # Characters that need to be escaped for latex:
252 # Characters that need to be escaped for latex:
253 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
253 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
254 # Magic command names as headers:
254 # Magic command names as headers:
255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
256 re.MULTILINE)
256 re.MULTILINE)
257 # Magic commands
257 # Magic commands
258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
259 re.MULTILINE)
259 re.MULTILINE)
260 # Paragraph continue
260 # Paragraph continue
261 par_re = re.compile(r'\\$',re.MULTILINE)
261 par_re = re.compile(r'\\$',re.MULTILINE)
262
262
263 # The "\n" symbol
263 # The "\n" symbol
264 newline_re = re.compile(r'\\n')
264 newline_re = re.compile(r'\\n')
265
265
266 # Now build the string for output:
266 # Now build the string for output:
267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
269 strng)
269 strng)
270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
271 strng = par_re.sub(r'\\\\',strng)
271 strng = par_re.sub(r'\\\\',strng)
272 strng = escape_re.sub(r'\\\1',strng)
272 strng = escape_re.sub(r'\\\1',strng)
273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
274 return strng
274 return strng
275
275
276 def format_screen(self,strng):
276 def format_screen(self,strng):
277 """Format a string for screen printing.
277 """Format a string for screen printing.
278
278
279 This removes some latex-type format codes."""
279 This removes some latex-type format codes."""
280 # Paragraph continue
280 # Paragraph continue
281 par_re = re.compile(r'\\$',re.MULTILINE)
281 par_re = re.compile(r'\\$',re.MULTILINE)
282 strng = par_re.sub('',strng)
282 strng = par_re.sub('',strng)
283 return strng
283 return strng
284
284
285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
286 """Parse options passed to an argument string.
286 """Parse options passed to an argument string.
287
287
288 The interface is similar to that of getopt(), but it returns back a
288 The interface is similar to that of getopt(), but it returns back a
289 Struct with the options as keys and the stripped argument string still
289 Struct with the options as keys and the stripped argument string still
290 as a string.
290 as a string.
291
291
292 arg_str is quoted as a true sys.argv vector by using shlex.split.
292 arg_str is quoted as a true sys.argv vector by using shlex.split.
293 This allows us to easily expand variables, glob files, quote
293 This allows us to easily expand variables, glob files, quote
294 arguments, etc.
294 arguments, etc.
295
295
296 Options:
296 Options:
297 -mode: default 'string'. If given as 'list', the argument string is
297 -mode: default 'string'. If given as 'list', the argument string is
298 returned as a list (split on whitespace) instead of a string.
298 returned as a list (split on whitespace) instead of a string.
299
299
300 -list_all: put all option values in lists. Normally only options
300 -list_all: put all option values in lists. Normally only options
301 appearing more than once are put in a list.
301 appearing more than once are put in a list.
302
302
303 -posix (True): whether to split the input line in POSIX mode or not,
303 -posix (True): whether to split the input line in POSIX mode or not,
304 as per the conventions outlined in the shlex module from the
304 as per the conventions outlined in the shlex module from the
305 standard library."""
305 standard library."""
306
306
307 # inject default options at the beginning of the input line
307 # inject default options at the beginning of the input line
308 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
308 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
309 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
309 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
310
310
311 mode = kw.get('mode','string')
311 mode = kw.get('mode','string')
312 if mode not in ['string','list']:
312 if mode not in ['string','list']:
313 raise ValueError,'incorrect mode given: %s' % mode
313 raise ValueError,'incorrect mode given: %s' % mode
314 # Get options
314 # Get options
315 list_all = kw.get('list_all',0)
315 list_all = kw.get('list_all',0)
316 posix = kw.get('posix',True)
316 posix = kw.get('posix',True)
317
317
318 # Check if we have more than one argument to warrant extra processing:
318 # Check if we have more than one argument to warrant extra processing:
319 odict = {} # Dictionary with options
319 odict = {} # Dictionary with options
320 args = arg_str.split()
320 args = arg_str.split()
321 if len(args) >= 1:
321 if len(args) >= 1:
322 # If the list of inputs only has 0 or 1 thing in it, there's no
322 # If the list of inputs only has 0 or 1 thing in it, there's no
323 # need to look for options
323 # need to look for options
324 argv = arg_split(arg_str,posix)
324 argv = arg_split(arg_str,posix)
325 # Do regular option processing
325 # Do regular option processing
326 try:
326 try:
327 opts,args = getopt(argv,opt_str,*long_opts)
327 opts,args = getopt(argv,opt_str,*long_opts)
328 except GetoptError,e:
328 except GetoptError,e:
329 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
329 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
330 " ".join(long_opts)))
330 " ".join(long_opts)))
331 for o,a in opts:
331 for o,a in opts:
332 if o.startswith('--'):
332 if o.startswith('--'):
333 o = o[2:]
333 o = o[2:]
334 else:
334 else:
335 o = o[1:]
335 o = o[1:]
336 try:
336 try:
337 odict[o].append(a)
337 odict[o].append(a)
338 except AttributeError:
338 except AttributeError:
339 odict[o] = [odict[o],a]
339 odict[o] = [odict[o],a]
340 except KeyError:
340 except KeyError:
341 if list_all:
341 if list_all:
342 odict[o] = [a]
342 odict[o] = [a]
343 else:
343 else:
344 odict[o] = a
344 odict[o] = a
345
345
346 # Prepare opts,args for return
346 # Prepare opts,args for return
347 opts = Struct(odict)
347 opts = Struct(odict)
348 if mode == 'string':
348 if mode == 'string':
349 args = ' '.join(args)
349 args = ' '.join(args)
350
350
351 return opts,args
351 return opts,args
352
352
353 #......................................................................
353 #......................................................................
354 # And now the actual magic functions
354 # And now the actual magic functions
355
355
356 # Functions for IPython shell work (vars,funcs, config, etc)
356 # Functions for IPython shell work (vars,funcs, config, etc)
357 def magic_lsmagic(self, parameter_s = ''):
357 def magic_lsmagic(self, parameter_s = ''):
358 """List currently available magic functions."""
358 """List currently available magic functions."""
359 mesc = self.shell.ESC_MAGIC
359 mesc = self.shell.ESC_MAGIC
360 print 'Available magic functions:\n'+mesc+\
360 print 'Available magic functions:\n'+mesc+\
361 (' '+mesc).join(self.lsmagic())
361 (' '+mesc).join(self.lsmagic())
362 print '\n' + Magic.auto_status[self.shell.rc.automagic]
362 print '\n' + Magic.auto_status[self.shell.rc.automagic]
363 return None
363 return None
364
364
365 def magic_magic(self, parameter_s = ''):
365 def magic_magic(self, parameter_s = ''):
366 """Print information about the magic function system."""
366 """Print information about the magic function system."""
367
367
368 mode = ''
368 mode = ''
369 try:
369 try:
370 if parameter_s.split()[0] == '-latex':
370 if parameter_s.split()[0] == '-latex':
371 mode = 'latex'
371 mode = 'latex'
372 if parameter_s.split()[0] == '-brief':
372 if parameter_s.split()[0] == '-brief':
373 mode = 'brief'
373 mode = 'brief'
374 except:
374 except:
375 pass
375 pass
376
376
377 magic_docs = []
377 magic_docs = []
378 for fname in self.lsmagic():
378 for fname in self.lsmagic():
379 mname = 'magic_' + fname
379 mname = 'magic_' + fname
380 for space in (Magic,self,self.__class__):
380 for space in (Magic,self,self.__class__):
381 try:
381 try:
382 fn = space.__dict__[mname]
382 fn = space.__dict__[mname]
383 except KeyError:
383 except KeyError:
384 pass
384 pass
385 else:
385 else:
386 break
386 break
387 if mode == 'brief':
387 if mode == 'brief':
388 # only first line
388 # only first line
389 fndoc = fn.__doc__.split('\n',1)[0]
389 fndoc = fn.__doc__.split('\n',1)[0]
390 else:
390 else:
391 fndoc = fn.__doc__
391 fndoc = fn.__doc__
392
392
393 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
393 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
394 fname,fndoc))
394 fname,fndoc))
395 magic_docs = ''.join(magic_docs)
395 magic_docs = ''.join(magic_docs)
396
396
397 if mode == 'latex':
397 if mode == 'latex':
398 print self.format_latex(magic_docs)
398 print self.format_latex(magic_docs)
399 return
399 return
400 else:
400 else:
401 magic_docs = self.format_screen(magic_docs)
401 magic_docs = self.format_screen(magic_docs)
402 if mode == 'brief':
402 if mode == 'brief':
403 return magic_docs
403 return magic_docs
404
404
405 outmsg = """
405 outmsg = """
406 IPython's 'magic' functions
406 IPython's 'magic' functions
407 ===========================
407 ===========================
408
408
409 The magic function system provides a series of functions which allow you to
409 The magic function system provides a series of functions which allow you to
410 control the behavior of IPython itself, plus a lot of system-type
410 control the behavior of IPython itself, plus a lot of system-type
411 features. All these functions are prefixed with a % character, but parameters
411 features. All these functions are prefixed with a % character, but parameters
412 are given without parentheses or quotes.
412 are given without parentheses or quotes.
413
413
414 NOTE: If you have 'automagic' enabled (via the command line option or with the
414 NOTE: If you have 'automagic' enabled (via the command line option or with the
415 %automagic function), you don't need to type in the % explicitly. By default,
415 %automagic function), you don't need to type in the % explicitly. By default,
416 IPython ships with automagic on, so you should only rarely need the % escape.
416 IPython ships with automagic on, so you should only rarely need the % escape.
417
417
418 Example: typing '%cd mydir' (without the quotes) changes you working directory
418 Example: typing '%cd mydir' (without the quotes) changes you working directory
419 to 'mydir', if it exists.
419 to 'mydir', if it exists.
420
420
421 You can define your own magic functions to extend the system. See the supplied
421 You can define your own magic functions to extend the system. See the supplied
422 ipythonrc and example-magic.py files for details (in your ipython
422 ipythonrc and example-magic.py files for details (in your ipython
423 configuration directory, typically $HOME/.ipython/).
423 configuration directory, typically $HOME/.ipython/).
424
424
425 You can also define your own aliased names for magic functions. In your
425 You can also define your own aliased names for magic functions. In your
426 ipythonrc file, placing a line like:
426 ipythonrc file, placing a line like:
427
427
428 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
428 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
429
429
430 will define %pf as a new name for %profile.
430 will define %pf as a new name for %profile.
431
431
432 You can also call magics in code using the ipmagic() function, which IPython
432 You can also call magics in code using the ipmagic() function, which IPython
433 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
433 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
434
434
435 For a list of the available magic functions, use %lsmagic. For a description
435 For a list of the available magic functions, use %lsmagic. For a description
436 of any of them, type %magic_name?, e.g. '%cd?'.
436 of any of them, type %magic_name?, e.g. '%cd?'.
437
437
438 Currently the magic system has the following functions:\n"""
438 Currently the magic system has the following functions:\n"""
439
439
440 mesc = self.shell.ESC_MAGIC
440 mesc = self.shell.ESC_MAGIC
441 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
441 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
442 "\n\n%s%s\n\n%s" % (outmsg,
442 "\n\n%s%s\n\n%s" % (outmsg,
443 magic_docs,mesc,mesc,
443 magic_docs,mesc,mesc,
444 (' '+mesc).join(self.lsmagic()),
444 (' '+mesc).join(self.lsmagic()),
445 Magic.auto_status[self.shell.rc.automagic] ) )
445 Magic.auto_status[self.shell.rc.automagic] ) )
446
446
447 page(outmsg,screen_lines=self.shell.rc.screen_length)
447 page(outmsg,screen_lines=self.shell.rc.screen_length)
448
448
449 def magic_automagic(self, parameter_s = ''):
449 def magic_automagic(self, parameter_s = ''):
450 """Make magic functions callable without having to type the initial %.
450 """Make magic functions callable without having to type the initial %.
451
451
452 Toggles on/off (when off, you must call it as %automagic, of
452 Toggles on/off (when off, you must call it as %automagic, of
453 course). Note that magic functions have lowest priority, so if there's
453 course). Note that magic functions have lowest priority, so if there's
454 a variable whose name collides with that of a magic fn, automagic
454 a variable whose name collides with that of a magic fn, automagic
455 won't work for that function (you get the variable instead). However,
455 won't work for that function (you get the variable instead). However,
456 if you delete the variable (del var), the previously shadowed magic
456 if you delete the variable (del var), the previously shadowed magic
457 function becomes visible to automagic again."""
457 function becomes visible to automagic again."""
458
458
459 rc = self.shell.rc
459 rc = self.shell.rc
460 rc.automagic = not rc.automagic
460 rc.automagic = not rc.automagic
461 print '\n' + Magic.auto_status[rc.automagic]
461 print '\n' + Magic.auto_status[rc.automagic]
462
462
463 def magic_autocall(self, parameter_s = ''):
463 def magic_autocall(self, parameter_s = ''):
464 """Make functions callable without having to type parentheses.
464 """Make functions callable without having to type parentheses.
465
465
466 Usage:
466 Usage:
467
467
468 %autocall [mode]
468 %autocall [mode]
469
469
470 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
470 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
471 value is toggled on and off (remembering the previous state)."""
471 value is toggled on and off (remembering the previous state)."""
472
472
473 rc = self.shell.rc
473 rc = self.shell.rc
474
474
475 if parameter_s:
475 if parameter_s:
476 arg = int(parameter_s)
476 arg = int(parameter_s)
477 else:
477 else:
478 arg = 'toggle'
478 arg = 'toggle'
479
479
480 if not arg in (0,1,2,'toggle'):
480 if not arg in (0,1,2,'toggle'):
481 error('Valid modes: (0->Off, 1->Smart, 2->Full')
481 error('Valid modes: (0->Off, 1->Smart, 2->Full')
482 return
482 return
483
483
484 if arg in (0,1,2):
484 if arg in (0,1,2):
485 rc.autocall = arg
485 rc.autocall = arg
486 else: # toggle
486 else: # toggle
487 if rc.autocall:
487 if rc.autocall:
488 self._magic_state.autocall_save = rc.autocall
488 self._magic_state.autocall_save = rc.autocall
489 rc.autocall = 0
489 rc.autocall = 0
490 else:
490 else:
491 try:
491 try:
492 rc.autocall = self._magic_state.autocall_save
492 rc.autocall = self._magic_state.autocall_save
493 except AttributeError:
493 except AttributeError:
494 rc.autocall = self._magic_state.autocall_save = 1
494 rc.autocall = self._magic_state.autocall_save = 1
495
495
496 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
496 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
497
497
498 def magic_autoindent(self, parameter_s = ''):
498 def magic_autoindent(self, parameter_s = ''):
499 """Toggle autoindent on/off (if available)."""
499 """Toggle autoindent on/off (if available)."""
500
500
501 self.shell.set_autoindent()
501 self.shell.set_autoindent()
502 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
502 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
503
503
504 def magic_system_verbose(self, parameter_s = ''):
504 def magic_system_verbose(self, parameter_s = ''):
505 """Toggle verbose printing of system calls on/off."""
505 """Set verbose printing of system calls.
506
506
507 self.shell.rc_set_toggle('system_verbose')
507 If called without an argument, act as a toggle"""
508
509 if parameter_s:
510 val = bool(eval(parameter_s))
511 else:
512 val = None
513
514 self.shell.rc_set_toggle('system_verbose',val)
508 print "System verbose printing is:",\
515 print "System verbose printing is:",\
509 ['OFF','ON'][self.shell.rc.system_verbose]
516 ['OFF','ON'][self.shell.rc.system_verbose]
510
517
511 def magic_history(self, parameter_s = ''):
518 def magic_history(self, parameter_s = ''):
512 """Print input history (_i<n> variables), with most recent last.
519 """Print input history (_i<n> variables), with most recent last.
513
520
514 %history -> print at most 40 inputs (some may be multi-line)\\
521 %history -> print at most 40 inputs (some may be multi-line)\\
515 %history n -> print at most n inputs\\
522 %history n -> print at most n inputs\\
516 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
523 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
517
524
518 Each input's number <n> is shown, and is accessible as the
525 Each input's number <n> is shown, and is accessible as the
519 automatically generated variable _i<n>. Multi-line statements are
526 automatically generated variable _i<n>. Multi-line statements are
520 printed starting at a new line for easy copy/paste.
527 printed starting at a new line for easy copy/paste.
521
528
522
529
523 Options:
530 Options:
524
531
525 -n: do NOT print line numbers. This is useful if you want to get a
532 -n: do NOT print line numbers. This is useful if you want to get a
526 printout of many lines which can be directly pasted into a text
533 printout of many lines which can be directly pasted into a text
527 editor.
534 editor.
528
535
529 This feature is only available if numbered prompts are in use.
536 This feature is only available if numbered prompts are in use.
530
537
531 -r: print the 'raw' history. IPython filters your input and
538 -r: print the 'raw' history. IPython filters your input and
532 converts it all into valid Python source before executing it (things
539 converts it all into valid Python source before executing it (things
533 like magics or aliases are turned into function calls, for
540 like magics or aliases are turned into function calls, for
534 example). With this option, you'll see the unfiltered history
541 example). With this option, you'll see the unfiltered history
535 instead of the filtered version: '%cd /' will be seen as '%cd /'
542 instead of the filtered version: '%cd /' will be seen as '%cd /'
536 instead of '_ip.magic("%cd /")'.
543 instead of '_ip.magic("%cd /")'.
537 """
544 """
538
545
539 shell = self.shell
546 shell = self.shell
540 if not shell.outputcache.do_full_cache:
547 if not shell.outputcache.do_full_cache:
541 print 'This feature is only available if numbered prompts are in use.'
548 print 'This feature is only available if numbered prompts are in use.'
542 return
549 return
543 opts,args = self.parse_options(parameter_s,'nr',mode='list')
550 opts,args = self.parse_options(parameter_s,'nr',mode='list')
544
551
545 if opts.has_key('r'):
552 if opts.has_key('r'):
546 input_hist = shell.input_hist_raw
553 input_hist = shell.input_hist_raw
547 else:
554 else:
548 input_hist = shell.input_hist
555 input_hist = shell.input_hist
549
556
550 default_length = 40
557 default_length = 40
551 if len(args) == 0:
558 if len(args) == 0:
552 final = len(input_hist)
559 final = len(input_hist)
553 init = max(1,final-default_length)
560 init = max(1,final-default_length)
554 elif len(args) == 1:
561 elif len(args) == 1:
555 final = len(input_hist)
562 final = len(input_hist)
556 init = max(1,final-int(args[0]))
563 init = max(1,final-int(args[0]))
557 elif len(args) == 2:
564 elif len(args) == 2:
558 init,final = map(int,args)
565 init,final = map(int,args)
559 else:
566 else:
560 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
567 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
561 print self.magic_hist.__doc__
568 print self.magic_hist.__doc__
562 return
569 return
563 width = len(str(final))
570 width = len(str(final))
564 line_sep = ['','\n']
571 line_sep = ['','\n']
565 print_nums = not opts.has_key('n')
572 print_nums = not opts.has_key('n')
566 for in_num in range(init,final):
573 for in_num in range(init,final):
567 inline = input_hist[in_num]
574 inline = input_hist[in_num]
568 multiline = int(inline.count('\n') > 1)
575 multiline = int(inline.count('\n') > 1)
569 if print_nums:
576 if print_nums:
570 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
577 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
571 print inline,
578 print inline,
572
579
573 def magic_hist(self, parameter_s=''):
580 def magic_hist(self, parameter_s=''):
574 """Alternate name for %history."""
581 """Alternate name for %history."""
575 return self.magic_history(parameter_s)
582 return self.magic_history(parameter_s)
576
583
577 def magic_p(self, parameter_s=''):
584 def magic_p(self, parameter_s=''):
578 """Just a short alias for Python's 'print'."""
585 """Just a short alias for Python's 'print'."""
579 exec 'print ' + parameter_s in self.shell.user_ns
586 exec 'print ' + parameter_s in self.shell.user_ns
580
587
581 def magic_r(self, parameter_s=''):
588 def magic_r(self, parameter_s=''):
582 """Repeat previous input.
589 """Repeat previous input.
583
590
584 If given an argument, repeats the previous command which starts with
591 If given an argument, repeats the previous command which starts with
585 the same string, otherwise it just repeats the previous input.
592 the same string, otherwise it just repeats the previous input.
586
593
587 Shell escaped commands (with ! as first character) are not recognized
594 Shell escaped commands (with ! as first character) are not recognized
588 by this system, only pure python code and magic commands.
595 by this system, only pure python code and magic commands.
589 """
596 """
590
597
591 start = parameter_s.strip()
598 start = parameter_s.strip()
592 esc_magic = self.shell.ESC_MAGIC
599 esc_magic = self.shell.ESC_MAGIC
593 # Identify magic commands even if automagic is on (which means
600 # Identify magic commands even if automagic is on (which means
594 # the in-memory version is different from that typed by the user).
601 # the in-memory version is different from that typed by the user).
595 if self.shell.rc.automagic:
602 if self.shell.rc.automagic:
596 start_magic = esc_magic+start
603 start_magic = esc_magic+start
597 else:
604 else:
598 start_magic = start
605 start_magic = start
599 # Look through the input history in reverse
606 # Look through the input history in reverse
600 for n in range(len(self.shell.input_hist)-2,0,-1):
607 for n in range(len(self.shell.input_hist)-2,0,-1):
601 input = self.shell.input_hist[n]
608 input = self.shell.input_hist[n]
602 # skip plain 'r' lines so we don't recurse to infinity
609 # skip plain 'r' lines so we don't recurse to infinity
603 if input != '_ip.magic("r")\n' and \
610 if input != '_ip.magic("r")\n' and \
604 (input.startswith(start) or input.startswith(start_magic)):
611 (input.startswith(start) or input.startswith(start_magic)):
605 #print 'match',`input` # dbg
612 #print 'match',`input` # dbg
606 print 'Executing:',input,
613 print 'Executing:',input,
607 self.shell.runlines(input)
614 self.shell.runlines(input)
608 return
615 return
609 print 'No previous input matching `%s` found.' % start
616 print 'No previous input matching `%s` found.' % start
610
617
611 def magic_page(self, parameter_s=''):
618 def magic_page(self, parameter_s=''):
612 """Pretty print the object and display it through a pager.
619 """Pretty print the object and display it through a pager.
613
620
614 If no parameter is given, use _ (last output)."""
621 If no parameter is given, use _ (last output)."""
615 # After a function contributed by Olivier Aubert, slightly modified.
622 # After a function contributed by Olivier Aubert, slightly modified.
616
623
617 oname = parameter_s and parameter_s or '_'
624 oname = parameter_s and parameter_s or '_'
618 info = self._ofind(oname)
625 info = self._ofind(oname)
619 if info['found']:
626 if info['found']:
620 page(pformat(info['obj']))
627 page(pformat(info['obj']))
621 else:
628 else:
622 print 'Object `%s` not found' % oname
629 print 'Object `%s` not found' % oname
623
630
624 def magic_profile(self, parameter_s=''):
631 def magic_profile(self, parameter_s=''):
625 """Print your currently active IPyhton profile."""
632 """Print your currently active IPyhton profile."""
626 if self.shell.rc.profile:
633 if self.shell.rc.profile:
627 printpl('Current IPython profile: $self.shell.rc.profile.')
634 printpl('Current IPython profile: $self.shell.rc.profile.')
628 else:
635 else:
629 print 'No profile active.'
636 print 'No profile active.'
630
637
631 def _inspect(self,meth,oname,namespaces=None,**kw):
638 def _inspect(self,meth,oname,namespaces=None,**kw):
632 """Generic interface to the inspector system.
639 """Generic interface to the inspector system.
633
640
634 This function is meant to be called by pdef, pdoc & friends."""
641 This function is meant to be called by pdef, pdoc & friends."""
635
642
636 oname = oname.strip()
643 oname = oname.strip()
637 info = Struct(self._ofind(oname, namespaces))
644 info = Struct(self._ofind(oname, namespaces))
638
645
639 if info.found:
646 if info.found:
640 # Get the docstring of the class property if it exists.
647 # Get the docstring of the class property if it exists.
641 path = oname.split('.')
648 path = oname.split('.')
642 root = '.'.join(path[:-1])
649 root = '.'.join(path[:-1])
643 if info.parent is not None:
650 if info.parent is not None:
644 try:
651 try:
645 target = getattr(info.parent, '__class__')
652 target = getattr(info.parent, '__class__')
646 # The object belongs to a class instance.
653 # The object belongs to a class instance.
647 try:
654 try:
648 target = getattr(target, path[-1])
655 target = getattr(target, path[-1])
649 # The class defines the object.
656 # The class defines the object.
650 if isinstance(target, property):
657 if isinstance(target, property):
651 oname = root + '.__class__.' + path[-1]
658 oname = root + '.__class__.' + path[-1]
652 info = Struct(self._ofind(oname))
659 info = Struct(self._ofind(oname))
653 except AttributeError: pass
660 except AttributeError: pass
654 except AttributeError: pass
661 except AttributeError: pass
655
662
656 pmethod = getattr(self.shell.inspector,meth)
663 pmethod = getattr(self.shell.inspector,meth)
657 formatter = info.ismagic and self.format_screen or None
664 formatter = info.ismagic and self.format_screen or None
658 if meth == 'pdoc':
665 if meth == 'pdoc':
659 pmethod(info.obj,oname,formatter)
666 pmethod(info.obj,oname,formatter)
660 elif meth == 'pinfo':
667 elif meth == 'pinfo':
661 pmethod(info.obj,oname,formatter,info,**kw)
668 pmethod(info.obj,oname,formatter,info,**kw)
662 else:
669 else:
663 pmethod(info.obj,oname)
670 pmethod(info.obj,oname)
664 else:
671 else:
665 print 'Object `%s` not found.' % oname
672 print 'Object `%s` not found.' % oname
666 return 'not found' # so callers can take other action
673 return 'not found' # so callers can take other action
667
674
668 def magic_pdef(self, parameter_s='', namespaces=None):
675 def magic_pdef(self, parameter_s='', namespaces=None):
669 """Print the definition header for any callable object.
676 """Print the definition header for any callable object.
670
677
671 If the object is a class, print the constructor information."""
678 If the object is a class, print the constructor information."""
672 print "+++"
679 print "+++"
673 self._inspect('pdef',parameter_s, namespaces)
680 self._inspect('pdef',parameter_s, namespaces)
674
681
675 def magic_pdoc(self, parameter_s='', namespaces=None):
682 def magic_pdoc(self, parameter_s='', namespaces=None):
676 """Print the docstring for an object.
683 """Print the docstring for an object.
677
684
678 If the given object is a class, it will print both the class and the
685 If the given object is a class, it will print both the class and the
679 constructor docstrings."""
686 constructor docstrings."""
680 self._inspect('pdoc',parameter_s, namespaces)
687 self._inspect('pdoc',parameter_s, namespaces)
681
688
682 def magic_psource(self, parameter_s='', namespaces=None):
689 def magic_psource(self, parameter_s='', namespaces=None):
683 """Print (or run through pager) the source code for an object."""
690 """Print (or run through pager) the source code for an object."""
684 self._inspect('psource',parameter_s, namespaces)
691 self._inspect('psource',parameter_s, namespaces)
685
692
686 def magic_pfile(self, parameter_s=''):
693 def magic_pfile(self, parameter_s=''):
687 """Print (or run through pager) the file where an object is defined.
694 """Print (or run through pager) the file where an object is defined.
688
695
689 The file opens at the line where the object definition begins. IPython
696 The file opens at the line where the object definition begins. IPython
690 will honor the environment variable PAGER if set, and otherwise will
697 will honor the environment variable PAGER if set, and otherwise will
691 do its best to print the file in a convenient form.
698 do its best to print the file in a convenient form.
692
699
693 If the given argument is not an object currently defined, IPython will
700 If the given argument is not an object currently defined, IPython will
694 try to interpret it as a filename (automatically adding a .py extension
701 try to interpret it as a filename (automatically adding a .py extension
695 if needed). You can thus use %pfile as a syntax highlighting code
702 if needed). You can thus use %pfile as a syntax highlighting code
696 viewer."""
703 viewer."""
697
704
698 # first interpret argument as an object name
705 # first interpret argument as an object name
699 out = self._inspect('pfile',parameter_s)
706 out = self._inspect('pfile',parameter_s)
700 # if not, try the input as a filename
707 # if not, try the input as a filename
701 if out == 'not found':
708 if out == 'not found':
702 try:
709 try:
703 filename = get_py_filename(parameter_s)
710 filename = get_py_filename(parameter_s)
704 except IOError,msg:
711 except IOError,msg:
705 print msg
712 print msg
706 return
713 return
707 page(self.shell.inspector.format(file(filename).read()))
714 page(self.shell.inspector.format(file(filename).read()))
708
715
709 def magic_pinfo(self, parameter_s='', namespaces=None):
716 def magic_pinfo(self, parameter_s='', namespaces=None):
710 """Provide detailed information about an object.
717 """Provide detailed information about an object.
711
718
712 '%pinfo object' is just a synonym for object? or ?object."""
719 '%pinfo object' is just a synonym for object? or ?object."""
713
720
714 #print 'pinfo par: <%s>' % parameter_s # dbg
721 #print 'pinfo par: <%s>' % parameter_s # dbg
715
722
716 # detail_level: 0 -> obj? , 1 -> obj??
723 # detail_level: 0 -> obj? , 1 -> obj??
717 detail_level = 0
724 detail_level = 0
718 # We need to detect if we got called as 'pinfo pinfo foo', which can
725 # We need to detect if we got called as 'pinfo pinfo foo', which can
719 # happen if the user types 'pinfo foo?' at the cmd line.
726 # happen if the user types 'pinfo foo?' at the cmd line.
720 pinfo,qmark1,oname,qmark2 = \
727 pinfo,qmark1,oname,qmark2 = \
721 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
728 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
722 if pinfo or qmark1 or qmark2:
729 if pinfo or qmark1 or qmark2:
723 detail_level = 1
730 detail_level = 1
724 if "*" in oname:
731 if "*" in oname:
725 self.magic_psearch(oname)
732 self.magic_psearch(oname)
726 else:
733 else:
727 self._inspect('pinfo', oname, detail_level=detail_level,
734 self._inspect('pinfo', oname, detail_level=detail_level,
728 namespaces=namespaces)
735 namespaces=namespaces)
729
736
730 def magic_psearch(self, parameter_s=''):
737 def magic_psearch(self, parameter_s=''):
731 """Search for object in namespaces by wildcard.
738 """Search for object in namespaces by wildcard.
732
739
733 %psearch [options] PATTERN [OBJECT TYPE]
740 %psearch [options] PATTERN [OBJECT TYPE]
734
741
735 Note: ? can be used as a synonym for %psearch, at the beginning or at
742 Note: ? can be used as a synonym for %psearch, at the beginning or at
736 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
743 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
737 rest of the command line must be unchanged (options come first), so
744 rest of the command line must be unchanged (options come first), so
738 for example the following forms are equivalent
745 for example the following forms are equivalent
739
746
740 %psearch -i a* function
747 %psearch -i a* function
741 -i a* function?
748 -i a* function?
742 ?-i a* function
749 ?-i a* function
743
750
744 Arguments:
751 Arguments:
745
752
746 PATTERN
753 PATTERN
747
754
748 where PATTERN is a string containing * as a wildcard similar to its
755 where PATTERN is a string containing * as a wildcard similar to its
749 use in a shell. The pattern is matched in all namespaces on the
756 use in a shell. The pattern is matched in all namespaces on the
750 search path. By default objects starting with a single _ are not
757 search path. By default objects starting with a single _ are not
751 matched, many IPython generated objects have a single
758 matched, many IPython generated objects have a single
752 underscore. The default is case insensitive matching. Matching is
759 underscore. The default is case insensitive matching. Matching is
753 also done on the attributes of objects and not only on the objects
760 also done on the attributes of objects and not only on the objects
754 in a module.
761 in a module.
755
762
756 [OBJECT TYPE]
763 [OBJECT TYPE]
757
764
758 Is the name of a python type from the types module. The name is
765 Is the name of a python type from the types module. The name is
759 given in lowercase without the ending type, ex. StringType is
766 given in lowercase without the ending type, ex. StringType is
760 written string. By adding a type here only objects matching the
767 written string. By adding a type here only objects matching the
761 given type are matched. Using all here makes the pattern match all
768 given type are matched. Using all here makes the pattern match all
762 types (this is the default).
769 types (this is the default).
763
770
764 Options:
771 Options:
765
772
766 -a: makes the pattern match even objects whose names start with a
773 -a: makes the pattern match even objects whose names start with a
767 single underscore. These names are normally ommitted from the
774 single underscore. These names are normally ommitted from the
768 search.
775 search.
769
776
770 -i/-c: make the pattern case insensitive/sensitive. If neither of
777 -i/-c: make the pattern case insensitive/sensitive. If neither of
771 these options is given, the default is read from your ipythonrc
778 these options is given, the default is read from your ipythonrc
772 file. The option name which sets this value is
779 file. The option name which sets this value is
773 'wildcards_case_sensitive'. If this option is not specified in your
780 'wildcards_case_sensitive'. If this option is not specified in your
774 ipythonrc file, IPython's internal default is to do a case sensitive
781 ipythonrc file, IPython's internal default is to do a case sensitive
775 search.
782 search.
776
783
777 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
784 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
778 specifiy can be searched in any of the following namespaces:
785 specifiy can be searched in any of the following namespaces:
779 'builtin', 'user', 'user_global','internal', 'alias', where
786 'builtin', 'user', 'user_global','internal', 'alias', where
780 'builtin' and 'user' are the search defaults. Note that you should
787 'builtin' and 'user' are the search defaults. Note that you should
781 not use quotes when specifying namespaces.
788 not use quotes when specifying namespaces.
782
789
783 'Builtin' contains the python module builtin, 'user' contains all
790 'Builtin' contains the python module builtin, 'user' contains all
784 user data, 'alias' only contain the shell aliases and no python
791 user data, 'alias' only contain the shell aliases and no python
785 objects, 'internal' contains objects used by IPython. The
792 objects, 'internal' contains objects used by IPython. The
786 'user_global' namespace is only used by embedded IPython instances,
793 'user_global' namespace is only used by embedded IPython instances,
787 and it contains module-level globals. You can add namespaces to the
794 and it contains module-level globals. You can add namespaces to the
788 search with -s or exclude them with -e (these options can be given
795 search with -s or exclude them with -e (these options can be given
789 more than once).
796 more than once).
790
797
791 Examples:
798 Examples:
792
799
793 %psearch a* -> objects beginning with an a
800 %psearch a* -> objects beginning with an a
794 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
801 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
795 %psearch a* function -> all functions beginning with an a
802 %psearch a* function -> all functions beginning with an a
796 %psearch re.e* -> objects beginning with an e in module re
803 %psearch re.e* -> objects beginning with an e in module re
797 %psearch r*.e* -> objects that start with e in modules starting in r
804 %psearch r*.e* -> objects that start with e in modules starting in r
798 %psearch r*.* string -> all strings in modules beginning with r
805 %psearch r*.* string -> all strings in modules beginning with r
799
806
800 Case sensitve search:
807 Case sensitve search:
801
808
802 %psearch -c a* list all object beginning with lower case a
809 %psearch -c a* list all object beginning with lower case a
803
810
804 Show objects beginning with a single _:
811 Show objects beginning with a single _:
805
812
806 %psearch -a _* list objects beginning with a single underscore"""
813 %psearch -a _* list objects beginning with a single underscore"""
807
814
808 # default namespaces to be searched
815 # default namespaces to be searched
809 def_search = ['user','builtin']
816 def_search = ['user','builtin']
810
817
811 # Process options/args
818 # Process options/args
812 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
819 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
813 opt = opts.get
820 opt = opts.get
814 shell = self.shell
821 shell = self.shell
815 psearch = shell.inspector.psearch
822 psearch = shell.inspector.psearch
816
823
817 # select case options
824 # select case options
818 if opts.has_key('i'):
825 if opts.has_key('i'):
819 ignore_case = True
826 ignore_case = True
820 elif opts.has_key('c'):
827 elif opts.has_key('c'):
821 ignore_case = False
828 ignore_case = False
822 else:
829 else:
823 ignore_case = not shell.rc.wildcards_case_sensitive
830 ignore_case = not shell.rc.wildcards_case_sensitive
824
831
825 # Build list of namespaces to search from user options
832 # Build list of namespaces to search from user options
826 def_search.extend(opt('s',[]))
833 def_search.extend(opt('s',[]))
827 ns_exclude = ns_exclude=opt('e',[])
834 ns_exclude = ns_exclude=opt('e',[])
828 ns_search = [nm for nm in def_search if nm not in ns_exclude]
835 ns_search = [nm for nm in def_search if nm not in ns_exclude]
829
836
830 # Call the actual search
837 # Call the actual search
831 try:
838 try:
832 psearch(args,shell.ns_table,ns_search,
839 psearch(args,shell.ns_table,ns_search,
833 show_all=opt('a'),ignore_case=ignore_case)
840 show_all=opt('a'),ignore_case=ignore_case)
834 except:
841 except:
835 shell.showtraceback()
842 shell.showtraceback()
836
843
837 def magic_who_ls(self, parameter_s=''):
844 def magic_who_ls(self, parameter_s=''):
838 """Return a sorted list of all interactive variables.
845 """Return a sorted list of all interactive variables.
839
846
840 If arguments are given, only variables of types matching these
847 If arguments are given, only variables of types matching these
841 arguments are returned."""
848 arguments are returned."""
842
849
843 user_ns = self.shell.user_ns
850 user_ns = self.shell.user_ns
844 internal_ns = self.shell.internal_ns
851 internal_ns = self.shell.internal_ns
845 user_config_ns = self.shell.user_config_ns
852 user_config_ns = self.shell.user_config_ns
846 out = []
853 out = []
847 typelist = parameter_s.split()
854 typelist = parameter_s.split()
848
855
849 for i in user_ns:
856 for i in user_ns:
850 if not (i.startswith('_') or i.startswith('_i')) \
857 if not (i.startswith('_') or i.startswith('_i')) \
851 and not (i in internal_ns or i in user_config_ns):
858 and not (i in internal_ns or i in user_config_ns):
852 if typelist:
859 if typelist:
853 if type(user_ns[i]).__name__ in typelist:
860 if type(user_ns[i]).__name__ in typelist:
854 out.append(i)
861 out.append(i)
855 else:
862 else:
856 out.append(i)
863 out.append(i)
857 out.sort()
864 out.sort()
858 return out
865 return out
859
866
860 def magic_who(self, parameter_s=''):
867 def magic_who(self, parameter_s=''):
861 """Print all interactive variables, with some minimal formatting.
868 """Print all interactive variables, with some minimal formatting.
862
869
863 If any arguments are given, only variables whose type matches one of
870 If any arguments are given, only variables whose type matches one of
864 these are printed. For example:
871 these are printed. For example:
865
872
866 %who function str
873 %who function str
867
874
868 will only list functions and strings, excluding all other types of
875 will only list functions and strings, excluding all other types of
869 variables. To find the proper type names, simply use type(var) at a
876 variables. To find the proper type names, simply use type(var) at a
870 command line to see how python prints type names. For example:
877 command line to see how python prints type names. For example:
871
878
872 In [1]: type('hello')\\
879 In [1]: type('hello')\\
873 Out[1]: <type 'str'>
880 Out[1]: <type 'str'>
874
881
875 indicates that the type name for strings is 'str'.
882 indicates that the type name for strings is 'str'.
876
883
877 %who always excludes executed names loaded through your configuration
884 %who always excludes executed names loaded through your configuration
878 file and things which are internal to IPython.
885 file and things which are internal to IPython.
879
886
880 This is deliberate, as typically you may load many modules and the
887 This is deliberate, as typically you may load many modules and the
881 purpose of %who is to show you only what you've manually defined."""
888 purpose of %who is to show you only what you've manually defined."""
882
889
883 varlist = self.magic_who_ls(parameter_s)
890 varlist = self.magic_who_ls(parameter_s)
884 if not varlist:
891 if not varlist:
885 print 'Interactive namespace is empty.'
892 print 'Interactive namespace is empty.'
886 return
893 return
887
894
888 # if we have variables, move on...
895 # if we have variables, move on...
889
896
890 # stupid flushing problem: when prompts have no separators, stdout is
897 # stupid flushing problem: when prompts have no separators, stdout is
891 # getting lost. I'm starting to think this is a python bug. I'm having
898 # getting lost. I'm starting to think this is a python bug. I'm having
892 # to force a flush with a print because even a sys.stdout.flush
899 # to force a flush with a print because even a sys.stdout.flush
893 # doesn't seem to do anything!
900 # doesn't seem to do anything!
894
901
895 count = 0
902 count = 0
896 for i in varlist:
903 for i in varlist:
897 print i+'\t',
904 print i+'\t',
898 count += 1
905 count += 1
899 if count > 8:
906 if count > 8:
900 count = 0
907 count = 0
901 print
908 print
902 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
909 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
903
910
904 print # well, this does force a flush at the expense of an extra \n
911 print # well, this does force a flush at the expense of an extra \n
905
912
906 def magic_whos(self, parameter_s=''):
913 def magic_whos(self, parameter_s=''):
907 """Like %who, but gives some extra information about each variable.
914 """Like %who, but gives some extra information about each variable.
908
915
909 The same type filtering of %who can be applied here.
916 The same type filtering of %who can be applied here.
910
917
911 For all variables, the type is printed. Additionally it prints:
918 For all variables, the type is printed. Additionally it prints:
912
919
913 - For {},[],(): their length.
920 - For {},[],(): their length.
914
921
915 - For Numeric arrays, a summary with shape, number of elements,
922 - For Numeric arrays, a summary with shape, number of elements,
916 typecode and size in memory.
923 typecode and size in memory.
917
924
918 - Everything else: a string representation, snipping their middle if
925 - Everything else: a string representation, snipping their middle if
919 too long."""
926 too long."""
920
927
921 varnames = self.magic_who_ls(parameter_s)
928 varnames = self.magic_who_ls(parameter_s)
922 if not varnames:
929 if not varnames:
923 print 'Interactive namespace is empty.'
930 print 'Interactive namespace is empty.'
924 return
931 return
925
932
926 # if we have variables, move on...
933 # if we have variables, move on...
927
934
928 # for these types, show len() instead of data:
935 # for these types, show len() instead of data:
929 seq_types = [types.DictType,types.ListType,types.TupleType]
936 seq_types = [types.DictType,types.ListType,types.TupleType]
930
937
931 # for Numeric arrays, display summary info
938 # for Numeric arrays, display summary info
932 try:
939 try:
933 import Numeric
940 import Numeric
934 except ImportError:
941 except ImportError:
935 array_type = None
942 array_type = None
936 else:
943 else:
937 array_type = Numeric.ArrayType.__name__
944 array_type = Numeric.ArrayType.__name__
938
945
939 # Find all variable names and types so we can figure out column sizes
946 # Find all variable names and types so we can figure out column sizes
940 get_vars = lambda i: self.shell.user_ns[i]
947 get_vars = lambda i: self.shell.user_ns[i]
941 type_name = lambda v: type(v).__name__
948 type_name = lambda v: type(v).__name__
942 varlist = map(get_vars,varnames)
949 varlist = map(get_vars,varnames)
943
950
944 typelist = []
951 typelist = []
945 for vv in varlist:
952 for vv in varlist:
946 tt = type_name(vv)
953 tt = type_name(vv)
947 if tt=='instance':
954 if tt=='instance':
948 typelist.append(str(vv.__class__))
955 typelist.append(str(vv.__class__))
949 else:
956 else:
950 typelist.append(tt)
957 typelist.append(tt)
951
958
952 # column labels and # of spaces as separator
959 # column labels and # of spaces as separator
953 varlabel = 'Variable'
960 varlabel = 'Variable'
954 typelabel = 'Type'
961 typelabel = 'Type'
955 datalabel = 'Data/Info'
962 datalabel = 'Data/Info'
956 colsep = 3
963 colsep = 3
957 # variable format strings
964 # variable format strings
958 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
965 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
959 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
966 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
960 aformat = "%s: %s elems, type `%s`, %s bytes"
967 aformat = "%s: %s elems, type `%s`, %s bytes"
961 # find the size of the columns to format the output nicely
968 # find the size of the columns to format the output nicely
962 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
969 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
963 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
970 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
964 # table header
971 # table header
965 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
972 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
966 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
973 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
967 # and the table itself
974 # and the table itself
968 kb = 1024
975 kb = 1024
969 Mb = 1048576 # kb**2
976 Mb = 1048576 # kb**2
970 for vname,var,vtype in zip(varnames,varlist,typelist):
977 for vname,var,vtype in zip(varnames,varlist,typelist):
971 print itpl(vformat),
978 print itpl(vformat),
972 if vtype in seq_types:
979 if vtype in seq_types:
973 print len(var)
980 print len(var)
974 elif vtype==array_type:
981 elif vtype==array_type:
975 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
982 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
976 vsize = Numeric.size(var)
983 vsize = Numeric.size(var)
977 vbytes = vsize*var.itemsize()
984 vbytes = vsize*var.itemsize()
978 if vbytes < 100000:
985 if vbytes < 100000:
979 print aformat % (vshape,vsize,var.typecode(),vbytes)
986 print aformat % (vshape,vsize,var.typecode(),vbytes)
980 else:
987 else:
981 print aformat % (vshape,vsize,var.typecode(),vbytes),
988 print aformat % (vshape,vsize,var.typecode(),vbytes),
982 if vbytes < Mb:
989 if vbytes < Mb:
983 print '(%s kb)' % (vbytes/kb,)
990 print '(%s kb)' % (vbytes/kb,)
984 else:
991 else:
985 print '(%s Mb)' % (vbytes/Mb,)
992 print '(%s Mb)' % (vbytes/Mb,)
986 else:
993 else:
987 vstr = str(var).replace('\n','\\n')
994 vstr = str(var).replace('\n','\\n')
988 if len(vstr) < 50:
995 if len(vstr) < 50:
989 print vstr
996 print vstr
990 else:
997 else:
991 printpl(vfmt_short)
998 printpl(vfmt_short)
992
999
993 def magic_reset(self, parameter_s=''):
1000 def magic_reset(self, parameter_s=''):
994 """Resets the namespace by removing all names defined by the user.
1001 """Resets the namespace by removing all names defined by the user.
995
1002
996 Input/Output history are left around in case you need them."""
1003 Input/Output history are left around in case you need them."""
997
1004
998 ans = self.shell.ask_yes_no(
1005 ans = self.shell.ask_yes_no(
999 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1006 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1000 if not ans:
1007 if not ans:
1001 print 'Nothing done.'
1008 print 'Nothing done.'
1002 return
1009 return
1003 user_ns = self.shell.user_ns
1010 user_ns = self.shell.user_ns
1004 for i in self.magic_who_ls():
1011 for i in self.magic_who_ls():
1005 del(user_ns[i])
1012 del(user_ns[i])
1006
1013
1007 def magic_config(self,parameter_s=''):
1014 def magic_config(self,parameter_s=''):
1008 """Show IPython's internal configuration."""
1015 """Handle IPython's internal configuration.
1016
1017 If called without arguments, it will print IPython's complete internal
1018 configuration.
1019
1020 If called with one argument, it will print the value of that key in
1021 the configuration.
1022
1023 If called with more than one argument, the first is interpreted as a
1024 key and the rest as a Python expression which gets eval()'d.
1025
1026 Examples:
1027
1028 In [1]: s='A Python string'
1029
1030 In [2]: !echo $s
1031 A Python string
1009
1032
1010 page('Current configuration structure:\n'+
1033 In [3]: config system_verbose True
1011 pformat(self.shell.rc.dict()))
1034
1035 In [4]: !echo $s
1036 IPython system call: echo A Python string
1037 A Python string
1038
1039 In [5]: %config system_header 'sys> '
1040
1041 In [6]: !echo $s
1042 sys> echo A Python string
1043 A Python string
1044
1045 # Notice the extra quotes to protect the string after interpolation:
1046 In [7]: header = "'sys2> '"
1047
1048 In [8]: %config system_header $header
1049
1050 In [9]: !echo $s
1051 sys2> echo A Python string
1052 A Python string
1053 """
1054
1055 args = parameter_s.split(None,1)
1056 key = args[0]
1057 if len(args)==1:
1058 self.shell.ipconfig(key)
1059 else:
1060 self.shell.ipconfig(key,eval(args[1]))
1012
1061
1013 def magic_logstart(self,parameter_s=''):
1062 def magic_logstart(self,parameter_s=''):
1014 """Start logging anywhere in a session.
1063 """Start logging anywhere in a session.
1015
1064
1016 %logstart [-o|-r|-t] [log_name [log_mode]]
1065 %logstart [-o|-r|-t] [log_name [log_mode]]
1017
1066
1018 If no name is given, it defaults to a file named 'ipython_log.py' in your
1067 If no name is given, it defaults to a file named 'ipython_log.py' in your
1019 current directory, in 'rotate' mode (see below).
1068 current directory, in 'rotate' mode (see below).
1020
1069
1021 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1070 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1022 history up to that point and then continues logging.
1071 history up to that point and then continues logging.
1023
1072
1024 %logstart takes a second optional parameter: logging mode. This can be one
1073 %logstart takes a second optional parameter: logging mode. This can be one
1025 of (note that the modes are given unquoted):\\
1074 of (note that the modes are given unquoted):\\
1026 append: well, that says it.\\
1075 append: well, that says it.\\
1027 backup: rename (if exists) to name~ and start name.\\
1076 backup: rename (if exists) to name~ and start name.\\
1028 global: single logfile in your home dir, appended to.\\
1077 global: single logfile in your home dir, appended to.\\
1029 over : overwrite existing log.\\
1078 over : overwrite existing log.\\
1030 rotate: create rotating logs name.1~, name.2~, etc.
1079 rotate: create rotating logs name.1~, name.2~, etc.
1031
1080
1032 Options:
1081 Options:
1033
1082
1034 -o: log also IPython's output. In this mode, all commands which
1083 -o: log also IPython's output. In this mode, all commands which
1035 generate an Out[NN] prompt are recorded to the logfile, right after
1084 generate an Out[NN] prompt are recorded to the logfile, right after
1036 their corresponding input line. The output lines are always
1085 their corresponding input line. The output lines are always
1037 prepended with a '#[Out]# ' marker, so that the log remains valid
1086 prepended with a '#[Out]# ' marker, so that the log remains valid
1038 Python code.
1087 Python code.
1039
1088
1040 Since this marker is always the same, filtering only the output from
1089 Since this marker is always the same, filtering only the output from
1041 a log is very easy, using for example a simple awk call:
1090 a log is very easy, using for example a simple awk call:
1042
1091
1043 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1092 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1044
1093
1045 -r: log 'raw' input. Normally, IPython's logs contain the processed
1094 -r: log 'raw' input. Normally, IPython's logs contain the processed
1046 input, so that user lines are logged in their final form, converted
1095 input, so that user lines are logged in their final form, converted
1047 into valid Python. For example, %Exit is logged as
1096 into valid Python. For example, %Exit is logged as
1048 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1097 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1049 exactly as typed, with no transformations applied.
1098 exactly as typed, with no transformations applied.
1050
1099
1051 -t: put timestamps before each input line logged (these are put in
1100 -t: put timestamps before each input line logged (these are put in
1052 comments)."""
1101 comments)."""
1053
1102
1054 opts,par = self.parse_options(parameter_s,'ort')
1103 opts,par = self.parse_options(parameter_s,'ort')
1055 log_output = 'o' in opts
1104 log_output = 'o' in opts
1056 log_raw_input = 'r' in opts
1105 log_raw_input = 'r' in opts
1057 timestamp = 't' in opts
1106 timestamp = 't' in opts
1058
1107
1059 rc = self.shell.rc
1108 rc = self.shell.rc
1060 logger = self.shell.logger
1109 logger = self.shell.logger
1061
1110
1062 # if no args are given, the defaults set in the logger constructor by
1111 # if no args are given, the defaults set in the logger constructor by
1063 # ipytohn remain valid
1112 # ipytohn remain valid
1064 if par:
1113 if par:
1065 try:
1114 try:
1066 logfname,logmode = par.split()
1115 logfname,logmode = par.split()
1067 except:
1116 except:
1068 logfname = par
1117 logfname = par
1069 logmode = 'backup'
1118 logmode = 'backup'
1070 else:
1119 else:
1071 logfname = logger.logfname
1120 logfname = logger.logfname
1072 logmode = logger.logmode
1121 logmode = logger.logmode
1073 # put logfname into rc struct as if it had been called on the command
1122 # put logfname into rc struct as if it had been called on the command
1074 # line, so it ends up saved in the log header Save it in case we need
1123 # line, so it ends up saved in the log header Save it in case we need
1075 # to restore it...
1124 # to restore it...
1076 old_logfile = rc.opts.get('logfile','')
1125 old_logfile = rc.opts.get('logfile','')
1077 if logfname:
1126 if logfname:
1078 logfname = os.path.expanduser(logfname)
1127 logfname = os.path.expanduser(logfname)
1079 rc.opts.logfile = logfname
1128 rc.opts.logfile = logfname
1080 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1129 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1081 try:
1130 try:
1082 started = logger.logstart(logfname,loghead,logmode,
1131 started = logger.logstart(logfname,loghead,logmode,
1083 log_output,timestamp,log_raw_input)
1132 log_output,timestamp,log_raw_input)
1084 except:
1133 except:
1085 rc.opts.logfile = old_logfile
1134 rc.opts.logfile = old_logfile
1086 warn("Couldn't start log: %s" % sys.exc_info()[1])
1135 warn("Couldn't start log: %s" % sys.exc_info()[1])
1087 else:
1136 else:
1088 # log input history up to this point, optionally interleaving
1137 # log input history up to this point, optionally interleaving
1089 # output if requested
1138 # output if requested
1090
1139
1091 if timestamp:
1140 if timestamp:
1092 # disable timestamping for the previous history, since we've
1141 # disable timestamping for the previous history, since we've
1093 # lost those already (no time machine here).
1142 # lost those already (no time machine here).
1094 logger.timestamp = False
1143 logger.timestamp = False
1095
1144
1096 if log_raw_input:
1145 if log_raw_input:
1097 input_hist = self.shell.input_hist_raw
1146 input_hist = self.shell.input_hist_raw
1098 else:
1147 else:
1099 input_hist = self.shell.input_hist
1148 input_hist = self.shell.input_hist
1100
1149
1101 if log_output:
1150 if log_output:
1102 log_write = logger.log_write
1151 log_write = logger.log_write
1103 output_hist = self.shell.output_hist
1152 output_hist = self.shell.output_hist
1104 for n in range(1,len(input_hist)-1):
1153 for n in range(1,len(input_hist)-1):
1105 log_write(input_hist[n].rstrip())
1154 log_write(input_hist[n].rstrip())
1106 if n in output_hist:
1155 if n in output_hist:
1107 log_write(repr(output_hist[n]),'output')
1156 log_write(repr(output_hist[n]),'output')
1108 else:
1157 else:
1109 logger.log_write(input_hist[1:])
1158 logger.log_write(input_hist[1:])
1110 if timestamp:
1159 if timestamp:
1111 # re-enable timestamping
1160 # re-enable timestamping
1112 logger.timestamp = True
1161 logger.timestamp = True
1113
1162
1114 print ('Activating auto-logging. '
1163 print ('Activating auto-logging. '
1115 'Current session state plus future input saved.')
1164 'Current session state plus future input saved.')
1116 logger.logstate()
1165 logger.logstate()
1117
1166
1118 def magic_logoff(self,parameter_s=''):
1167 def magic_logoff(self,parameter_s=''):
1119 """Temporarily stop logging.
1168 """Temporarily stop logging.
1120
1169
1121 You must have previously started logging."""
1170 You must have previously started logging."""
1122 self.shell.logger.switch_log(0)
1171 self.shell.logger.switch_log(0)
1123
1172
1124 def magic_logon(self,parameter_s=''):
1173 def magic_logon(self,parameter_s=''):
1125 """Restart logging.
1174 """Restart logging.
1126
1175
1127 This function is for restarting logging which you've temporarily
1176 This function is for restarting logging which you've temporarily
1128 stopped with %logoff. For starting logging for the first time, you
1177 stopped with %logoff. For starting logging for the first time, you
1129 must use the %logstart function, which allows you to specify an
1178 must use the %logstart function, which allows you to specify an
1130 optional log filename."""
1179 optional log filename."""
1131
1180
1132 self.shell.logger.switch_log(1)
1181 self.shell.logger.switch_log(1)
1133
1182
1134 def magic_logstate(self,parameter_s=''):
1183 def magic_logstate(self,parameter_s=''):
1135 """Print the status of the logging system."""
1184 """Print the status of the logging system."""
1136
1185
1137 self.shell.logger.logstate()
1186 self.shell.logger.logstate()
1138
1187
1139 def magic_pdb(self, parameter_s=''):
1188 def magic_pdb(self, parameter_s=''):
1140 """Control the calling of the pdb interactive debugger.
1189 """Control the calling of the pdb interactive debugger.
1141
1190
1142 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1191 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1143 argument it works as a toggle.
1192 argument it works as a toggle.
1144
1193
1145 When an exception is triggered, IPython can optionally call the
1194 When an exception is triggered, IPython can optionally call the
1146 interactive pdb debugger after the traceback printout. %pdb toggles
1195 interactive pdb debugger after the traceback printout. %pdb toggles
1147 this feature on and off."""
1196 this feature on and off."""
1148
1197
1149 par = parameter_s.strip().lower()
1198 par = parameter_s.strip().lower()
1150
1199
1151 if par:
1200 if par:
1152 try:
1201 try:
1153 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1202 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1154 except KeyError:
1203 except KeyError:
1155 print ('Incorrect argument. Use on/1, off/0, '
1204 print ('Incorrect argument. Use on/1, off/0, '
1156 'or nothing for a toggle.')
1205 'or nothing for a toggle.')
1157 return
1206 return
1158 else:
1207 else:
1159 # toggle
1208 # toggle
1160 new_pdb = not self.shell.InteractiveTB.call_pdb
1209 new_pdb = not self.shell.InteractiveTB.call_pdb
1161
1210
1162 # set on the shell
1211 # set on the shell
1163 self.shell.call_pdb = new_pdb
1212 self.shell.call_pdb = new_pdb
1164 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1213 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1165
1214
1166 def magic_prun(self, parameter_s ='',user_mode=1,
1215 def magic_prun(self, parameter_s ='',user_mode=1,
1167 opts=None,arg_lst=None,prog_ns=None):
1216 opts=None,arg_lst=None,prog_ns=None):
1168
1217
1169 """Run a statement through the python code profiler.
1218 """Run a statement through the python code profiler.
1170
1219
1171 Usage:\\
1220 Usage:\\
1172 %prun [options] statement
1221 %prun [options] statement
1173
1222
1174 The given statement (which doesn't require quote marks) is run via the
1223 The given statement (which doesn't require quote marks) is run via the
1175 python profiler in a manner similar to the profile.run() function.
1224 python profiler in a manner similar to the profile.run() function.
1176 Namespaces are internally managed to work correctly; profile.run
1225 Namespaces are internally managed to work correctly; profile.run
1177 cannot be used in IPython because it makes certain assumptions about
1226 cannot be used in IPython because it makes certain assumptions about
1178 namespaces which do not hold under IPython.
1227 namespaces which do not hold under IPython.
1179
1228
1180 Options:
1229 Options:
1181
1230
1182 -l <limit>: you can place restrictions on what or how much of the
1231 -l <limit>: you can place restrictions on what or how much of the
1183 profile gets printed. The limit value can be:
1232 profile gets printed. The limit value can be:
1184
1233
1185 * A string: only information for function names containing this string
1234 * A string: only information for function names containing this string
1186 is printed.
1235 is printed.
1187
1236
1188 * An integer: only these many lines are printed.
1237 * An integer: only these many lines are printed.
1189
1238
1190 * A float (between 0 and 1): this fraction of the report is printed
1239 * A float (between 0 and 1): this fraction of the report is printed
1191 (for example, use a limit of 0.4 to see the topmost 40% only).
1240 (for example, use a limit of 0.4 to see the topmost 40% only).
1192
1241
1193 You can combine several limits with repeated use of the option. For
1242 You can combine several limits with repeated use of the option. For
1194 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1243 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1195 information about class constructors.
1244 information about class constructors.
1196
1245
1197 -r: return the pstats.Stats object generated by the profiling. This
1246 -r: return the pstats.Stats object generated by the profiling. This
1198 object has all the information about the profile in it, and you can
1247 object has all the information about the profile in it, and you can
1199 later use it for further analysis or in other functions.
1248 later use it for further analysis or in other functions.
1200
1249
1201 Since magic functions have a particular form of calling which prevents
1250 Since magic functions have a particular form of calling which prevents
1202 you from writing something like:\\
1251 you from writing something like:\\
1203 In [1]: p = %prun -r print 4 # invalid!\\
1252 In [1]: p = %prun -r print 4 # invalid!\\
1204 you must instead use IPython's automatic variables to assign this:\\
1253 you must instead use IPython's automatic variables to assign this:\\
1205 In [1]: %prun -r print 4 \\
1254 In [1]: %prun -r print 4 \\
1206 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1255 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1207 In [2]: stats = _
1256 In [2]: stats = _
1208
1257
1209 If you really need to assign this value via an explicit function call,
1258 If you really need to assign this value via an explicit function call,
1210 you can always tap directly into the true name of the magic function
1259 you can always tap directly into the true name of the magic function
1211 by using the _ip.magic function:\\
1260 by using the _ip.magic function:\\
1212 In [3]: stats = _ip.magic('prun','-r print 4')
1261 In [3]: stats = _ip.magic('prun','-r print 4')
1213
1262
1214 You can type _ip.magic? for more details.
1263 You can type _ip.magic? for more details.
1215
1264
1216 -s <key>: sort profile by given key. You can provide more than one key
1265 -s <key>: sort profile by given key. You can provide more than one key
1217 by using the option several times: '-s key1 -s key2 -s key3...'. The
1266 by using the option several times: '-s key1 -s key2 -s key3...'. The
1218 default sorting key is 'time'.
1267 default sorting key is 'time'.
1219
1268
1220 The following is copied verbatim from the profile documentation
1269 The following is copied verbatim from the profile documentation
1221 referenced below:
1270 referenced below:
1222
1271
1223 When more than one key is provided, additional keys are used as
1272 When more than one key is provided, additional keys are used as
1224 secondary criteria when the there is equality in all keys selected
1273 secondary criteria when the there is equality in all keys selected
1225 before them.
1274 before them.
1226
1275
1227 Abbreviations can be used for any key names, as long as the
1276 Abbreviations can be used for any key names, as long as the
1228 abbreviation is unambiguous. The following are the keys currently
1277 abbreviation is unambiguous. The following are the keys currently
1229 defined:
1278 defined:
1230
1279
1231 Valid Arg Meaning\\
1280 Valid Arg Meaning\\
1232 "calls" call count\\
1281 "calls" call count\\
1233 "cumulative" cumulative time\\
1282 "cumulative" cumulative time\\
1234 "file" file name\\
1283 "file" file name\\
1235 "module" file name\\
1284 "module" file name\\
1236 "pcalls" primitive call count\\
1285 "pcalls" primitive call count\\
1237 "line" line number\\
1286 "line" line number\\
1238 "name" function name\\
1287 "name" function name\\
1239 "nfl" name/file/line\\
1288 "nfl" name/file/line\\
1240 "stdname" standard name\\
1289 "stdname" standard name\\
1241 "time" internal time
1290 "time" internal time
1242
1291
1243 Note that all sorts on statistics are in descending order (placing
1292 Note that all sorts on statistics are in descending order (placing
1244 most time consuming items first), where as name, file, and line number
1293 most time consuming items first), where as name, file, and line number
1245 searches are in ascending order (i.e., alphabetical). The subtle
1294 searches are in ascending order (i.e., alphabetical). The subtle
1246 distinction between "nfl" and "stdname" is that the standard name is a
1295 distinction between "nfl" and "stdname" is that the standard name is a
1247 sort of the name as printed, which means that the embedded line
1296 sort of the name as printed, which means that the embedded line
1248 numbers get compared in an odd way. For example, lines 3, 20, and 40
1297 numbers get compared in an odd way. For example, lines 3, 20, and 40
1249 would (if the file names were the same) appear in the string order
1298 would (if the file names were the same) appear in the string order
1250 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1299 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1251 line numbers. In fact, sort_stats("nfl") is the same as
1300 line numbers. In fact, sort_stats("nfl") is the same as
1252 sort_stats("name", "file", "line").
1301 sort_stats("name", "file", "line").
1253
1302
1254 -T <filename>: save profile results as shown on screen to a text
1303 -T <filename>: save profile results as shown on screen to a text
1255 file. The profile is still shown on screen.
1304 file. The profile is still shown on screen.
1256
1305
1257 -D <filename>: save (via dump_stats) profile statistics to given
1306 -D <filename>: save (via dump_stats) profile statistics to given
1258 filename. This data is in a format understod by the pstats module, and
1307 filename. This data is in a format understod by the pstats module, and
1259 is generated by a call to the dump_stats() method of profile
1308 is generated by a call to the dump_stats() method of profile
1260 objects. The profile is still shown on screen.
1309 objects. The profile is still shown on screen.
1261
1310
1262 If you want to run complete programs under the profiler's control, use
1311 If you want to run complete programs under the profiler's control, use
1263 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1312 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1264 contains profiler specific options as described here.
1313 contains profiler specific options as described here.
1265
1314
1266 You can read the complete documentation for the profile module with:\\
1315 You can read the complete documentation for the profile module with:\\
1267 In [1]: import profile; profile.help() """
1316 In [1]: import profile; profile.help() """
1268
1317
1269 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1318 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1270 # protect user quote marks
1319 # protect user quote marks
1271 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1320 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1272
1321
1273 if user_mode: # regular user call
1322 if user_mode: # regular user call
1274 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1323 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1275 list_all=1)
1324 list_all=1)
1276 namespace = self.shell.user_ns
1325 namespace = self.shell.user_ns
1277 else: # called to run a program by %run -p
1326 else: # called to run a program by %run -p
1278 try:
1327 try:
1279 filename = get_py_filename(arg_lst[0])
1328 filename = get_py_filename(arg_lst[0])
1280 except IOError,msg:
1329 except IOError,msg:
1281 error(msg)
1330 error(msg)
1282 return
1331 return
1283
1332
1284 arg_str = 'execfile(filename,prog_ns)'
1333 arg_str = 'execfile(filename,prog_ns)'
1285 namespace = locals()
1334 namespace = locals()
1286
1335
1287 opts.merge(opts_def)
1336 opts.merge(opts_def)
1288
1337
1289 prof = profile.Profile()
1338 prof = profile.Profile()
1290 try:
1339 try:
1291 prof = prof.runctx(arg_str,namespace,namespace)
1340 prof = prof.runctx(arg_str,namespace,namespace)
1292 sys_exit = ''
1341 sys_exit = ''
1293 except SystemExit:
1342 except SystemExit:
1294 sys_exit = """*** SystemExit exception caught in code being profiled."""
1343 sys_exit = """*** SystemExit exception caught in code being profiled."""
1295
1344
1296 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1345 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1297
1346
1298 lims = opts.l
1347 lims = opts.l
1299 if lims:
1348 if lims:
1300 lims = [] # rebuild lims with ints/floats/strings
1349 lims = [] # rebuild lims with ints/floats/strings
1301 for lim in opts.l:
1350 for lim in opts.l:
1302 try:
1351 try:
1303 lims.append(int(lim))
1352 lims.append(int(lim))
1304 except ValueError:
1353 except ValueError:
1305 try:
1354 try:
1306 lims.append(float(lim))
1355 lims.append(float(lim))
1307 except ValueError:
1356 except ValueError:
1308 lims.append(lim)
1357 lims.append(lim)
1309
1358
1310 # trap output
1359 # trap output
1311 sys_stdout = sys.stdout
1360 sys_stdout = sys.stdout
1312 stdout_trap = StringIO()
1361 stdout_trap = StringIO()
1313 try:
1362 try:
1314 sys.stdout = stdout_trap
1363 sys.stdout = stdout_trap
1315 stats.print_stats(*lims)
1364 stats.print_stats(*lims)
1316 finally:
1365 finally:
1317 sys.stdout = sys_stdout
1366 sys.stdout = sys_stdout
1318 output = stdout_trap.getvalue()
1367 output = stdout_trap.getvalue()
1319 output = output.rstrip()
1368 output = output.rstrip()
1320
1369
1321 page(output,screen_lines=self.shell.rc.screen_length)
1370 page(output,screen_lines=self.shell.rc.screen_length)
1322 print sys_exit,
1371 print sys_exit,
1323
1372
1324 dump_file = opts.D[0]
1373 dump_file = opts.D[0]
1325 text_file = opts.T[0]
1374 text_file = opts.T[0]
1326 if dump_file:
1375 if dump_file:
1327 prof.dump_stats(dump_file)
1376 prof.dump_stats(dump_file)
1328 print '\n*** Profile stats marshalled to file',\
1377 print '\n*** Profile stats marshalled to file',\
1329 `dump_file`+'.',sys_exit
1378 `dump_file`+'.',sys_exit
1330 if text_file:
1379 if text_file:
1331 file(text_file,'w').write(output)
1380 file(text_file,'w').write(output)
1332 print '\n*** Profile printout saved to text file',\
1381 print '\n*** Profile printout saved to text file',\
1333 `text_file`+'.',sys_exit
1382 `text_file`+'.',sys_exit
1334
1383
1335 if opts.has_key('r'):
1384 if opts.has_key('r'):
1336 return stats
1385 return stats
1337 else:
1386 else:
1338 return None
1387 return None
1339
1388
1340 def magic_run(self, parameter_s ='',runner=None):
1389 def magic_run(self, parameter_s ='',runner=None):
1341 """Run the named file inside IPython as a program.
1390 """Run the named file inside IPython as a program.
1342
1391
1343 Usage:\\
1392 Usage:\\
1344 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1393 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1345
1394
1346 Parameters after the filename are passed as command-line arguments to
1395 Parameters after the filename are passed as command-line arguments to
1347 the program (put in sys.argv). Then, control returns to IPython's
1396 the program (put in sys.argv). Then, control returns to IPython's
1348 prompt.
1397 prompt.
1349
1398
1350 This is similar to running at a system prompt:\\
1399 This is similar to running at a system prompt:\\
1351 $ python file args\\
1400 $ python file args\\
1352 but with the advantage of giving you IPython's tracebacks, and of
1401 but with the advantage of giving you IPython's tracebacks, and of
1353 loading all variables into your interactive namespace for further use
1402 loading all variables into your interactive namespace for further use
1354 (unless -p is used, see below).
1403 (unless -p is used, see below).
1355
1404
1356 The file is executed in a namespace initially consisting only of
1405 The file is executed in a namespace initially consisting only of
1357 __name__=='__main__' and sys.argv constructed as indicated. It thus
1406 __name__=='__main__' and sys.argv constructed as indicated. It thus
1358 sees its environment as if it were being run as a stand-alone
1407 sees its environment as if it were being run as a stand-alone
1359 program. But after execution, the IPython interactive namespace gets
1408 program. But after execution, the IPython interactive namespace gets
1360 updated with all variables defined in the program (except for __name__
1409 updated with all variables defined in the program (except for __name__
1361 and sys.argv). This allows for very convenient loading of code for
1410 and sys.argv). This allows for very convenient loading of code for
1362 interactive work, while giving each program a 'clean sheet' to run in.
1411 interactive work, while giving each program a 'clean sheet' to run in.
1363
1412
1364 Options:
1413 Options:
1365
1414
1366 -n: __name__ is NOT set to '__main__', but to the running file's name
1415 -n: __name__ is NOT set to '__main__', but to the running file's name
1367 without extension (as python does under import). This allows running
1416 without extension (as python does under import). This allows running
1368 scripts and reloading the definitions in them without calling code
1417 scripts and reloading the definitions in them without calling code
1369 protected by an ' if __name__ == "__main__" ' clause.
1418 protected by an ' if __name__ == "__main__" ' clause.
1370
1419
1371 -i: run the file in IPython's namespace instead of an empty one. This
1420 -i: run the file in IPython's namespace instead of an empty one. This
1372 is useful if you are experimenting with code written in a text editor
1421 is useful if you are experimenting with code written in a text editor
1373 which depends on variables defined interactively.
1422 which depends on variables defined interactively.
1374
1423
1375 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1424 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1376 being run. This is particularly useful if IPython is being used to
1425 being run. This is particularly useful if IPython is being used to
1377 run unittests, which always exit with a sys.exit() call. In such
1426 run unittests, which always exit with a sys.exit() call. In such
1378 cases you are interested in the output of the test results, not in
1427 cases you are interested in the output of the test results, not in
1379 seeing a traceback of the unittest module.
1428 seeing a traceback of the unittest module.
1380
1429
1381 -t: print timing information at the end of the run. IPython will give
1430 -t: print timing information at the end of the run. IPython will give
1382 you an estimated CPU time consumption for your script, which under
1431 you an estimated CPU time consumption for your script, which under
1383 Unix uses the resource module to avoid the wraparound problems of
1432 Unix uses the resource module to avoid the wraparound problems of
1384 time.clock(). Under Unix, an estimate of time spent on system tasks
1433 time.clock(). Under Unix, an estimate of time spent on system tasks
1385 is also given (for Windows platforms this is reported as 0.0).
1434 is also given (for Windows platforms this is reported as 0.0).
1386
1435
1387 If -t is given, an additional -N<N> option can be given, where <N>
1436 If -t is given, an additional -N<N> option can be given, where <N>
1388 must be an integer indicating how many times you want the script to
1437 must be an integer indicating how many times you want the script to
1389 run. The final timing report will include total and per run results.
1438 run. The final timing report will include total and per run results.
1390
1439
1391 For example (testing the script uniq_stable.py):
1440 For example (testing the script uniq_stable.py):
1392
1441
1393 In [1]: run -t uniq_stable
1442 In [1]: run -t uniq_stable
1394
1443
1395 IPython CPU timings (estimated):\\
1444 IPython CPU timings (estimated):\\
1396 User : 0.19597 s.\\
1445 User : 0.19597 s.\\
1397 System: 0.0 s.\\
1446 System: 0.0 s.\\
1398
1447
1399 In [2]: run -t -N5 uniq_stable
1448 In [2]: run -t -N5 uniq_stable
1400
1449
1401 IPython CPU timings (estimated):\\
1450 IPython CPU timings (estimated):\\
1402 Total runs performed: 5\\
1451 Total runs performed: 5\\
1403 Times : Total Per run\\
1452 Times : Total Per run\\
1404 User : 0.910862 s, 0.1821724 s.\\
1453 User : 0.910862 s, 0.1821724 s.\\
1405 System: 0.0 s, 0.0 s.
1454 System: 0.0 s, 0.0 s.
1406
1455
1407 -d: run your program under the control of pdb, the Python debugger.
1456 -d: run your program under the control of pdb, the Python debugger.
1408 This allows you to execute your program step by step, watch variables,
1457 This allows you to execute your program step by step, watch variables,
1409 etc. Internally, what IPython does is similar to calling:
1458 etc. Internally, what IPython does is similar to calling:
1410
1459
1411 pdb.run('execfile("YOURFILENAME")')
1460 pdb.run('execfile("YOURFILENAME")')
1412
1461
1413 with a breakpoint set on line 1 of your file. You can change the line
1462 with a breakpoint set on line 1 of your file. You can change the line
1414 number for this automatic breakpoint to be <N> by using the -bN option
1463 number for this automatic breakpoint to be <N> by using the -bN option
1415 (where N must be an integer). For example:
1464 (where N must be an integer). For example:
1416
1465
1417 %run -d -b40 myscript
1466 %run -d -b40 myscript
1418
1467
1419 will set the first breakpoint at line 40 in myscript.py. Note that
1468 will set the first breakpoint at line 40 in myscript.py. Note that
1420 the first breakpoint must be set on a line which actually does
1469 the first breakpoint must be set on a line which actually does
1421 something (not a comment or docstring) for it to stop execution.
1470 something (not a comment or docstring) for it to stop execution.
1422
1471
1423 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1472 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1424 first enter 'c' (without qoutes) to start execution up to the first
1473 first enter 'c' (without qoutes) to start execution up to the first
1425 breakpoint.
1474 breakpoint.
1426
1475
1427 Entering 'help' gives information about the use of the debugger. You
1476 Entering 'help' gives information about the use of the debugger. You
1428 can easily see pdb's full documentation with "import pdb;pdb.help()"
1477 can easily see pdb's full documentation with "import pdb;pdb.help()"
1429 at a prompt.
1478 at a prompt.
1430
1479
1431 -p: run program under the control of the Python profiler module (which
1480 -p: run program under the control of the Python profiler module (which
1432 prints a detailed report of execution times, function calls, etc).
1481 prints a detailed report of execution times, function calls, etc).
1433
1482
1434 You can pass other options after -p which affect the behavior of the
1483 You can pass other options after -p which affect the behavior of the
1435 profiler itself. See the docs for %prun for details.
1484 profiler itself. See the docs for %prun for details.
1436
1485
1437 In this mode, the program's variables do NOT propagate back to the
1486 In this mode, the program's variables do NOT propagate back to the
1438 IPython interactive namespace (because they remain in the namespace
1487 IPython interactive namespace (because they remain in the namespace
1439 where the profiler executes them).
1488 where the profiler executes them).
1440
1489
1441 Internally this triggers a call to %prun, see its documentation for
1490 Internally this triggers a call to %prun, see its documentation for
1442 details on the options available specifically for profiling."""
1491 details on the options available specifically for profiling."""
1443
1492
1444 # get arguments and set sys.argv for program to be run.
1493 # get arguments and set sys.argv for program to be run.
1445 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1494 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1446 mode='list',list_all=1)
1495 mode='list',list_all=1)
1447
1496
1448 try:
1497 try:
1449 filename = get_py_filename(arg_lst[0])
1498 filename = get_py_filename(arg_lst[0])
1450 except IndexError:
1499 except IndexError:
1451 warn('you must provide at least a filename.')
1500 warn('you must provide at least a filename.')
1452 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1501 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1453 return
1502 return
1454 except IOError,msg:
1503 except IOError,msg:
1455 error(msg)
1504 error(msg)
1456 return
1505 return
1457
1506
1458 # Control the response to exit() calls made by the script being run
1507 # Control the response to exit() calls made by the script being run
1459 exit_ignore = opts.has_key('e')
1508 exit_ignore = opts.has_key('e')
1460
1509
1461 # Make sure that the running script gets a proper sys.argv as if it
1510 # Make sure that the running script gets a proper sys.argv as if it
1462 # were run from a system shell.
1511 # were run from a system shell.
1463 save_argv = sys.argv # save it for later restoring
1512 save_argv = sys.argv # save it for later restoring
1464 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1513 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1465
1514
1466 if opts.has_key('i'):
1515 if opts.has_key('i'):
1467 prog_ns = self.shell.user_ns
1516 prog_ns = self.shell.user_ns
1468 __name__save = self.shell.user_ns['__name__']
1517 __name__save = self.shell.user_ns['__name__']
1469 prog_ns['__name__'] = '__main__'
1518 prog_ns['__name__'] = '__main__'
1470 else:
1519 else:
1471 if opts.has_key('n'):
1520 if opts.has_key('n'):
1472 name = os.path.splitext(os.path.basename(filename))[0]
1521 name = os.path.splitext(os.path.basename(filename))[0]
1473 else:
1522 else:
1474 name = '__main__'
1523 name = '__main__'
1475 prog_ns = {'__name__':name}
1524 prog_ns = {'__name__':name}
1476
1525
1477 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1526 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1478 # set the __file__ global in the script's namespace
1527 # set the __file__ global in the script's namespace
1479 prog_ns['__file__'] = filename
1528 prog_ns['__file__'] = filename
1480
1529
1481 # pickle fix. See iplib for an explanation. But we need to make sure
1530 # pickle fix. See iplib for an explanation. But we need to make sure
1482 # that, if we overwrite __main__, we replace it at the end
1531 # that, if we overwrite __main__, we replace it at the end
1483 if prog_ns['__name__'] == '__main__':
1532 if prog_ns['__name__'] == '__main__':
1484 restore_main = sys.modules['__main__']
1533 restore_main = sys.modules['__main__']
1485 else:
1534 else:
1486 restore_main = False
1535 restore_main = False
1487
1536
1488 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1537 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1489
1538
1490 stats = None
1539 stats = None
1491 try:
1540 try:
1492 if self.shell.has_readline:
1541 if self.shell.has_readline:
1493 self.shell.savehist()
1542 self.shell.savehist()
1494
1543
1495 if opts.has_key('p'):
1544 if opts.has_key('p'):
1496 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1545 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1497 else:
1546 else:
1498 if opts.has_key('d'):
1547 if opts.has_key('d'):
1499 deb = Debugger.Pdb(self.shell.rc.colors)
1548 deb = Debugger.Pdb(self.shell.rc.colors)
1500 # reset Breakpoint state, which is moronically kept
1549 # reset Breakpoint state, which is moronically kept
1501 # in a class
1550 # in a class
1502 bdb.Breakpoint.next = 1
1551 bdb.Breakpoint.next = 1
1503 bdb.Breakpoint.bplist = {}
1552 bdb.Breakpoint.bplist = {}
1504 bdb.Breakpoint.bpbynumber = [None]
1553 bdb.Breakpoint.bpbynumber = [None]
1505 # Set an initial breakpoint to stop execution
1554 # Set an initial breakpoint to stop execution
1506 maxtries = 10
1555 maxtries = 10
1507 bp = int(opts.get('b',[1])[0])
1556 bp = int(opts.get('b',[1])[0])
1508 checkline = deb.checkline(filename,bp)
1557 checkline = deb.checkline(filename,bp)
1509 if not checkline:
1558 if not checkline:
1510 for bp in range(bp+1,bp+maxtries+1):
1559 for bp in range(bp+1,bp+maxtries+1):
1511 if deb.checkline(filename,bp):
1560 if deb.checkline(filename,bp):
1512 break
1561 break
1513 else:
1562 else:
1514 msg = ("\nI failed to find a valid line to set "
1563 msg = ("\nI failed to find a valid line to set "
1515 "a breakpoint\n"
1564 "a breakpoint\n"
1516 "after trying up to line: %s.\n"
1565 "after trying up to line: %s.\n"
1517 "Please set a valid breakpoint manually "
1566 "Please set a valid breakpoint manually "
1518 "with the -b option." % bp)
1567 "with the -b option." % bp)
1519 error(msg)
1568 error(msg)
1520 return
1569 return
1521 # if we find a good linenumber, set the breakpoint
1570 # if we find a good linenumber, set the breakpoint
1522 deb.do_break('%s:%s' % (filename,bp))
1571 deb.do_break('%s:%s' % (filename,bp))
1523 # Start file run
1572 # Start file run
1524 print "NOTE: Enter 'c' at the",
1573 print "NOTE: Enter 'c' at the",
1525 print "%s prompt to start your script." % deb.prompt
1574 print "%s prompt to start your script." % deb.prompt
1526 try:
1575 try:
1527 deb.run('execfile("%s")' % filename,prog_ns)
1576 deb.run('execfile("%s")' % filename,prog_ns)
1528
1577
1529 except:
1578 except:
1530 etype, value, tb = sys.exc_info()
1579 etype, value, tb = sys.exc_info()
1531 # Skip three frames in the traceback: the %run one,
1580 # Skip three frames in the traceback: the %run one,
1532 # one inside bdb.py, and the command-line typed by the
1581 # one inside bdb.py, and the command-line typed by the
1533 # user (run by exec in pdb itself).
1582 # user (run by exec in pdb itself).
1534 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1583 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1535 else:
1584 else:
1536 if runner is None:
1585 if runner is None:
1537 runner = self.shell.safe_execfile
1586 runner = self.shell.safe_execfile
1538 if opts.has_key('t'):
1587 if opts.has_key('t'):
1539 try:
1588 try:
1540 nruns = int(opts['N'][0])
1589 nruns = int(opts['N'][0])
1541 if nruns < 1:
1590 if nruns < 1:
1542 error('Number of runs must be >=1')
1591 error('Number of runs must be >=1')
1543 return
1592 return
1544 except (KeyError):
1593 except (KeyError):
1545 nruns = 1
1594 nruns = 1
1546 if nruns == 1:
1595 if nruns == 1:
1547 t0 = clock2()
1596 t0 = clock2()
1548 runner(filename,prog_ns,prog_ns,
1597 runner(filename,prog_ns,prog_ns,
1549 exit_ignore=exit_ignore)
1598 exit_ignore=exit_ignore)
1550 t1 = clock2()
1599 t1 = clock2()
1551 t_usr = t1[0]-t0[0]
1600 t_usr = t1[0]-t0[0]
1552 t_sys = t1[1]-t1[1]
1601 t_sys = t1[1]-t1[1]
1553 print "\nIPython CPU timings (estimated):"
1602 print "\nIPython CPU timings (estimated):"
1554 print " User : %10s s." % t_usr
1603 print " User : %10s s." % t_usr
1555 print " System: %10s s." % t_sys
1604 print " System: %10s s." % t_sys
1556 else:
1605 else:
1557 runs = range(nruns)
1606 runs = range(nruns)
1558 t0 = clock2()
1607 t0 = clock2()
1559 for nr in runs:
1608 for nr in runs:
1560 runner(filename,prog_ns,prog_ns,
1609 runner(filename,prog_ns,prog_ns,
1561 exit_ignore=exit_ignore)
1610 exit_ignore=exit_ignore)
1562 t1 = clock2()
1611 t1 = clock2()
1563 t_usr = t1[0]-t0[0]
1612 t_usr = t1[0]-t0[0]
1564 t_sys = t1[1]-t1[1]
1613 t_sys = t1[1]-t1[1]
1565 print "\nIPython CPU timings (estimated):"
1614 print "\nIPython CPU timings (estimated):"
1566 print "Total runs performed:",nruns
1615 print "Total runs performed:",nruns
1567 print " Times : %10s %10s" % ('Total','Per run')
1616 print " Times : %10s %10s" % ('Total','Per run')
1568 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1617 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1569 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1618 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1570
1619
1571 else:
1620 else:
1572 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1621 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1573 if opts.has_key('i'):
1622 if opts.has_key('i'):
1574 self.shell.user_ns['__name__'] = __name__save
1623 self.shell.user_ns['__name__'] = __name__save
1575 else:
1624 else:
1576 # update IPython interactive namespace
1625 # update IPython interactive namespace
1577 del prog_ns['__name__']
1626 del prog_ns['__name__']
1578 self.shell.user_ns.update(prog_ns)
1627 self.shell.user_ns.update(prog_ns)
1579 finally:
1628 finally:
1580 sys.argv = save_argv
1629 sys.argv = save_argv
1581 if restore_main:
1630 if restore_main:
1582 sys.modules['__main__'] = restore_main
1631 sys.modules['__main__'] = restore_main
1583 if self.shell.has_readline:
1632 if self.shell.has_readline:
1584 self.shell.readline.read_history_file(self.shell.histfile)
1633 self.shell.readline.read_history_file(self.shell.histfile)
1585
1634
1586 return stats
1635 return stats
1587
1636
1588 def magic_runlog(self, parameter_s =''):
1637 def magic_runlog(self, parameter_s =''):
1589 """Run files as logs.
1638 """Run files as logs.
1590
1639
1591 Usage:\\
1640 Usage:\\
1592 %runlog file1 file2 ...
1641 %runlog file1 file2 ...
1593
1642
1594 Run the named files (treating them as log files) in sequence inside
1643 Run the named files (treating them as log files) in sequence inside
1595 the interpreter, and return to the prompt. This is much slower than
1644 the interpreter, and return to the prompt. This is much slower than
1596 %run because each line is executed in a try/except block, but it
1645 %run because each line is executed in a try/except block, but it
1597 allows running files with syntax errors in them.
1646 allows running files with syntax errors in them.
1598
1647
1599 Normally IPython will guess when a file is one of its own logfiles, so
1648 Normally IPython will guess when a file is one of its own logfiles, so
1600 you can typically use %run even for logs. This shorthand allows you to
1649 you can typically use %run even for logs. This shorthand allows you to
1601 force any file to be treated as a log file."""
1650 force any file to be treated as a log file."""
1602
1651
1603 for f in parameter_s.split():
1652 for f in parameter_s.split():
1604 self.shell.safe_execfile(f,self.shell.user_ns,
1653 self.shell.safe_execfile(f,self.shell.user_ns,
1605 self.shell.user_ns,islog=1)
1654 self.shell.user_ns,islog=1)
1606
1655
1607 def magic_timeit(self, parameter_s =''):
1656 def magic_timeit(self, parameter_s =''):
1608 """Time execution of a Python statement or expression
1657 """Time execution of a Python statement or expression
1609
1658
1610 Usage:\\
1659 Usage:\\
1611 %timeit [-n<N> -r<R> [-t|-c]] statement
1660 %timeit [-n<N> -r<R> [-t|-c]] statement
1612
1661
1613 Time execution of a Python statement or expression using the timeit
1662 Time execution of a Python statement or expression using the timeit
1614 module.
1663 module.
1615
1664
1616 Options:
1665 Options:
1617 -n<N>: execute the given statement <N> times in a loop. If this value
1666 -n<N>: execute the given statement <N> times in a loop. If this value
1618 is not given, a fitting value is chosen.
1667 is not given, a fitting value is chosen.
1619
1668
1620 -r<R>: repeat the loop iteration <R> times and take the best result.
1669 -r<R>: repeat the loop iteration <R> times and take the best result.
1621 Default: 3
1670 Default: 3
1622
1671
1623 -t: use time.time to measure the time, which is the default on Unix.
1672 -t: use time.time to measure the time, which is the default on Unix.
1624 This function measures wall time.
1673 This function measures wall time.
1625
1674
1626 -c: use time.clock to measure the time, which is the default on
1675 -c: use time.clock to measure the time, which is the default on
1627 Windows and measures wall time. On Unix, resource.getrusage is used
1676 Windows and measures wall time. On Unix, resource.getrusage is used
1628 instead and returns the CPU user time.
1677 instead and returns the CPU user time.
1629
1678
1630 -p<P>: use a precision of <P> digits to display the timing result.
1679 -p<P>: use a precision of <P> digits to display the timing result.
1631 Default: 3
1680 Default: 3
1632
1681
1633
1682
1634 Examples:\\
1683 Examples:\\
1635 In [1]: %timeit pass
1684 In [1]: %timeit pass
1636 10000000 loops, best of 3: 53.3 ns per loop
1685 10000000 loops, best of 3: 53.3 ns per loop
1637
1686
1638 In [2]: u = None
1687 In [2]: u = None
1639
1688
1640 In [3]: %timeit u is None
1689 In [3]: %timeit u is None
1641 10000000 loops, best of 3: 184 ns per loop
1690 10000000 loops, best of 3: 184 ns per loop
1642
1691
1643 In [4]: %timeit -r 4 u == None
1692 In [4]: %timeit -r 4 u == None
1644 1000000 loops, best of 4: 242 ns per loop
1693 1000000 loops, best of 4: 242 ns per loop
1645
1694
1646 In [5]: import time
1695 In [5]: import time
1647
1696
1648 In [6]: %timeit -n1 time.sleep(2)
1697 In [6]: %timeit -n1 time.sleep(2)
1649 1 loops, best of 3: 2 s per loop
1698 1 loops, best of 3: 2 s per loop
1650
1699
1651
1700
1652 The times reported by %timeit will be slightly higher than those
1701 The times reported by %timeit will be slightly higher than those
1653 reported by the timeit.py script when variables are accessed. This is
1702 reported by the timeit.py script when variables are accessed. This is
1654 due to the fact that %timeit executes the statement in the namespace
1703 due to the fact that %timeit executes the statement in the namespace
1655 of the shell, compared with timeit.py, which uses a single setup
1704 of the shell, compared with timeit.py, which uses a single setup
1656 statement to import function or create variables. Generally, the bias
1705 statement to import function or create variables. Generally, the bias
1657 does not matter as long as results from timeit.py are not mixed with
1706 does not matter as long as results from timeit.py are not mixed with
1658 those from %timeit."""
1707 those from %timeit."""
1659
1708
1660 import timeit
1709 import timeit
1661 import math
1710 import math
1662
1711
1663 units = ["s", "ms", "\xc2\xb5s", "ns"]
1712 units = ["s", "ms", "\xc2\xb5s", "ns"]
1664 scaling = [1, 1e3, 1e6, 1e9]
1713 scaling = [1, 1e3, 1e6, 1e9]
1665
1714
1666 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1715 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1667 posix=False)
1716 posix=False)
1668 if stmt == "":
1717 if stmt == "":
1669 return
1718 return
1670 timefunc = timeit.default_timer
1719 timefunc = timeit.default_timer
1671 number = int(getattr(opts, "n", 0))
1720 number = int(getattr(opts, "n", 0))
1672 repeat = int(getattr(opts, "r", timeit.default_repeat))
1721 repeat = int(getattr(opts, "r", timeit.default_repeat))
1673 precision = int(getattr(opts, "p", 3))
1722 precision = int(getattr(opts, "p", 3))
1674 if hasattr(opts, "t"):
1723 if hasattr(opts, "t"):
1675 timefunc = time.time
1724 timefunc = time.time
1676 if hasattr(opts, "c"):
1725 if hasattr(opts, "c"):
1677 timefunc = clock
1726 timefunc = clock
1678
1727
1679 timer = timeit.Timer(timer=timefunc)
1728 timer = timeit.Timer(timer=timefunc)
1680 # this code has tight coupling to the inner workings of timeit.Timer,
1729 # this code has tight coupling to the inner workings of timeit.Timer,
1681 # but is there a better way to achieve that the code stmt has access
1730 # but is there a better way to achieve that the code stmt has access
1682 # to the shell namespace?
1731 # to the shell namespace?
1683
1732
1684 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1733 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1685 'setup': "pass"}
1734 'setup': "pass"}
1686 code = compile(src, "<magic-timeit>", "exec")
1735 code = compile(src, "<magic-timeit>", "exec")
1687 ns = {}
1736 ns = {}
1688 exec code in self.shell.user_ns, ns
1737 exec code in self.shell.user_ns, ns
1689 timer.inner = ns["inner"]
1738 timer.inner = ns["inner"]
1690
1739
1691 if number == 0:
1740 if number == 0:
1692 # determine number so that 0.2 <= total time < 2.0
1741 # determine number so that 0.2 <= total time < 2.0
1693 number = 1
1742 number = 1
1694 for i in range(1, 10):
1743 for i in range(1, 10):
1695 number *= 10
1744 number *= 10
1696 if timer.timeit(number) >= 0.2:
1745 if timer.timeit(number) >= 0.2:
1697 break
1746 break
1698
1747
1699 best = min(timer.repeat(repeat, number)) / number
1748 best = min(timer.repeat(repeat, number)) / number
1700
1749
1701 if best > 0.0:
1750 if best > 0.0:
1702 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1751 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1703 else:
1752 else:
1704 order = 3
1753 order = 3
1705 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1754 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1706 precision,
1755 precision,
1707 best * scaling[order],
1756 best * scaling[order],
1708 units[order])
1757 units[order])
1709
1758
1710 def magic_time(self,parameter_s = ''):
1759 def magic_time(self,parameter_s = ''):
1711 """Time execution of a Python statement or expression.
1760 """Time execution of a Python statement or expression.
1712
1761
1713 The CPU and wall clock times are printed, and the value of the
1762 The CPU and wall clock times are printed, and the value of the
1714 expression (if any) is returned. Note that under Win32, system time
1763 expression (if any) is returned. Note that under Win32, system time
1715 is always reported as 0, since it can not be measured.
1764 is always reported as 0, since it can not be measured.
1716
1765
1717 This function provides very basic timing functionality. In Python
1766 This function provides very basic timing functionality. In Python
1718 2.3, the timeit module offers more control and sophistication, so this
1767 2.3, the timeit module offers more control and sophistication, so this
1719 could be rewritten to use it (patches welcome).
1768 could be rewritten to use it (patches welcome).
1720
1769
1721 Some examples:
1770 Some examples:
1722
1771
1723 In [1]: time 2**128
1772 In [1]: time 2**128
1724 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1773 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1725 Wall time: 0.00
1774 Wall time: 0.00
1726 Out[1]: 340282366920938463463374607431768211456L
1775 Out[1]: 340282366920938463463374607431768211456L
1727
1776
1728 In [2]: n = 1000000
1777 In [2]: n = 1000000
1729
1778
1730 In [3]: time sum(range(n))
1779 In [3]: time sum(range(n))
1731 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1780 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1732 Wall time: 1.37
1781 Wall time: 1.37
1733 Out[3]: 499999500000L
1782 Out[3]: 499999500000L
1734
1783
1735 In [4]: time print 'hello world'
1784 In [4]: time print 'hello world'
1736 hello world
1785 hello world
1737 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1786 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1738 Wall time: 0.00
1787 Wall time: 0.00
1739 """
1788 """
1740
1789
1741 # fail immediately if the given expression can't be compiled
1790 # fail immediately if the given expression can't be compiled
1742 try:
1791 try:
1743 mode = 'eval'
1792 mode = 'eval'
1744 code = compile(parameter_s,'<timed eval>',mode)
1793 code = compile(parameter_s,'<timed eval>',mode)
1745 except SyntaxError:
1794 except SyntaxError:
1746 mode = 'exec'
1795 mode = 'exec'
1747 code = compile(parameter_s,'<timed exec>',mode)
1796 code = compile(parameter_s,'<timed exec>',mode)
1748 # skew measurement as little as possible
1797 # skew measurement as little as possible
1749 glob = self.shell.user_ns
1798 glob = self.shell.user_ns
1750 clk = clock2
1799 clk = clock2
1751 wtime = time.time
1800 wtime = time.time
1752 # time execution
1801 # time execution
1753 wall_st = wtime()
1802 wall_st = wtime()
1754 if mode=='eval':
1803 if mode=='eval':
1755 st = clk()
1804 st = clk()
1756 out = eval(code,glob)
1805 out = eval(code,glob)
1757 end = clk()
1806 end = clk()
1758 else:
1807 else:
1759 st = clk()
1808 st = clk()
1760 exec code in glob
1809 exec code in glob
1761 end = clk()
1810 end = clk()
1762 out = None
1811 out = None
1763 wall_end = wtime()
1812 wall_end = wtime()
1764 # Compute actual times and report
1813 # Compute actual times and report
1765 wall_time = wall_end-wall_st
1814 wall_time = wall_end-wall_st
1766 cpu_user = end[0]-st[0]
1815 cpu_user = end[0]-st[0]
1767 cpu_sys = end[1]-st[1]
1816 cpu_sys = end[1]-st[1]
1768 cpu_tot = cpu_user+cpu_sys
1817 cpu_tot = cpu_user+cpu_sys
1769 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1818 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1770 (cpu_user,cpu_sys,cpu_tot)
1819 (cpu_user,cpu_sys,cpu_tot)
1771 print "Wall time: %.2f" % wall_time
1820 print "Wall time: %.2f" % wall_time
1772 return out
1821 return out
1773
1822
1774 def magic_macro(self,parameter_s = ''):
1823 def magic_macro(self,parameter_s = ''):
1775 """Define a set of input lines as a macro for future re-execution.
1824 """Define a set of input lines as a macro for future re-execution.
1776
1825
1777 Usage:\\
1826 Usage:\\
1778 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1827 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1779
1828
1780 Options:
1829 Options:
1781
1830
1782 -r: use 'raw' input. By default, the 'processed' history is used,
1831 -r: use 'raw' input. By default, the 'processed' history is used,
1783 so that magics are loaded in their transformed version to valid
1832 so that magics are loaded in their transformed version to valid
1784 Python. If this option is given, the raw input as typed as the
1833 Python. If this option is given, the raw input as typed as the
1785 command line is used instead.
1834 command line is used instead.
1786
1835
1787 This will define a global variable called `name` which is a string
1836 This will define a global variable called `name` which is a string
1788 made of joining the slices and lines you specify (n1,n2,... numbers
1837 made of joining the slices and lines you specify (n1,n2,... numbers
1789 above) from your input history into a single string. This variable
1838 above) from your input history into a single string. This variable
1790 acts like an automatic function which re-executes those lines as if
1839 acts like an automatic function which re-executes those lines as if
1791 you had typed them. You just type 'name' at the prompt and the code
1840 you had typed them. You just type 'name' at the prompt and the code
1792 executes.
1841 executes.
1793
1842
1794 The notation for indicating number ranges is: n1-n2 means 'use line
1843 The notation for indicating number ranges is: n1-n2 means 'use line
1795 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1844 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1796 using the lines numbered 5,6 and 7.
1845 using the lines numbered 5,6 and 7.
1797
1846
1798 Note: as a 'hidden' feature, you can also use traditional python slice
1847 Note: as a 'hidden' feature, you can also use traditional python slice
1799 notation, where N:M means numbers N through M-1.
1848 notation, where N:M means numbers N through M-1.
1800
1849
1801 For example, if your history contains (%hist prints it):
1850 For example, if your history contains (%hist prints it):
1802
1851
1803 44: x=1\\
1852 44: x=1\\
1804 45: y=3\\
1853 45: y=3\\
1805 46: z=x+y\\
1854 46: z=x+y\\
1806 47: print x\\
1855 47: print x\\
1807 48: a=5\\
1856 48: a=5\\
1808 49: print 'x',x,'y',y\\
1857 49: print 'x',x,'y',y\\
1809
1858
1810 you can create a macro with lines 44 through 47 (included) and line 49
1859 you can create a macro with lines 44 through 47 (included) and line 49
1811 called my_macro with:
1860 called my_macro with:
1812
1861
1813 In [51]: %macro my_macro 44-47 49
1862 In [51]: %macro my_macro 44-47 49
1814
1863
1815 Now, typing `my_macro` (without quotes) will re-execute all this code
1864 Now, typing `my_macro` (without quotes) will re-execute all this code
1816 in one pass.
1865 in one pass.
1817
1866
1818 You don't need to give the line-numbers in order, and any given line
1867 You don't need to give the line-numbers in order, and any given line
1819 number can appear multiple times. You can assemble macros with any
1868 number can appear multiple times. You can assemble macros with any
1820 lines from your input history in any order.
1869 lines from your input history in any order.
1821
1870
1822 The macro is a simple object which holds its value in an attribute,
1871 The macro is a simple object which holds its value in an attribute,
1823 but IPython's display system checks for macros and executes them as
1872 but IPython's display system checks for macros and executes them as
1824 code instead of printing them when you type their name.
1873 code instead of printing them when you type their name.
1825
1874
1826 You can view a macro's contents by explicitly printing it with:
1875 You can view a macro's contents by explicitly printing it with:
1827
1876
1828 'print macro_name'.
1877 'print macro_name'.
1829
1878
1830 For one-off cases which DON'T contain magic function calls in them you
1879 For one-off cases which DON'T contain magic function calls in them you
1831 can obtain similar results by explicitly executing slices from your
1880 can obtain similar results by explicitly executing slices from your
1832 input history with:
1881 input history with:
1833
1882
1834 In [60]: exec In[44:48]+In[49]"""
1883 In [60]: exec In[44:48]+In[49]"""
1835
1884
1836 opts,args = self.parse_options(parameter_s,'r',mode='list')
1885 opts,args = self.parse_options(parameter_s,'r',mode='list')
1837 name,ranges = args[0], args[1:]
1886 name,ranges = args[0], args[1:]
1838 #print 'rng',ranges # dbg
1887 #print 'rng',ranges # dbg
1839 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1888 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1840 macro = Macro(lines)
1889 macro = Macro(lines)
1841 self.shell.user_ns.update({name:macro})
1890 self.shell.user_ns.update({name:macro})
1842 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1891 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1843 print 'Macro contents:'
1892 print 'Macro contents:'
1844 print macro,
1893 print macro,
1845
1894
1846 def magic_save(self,parameter_s = ''):
1895 def magic_save(self,parameter_s = ''):
1847 """Save a set of lines to a given filename.
1896 """Save a set of lines to a given filename.
1848
1897
1849 Usage:\\
1898 Usage:\\
1850 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1899 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1851
1900
1852 Options:
1901 Options:
1853
1902
1854 -r: use 'raw' input. By default, the 'processed' history is used,
1903 -r: use 'raw' input. By default, the 'processed' history is used,
1855 so that magics are loaded in their transformed version to valid
1904 so that magics are loaded in their transformed version to valid
1856 Python. If this option is given, the raw input as typed as the
1905 Python. If this option is given, the raw input as typed as the
1857 command line is used instead.
1906 command line is used instead.
1858
1907
1859 This function uses the same syntax as %macro for line extraction, but
1908 This function uses the same syntax as %macro for line extraction, but
1860 instead of creating a macro it saves the resulting string to the
1909 instead of creating a macro it saves the resulting string to the
1861 filename you specify.
1910 filename you specify.
1862
1911
1863 It adds a '.py' extension to the file if you don't do so yourself, and
1912 It adds a '.py' extension to the file if you don't do so yourself, and
1864 it asks for confirmation before overwriting existing files."""
1913 it asks for confirmation before overwriting existing files."""
1865
1914
1866 opts,args = self.parse_options(parameter_s,'r',mode='list')
1915 opts,args = self.parse_options(parameter_s,'r',mode='list')
1867 fname,ranges = args[0], args[1:]
1916 fname,ranges = args[0], args[1:]
1868 if not fname.endswith('.py'):
1917 if not fname.endswith('.py'):
1869 fname += '.py'
1918 fname += '.py'
1870 if os.path.isfile(fname):
1919 if os.path.isfile(fname):
1871 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1920 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1872 if ans.lower() not in ['y','yes']:
1921 if ans.lower() not in ['y','yes']:
1873 print 'Operation cancelled.'
1922 print 'Operation cancelled.'
1874 return
1923 return
1875 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1924 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1876 f = file(fname,'w')
1925 f = file(fname,'w')
1877 f.write(cmds)
1926 f.write(cmds)
1878 f.close()
1927 f.close()
1879 print 'The following commands were written to file `%s`:' % fname
1928 print 'The following commands were written to file `%s`:' % fname
1880 print cmds
1929 print cmds
1881
1930
1882 def _edit_macro(self,mname,macro):
1931 def _edit_macro(self,mname,macro):
1883 """open an editor with the macro data in a file"""
1932 """open an editor with the macro data in a file"""
1884 filename = self.shell.mktempfile(macro.value)
1933 filename = self.shell.mktempfile(macro.value)
1885 self.shell.hooks.editor(filename)
1934 self.shell.hooks.editor(filename)
1886
1935
1887 # and make a new macro object, to replace the old one
1936 # and make a new macro object, to replace the old one
1888 mfile = open(filename)
1937 mfile = open(filename)
1889 mvalue = mfile.read()
1938 mvalue = mfile.read()
1890 mfile.close()
1939 mfile.close()
1891 self.shell.user_ns[mname] = Macro(mvalue)
1940 self.shell.user_ns[mname] = Macro(mvalue)
1892
1941
1893 def magic_ed(self,parameter_s=''):
1942 def magic_ed(self,parameter_s=''):
1894 """Alias to %edit."""
1943 """Alias to %edit."""
1895 return self.magic_edit(parameter_s)
1944 return self.magic_edit(parameter_s)
1896
1945
1897 def magic_edit(self,parameter_s='',last_call=['','']):
1946 def magic_edit(self,parameter_s='',last_call=['','']):
1898 """Bring up an editor and execute the resulting code.
1947 """Bring up an editor and execute the resulting code.
1899
1948
1900 Usage:
1949 Usage:
1901 %edit [options] [args]
1950 %edit [options] [args]
1902
1951
1903 %edit runs IPython's editor hook. The default version of this hook is
1952 %edit runs IPython's editor hook. The default version of this hook is
1904 set to call the __IPYTHON__.rc.editor command. This is read from your
1953 set to call the __IPYTHON__.rc.editor command. This is read from your
1905 environment variable $EDITOR. If this isn't found, it will default to
1954 environment variable $EDITOR. If this isn't found, it will default to
1906 vi under Linux/Unix and to notepad under Windows. See the end of this
1955 vi under Linux/Unix and to notepad under Windows. See the end of this
1907 docstring for how to change the editor hook.
1956 docstring for how to change the editor hook.
1908
1957
1909 You can also set the value of this editor via the command line option
1958 You can also set the value of this editor via the command line option
1910 '-editor' or in your ipythonrc file. This is useful if you wish to use
1959 '-editor' or in your ipythonrc file. This is useful if you wish to use
1911 specifically for IPython an editor different from your typical default
1960 specifically for IPython an editor different from your typical default
1912 (and for Windows users who typically don't set environment variables).
1961 (and for Windows users who typically don't set environment variables).
1913
1962
1914 This command allows you to conveniently edit multi-line code right in
1963 This command allows you to conveniently edit multi-line code right in
1915 your IPython session.
1964 your IPython session.
1916
1965
1917 If called without arguments, %edit opens up an empty editor with a
1966 If called without arguments, %edit opens up an empty editor with a
1918 temporary file and will execute the contents of this file when you
1967 temporary file and will execute the contents of this file when you
1919 close it (don't forget to save it!).
1968 close it (don't forget to save it!).
1920
1969
1921
1970
1922 Options:
1971 Options:
1923
1972
1924 -n <number>: open the editor at a specified line number. By default,
1973 -n <number>: open the editor at a specified line number. By default,
1925 the IPython editor hook uses the unix syntax 'editor +N filename', but
1974 the IPython editor hook uses the unix syntax 'editor +N filename', but
1926 you can configure this by providing your own modified hook if your
1975 you can configure this by providing your own modified hook if your
1927 favorite editor supports line-number specifications with a different
1976 favorite editor supports line-number specifications with a different
1928 syntax.
1977 syntax.
1929
1978
1930 -p: this will call the editor with the same data as the previous time
1979 -p: this will call the editor with the same data as the previous time
1931 it was used, regardless of how long ago (in your current session) it
1980 it was used, regardless of how long ago (in your current session) it
1932 was.
1981 was.
1933
1982
1934 -r: use 'raw' input. This option only applies to input taken from the
1983 -r: use 'raw' input. This option only applies to input taken from the
1935 user's history. By default, the 'processed' history is used, so that
1984 user's history. By default, the 'processed' history is used, so that
1936 magics are loaded in their transformed version to valid Python. If
1985 magics are loaded in their transformed version to valid Python. If
1937 this option is given, the raw input as typed as the command line is
1986 this option is given, the raw input as typed as the command line is
1938 used instead. When you exit the editor, it will be executed by
1987 used instead. When you exit the editor, it will be executed by
1939 IPython's own processor.
1988 IPython's own processor.
1940
1989
1941 -x: do not execute the edited code immediately upon exit. This is
1990 -x: do not execute the edited code immediately upon exit. This is
1942 mainly useful if you are editing programs which need to be called with
1991 mainly useful if you are editing programs which need to be called with
1943 command line arguments, which you can then do using %run.
1992 command line arguments, which you can then do using %run.
1944
1993
1945
1994
1946 Arguments:
1995 Arguments:
1947
1996
1948 If arguments are given, the following possibilites exist:
1997 If arguments are given, the following possibilites exist:
1949
1998
1950 - The arguments are numbers or pairs of colon-separated numbers (like
1999 - The arguments are numbers or pairs of colon-separated numbers (like
1951 1 4:8 9). These are interpreted as lines of previous input to be
2000 1 4:8 9). These are interpreted as lines of previous input to be
1952 loaded into the editor. The syntax is the same of the %macro command.
2001 loaded into the editor. The syntax is the same of the %macro command.
1953
2002
1954 - If the argument doesn't start with a number, it is evaluated as a
2003 - If the argument doesn't start with a number, it is evaluated as a
1955 variable and its contents loaded into the editor. You can thus edit
2004 variable and its contents loaded into the editor. You can thus edit
1956 any string which contains python code (including the result of
2005 any string which contains python code (including the result of
1957 previous edits).
2006 previous edits).
1958
2007
1959 - If the argument is the name of an object (other than a string),
2008 - If the argument is the name of an object (other than a string),
1960 IPython will try to locate the file where it was defined and open the
2009 IPython will try to locate the file where it was defined and open the
1961 editor at the point where it is defined. You can use `%edit function`
2010 editor at the point where it is defined. You can use `%edit function`
1962 to load an editor exactly at the point where 'function' is defined,
2011 to load an editor exactly at the point where 'function' is defined,
1963 edit it and have the file be executed automatically.
2012 edit it and have the file be executed automatically.
1964
2013
1965 If the object is a macro (see %macro for details), this opens up your
2014 If the object is a macro (see %macro for details), this opens up your
1966 specified editor with a temporary file containing the macro's data.
2015 specified editor with a temporary file containing the macro's data.
1967 Upon exit, the macro is reloaded with the contents of the file.
2016 Upon exit, the macro is reloaded with the contents of the file.
1968
2017
1969 Note: opening at an exact line is only supported under Unix, and some
2018 Note: opening at an exact line is only supported under Unix, and some
1970 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2019 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1971 '+NUMBER' parameter necessary for this feature. Good editors like
2020 '+NUMBER' parameter necessary for this feature. Good editors like
1972 (X)Emacs, vi, jed, pico and joe all do.
2021 (X)Emacs, vi, jed, pico and joe all do.
1973
2022
1974 - If the argument is not found as a variable, IPython will look for a
2023 - If the argument is not found as a variable, IPython will look for a
1975 file with that name (adding .py if necessary) and load it into the
2024 file with that name (adding .py if necessary) and load it into the
1976 editor. It will execute its contents with execfile() when you exit,
2025 editor. It will execute its contents with execfile() when you exit,
1977 loading any code in the file into your interactive namespace.
2026 loading any code in the file into your interactive namespace.
1978
2027
1979 After executing your code, %edit will return as output the code you
2028 After executing your code, %edit will return as output the code you
1980 typed in the editor (except when it was an existing file). This way
2029 typed in the editor (except when it was an existing file). This way
1981 you can reload the code in further invocations of %edit as a variable,
2030 you can reload the code in further invocations of %edit as a variable,
1982 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2031 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1983 the output.
2032 the output.
1984
2033
1985 Note that %edit is also available through the alias %ed.
2034 Note that %edit is also available through the alias %ed.
1986
2035
1987 This is an example of creating a simple function inside the editor and
2036 This is an example of creating a simple function inside the editor and
1988 then modifying it. First, start up the editor:
2037 then modifying it. First, start up the editor:
1989
2038
1990 In [1]: ed\\
2039 In [1]: ed\\
1991 Editing... done. Executing edited code...\\
2040 Editing... done. Executing edited code...\\
1992 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2041 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1993
2042
1994 We can then call the function foo():
2043 We can then call the function foo():
1995
2044
1996 In [2]: foo()\\
2045 In [2]: foo()\\
1997 foo() was defined in an editing session
2046 foo() was defined in an editing session
1998
2047
1999 Now we edit foo. IPython automatically loads the editor with the
2048 Now we edit foo. IPython automatically loads the editor with the
2000 (temporary) file where foo() was previously defined:
2049 (temporary) file where foo() was previously defined:
2001
2050
2002 In [3]: ed foo\\
2051 In [3]: ed foo\\
2003 Editing... done. Executing edited code...
2052 Editing... done. Executing edited code...
2004
2053
2005 And if we call foo() again we get the modified version:
2054 And if we call foo() again we get the modified version:
2006
2055
2007 In [4]: foo()\\
2056 In [4]: foo()\\
2008 foo() has now been changed!
2057 foo() has now been changed!
2009
2058
2010 Here is an example of how to edit a code snippet successive
2059 Here is an example of how to edit a code snippet successive
2011 times. First we call the editor:
2060 times. First we call the editor:
2012
2061
2013 In [8]: ed\\
2062 In [8]: ed\\
2014 Editing... done. Executing edited code...\\
2063 Editing... done. Executing edited code...\\
2015 hello\\
2064 hello\\
2016 Out[8]: "print 'hello'\\n"
2065 Out[8]: "print 'hello'\\n"
2017
2066
2018 Now we call it again with the previous output (stored in _):
2067 Now we call it again with the previous output (stored in _):
2019
2068
2020 In [9]: ed _\\
2069 In [9]: ed _\\
2021 Editing... done. Executing edited code...\\
2070 Editing... done. Executing edited code...\\
2022 hello world\\
2071 hello world\\
2023 Out[9]: "print 'hello world'\\n"
2072 Out[9]: "print 'hello world'\\n"
2024
2073
2025 Now we call it with the output #8 (stored in _8, also as Out[8]):
2074 Now we call it with the output #8 (stored in _8, also as Out[8]):
2026
2075
2027 In [10]: ed _8\\
2076 In [10]: ed _8\\
2028 Editing... done. Executing edited code...\\
2077 Editing... done. Executing edited code...\\
2029 hello again\\
2078 hello again\\
2030 Out[10]: "print 'hello again'\\n"
2079 Out[10]: "print 'hello again'\\n"
2031
2080
2032
2081
2033 Changing the default editor hook:
2082 Changing the default editor hook:
2034
2083
2035 If you wish to write your own editor hook, you can put it in a
2084 If you wish to write your own editor hook, you can put it in a
2036 configuration file which you load at startup time. The default hook
2085 configuration file which you load at startup time. The default hook
2037 is defined in the IPython.hooks module, and you can use that as a
2086 is defined in the IPython.hooks module, and you can use that as a
2038 starting example for further modifications. That file also has
2087 starting example for further modifications. That file also has
2039 general instructions on how to set a new hook for use once you've
2088 general instructions on how to set a new hook for use once you've
2040 defined it."""
2089 defined it."""
2041
2090
2042 # FIXME: This function has become a convoluted mess. It needs a
2091 # FIXME: This function has become a convoluted mess. It needs a
2043 # ground-up rewrite with clean, simple logic.
2092 # ground-up rewrite with clean, simple logic.
2044
2093
2045 def make_filename(arg):
2094 def make_filename(arg):
2046 "Make a filename from the given args"
2095 "Make a filename from the given args"
2047 try:
2096 try:
2048 filename = get_py_filename(arg)
2097 filename = get_py_filename(arg)
2049 except IOError:
2098 except IOError:
2050 if args.endswith('.py'):
2099 if args.endswith('.py'):
2051 filename = arg
2100 filename = arg
2052 else:
2101 else:
2053 filename = None
2102 filename = None
2054 return filename
2103 return filename
2055
2104
2056 # custom exceptions
2105 # custom exceptions
2057 class DataIsObject(Exception): pass
2106 class DataIsObject(Exception): pass
2058
2107
2059 opts,args = self.parse_options(parameter_s,'prxn:')
2108 opts,args = self.parse_options(parameter_s,'prxn:')
2060 # Set a few locals from the options for convenience:
2109 # Set a few locals from the options for convenience:
2061 opts_p = opts.has_key('p')
2110 opts_p = opts.has_key('p')
2062 opts_r = opts.has_key('r')
2111 opts_r = opts.has_key('r')
2063
2112
2064 # Default line number value
2113 # Default line number value
2065 lineno = opts.get('n',None)
2114 lineno = opts.get('n',None)
2066
2115
2067 if opts_p:
2116 if opts_p:
2068 args = '_%s' % last_call[0]
2117 args = '_%s' % last_call[0]
2069 if not self.shell.user_ns.has_key(args):
2118 if not self.shell.user_ns.has_key(args):
2070 args = last_call[1]
2119 args = last_call[1]
2071
2120
2072 # use last_call to remember the state of the previous call, but don't
2121 # use last_call to remember the state of the previous call, but don't
2073 # let it be clobbered by successive '-p' calls.
2122 # let it be clobbered by successive '-p' calls.
2074 try:
2123 try:
2075 last_call[0] = self.shell.outputcache.prompt_count
2124 last_call[0] = self.shell.outputcache.prompt_count
2076 if not opts_p:
2125 if not opts_p:
2077 last_call[1] = parameter_s
2126 last_call[1] = parameter_s
2078 except:
2127 except:
2079 pass
2128 pass
2080
2129
2081 # by default this is done with temp files, except when the given
2130 # by default this is done with temp files, except when the given
2082 # arg is a filename
2131 # arg is a filename
2083 use_temp = 1
2132 use_temp = 1
2084
2133
2085 if re.match(r'\d',args):
2134 if re.match(r'\d',args):
2086 # Mode where user specifies ranges of lines, like in %macro.
2135 # Mode where user specifies ranges of lines, like in %macro.
2087 # This means that you can't edit files whose names begin with
2136 # This means that you can't edit files whose names begin with
2088 # numbers this way. Tough.
2137 # numbers this way. Tough.
2089 ranges = args.split()
2138 ranges = args.split()
2090 data = ''.join(self.extract_input_slices(ranges,opts_r))
2139 data = ''.join(self.extract_input_slices(ranges,opts_r))
2091 elif args.endswith('.py'):
2140 elif args.endswith('.py'):
2092 filename = make_filename(args)
2141 filename = make_filename(args)
2093 data = ''
2142 data = ''
2094 use_temp = 0
2143 use_temp = 0
2095 elif args:
2144 elif args:
2096 try:
2145 try:
2097 # Load the parameter given as a variable. If not a string,
2146 # Load the parameter given as a variable. If not a string,
2098 # process it as an object instead (below)
2147 # process it as an object instead (below)
2099
2148
2100 #print '*** args',args,'type',type(args) # dbg
2149 #print '*** args',args,'type',type(args) # dbg
2101 data = eval(args,self.shell.user_ns)
2150 data = eval(args,self.shell.user_ns)
2102 if not type(data) in StringTypes:
2151 if not type(data) in StringTypes:
2103 raise DataIsObject
2152 raise DataIsObject
2104
2153
2105 except (NameError,SyntaxError):
2154 except (NameError,SyntaxError):
2106 # given argument is not a variable, try as a filename
2155 # given argument is not a variable, try as a filename
2107 filename = make_filename(args)
2156 filename = make_filename(args)
2108 if filename is None:
2157 if filename is None:
2109 warn("Argument given (%s) can't be found as a variable "
2158 warn("Argument given (%s) can't be found as a variable "
2110 "or as a filename." % args)
2159 "or as a filename." % args)
2111 return
2160 return
2112
2161
2113 data = ''
2162 data = ''
2114 use_temp = 0
2163 use_temp = 0
2115 except DataIsObject:
2164 except DataIsObject:
2116
2165
2117 # macros have a special edit function
2166 # macros have a special edit function
2118 if isinstance(data,Macro):
2167 if isinstance(data,Macro):
2119 self._edit_macro(args,data)
2168 self._edit_macro(args,data)
2120 return
2169 return
2121
2170
2122 # For objects, try to edit the file where they are defined
2171 # For objects, try to edit the file where they are defined
2123 try:
2172 try:
2124 filename = inspect.getabsfile(data)
2173 filename = inspect.getabsfile(data)
2125 datafile = 1
2174 datafile = 1
2126 except TypeError:
2175 except TypeError:
2127 filename = make_filename(args)
2176 filename = make_filename(args)
2128 datafile = 1
2177 datafile = 1
2129 warn('Could not find file where `%s` is defined.\n'
2178 warn('Could not find file where `%s` is defined.\n'
2130 'Opening a file named `%s`' % (args,filename))
2179 'Opening a file named `%s`' % (args,filename))
2131 # Now, make sure we can actually read the source (if it was in
2180 # Now, make sure we can actually read the source (if it was in
2132 # a temp file it's gone by now).
2181 # a temp file it's gone by now).
2133 if datafile:
2182 if datafile:
2134 try:
2183 try:
2135 if lineno is None:
2184 if lineno is None:
2136 lineno = inspect.getsourcelines(data)[1]
2185 lineno = inspect.getsourcelines(data)[1]
2137 except IOError:
2186 except IOError:
2138 filename = make_filename(args)
2187 filename = make_filename(args)
2139 if filename is None:
2188 if filename is None:
2140 warn('The file `%s` where `%s` was defined cannot '
2189 warn('The file `%s` where `%s` was defined cannot '
2141 'be read.' % (filename,data))
2190 'be read.' % (filename,data))
2142 return
2191 return
2143 use_temp = 0
2192 use_temp = 0
2144 else:
2193 else:
2145 data = ''
2194 data = ''
2146
2195
2147 if use_temp:
2196 if use_temp:
2148 filename = self.shell.mktempfile(data)
2197 filename = self.shell.mktempfile(data)
2149 print 'IPython will make a temporary file named:',filename
2198 print 'IPython will make a temporary file named:',filename
2150
2199
2151 # do actual editing here
2200 # do actual editing here
2152 print 'Editing...',
2201 print 'Editing...',
2153 sys.stdout.flush()
2202 sys.stdout.flush()
2154 self.shell.hooks.editor(filename,lineno)
2203 self.shell.hooks.editor(filename,lineno)
2155 if opts.has_key('x'): # -x prevents actual execution
2204 if opts.has_key('x'): # -x prevents actual execution
2156 print
2205 print
2157 else:
2206 else:
2158 print 'done. Executing edited code...'
2207 print 'done. Executing edited code...'
2159 if opts_r:
2208 if opts_r:
2160 self.shell.runlines(file_read(filename))
2209 self.shell.runlines(file_read(filename))
2161 else:
2210 else:
2162 self.shell.safe_execfile(filename,self.shell.user_ns)
2211 self.shell.safe_execfile(filename,self.shell.user_ns)
2163 if use_temp:
2212 if use_temp:
2164 try:
2213 try:
2165 return open(filename).read()
2214 return open(filename).read()
2166 except IOError,msg:
2215 except IOError,msg:
2167 if msg.filename == filename:
2216 if msg.filename == filename:
2168 warn('File not found. Did you forget to save?')
2217 warn('File not found. Did you forget to save?')
2169 return
2218 return
2170 else:
2219 else:
2171 self.shell.showtraceback()
2220 self.shell.showtraceback()
2172
2221
2173 def magic_xmode(self,parameter_s = ''):
2222 def magic_xmode(self,parameter_s = ''):
2174 """Switch modes for the exception handlers.
2223 """Switch modes for the exception handlers.
2175
2224
2176 Valid modes: Plain, Context and Verbose.
2225 Valid modes: Plain, Context and Verbose.
2177
2226
2178 If called without arguments, acts as a toggle."""
2227 If called without arguments, acts as a toggle."""
2179
2228
2180 def xmode_switch_err(name):
2229 def xmode_switch_err(name):
2181 warn('Error changing %s exception modes.\n%s' %
2230 warn('Error changing %s exception modes.\n%s' %
2182 (name,sys.exc_info()[1]))
2231 (name,sys.exc_info()[1]))
2183
2232
2184 shell = self.shell
2233 shell = self.shell
2185 new_mode = parameter_s.strip().capitalize()
2234 new_mode = parameter_s.strip().capitalize()
2186 try:
2235 try:
2187 shell.InteractiveTB.set_mode(mode=new_mode)
2236 shell.InteractiveTB.set_mode(mode=new_mode)
2188 print 'Exception reporting mode:',shell.InteractiveTB.mode
2237 print 'Exception reporting mode:',shell.InteractiveTB.mode
2189 except:
2238 except:
2190 xmode_switch_err('user')
2239 xmode_switch_err('user')
2191
2240
2192 # threaded shells use a special handler in sys.excepthook
2241 # threaded shells use a special handler in sys.excepthook
2193 if shell.isthreaded:
2242 if shell.isthreaded:
2194 try:
2243 try:
2195 shell.sys_excepthook.set_mode(mode=new_mode)
2244 shell.sys_excepthook.set_mode(mode=new_mode)
2196 except:
2245 except:
2197 xmode_switch_err('threaded')
2246 xmode_switch_err('threaded')
2198
2247
2199 def magic_colors(self,parameter_s = ''):
2248 def magic_colors(self,parameter_s = ''):
2200 """Switch color scheme for prompts, info system and exception handlers.
2249 """Switch color scheme for prompts, info system and exception handlers.
2201
2250
2202 Currently implemented schemes: NoColor, Linux, LightBG.
2251 Currently implemented schemes: NoColor, Linux, LightBG.
2203
2252
2204 Color scheme names are not case-sensitive."""
2253 Color scheme names are not case-sensitive."""
2205
2254
2206 def color_switch_err(name):
2255 def color_switch_err(name):
2207 warn('Error changing %s color schemes.\n%s' %
2256 warn('Error changing %s color schemes.\n%s' %
2208 (name,sys.exc_info()[1]))
2257 (name,sys.exc_info()[1]))
2209
2258
2210
2259
2211 new_scheme = parameter_s.strip()
2260 new_scheme = parameter_s.strip()
2212 if not new_scheme:
2261 if not new_scheme:
2213 print 'You must specify a color scheme.'
2262 print 'You must specify a color scheme.'
2214 return
2263 return
2215 import IPython.rlineimpl as readline
2264 import IPython.rlineimpl as readline
2216 if not readline.have_readline:
2265 if not readline.have_readline:
2217 msg = """\
2266 msg = """\
2218 Proper color support under MS Windows requires the pyreadline library.
2267 Proper color support under MS Windows requires the pyreadline library.
2219 You can find it at:
2268 You can find it at:
2220 http://ipython.scipy.org/moin/PyReadline/Intro
2269 http://ipython.scipy.org/moin/PyReadline/Intro
2221 Gary's readline needs the ctypes module, from:
2270 Gary's readline needs the ctypes module, from:
2222 http://starship.python.net/crew/theller/ctypes
2271 http://starship.python.net/crew/theller/ctypes
2223 (Note that ctypes is already part of Python versions 2.5 and newer).
2272 (Note that ctypes is already part of Python versions 2.5 and newer).
2224
2273
2225 Defaulting color scheme to 'NoColor'"""
2274 Defaulting color scheme to 'NoColor'"""
2226 new_scheme = 'NoColor'
2275 new_scheme = 'NoColor'
2227 warn(msg)
2276 warn(msg)
2228 # local shortcut
2277 # local shortcut
2229 shell = self.shell
2278 shell = self.shell
2230
2279
2231 # Set prompt colors
2280 # Set prompt colors
2232 try:
2281 try:
2233 shell.outputcache.set_colors(new_scheme)
2282 shell.outputcache.set_colors(new_scheme)
2234 except:
2283 except:
2235 color_switch_err('prompt')
2284 color_switch_err('prompt')
2236 else:
2285 else:
2237 shell.rc.colors = \
2286 shell.rc.colors = \
2238 shell.outputcache.color_table.active_scheme_name
2287 shell.outputcache.color_table.active_scheme_name
2239 # Set exception colors
2288 # Set exception colors
2240 try:
2289 try:
2241 shell.InteractiveTB.set_colors(scheme = new_scheme)
2290 shell.InteractiveTB.set_colors(scheme = new_scheme)
2242 shell.SyntaxTB.set_colors(scheme = new_scheme)
2291 shell.SyntaxTB.set_colors(scheme = new_scheme)
2243 except:
2292 except:
2244 color_switch_err('exception')
2293 color_switch_err('exception')
2245
2294
2246 # threaded shells use a verbose traceback in sys.excepthook
2295 # threaded shells use a verbose traceback in sys.excepthook
2247 if shell.isthreaded:
2296 if shell.isthreaded:
2248 try:
2297 try:
2249 shell.sys_excepthook.set_colors(scheme=new_scheme)
2298 shell.sys_excepthook.set_colors(scheme=new_scheme)
2250 except:
2299 except:
2251 color_switch_err('system exception handler')
2300 color_switch_err('system exception handler')
2252
2301
2253 # Set info (for 'object?') colors
2302 # Set info (for 'object?') colors
2254 if shell.rc.color_info:
2303 if shell.rc.color_info:
2255 try:
2304 try:
2256 shell.inspector.set_active_scheme(new_scheme)
2305 shell.inspector.set_active_scheme(new_scheme)
2257 except:
2306 except:
2258 color_switch_err('object inspector')
2307 color_switch_err('object inspector')
2259 else:
2308 else:
2260 shell.inspector.set_active_scheme('NoColor')
2309 shell.inspector.set_active_scheme('NoColor')
2261
2310
2262 def magic_color_info(self,parameter_s = ''):
2311 def magic_color_info(self,parameter_s = ''):
2263 """Toggle color_info.
2312 """Toggle color_info.
2264
2313
2265 The color_info configuration parameter controls whether colors are
2314 The color_info configuration parameter controls whether colors are
2266 used for displaying object details (by things like %psource, %pfile or
2315 used for displaying object details (by things like %psource, %pfile or
2267 the '?' system). This function toggles this value with each call.
2316 the '?' system). This function toggles this value with each call.
2268
2317
2269 Note that unless you have a fairly recent pager (less works better
2318 Note that unless you have a fairly recent pager (less works better
2270 than more) in your system, using colored object information displays
2319 than more) in your system, using colored object information displays
2271 will not work properly. Test it and see."""
2320 will not work properly. Test it and see."""
2272
2321
2273 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2322 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2274 self.magic_colors(self.shell.rc.colors)
2323 self.magic_colors(self.shell.rc.colors)
2275 print 'Object introspection functions have now coloring:',
2324 print 'Object introspection functions have now coloring:',
2276 print ['OFF','ON'][self.shell.rc.color_info]
2325 print ['OFF','ON'][self.shell.rc.color_info]
2277
2326
2278 def magic_Pprint(self, parameter_s=''):
2327 def magic_Pprint(self, parameter_s=''):
2279 """Toggle pretty printing on/off."""
2328 """Toggle pretty printing on/off."""
2280
2329
2281 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2330 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2282 print 'Pretty printing has been turned', \
2331 print 'Pretty printing has been turned', \
2283 ['OFF','ON'][self.shell.rc.pprint]
2332 ['OFF','ON'][self.shell.rc.pprint]
2284
2333
2285 def magic_exit(self, parameter_s=''):
2334 def magic_exit(self, parameter_s=''):
2286 """Exit IPython, confirming if configured to do so.
2335 """Exit IPython, confirming if configured to do so.
2287
2336
2288 You can configure whether IPython asks for confirmation upon exit by
2337 You can configure whether IPython asks for confirmation upon exit by
2289 setting the confirm_exit flag in the ipythonrc file."""
2338 setting the confirm_exit flag in the ipythonrc file."""
2290
2339
2291 self.shell.exit()
2340 self.shell.exit()
2292
2341
2293 def magic_quit(self, parameter_s=''):
2342 def magic_quit(self, parameter_s=''):
2294 """Exit IPython, confirming if configured to do so (like %exit)"""
2343 """Exit IPython, confirming if configured to do so (like %exit)"""
2295
2344
2296 self.shell.exit()
2345 self.shell.exit()
2297
2346
2298 def magic_Exit(self, parameter_s=''):
2347 def magic_Exit(self, parameter_s=''):
2299 """Exit IPython without confirmation."""
2348 """Exit IPython without confirmation."""
2300
2349
2301 self.shell.exit_now = True
2350 self.shell.exit_now = True
2302
2351
2303 def magic_Quit(self, parameter_s=''):
2352 def magic_Quit(self, parameter_s=''):
2304 """Exit IPython without confirmation (like %Exit)."""
2353 """Exit IPython without confirmation (like %Exit)."""
2305
2354
2306 self.shell.exit_now = True
2355 self.shell.exit_now = True
2307
2356
2308 #......................................................................
2357 #......................................................................
2309 # Functions to implement unix shell-type things
2358 # Functions to implement unix shell-type things
2310
2359
2311 def magic_alias(self, parameter_s = ''):
2360 def magic_alias(self, parameter_s = ''):
2312 """Define an alias for a system command.
2361 """Define an alias for a system command.
2313
2362
2314 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2363 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2315
2364
2316 Then, typing 'alias_name params' will execute the system command 'cmd
2365 Then, typing 'alias_name params' will execute the system command 'cmd
2317 params' (from your underlying operating system).
2366 params' (from your underlying operating system).
2318
2367
2319 Aliases have lower precedence than magic functions and Python normal
2368 Aliases have lower precedence than magic functions and Python normal
2320 variables, so if 'foo' is both a Python variable and an alias, the
2369 variables, so if 'foo' is both a Python variable and an alias, the
2321 alias can not be executed until 'del foo' removes the Python variable.
2370 alias can not be executed until 'del foo' removes the Python variable.
2322
2371
2323 You can use the %l specifier in an alias definition to represent the
2372 You can use the %l specifier in an alias definition to represent the
2324 whole line when the alias is called. For example:
2373 whole line when the alias is called. For example:
2325
2374
2326 In [2]: alias all echo "Input in brackets: <%l>"\\
2375 In [2]: alias all echo "Input in brackets: <%l>"\\
2327 In [3]: all hello world\\
2376 In [3]: all hello world\\
2328 Input in brackets: <hello world>
2377 Input in brackets: <hello world>
2329
2378
2330 You can also define aliases with parameters using %s specifiers (one
2379 You can also define aliases with parameters using %s specifiers (one
2331 per parameter):
2380 per parameter):
2332
2381
2333 In [1]: alias parts echo first %s second %s\\
2382 In [1]: alias parts echo first %s second %s\\
2334 In [2]: %parts A B\\
2383 In [2]: %parts A B\\
2335 first A second B\\
2384 first A second B\\
2336 In [3]: %parts A\\
2385 In [3]: %parts A\\
2337 Incorrect number of arguments: 2 expected.\\
2386 Incorrect number of arguments: 2 expected.\\
2338 parts is an alias to: 'echo first %s second %s'
2387 parts is an alias to: 'echo first %s second %s'
2339
2388
2340 Note that %l and %s are mutually exclusive. You can only use one or
2389 Note that %l and %s are mutually exclusive. You can only use one or
2341 the other in your aliases.
2390 the other in your aliases.
2342
2391
2343 Aliases expand Python variables just like system calls using ! or !!
2392 Aliases expand Python variables just like system calls using ! or !!
2344 do: all expressions prefixed with '$' get expanded. For details of
2393 do: all expressions prefixed with '$' get expanded. For details of
2345 the semantic rules, see PEP-215:
2394 the semantic rules, see PEP-215:
2346 http://www.python.org/peps/pep-0215.html. This is the library used by
2395 http://www.python.org/peps/pep-0215.html. This is the library used by
2347 IPython for variable expansion. If you want to access a true shell
2396 IPython for variable expansion. If you want to access a true shell
2348 variable, an extra $ is necessary to prevent its expansion by IPython:
2397 variable, an extra $ is necessary to prevent its expansion by IPython:
2349
2398
2350 In [6]: alias show echo\\
2399 In [6]: alias show echo\\
2351 In [7]: PATH='A Python string'\\
2400 In [7]: PATH='A Python string'\\
2352 In [8]: show $PATH\\
2401 In [8]: show $PATH\\
2353 A Python string\\
2402 A Python string\\
2354 In [9]: show $$PATH\\
2403 In [9]: show $$PATH\\
2355 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2404 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2356
2405
2357 You can use the alias facility to acess all of $PATH. See the %rehash
2406 You can use the alias facility to acess all of $PATH. See the %rehash
2358 and %rehashx functions, which automatically create aliases for the
2407 and %rehashx functions, which automatically create aliases for the
2359 contents of your $PATH.
2408 contents of your $PATH.
2360
2409
2361 If called with no parameters, %alias prints the current alias table."""
2410 If called with no parameters, %alias prints the current alias table."""
2362
2411
2363 par = parameter_s.strip()
2412 par = parameter_s.strip()
2364 if not par:
2413 if not par:
2365 stored = self.db.get('stored_aliases', {} )
2414 stored = self.db.get('stored_aliases', {} )
2366 atab = self.shell.alias_table
2415 atab = self.shell.alias_table
2367 aliases = atab.keys()
2416 aliases = atab.keys()
2368 aliases.sort()
2417 aliases.sort()
2369 res = []
2418 res = []
2370 showlast = []
2419 showlast = []
2371 for alias in aliases:
2420 for alias in aliases:
2372 tgt = atab[alias][1]
2421 tgt = atab[alias][1]
2373 # 'interesting' aliases
2422 # 'interesting' aliases
2374 if (alias in stored or
2423 if (alias in stored or
2375 alias != os.path.splitext(tgt)[0] or
2424 alias != os.path.splitext(tgt)[0] or
2376 ' ' in tgt):
2425 ' ' in tgt):
2377 showlast.append((alias, tgt))
2426 showlast.append((alias, tgt))
2378 else:
2427 else:
2379 res.append((alias, tgt ))
2428 res.append((alias, tgt ))
2380
2429
2381 # show most interesting aliases last
2430 # show most interesting aliases last
2382 res.extend(showlast)
2431 res.extend(showlast)
2383 print "Total number of aliases:",len(aliases)
2432 print "Total number of aliases:",len(aliases)
2384 return res
2433 return res
2385 try:
2434 try:
2386 alias,cmd = par.split(None,1)
2435 alias,cmd = par.split(None,1)
2387 except:
2436 except:
2388 print OInspect.getdoc(self.magic_alias)
2437 print OInspect.getdoc(self.magic_alias)
2389 else:
2438 else:
2390 nargs = cmd.count('%s')
2439 nargs = cmd.count('%s')
2391 if nargs>0 and cmd.find('%l')>=0:
2440 if nargs>0 and cmd.find('%l')>=0:
2392 error('The %s and %l specifiers are mutually exclusive '
2441 error('The %s and %l specifiers are mutually exclusive '
2393 'in alias definitions.')
2442 'in alias definitions.')
2394 else: # all looks OK
2443 else: # all looks OK
2395 self.shell.alias_table[alias] = (nargs,cmd)
2444 self.shell.alias_table[alias] = (nargs,cmd)
2396 self.shell.alias_table_validate(verbose=0)
2445 self.shell.alias_table_validate(verbose=0)
2397 # end magic_alias
2446 # end magic_alias
2398
2447
2399 def magic_unalias(self, parameter_s = ''):
2448 def magic_unalias(self, parameter_s = ''):
2400 """Remove an alias"""
2449 """Remove an alias"""
2401
2450
2402 aname = parameter_s.strip()
2451 aname = parameter_s.strip()
2403 if aname in self.shell.alias_table:
2452 if aname in self.shell.alias_table:
2404 del self.shell.alias_table[aname]
2453 del self.shell.alias_table[aname]
2405 stored = self.db.get('stored_aliases', {} )
2454 stored = self.db.get('stored_aliases', {} )
2406 if aname in stored:
2455 if aname in stored:
2407 print "Removing %stored alias",aname
2456 print "Removing %stored alias",aname
2408 del stored[aname]
2457 del stored[aname]
2409 self.db['stored_aliases'] = stored
2458 self.db['stored_aliases'] = stored
2410
2459
2411 def magic_rehash(self, parameter_s = ''):
2460 def magic_rehash(self, parameter_s = ''):
2412 """Update the alias table with all entries in $PATH.
2461 """Update the alias table with all entries in $PATH.
2413
2462
2414 This version does no checks on execute permissions or whether the
2463 This version does no checks on execute permissions or whether the
2415 contents of $PATH are truly files (instead of directories or something
2464 contents of $PATH are truly files (instead of directories or something
2416 else). For such a safer (but slower) version, use %rehashx."""
2465 else). For such a safer (but slower) version, use %rehashx."""
2417
2466
2418 # This function (and rehashx) manipulate the alias_table directly
2467 # This function (and rehashx) manipulate the alias_table directly
2419 # rather than calling magic_alias, for speed reasons. A rehash on a
2468 # rather than calling magic_alias, for speed reasons. A rehash on a
2420 # typical Linux box involves several thousand entries, so efficiency
2469 # typical Linux box involves several thousand entries, so efficiency
2421 # here is a top concern.
2470 # here is a top concern.
2422
2471
2423 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2472 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2424 alias_table = self.shell.alias_table
2473 alias_table = self.shell.alias_table
2425 for pdir in path:
2474 for pdir in path:
2426 for ff in os.listdir(pdir):
2475 for ff in os.listdir(pdir):
2427 # each entry in the alias table must be (N,name), where
2476 # each entry in the alias table must be (N,name), where
2428 # N is the number of positional arguments of the alias.
2477 # N is the number of positional arguments of the alias.
2429 alias_table[ff] = (0,ff)
2478 alias_table[ff] = (0,ff)
2430 # Make sure the alias table doesn't contain keywords or builtins
2479 # Make sure the alias table doesn't contain keywords or builtins
2431 self.shell.alias_table_validate()
2480 self.shell.alias_table_validate()
2432 # Call again init_auto_alias() so we get 'rm -i' and other modified
2481 # Call again init_auto_alias() so we get 'rm -i' and other modified
2433 # aliases since %rehash will probably clobber them
2482 # aliases since %rehash will probably clobber them
2434 self.shell.init_auto_alias()
2483 self.shell.init_auto_alias()
2435
2484
2436 def magic_rehashx(self, parameter_s = ''):
2485 def magic_rehashx(self, parameter_s = ''):
2437 """Update the alias table with all executable files in $PATH.
2486 """Update the alias table with all executable files in $PATH.
2438
2487
2439 This version explicitly checks that every entry in $PATH is a file
2488 This version explicitly checks that every entry in $PATH is a file
2440 with execute access (os.X_OK), so it is much slower than %rehash.
2489 with execute access (os.X_OK), so it is much slower than %rehash.
2441
2490
2442 Under Windows, it checks executability as a match agains a
2491 Under Windows, it checks executability as a match agains a
2443 '|'-separated string of extensions, stored in the IPython config
2492 '|'-separated string of extensions, stored in the IPython config
2444 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2493 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2445
2494
2446 path = [os.path.abspath(os.path.expanduser(p)) for p in
2495 path = [os.path.abspath(os.path.expanduser(p)) for p in
2447 os.environ['PATH'].split(os.pathsep)]
2496 os.environ['PATH'].split(os.pathsep)]
2448 path = filter(os.path.isdir,path)
2497 path = filter(os.path.isdir,path)
2449
2498
2450 alias_table = self.shell.alias_table
2499 alias_table = self.shell.alias_table
2451 syscmdlist = []
2500 syscmdlist = []
2452 if os.name == 'posix':
2501 if os.name == 'posix':
2453 isexec = lambda fname:os.path.isfile(fname) and \
2502 isexec = lambda fname:os.path.isfile(fname) and \
2454 os.access(fname,os.X_OK)
2503 os.access(fname,os.X_OK)
2455 else:
2504 else:
2456
2505
2457 try:
2506 try:
2458 winext = os.environ['pathext'].replace(';','|').replace('.','')
2507 winext = os.environ['pathext'].replace(';','|').replace('.','')
2459 except KeyError:
2508 except KeyError:
2460 winext = 'exe|com|bat|py'
2509 winext = 'exe|com|bat|py'
2461 if 'py' not in winext:
2510 if 'py' not in winext:
2462 winext += '|py'
2511 winext += '|py'
2463 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2512 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2464 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2513 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2465 savedir = os.getcwd()
2514 savedir = os.getcwd()
2466 try:
2515 try:
2467 # write the whole loop for posix/Windows so we don't have an if in
2516 # write the whole loop for posix/Windows so we don't have an if in
2468 # the innermost part
2517 # the innermost part
2469 if os.name == 'posix':
2518 if os.name == 'posix':
2470 for pdir in path:
2519 for pdir in path:
2471 os.chdir(pdir)
2520 os.chdir(pdir)
2472 for ff in os.listdir(pdir):
2521 for ff in os.listdir(pdir):
2473 if isexec(ff) and ff not in self.shell.no_alias:
2522 if isexec(ff) and ff not in self.shell.no_alias:
2474 # each entry in the alias table must be (N,name),
2523 # each entry in the alias table must be (N,name),
2475 # where N is the number of positional arguments of the
2524 # where N is the number of positional arguments of the
2476 # alias.
2525 # alias.
2477 alias_table[ff] = (0,ff)
2526 alias_table[ff] = (0,ff)
2478 syscmdlist.append(ff)
2527 syscmdlist.append(ff)
2479 else:
2528 else:
2480 for pdir in path:
2529 for pdir in path:
2481 os.chdir(pdir)
2530 os.chdir(pdir)
2482 for ff in os.listdir(pdir):
2531 for ff in os.listdir(pdir):
2483 if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias:
2532 if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias:
2484 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2533 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2485 syscmdlist.append(ff)
2534 syscmdlist.append(ff)
2486 # Make sure the alias table doesn't contain keywords or builtins
2535 # Make sure the alias table doesn't contain keywords or builtins
2487 self.shell.alias_table_validate()
2536 self.shell.alias_table_validate()
2488 # Call again init_auto_alias() so we get 'rm -i' and other
2537 # Call again init_auto_alias() so we get 'rm -i' and other
2489 # modified aliases since %rehashx will probably clobber them
2538 # modified aliases since %rehashx will probably clobber them
2490 self.shell.init_auto_alias()
2539 self.shell.init_auto_alias()
2491 db = self.getapi().db
2540 db = self.getapi().db
2492 db['syscmdlist'] = syscmdlist
2541 db['syscmdlist'] = syscmdlist
2493 finally:
2542 finally:
2494 os.chdir(savedir)
2543 os.chdir(savedir)
2495
2544
2496 def magic_pwd(self, parameter_s = ''):
2545 def magic_pwd(self, parameter_s = ''):
2497 """Return the current working directory path."""
2546 """Return the current working directory path."""
2498 return os.getcwd()
2547 return os.getcwd()
2499
2548
2500 def magic_cd(self, parameter_s=''):
2549 def magic_cd(self, parameter_s=''):
2501 """Change the current working directory.
2550 """Change the current working directory.
2502
2551
2503 This command automatically maintains an internal list of directories
2552 This command automatically maintains an internal list of directories
2504 you visit during your IPython session, in the variable _dh. The
2553 you visit during your IPython session, in the variable _dh. The
2505 command %dhist shows this history nicely formatted.
2554 command %dhist shows this history nicely formatted.
2506
2555
2507 Usage:
2556 Usage:
2508
2557
2509 cd 'dir': changes to directory 'dir'.
2558 cd 'dir': changes to directory 'dir'.
2510
2559
2511 cd -: changes to the last visited directory.
2560 cd -: changes to the last visited directory.
2512
2561
2513 cd -<n>: changes to the n-th directory in the directory history.
2562 cd -<n>: changes to the n-th directory in the directory history.
2514
2563
2515 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2564 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2516 (note: cd <bookmark_name> is enough if there is no
2565 (note: cd <bookmark_name> is enough if there is no
2517 directory <bookmark_name>, but a bookmark with the name exists.)
2566 directory <bookmark_name>, but a bookmark with the name exists.)
2518
2567
2519 Options:
2568 Options:
2520
2569
2521 -q: quiet. Do not print the working directory after the cd command is
2570 -q: quiet. Do not print the working directory after the cd command is
2522 executed. By default IPython's cd command does print this directory,
2571 executed. By default IPython's cd command does print this directory,
2523 since the default prompts do not display path information.
2572 since the default prompts do not display path information.
2524
2573
2525 Note that !cd doesn't work for this purpose because the shell where
2574 Note that !cd doesn't work for this purpose because the shell where
2526 !command runs is immediately discarded after executing 'command'."""
2575 !command runs is immediately discarded after executing 'command'."""
2527
2576
2528 parameter_s = parameter_s.strip()
2577 parameter_s = parameter_s.strip()
2529 #bkms = self.shell.persist.get("bookmarks",{})
2578 #bkms = self.shell.persist.get("bookmarks",{})
2530
2579
2531 numcd = re.match(r'(-)(\d+)$',parameter_s)
2580 numcd = re.match(r'(-)(\d+)$',parameter_s)
2532 # jump in directory history by number
2581 # jump in directory history by number
2533 if numcd:
2582 if numcd:
2534 nn = int(numcd.group(2))
2583 nn = int(numcd.group(2))
2535 try:
2584 try:
2536 ps = self.shell.user_ns['_dh'][nn]
2585 ps = self.shell.user_ns['_dh'][nn]
2537 except IndexError:
2586 except IndexError:
2538 print 'The requested directory does not exist in history.'
2587 print 'The requested directory does not exist in history.'
2539 return
2588 return
2540 else:
2589 else:
2541 opts = {}
2590 opts = {}
2542 else:
2591 else:
2543 #turn all non-space-escaping backslashes to slashes,
2592 #turn all non-space-escaping backslashes to slashes,
2544 # for c:\windows\directory\names\
2593 # for c:\windows\directory\names\
2545 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2594 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2546 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2595 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2547 # jump to previous
2596 # jump to previous
2548 if ps == '-':
2597 if ps == '-':
2549 try:
2598 try:
2550 ps = self.shell.user_ns['_dh'][-2]
2599 ps = self.shell.user_ns['_dh'][-2]
2551 except IndexError:
2600 except IndexError:
2552 print 'No previous directory to change to.'
2601 print 'No previous directory to change to.'
2553 return
2602 return
2554 # jump to bookmark if needed
2603 # jump to bookmark if needed
2555 else:
2604 else:
2556 if not os.path.isdir(ps) or opts.has_key('b'):
2605 if not os.path.isdir(ps) or opts.has_key('b'):
2557 bkms = self.db.get('bookmarks', {})
2606 bkms = self.db.get('bookmarks', {})
2558
2607
2559 if bkms.has_key(ps):
2608 if bkms.has_key(ps):
2560 target = bkms[ps]
2609 target = bkms[ps]
2561 print '(bookmark:%s) -> %s' % (ps,target)
2610 print '(bookmark:%s) -> %s' % (ps,target)
2562 ps = target
2611 ps = target
2563 else:
2612 else:
2564 if opts.has_key('b'):
2613 if opts.has_key('b'):
2565 error("Bookmark '%s' not found. "
2614 error("Bookmark '%s' not found. "
2566 "Use '%%bookmark -l' to see your bookmarks." % ps)
2615 "Use '%%bookmark -l' to see your bookmarks." % ps)
2567 return
2616 return
2568
2617
2569 # at this point ps should point to the target dir
2618 # at this point ps should point to the target dir
2570 if ps:
2619 if ps:
2571 try:
2620 try:
2572 os.chdir(os.path.expanduser(ps))
2621 os.chdir(os.path.expanduser(ps))
2573 ttitle = ("IPy:" + (
2622 ttitle = ("IPy:" + (
2574 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2623 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2575 platutils.set_term_title(ttitle)
2624 platutils.set_term_title(ttitle)
2576 except OSError:
2625 except OSError:
2577 print sys.exc_info()[1]
2626 print sys.exc_info()[1]
2578 else:
2627 else:
2579 self.shell.user_ns['_dh'].append(os.getcwd())
2628 self.shell.user_ns['_dh'].append(os.getcwd())
2580 else:
2629 else:
2581 os.chdir(self.shell.home_dir)
2630 os.chdir(self.shell.home_dir)
2582 platutils.set_term_title("IPy:~")
2631 platutils.set_term_title("IPy:~")
2583 self.shell.user_ns['_dh'].append(os.getcwd())
2632 self.shell.user_ns['_dh'].append(os.getcwd())
2584 if not 'q' in opts:
2633 if not 'q' in opts:
2585 print self.shell.user_ns['_dh'][-1]
2634 print self.shell.user_ns['_dh'][-1]
2586
2635
2587 def magic_dhist(self, parameter_s=''):
2636 def magic_dhist(self, parameter_s=''):
2588 """Print your history of visited directories.
2637 """Print your history of visited directories.
2589
2638
2590 %dhist -> print full history\\
2639 %dhist -> print full history\\
2591 %dhist n -> print last n entries only\\
2640 %dhist n -> print last n entries only\\
2592 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2641 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2593
2642
2594 This history is automatically maintained by the %cd command, and
2643 This history is automatically maintained by the %cd command, and
2595 always available as the global list variable _dh. You can use %cd -<n>
2644 always available as the global list variable _dh. You can use %cd -<n>
2596 to go to directory number <n>."""
2645 to go to directory number <n>."""
2597
2646
2598 dh = self.shell.user_ns['_dh']
2647 dh = self.shell.user_ns['_dh']
2599 if parameter_s:
2648 if parameter_s:
2600 try:
2649 try:
2601 args = map(int,parameter_s.split())
2650 args = map(int,parameter_s.split())
2602 except:
2651 except:
2603 self.arg_err(Magic.magic_dhist)
2652 self.arg_err(Magic.magic_dhist)
2604 return
2653 return
2605 if len(args) == 1:
2654 if len(args) == 1:
2606 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2655 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2607 elif len(args) == 2:
2656 elif len(args) == 2:
2608 ini,fin = args
2657 ini,fin = args
2609 else:
2658 else:
2610 self.arg_err(Magic.magic_dhist)
2659 self.arg_err(Magic.magic_dhist)
2611 return
2660 return
2612 else:
2661 else:
2613 ini,fin = 0,len(dh)
2662 ini,fin = 0,len(dh)
2614 nlprint(dh,
2663 nlprint(dh,
2615 header = 'Directory history (kept in _dh)',
2664 header = 'Directory history (kept in _dh)',
2616 start=ini,stop=fin)
2665 start=ini,stop=fin)
2617
2666
2618 def magic_env(self, parameter_s=''):
2667 def magic_env(self, parameter_s=''):
2619 """List environment variables."""
2668 """List environment variables."""
2620
2669
2621 return os.environ.data
2670 return os.environ.data
2622
2671
2623 def magic_pushd(self, parameter_s=''):
2672 def magic_pushd(self, parameter_s=''):
2624 """Place the current dir on stack and change directory.
2673 """Place the current dir on stack and change directory.
2625
2674
2626 Usage:\\
2675 Usage:\\
2627 %pushd ['dirname']
2676 %pushd ['dirname']
2628
2677
2629 %pushd with no arguments does a %pushd to your home directory.
2678 %pushd with no arguments does a %pushd to your home directory.
2630 """
2679 """
2631 if parameter_s == '': parameter_s = '~'
2680 if parameter_s == '': parameter_s = '~'
2632 dir_s = self.shell.dir_stack
2681 dir_s = self.shell.dir_stack
2633 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2682 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2634 os.path.expanduser(self.shell.dir_stack[0]):
2683 os.path.expanduser(self.shell.dir_stack[0]):
2635 try:
2684 try:
2636 self.magic_cd(parameter_s)
2685 self.magic_cd(parameter_s)
2637 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2686 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2638 self.magic_dirs()
2687 self.magic_dirs()
2639 except:
2688 except:
2640 print 'Invalid directory'
2689 print 'Invalid directory'
2641 else:
2690 else:
2642 print 'You are already there!'
2691 print 'You are already there!'
2643
2692
2644 def magic_popd(self, parameter_s=''):
2693 def magic_popd(self, parameter_s=''):
2645 """Change to directory popped off the top of the stack.
2694 """Change to directory popped off the top of the stack.
2646 """
2695 """
2647 if len (self.shell.dir_stack) > 1:
2696 if len (self.shell.dir_stack) > 1:
2648 self.shell.dir_stack.pop(0)
2697 self.shell.dir_stack.pop(0)
2649 self.magic_cd(self.shell.dir_stack[0])
2698 self.magic_cd(self.shell.dir_stack[0])
2650 print self.shell.dir_stack[0]
2699 print self.shell.dir_stack[0]
2651 else:
2700 else:
2652 print "You can't remove the starting directory from the stack:",\
2701 print "You can't remove the starting directory from the stack:",\
2653 self.shell.dir_stack
2702 self.shell.dir_stack
2654
2703
2655 def magic_dirs(self, parameter_s=''):
2704 def magic_dirs(self, parameter_s=''):
2656 """Return the current directory stack."""
2705 """Return the current directory stack."""
2657
2706
2658 return self.shell.dir_stack[:]
2707 return self.shell.dir_stack[:]
2659
2708
2660 def magic_sc(self, parameter_s=''):
2709 def magic_sc(self, parameter_s=''):
2661 """Shell capture - execute a shell command and capture its output.
2710 """Shell capture - execute a shell command and capture its output.
2662
2711
2663 DEPRECATED. Suboptimal, retained for backwards compatibility.
2712 DEPRECATED. Suboptimal, retained for backwards compatibility.
2664
2713
2665 You should use the form 'var = !command' instead. Example:
2714 You should use the form 'var = !command' instead. Example:
2666
2715
2667 "%sc -l myfiles = ls ~" should now be written as
2716 "%sc -l myfiles = ls ~" should now be written as
2668
2717
2669 "myfiles = !ls ~"
2718 "myfiles = !ls ~"
2670
2719
2671 myfiles.s, myfiles.l and myfiles.n still apply as documented
2720 myfiles.s, myfiles.l and myfiles.n still apply as documented
2672 below.
2721 below.
2673
2722
2674 --
2723 --
2675 %sc [options] varname=command
2724 %sc [options] varname=command
2676
2725
2677 IPython will run the given command using commands.getoutput(), and
2726 IPython will run the given command using commands.getoutput(), and
2678 will then update the user's interactive namespace with a variable
2727 will then update the user's interactive namespace with a variable
2679 called varname, containing the value of the call. Your command can
2728 called varname, containing the value of the call. Your command can
2680 contain shell wildcards, pipes, etc.
2729 contain shell wildcards, pipes, etc.
2681
2730
2682 The '=' sign in the syntax is mandatory, and the variable name you
2731 The '=' sign in the syntax is mandatory, and the variable name you
2683 supply must follow Python's standard conventions for valid names.
2732 supply must follow Python's standard conventions for valid names.
2684
2733
2685 (A special format without variable name exists for internal use)
2734 (A special format without variable name exists for internal use)
2686
2735
2687 Options:
2736 Options:
2688
2737
2689 -l: list output. Split the output on newlines into a list before
2738 -l: list output. Split the output on newlines into a list before
2690 assigning it to the given variable. By default the output is stored
2739 assigning it to the given variable. By default the output is stored
2691 as a single string.
2740 as a single string.
2692
2741
2693 -v: verbose. Print the contents of the variable.
2742 -v: verbose. Print the contents of the variable.
2694
2743
2695 In most cases you should not need to split as a list, because the
2744 In most cases you should not need to split as a list, because the
2696 returned value is a special type of string which can automatically
2745 returned value is a special type of string which can automatically
2697 provide its contents either as a list (split on newlines) or as a
2746 provide its contents either as a list (split on newlines) or as a
2698 space-separated string. These are convenient, respectively, either
2747 space-separated string. These are convenient, respectively, either
2699 for sequential processing or to be passed to a shell command.
2748 for sequential processing or to be passed to a shell command.
2700
2749
2701 For example:
2750 For example:
2702
2751
2703 # Capture into variable a
2752 # Capture into variable a
2704 In [9]: sc a=ls *py
2753 In [9]: sc a=ls *py
2705
2754
2706 # a is a string with embedded newlines
2755 # a is a string with embedded newlines
2707 In [10]: a
2756 In [10]: a
2708 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2757 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2709
2758
2710 # which can be seen as a list:
2759 # which can be seen as a list:
2711 In [11]: a.l
2760 In [11]: a.l
2712 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2761 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2713
2762
2714 # or as a whitespace-separated string:
2763 # or as a whitespace-separated string:
2715 In [12]: a.s
2764 In [12]: a.s
2716 Out[12]: 'setup.py win32_manual_post_install.py'
2765 Out[12]: 'setup.py win32_manual_post_install.py'
2717
2766
2718 # a.s is useful to pass as a single command line:
2767 # a.s is useful to pass as a single command line:
2719 In [13]: !wc -l $a.s
2768 In [13]: !wc -l $a.s
2720 146 setup.py
2769 146 setup.py
2721 130 win32_manual_post_install.py
2770 130 win32_manual_post_install.py
2722 276 total
2771 276 total
2723
2772
2724 # while the list form is useful to loop over:
2773 # while the list form is useful to loop over:
2725 In [14]: for f in a.l:
2774 In [14]: for f in a.l:
2726 ....: !wc -l $f
2775 ....: !wc -l $f
2727 ....:
2776 ....:
2728 146 setup.py
2777 146 setup.py
2729 130 win32_manual_post_install.py
2778 130 win32_manual_post_install.py
2730
2779
2731 Similiarly, the lists returned by the -l option are also special, in
2780 Similiarly, the lists returned by the -l option are also special, in
2732 the sense that you can equally invoke the .s attribute on them to
2781 the sense that you can equally invoke the .s attribute on them to
2733 automatically get a whitespace-separated string from their contents:
2782 automatically get a whitespace-separated string from their contents:
2734
2783
2735 In [1]: sc -l b=ls *py
2784 In [1]: sc -l b=ls *py
2736
2785
2737 In [2]: b
2786 In [2]: b
2738 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2787 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2739
2788
2740 In [3]: b.s
2789 In [3]: b.s
2741 Out[3]: 'setup.py win32_manual_post_install.py'
2790 Out[3]: 'setup.py win32_manual_post_install.py'
2742
2791
2743 In summary, both the lists and strings used for ouptut capture have
2792 In summary, both the lists and strings used for ouptut capture have
2744 the following special attributes:
2793 the following special attributes:
2745
2794
2746 .l (or .list) : value as list.
2795 .l (or .list) : value as list.
2747 .n (or .nlstr): value as newline-separated string.
2796 .n (or .nlstr): value as newline-separated string.
2748 .s (or .spstr): value as space-separated string.
2797 .s (or .spstr): value as space-separated string.
2749 """
2798 """
2750
2799
2751 opts,args = self.parse_options(parameter_s,'lv')
2800 opts,args = self.parse_options(parameter_s,'lv')
2752 # Try to get a variable name and command to run
2801 # Try to get a variable name and command to run
2753 try:
2802 try:
2754 # the variable name must be obtained from the parse_options
2803 # the variable name must be obtained from the parse_options
2755 # output, which uses shlex.split to strip options out.
2804 # output, which uses shlex.split to strip options out.
2756 var,_ = args.split('=',1)
2805 var,_ = args.split('=',1)
2757 var = var.strip()
2806 var = var.strip()
2758 # But the the command has to be extracted from the original input
2807 # But the the command has to be extracted from the original input
2759 # parameter_s, not on what parse_options returns, to avoid the
2808 # parameter_s, not on what parse_options returns, to avoid the
2760 # quote stripping which shlex.split performs on it.
2809 # quote stripping which shlex.split performs on it.
2761 _,cmd = parameter_s.split('=',1)
2810 _,cmd = parameter_s.split('=',1)
2762 except ValueError:
2811 except ValueError:
2763 var,cmd = '',''
2812 var,cmd = '',''
2764 # If all looks ok, proceed
2813 # If all looks ok, proceed
2765 out,err = self.shell.getoutputerror(cmd)
2814 out,err = self.shell.getoutputerror(cmd)
2766 if err:
2815 if err:
2767 print >> Term.cerr,err
2816 print >> Term.cerr,err
2768 if opts.has_key('l'):
2817 if opts.has_key('l'):
2769 out = SList(out.split('\n'))
2818 out = SList(out.split('\n'))
2770 else:
2819 else:
2771 out = LSString(out)
2820 out = LSString(out)
2772 if opts.has_key('v'):
2821 if opts.has_key('v'):
2773 print '%s ==\n%s' % (var,pformat(out))
2822 print '%s ==\n%s' % (var,pformat(out))
2774 if var:
2823 if var:
2775 self.shell.user_ns.update({var:out})
2824 self.shell.user_ns.update({var:out})
2776 else:
2825 else:
2777 return out
2826 return out
2778
2827
2779 def magic_sx(self, parameter_s=''):
2828 def magic_sx(self, parameter_s=''):
2780 """Shell execute - run a shell command and capture its output.
2829 """Shell execute - run a shell command and capture its output.
2781
2830
2782 %sx command
2831 %sx command
2783
2832
2784 IPython will run the given command using commands.getoutput(), and
2833 IPython will run the given command using commands.getoutput(), and
2785 return the result formatted as a list (split on '\\n'). Since the
2834 return the result formatted as a list (split on '\\n'). Since the
2786 output is _returned_, it will be stored in ipython's regular output
2835 output is _returned_, it will be stored in ipython's regular output
2787 cache Out[N] and in the '_N' automatic variables.
2836 cache Out[N] and in the '_N' automatic variables.
2788
2837
2789 Notes:
2838 Notes:
2790
2839
2791 1) If an input line begins with '!!', then %sx is automatically
2840 1) If an input line begins with '!!', then %sx is automatically
2792 invoked. That is, while:
2841 invoked. That is, while:
2793 !ls
2842 !ls
2794 causes ipython to simply issue system('ls'), typing
2843 causes ipython to simply issue system('ls'), typing
2795 !!ls
2844 !!ls
2796 is a shorthand equivalent to:
2845 is a shorthand equivalent to:
2797 %sx ls
2846 %sx ls
2798
2847
2799 2) %sx differs from %sc in that %sx automatically splits into a list,
2848 2) %sx differs from %sc in that %sx automatically splits into a list,
2800 like '%sc -l'. The reason for this is to make it as easy as possible
2849 like '%sc -l'. The reason for this is to make it as easy as possible
2801 to process line-oriented shell output via further python commands.
2850 to process line-oriented shell output via further python commands.
2802 %sc is meant to provide much finer control, but requires more
2851 %sc is meant to provide much finer control, but requires more
2803 typing.
2852 typing.
2804
2853
2805 3) Just like %sc -l, this is a list with special attributes:
2854 3) Just like %sc -l, this is a list with special attributes:
2806
2855
2807 .l (or .list) : value as list.
2856 .l (or .list) : value as list.
2808 .n (or .nlstr): value as newline-separated string.
2857 .n (or .nlstr): value as newline-separated string.
2809 .s (or .spstr): value as whitespace-separated string.
2858 .s (or .spstr): value as whitespace-separated string.
2810
2859
2811 This is very useful when trying to use such lists as arguments to
2860 This is very useful when trying to use such lists as arguments to
2812 system commands."""
2861 system commands."""
2813
2862
2814 if parameter_s:
2863 if parameter_s:
2815 out,err = self.shell.getoutputerror(parameter_s)
2864 out,err = self.shell.getoutputerror(parameter_s)
2816 if err:
2865 if err:
2817 print >> Term.cerr,err
2866 print >> Term.cerr,err
2818 return SList(out.split('\n'))
2867 return SList(out.split('\n'))
2819
2868
2820 def magic_bg(self, parameter_s=''):
2869 def magic_bg(self, parameter_s=''):
2821 """Run a job in the background, in a separate thread.
2870 """Run a job in the background, in a separate thread.
2822
2871
2823 For example,
2872 For example,
2824
2873
2825 %bg myfunc(x,y,z=1)
2874 %bg myfunc(x,y,z=1)
2826
2875
2827 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2876 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2828 execution starts, a message will be printed indicating the job
2877 execution starts, a message will be printed indicating the job
2829 number. If your job number is 5, you can use
2878 number. If your job number is 5, you can use
2830
2879
2831 myvar = jobs.result(5) or myvar = jobs[5].result
2880 myvar = jobs.result(5) or myvar = jobs[5].result
2832
2881
2833 to assign this result to variable 'myvar'.
2882 to assign this result to variable 'myvar'.
2834
2883
2835 IPython has a job manager, accessible via the 'jobs' object. You can
2884 IPython has a job manager, accessible via the 'jobs' object. You can
2836 type jobs? to get more information about it, and use jobs.<TAB> to see
2885 type jobs? to get more information about it, and use jobs.<TAB> to see
2837 its attributes. All attributes not starting with an underscore are
2886 its attributes. All attributes not starting with an underscore are
2838 meant for public use.
2887 meant for public use.
2839
2888
2840 In particular, look at the jobs.new() method, which is used to create
2889 In particular, look at the jobs.new() method, which is used to create
2841 new jobs. This magic %bg function is just a convenience wrapper
2890 new jobs. This magic %bg function is just a convenience wrapper
2842 around jobs.new(), for expression-based jobs. If you want to create a
2891 around jobs.new(), for expression-based jobs. If you want to create a
2843 new job with an explicit function object and arguments, you must call
2892 new job with an explicit function object and arguments, you must call
2844 jobs.new() directly.
2893 jobs.new() directly.
2845
2894
2846 The jobs.new docstring also describes in detail several important
2895 The jobs.new docstring also describes in detail several important
2847 caveats associated with a thread-based model for background job
2896 caveats associated with a thread-based model for background job
2848 execution. Type jobs.new? for details.
2897 execution. Type jobs.new? for details.
2849
2898
2850 You can check the status of all jobs with jobs.status().
2899 You can check the status of all jobs with jobs.status().
2851
2900
2852 The jobs variable is set by IPython into the Python builtin namespace.
2901 The jobs variable is set by IPython into the Python builtin namespace.
2853 If you ever declare a variable named 'jobs', you will shadow this
2902 If you ever declare a variable named 'jobs', you will shadow this
2854 name. You can either delete your global jobs variable to regain
2903 name. You can either delete your global jobs variable to regain
2855 access to the job manager, or make a new name and assign it manually
2904 access to the job manager, or make a new name and assign it manually
2856 to the manager (stored in IPython's namespace). For example, to
2905 to the manager (stored in IPython's namespace). For example, to
2857 assign the job manager to the Jobs name, use:
2906 assign the job manager to the Jobs name, use:
2858
2907
2859 Jobs = __builtins__.jobs"""
2908 Jobs = __builtins__.jobs"""
2860
2909
2861 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2910 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2862
2911
2863
2912
2864 def magic_bookmark(self, parameter_s=''):
2913 def magic_bookmark(self, parameter_s=''):
2865 """Manage IPython's bookmark system.
2914 """Manage IPython's bookmark system.
2866
2915
2867 %bookmark <name> - set bookmark to current dir
2916 %bookmark <name> - set bookmark to current dir
2868 %bookmark <name> <dir> - set bookmark to <dir>
2917 %bookmark <name> <dir> - set bookmark to <dir>
2869 %bookmark -l - list all bookmarks
2918 %bookmark -l - list all bookmarks
2870 %bookmark -d <name> - remove bookmark
2919 %bookmark -d <name> - remove bookmark
2871 %bookmark -r - remove all bookmarks
2920 %bookmark -r - remove all bookmarks
2872
2921
2873 You can later on access a bookmarked folder with:
2922 You can later on access a bookmarked folder with:
2874 %cd -b <name>
2923 %cd -b <name>
2875 or simply '%cd <name>' if there is no directory called <name> AND
2924 or simply '%cd <name>' if there is no directory called <name> AND
2876 there is such a bookmark defined.
2925 there is such a bookmark defined.
2877
2926
2878 Your bookmarks persist through IPython sessions, but they are
2927 Your bookmarks persist through IPython sessions, but they are
2879 associated with each profile."""
2928 associated with each profile."""
2880
2929
2881 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2930 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2882 if len(args) > 2:
2931 if len(args) > 2:
2883 error('You can only give at most two arguments')
2932 error('You can only give at most two arguments')
2884 return
2933 return
2885
2934
2886 bkms = self.db.get('bookmarks',{})
2935 bkms = self.db.get('bookmarks',{})
2887
2936
2888 if opts.has_key('d'):
2937 if opts.has_key('d'):
2889 try:
2938 try:
2890 todel = args[0]
2939 todel = args[0]
2891 except IndexError:
2940 except IndexError:
2892 error('You must provide a bookmark to delete')
2941 error('You must provide a bookmark to delete')
2893 else:
2942 else:
2894 try:
2943 try:
2895 del bkms[todel]
2944 del bkms[todel]
2896 except:
2945 except:
2897 error("Can't delete bookmark '%s'" % todel)
2946 error("Can't delete bookmark '%s'" % todel)
2898 elif opts.has_key('r'):
2947 elif opts.has_key('r'):
2899 bkms = {}
2948 bkms = {}
2900 elif opts.has_key('l'):
2949 elif opts.has_key('l'):
2901 bks = bkms.keys()
2950 bks = bkms.keys()
2902 bks.sort()
2951 bks.sort()
2903 if bks:
2952 if bks:
2904 size = max(map(len,bks))
2953 size = max(map(len,bks))
2905 else:
2954 else:
2906 size = 0
2955 size = 0
2907 fmt = '%-'+str(size)+'s -> %s'
2956 fmt = '%-'+str(size)+'s -> %s'
2908 print 'Current bookmarks:'
2957 print 'Current bookmarks:'
2909 for bk in bks:
2958 for bk in bks:
2910 print fmt % (bk,bkms[bk])
2959 print fmt % (bk,bkms[bk])
2911 else:
2960 else:
2912 if not args:
2961 if not args:
2913 error("You must specify the bookmark name")
2962 error("You must specify the bookmark name")
2914 elif len(args)==1:
2963 elif len(args)==1:
2915 bkms[args[0]] = os.getcwd()
2964 bkms[args[0]] = os.getcwd()
2916 elif len(args)==2:
2965 elif len(args)==2:
2917 bkms[args[0]] = args[1]
2966 bkms[args[0]] = args[1]
2918 self.db['bookmarks'] = bkms
2967 self.db['bookmarks'] = bkms
2919
2968
2920 def magic_pycat(self, parameter_s=''):
2969 def magic_pycat(self, parameter_s=''):
2921 """Show a syntax-highlighted file through a pager.
2970 """Show a syntax-highlighted file through a pager.
2922
2971
2923 This magic is similar to the cat utility, but it will assume the file
2972 This magic is similar to the cat utility, but it will assume the file
2924 to be Python source and will show it with syntax highlighting. """
2973 to be Python source and will show it with syntax highlighting. """
2925
2974
2926 try:
2975 try:
2927 filename = get_py_filename(parameter_s)
2976 filename = get_py_filename(parameter_s)
2928 cont = file_read(filename)
2977 cont = file_read(filename)
2929 except IOError:
2978 except IOError:
2930 try:
2979 try:
2931 cont = eval(parameter_s,self.user_ns)
2980 cont = eval(parameter_s,self.user_ns)
2932 except NameError:
2981 except NameError:
2933 cont = None
2982 cont = None
2934 if cont is None:
2983 if cont is None:
2935 print "Error: no such file or variable"
2984 print "Error: no such file or variable"
2936 return
2985 return
2937
2986
2938 page(self.shell.pycolorize(cont),
2987 page(self.shell.pycolorize(cont),
2939 screen_lines=self.shell.rc.screen_length)
2988 screen_lines=self.shell.rc.screen_length)
2940
2989
2941 def magic_cpaste(self, parameter_s=''):
2990 def magic_cpaste(self, parameter_s=''):
2942 """Allows you to paste & execute a pre-formatted code block from clipboard
2991 """Allows you to paste & execute a pre-formatted code block from clipboard
2943
2992
2944 You must terminate the block with '--' (two minus-signs) alone on the
2993 You must terminate the block with '--' (two minus-signs) alone on the
2945 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2994 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2946 is the new sentinel for this operation)
2995 is the new sentinel for this operation)
2947
2996
2948 The block is dedented prior to execution to enable execution of
2997 The block is dedented prior to execution to enable execution of
2949 method definitions. '>' characters at the beginning of a line is
2998 method definitions. '>' characters at the beginning of a line is
2950 ignored, to allow pasting directly from e-mails. The executed block
2999 ignored, to allow pasting directly from e-mails. The executed block
2951 is also assigned to variable named 'pasted_block' for later editing
3000 is also assigned to variable named 'pasted_block' for later editing
2952 with '%edit pasted_block'.
3001 with '%edit pasted_block'.
2953
3002
2954 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3003 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2955 This assigns the pasted block to variable 'foo' as string, without
3004 This assigns the pasted block to variable 'foo' as string, without
2956 dedenting or executing it.
3005 dedenting or executing it.
2957
3006
2958 Do not be alarmed by garbled output on Windows (it's a readline bug).
3007 Do not be alarmed by garbled output on Windows (it's a readline bug).
2959 Just press enter and type -- (and press enter again) and the block
3008 Just press enter and type -- (and press enter again) and the block
2960 will be what was just pasted.
3009 will be what was just pasted.
2961
3010
2962 IPython statements (magics, shell escapes) are not supported (yet).
3011 IPython statements (magics, shell escapes) are not supported (yet).
2963 """
3012 """
2964 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3013 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2965 par = args.strip()
3014 par = args.strip()
2966 sentinel = opts.get('s','--')
3015 sentinel = opts.get('s','--')
2967
3016
2968 from IPython import iplib
3017 from IPython import iplib
2969 lines = []
3018 lines = []
2970 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3019 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2971 while 1:
3020 while 1:
2972 l = iplib.raw_input_original(':')
3021 l = iplib.raw_input_original(':')
2973 if l ==sentinel:
3022 if l ==sentinel:
2974 break
3023 break
2975 lines.append(l.lstrip('>'))
3024 lines.append(l.lstrip('>'))
2976 block = "\n".join(lines) + '\n'
3025 block = "\n".join(lines) + '\n'
2977 #print "block:\n",block
3026 #print "block:\n",block
2978 if not par:
3027 if not par:
2979 b = textwrap.dedent(block)
3028 b = textwrap.dedent(block)
2980 exec b in self.user_ns
3029 exec b in self.user_ns
2981 self.user_ns['pasted_block'] = b
3030 self.user_ns['pasted_block'] = b
2982 else:
3031 else:
2983 self.user_ns[par] = block
3032 self.user_ns[par] = block
2984 print "Block assigned to '%s'" % par
3033 print "Block assigned to '%s'" % par
2985
3034
2986 def magic_quickref(self,arg):
3035 def magic_quickref(self,arg):
2987 """ Show a quick reference sheet """
3036 """ Show a quick reference sheet """
2988 import IPython.usage
3037 import IPython.usage
2989 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3038 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2990
3039
2991 page(qr)
3040 page(qr)
2992
3041
2993 def magic_upgrade(self,arg):
3042 def magic_upgrade(self,arg):
2994 """ Upgrade your IPython installation
3043 """ Upgrade your IPython installation
2995
3044
2996 This will copy the config files that don't yet exist in your
3045 This will copy the config files that don't yet exist in your
2997 ipython dir from the system config dir. Use this after upgrading
3046 ipython dir from the system config dir. Use this after upgrading
2998 IPython if you don't wish to delete your .ipython dir.
3047 IPython if you don't wish to delete your .ipython dir.
2999
3048
3000 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3049 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3001 new users)
3050 new users)
3002
3051
3003 """
3052 """
3004 ip = self.getapi()
3053 ip = self.getapi()
3005 ipinstallation = path(IPython.__file__).dirname()
3054 ipinstallation = path(IPython.__file__).dirname()
3006 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3055 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3007 src_config = ipinstallation / 'UserConfig'
3056 src_config = ipinstallation / 'UserConfig'
3008 userdir = path(ip.options.ipythondir)
3057 userdir = path(ip.options.ipythondir)
3009 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3058 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3010 print ">",cmd
3059 print ">",cmd
3011 shell(cmd)
3060 shell(cmd)
3012 if arg == '-nolegacy':
3061 if arg == '-nolegacy':
3013 legacy = userdir.files('ipythonrc*')
3062 legacy = userdir.files('ipythonrc*')
3014 print "Nuking legacy files:",legacy
3063 print "Nuking legacy files:",legacy
3015
3064
3016 [p.remove() for p in legacy]
3065 [p.remove() for p in legacy]
3017 suffix = (sys.platform == 'win32' and '.ini' or '')
3066 suffix = (sys.platform == 'win32' and '.ini' or '')
3018 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3067 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3019
3068
3020
3069
3021 # end Magic
3070 # end Magic
@@ -1,607 +1,616 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 1329 2006-05-26 07:52:45Z fperez $
2 # $Id: ipythonrc 1879 2006-11-04 00:34:34Z fptest $
3
3
4 #***************************************************************************
4 #***************************************************************************
5 #
5 #
6 # Configuration file for IPython -- ipythonrc format
6 # Configuration file for IPython -- ipythonrc format
7 #
7 #
8 # The format of this file is simply one of 'key value' lines.
8 # The format of this file is simply one of 'key value' lines.
9 # Lines containing only whitespace at the beginning and then a # are ignored
9 # Lines containing only whitespace at the beginning and then a # are ignored
10 # as comments. But comments can NOT be put on lines with data.
10 # as comments. But comments can NOT be put on lines with data.
11
11
12 # The meaning and use of each key are explained below.
12 # The meaning and use of each key are explained below.
13
13
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15 # Section: included files
15 # Section: included files
16
16
17 # Put one or more *config* files (with the syntax of this file) you want to
17 # Put one or more *config* files (with the syntax of this file) you want to
18 # include. For keys with a unique value the outermost file has precedence. For
18 # include. For keys with a unique value the outermost file has precedence. For
19 # keys with multiple values, they all get assembled into a list which then
19 # keys with multiple values, they all get assembled into a list which then
20 # gets loaded by IPython.
20 # gets loaded by IPython.
21
21
22 # In this file, all lists of things should simply be space-separated.
22 # In this file, all lists of things should simply be space-separated.
23
23
24 # This allows you to build hierarchies of files which recursively load
24 # This allows you to build hierarchies of files which recursively load
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 # should only keep here basic things you always want available. Then you can
26 # should only keep here basic things you always want available. Then you can
27 # include it in every other special-purpose config file you create.
27 # include it in every other special-purpose config file you create.
28 include
28 include
29
29
30 #---------------------------------------------------------------------------
30 #---------------------------------------------------------------------------
31 # Section: startup setup
31 # Section: startup setup
32
32
33 # These are mostly things which parallel a command line option of the same
33 # These are mostly things which parallel a command line option of the same
34 # name.
34 # name.
35
35
36 # Keys in this section should only appear once. If any key from this section
36 # Keys in this section should only appear once. If any key from this section
37 # is encountered more than once, the last value remains, all earlier ones get
37 # is encountered more than once, the last value remains, all earlier ones get
38 # discarded.
38 # discarded.
39
39
40
40
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
42 # are automatically called when invoked at the command line, even if you don't
42 # are automatically called when invoked at the command line, even if you don't
43 # type parentheses. IPython adds the parentheses for you. For example:
43 # type parentheses. IPython adds the parentheses for you. For example:
44
44
45 #In [1]: str 45
45 #In [1]: str 45
46 #------> str(45)
46 #------> str(45)
47 #Out[1]: '45'
47 #Out[1]: '45'
48
48
49 # IPython reprints your line with '---->' indicating that it added
49 # IPython reprints your line with '---->' indicating that it added
50 # parentheses. While this option is very convenient for interactive use, it
50 # parentheses. While this option is very convenient for interactive use, it
51 # may occasionally cause problems with objects which have side-effects if
51 # may occasionally cause problems with objects which have side-effects if
52 # called unexpectedly.
52 # called unexpectedly.
53
53
54 # The valid values for autocall are:
54 # The valid values for autocall are:
55
55
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
57
57
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
59
59
60 # In this mode, you get:
60 # In this mode, you get:
61
61
62 #In [1]: callable
62 #In [1]: callable
63 #Out[1]: <built-in function callable>
63 #Out[1]: <built-in function callable>
64
64
65 #In [2]: callable 'hello'
65 #In [2]: callable 'hello'
66 #------> callable('hello')
66 #------> callable('hello')
67 #Out[2]: False
67 #Out[2]: False
68
68
69 # 2 -> Active always. Even if no arguments are present, the callable object
69 # 2 -> Active always. Even if no arguments are present, the callable object
70 # is called:
70 # is called:
71
71
72 #In [4]: callable
72 #In [4]: callable
73 #------> callable()
73 #------> callable()
74
74
75 # Note that even with autocall off, you can still use '/' at the start of a
75 # Note that even with autocall off, you can still use '/' at the start of a
76 # line to treat the first argument on the command line as a function and add
76 # line to treat the first argument on the command line as a function and add
77 # parentheses to it:
77 # parentheses to it:
78
78
79 #In [8]: /str 43
79 #In [8]: /str 43
80 #------> str(43)
80 #------> str(43)
81 #Out[8]: '43'
81 #Out[8]: '43'
82
82
83 autocall 1
83 autocall 1
84
84
85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
86 # source code (see the 'editor' variable below), it is possible that you save
86 # source code (see the 'editor' variable below), it is possible that you save
87 # a file with syntax errors in it. If this variable is true, IPython will ask
87 # a file with syntax errors in it. If this variable is true, IPython will ask
88 # you whether to re-open the editor immediately to correct such an error.
88 # you whether to re-open the editor immediately to correct such an error.
89
89
90 autoedit_syntax 0
90 autoedit_syntax 0
91
91
92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
93 # line, while also un-indenting automatically after 'raise' or 'return'.
93 # line, while also un-indenting automatically after 'raise' or 'return'.
94
94
95 # This feature uses the readline library, so it will honor your ~/.inputrc
95 # This feature uses the readline library, so it will honor your ~/.inputrc
96 # configuration (or whatever file your INPUTRC variable points to). Adding
96 # configuration (or whatever file your INPUTRC variable points to). Adding
97 # the following lines to your .inputrc file can make indent/unindenting more
97 # the following lines to your .inputrc file can make indent/unindenting more
98 # convenient (M-i indents, M-u unindents):
98 # convenient (M-i indents, M-u unindents):
99
99
100 # $if Python
100 # $if Python
101 # "\M-i": " "
101 # "\M-i": " "
102 # "\M-u": "\d\d\d\d"
102 # "\M-u": "\d\d\d\d"
103 # $endif
103 # $endif
104
104
105 # The feature is potentially a bit dangerous, because it can cause problems
105 # The feature is potentially a bit dangerous, because it can cause problems
106 # with pasting of indented code (the pasted code gets re-indented on each
106 # with pasting of indented code (the pasted code gets re-indented on each
107 # line). But it's a huge time-saver when working interactively. The magic
107 # line). But it's a huge time-saver when working interactively. The magic
108 # function %autoindent allows you to toggle it on/off at runtime.
108 # function %autoindent allows you to toggle it on/off at runtime.
109
109
110 autoindent 1
110 autoindent 1
111
111
112 # Auto-magic. This gives you access to all the magic functions without having
112 # Auto-magic. This gives you access to all the magic functions without having
113 # to prepend them with an % sign. If you define a variable with the same name
113 # to prepend them with an % sign. If you define a variable with the same name
114 # as a magic function (say who=1), you will need to access the magic function
114 # as a magic function (say who=1), you will need to access the magic function
115 # with % (%who in this example). However, if later you delete your variable
115 # with % (%who in this example). However, if later you delete your variable
116 # (del who), you'll recover the automagic calling form.
116 # (del who), you'll recover the automagic calling form.
117
117
118 # Considering that many magic functions provide a lot of shell-like
118 # Considering that many magic functions provide a lot of shell-like
119 # functionality, automagic gives you something close to a full Python+system
119 # functionality, automagic gives you something close to a full Python+system
120 # shell environment (and you can extend it further if you want).
120 # shell environment (and you can extend it further if you want).
121
121
122 automagic 1
122 automagic 1
123
123
124 # Size of the output cache. After this many entries are stored, the cache will
124 # Size of the output cache. After this many entries are stored, the cache will
125 # get flushed. Depending on the size of your intermediate calculations, you
125 # get flushed. Depending on the size of your intermediate calculations, you
126 # may have memory problems if you make it too big, since keeping things in the
126 # may have memory problems if you make it too big, since keeping things in the
127 # cache prevents Python from reclaiming the memory for old results. Experiment
127 # cache prevents Python from reclaiming the memory for old results. Experiment
128 # with a value that works well for you.
128 # with a value that works well for you.
129
129
130 # If you choose cache_size 0 IPython will revert to python's regular >>>
130 # If you choose cache_size 0 IPython will revert to python's regular >>>
131 # unnumbered prompt. You will still have _, __ and ___ for your last three
131 # unnumbered prompt. You will still have _, __ and ___ for your last three
132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
133 # you are running on a slow machine or with very limited memory, this may
133 # you are running on a slow machine or with very limited memory, this may
134 # help.
134 # help.
135
135
136 cache_size 1000
136 cache_size 1000
137
137
138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
139 # but that's your choice! Classic 1 -> same as IPython -classic.
139 # but that's your choice! Classic 1 -> same as IPython -classic.
140 # Note that this is _not_ the normal python interpreter, it's simply
140 # Note that this is _not_ the normal python interpreter, it's simply
141 # IPython emulating most of the classic interpreter's behavior.
141 # IPython emulating most of the classic interpreter's behavior.
142 classic 0
142 classic 0
143
143
144 # colors - Coloring option for prompts and traceback printouts.
144 # colors - Coloring option for prompts and traceback printouts.
145
145
146 # Currently available schemes: NoColor, Linux, LightBG.
146 # Currently available schemes: NoColor, Linux, LightBG.
147
147
148 # This option allows coloring the prompts and traceback printouts. This
148 # This option allows coloring the prompts and traceback printouts. This
149 # requires a terminal which can properly handle color escape sequences. If you
149 # requires a terminal which can properly handle color escape sequences. If you
150 # are having problems with this, use the NoColor scheme (uses no color escapes
150 # are having problems with this, use the NoColor scheme (uses no color escapes
151 # at all).
151 # at all).
152
152
153 # The Linux option works well in linux console type environments: dark
153 # The Linux option works well in linux console type environments: dark
154 # background with light fonts.
154 # background with light fonts.
155
155
156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
157 # in light background terminals.
157 # in light background terminals.
158
158
159 # keep uncommented only the one you want:
159 # keep uncommented only the one you want:
160 colors Linux
160 colors Linux
161 #colors LightBG
161 #colors LightBG
162 #colors NoColor
162 #colors NoColor
163
163
164 ########################
164 ########################
165 # Note to Windows users
165 # Note to Windows users
166 #
166 #
167 # Color and readline support is avaialble to Windows users via Gary Bishop's
167 # Color and readline support is avaialble to Windows users via Gary Bishop's
168 # readline library. You can find Gary's tools at
168 # readline library. You can find Gary's tools at
169 # http://sourceforge.net/projects/uncpythontools.
169 # http://sourceforge.net/projects/uncpythontools.
170 # Note that his readline module requires in turn the ctypes library, available
170 # Note that his readline module requires in turn the ctypes library, available
171 # at http://starship.python.net/crew/theller/ctypes.
171 # at http://starship.python.net/crew/theller/ctypes.
172 ########################
172 ########################
173
173
174 # color_info: IPython can display information about objects via a set of
174 # color_info: IPython can display information about objects via a set of
175 # functions, and optionally can use colors for this, syntax highlighting
175 # functions, and optionally can use colors for this, syntax highlighting
176 # source code and various other elements. This information is passed through a
176 # source code and various other elements. This information is passed through a
177 # pager (it defaults to 'less' if $PAGER is not set).
177 # pager (it defaults to 'less' if $PAGER is not set).
178
178
179 # If your pager has problems, try to setting it to properly handle escapes
179 # If your pager has problems, try to setting it to properly handle escapes
180 # (see the less manpage for detail), or disable this option. The magic
180 # (see the less manpage for detail), or disable this option. The magic
181 # function %color_info allows you to toggle this interactively for testing.
181 # function %color_info allows you to toggle this interactively for testing.
182
182
183 color_info 1
183 color_info 1
184
184
185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
187 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
187 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
188 # any confirmation.
188 # any confirmation.
189
189
190 confirm_exit 1
190 confirm_exit 1
191
191
192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
193 # still available as dreload() and appears as a builtin.
193 # still available as dreload() and appears as a builtin.
194
194
195 deep_reload 0
195 deep_reload 0
196
196
197 # Which editor to use with the %edit command. If you leave this at 0, IPython
197 # Which editor to use with the %edit command. If you leave this at 0, IPython
198 # will honor your EDITOR environment variable. Since this editor is invoked on
198 # will honor your EDITOR environment variable. Since this editor is invoked on
199 # the fly by ipython and is meant for editing small code snippets, you may
199 # the fly by ipython and is meant for editing small code snippets, you may
200 # want to use a small, lightweight editor here.
200 # want to use a small, lightweight editor here.
201
201
202 # For Emacs users, setting up your Emacs server properly as described in the
202 # For Emacs users, setting up your Emacs server properly as described in the
203 # manual is a good idea. An alternative is to use jed, a very light editor
203 # manual is a good idea. An alternative is to use jed, a very light editor
204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
205
205
206 editor 0
206 editor 0
207
207
208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
209 log 0
209 log 0
210
210
211 # Same as ipython -Logfile YourLogfileName.
211 # Same as ipython -Logfile YourLogfileName.
212 # Don't use with log 1 (use one or the other)
212 # Don't use with log 1 (use one or the other)
213 logfile ''
213 logfile ''
214
214
215 # banner 0 -> same as ipython -nobanner
215 # banner 0 -> same as ipython -nobanner
216 banner 1
216 banner 1
217
217
218 # messages 0 -> same as ipython -nomessages
218 # messages 0 -> same as ipython -nomessages
219 messages 1
219 messages 1
220
220
221 # Automatically call the pdb debugger after every uncaught exception. If you
221 # Automatically call the pdb debugger after every uncaught exception. If you
222 # are used to debugging using pdb, this puts you automatically inside of it
222 # are used to debugging using pdb, this puts you automatically inside of it
223 # after any call (either in IPython or in code called by it) which triggers an
223 # after any call (either in IPython or in code called by it) which triggers an
224 # exception which goes uncaught.
224 # exception which goes uncaught.
225 pdb 0
225 pdb 0
226
226
227 # Enable the pprint module for printing. pprint tends to give a more readable
227 # Enable the pprint module for printing. pprint tends to give a more readable
228 # display (than print) for complex nested data structures.
228 # display (than print) for complex nested data structures.
229 pprint 1
229 pprint 1
230
230
231 # Prompt strings
231 # Prompt strings
232
232
233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
234 # a few additional ones which are IPython-specific. All valid prompt escapes
234 # a few additional ones which are IPython-specific. All valid prompt escapes
235 # are described in detail in the Customization section of the IPython HTML/PDF
235 # are described in detail in the Customization section of the IPython HTML/PDF
236 # manual.
236 # manual.
237
237
238 # Use \# to represent the current prompt number, and quote them to protect
238 # Use \# to represent the current prompt number, and quote them to protect
239 # spaces.
239 # spaces.
240 prompt_in1 'In [\#]: '
240 prompt_in1 'In [\#]: '
241
241
242 # \D is replaced by as many dots as there are digits in the
242 # \D is replaced by as many dots as there are digits in the
243 # current value of \#.
243 # current value of \#.
244 prompt_in2 ' .\D.: '
244 prompt_in2 ' .\D.: '
245
245
246 prompt_out 'Out[\#]: '
246 prompt_out 'Out[\#]: '
247
247
248 # Select whether to left-pad the output prompts to match the length of the
248 # Select whether to left-pad the output prompts to match the length of the
249 # input ones. This allows you for example to use a simple '>' as an output
249 # input ones. This allows you for example to use a simple '>' as an output
250 # prompt, and yet have the output line up with the input. If set to false,
250 # prompt, and yet have the output line up with the input. If set to false,
251 # the output prompts will be unpadded (flush left).
251 # the output prompts will be unpadded (flush left).
252 prompts_pad_left 1
252 prompts_pad_left 1
253
253
254 # quick 1 -> same as ipython -quick
254 # quick 1 -> same as ipython -quick
255 quick 0
255 quick 0
256
256
257 # Use the readline library (1) or not (0). Most users will want this on, but
257 # Use the readline library (1) or not (0). Most users will want this on, but
258 # if you experience strange problems with line management (mainly when using
258 # if you experience strange problems with line management (mainly when using
259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
260 # prevents you from getting command history with the arrow keys, searching and
260 # prevents you from getting command history with the arrow keys, searching and
261 # name completion using TAB.
261 # name completion using TAB.
262
262
263 readline 1
263 readline 1
264
264
265 # Screen Length: number of lines of your screen. This is used to control
265 # Screen Length: number of lines of your screen. This is used to control
266 # printing of very long strings. Strings longer than this number of lines will
266 # printing of very long strings. Strings longer than this number of lines will
267 # be paged with the less command instead of directly printed.
267 # be paged with the less command instead of directly printed.
268
268
269 # The default value for this is 0, which means IPython will auto-detect your
269 # The default value for this is 0, which means IPython will auto-detect your
270 # screen size every time it needs to print. If for some reason this isn't
270 # screen size every time it needs to print. If for some reason this isn't
271 # working well (it needs curses support), specify it yourself. Otherwise don't
271 # working well (it needs curses support), specify it yourself. Otherwise don't
272 # change the default.
272 # change the default.
273
273
274 screen_length 0
274 screen_length 0
275
275
276 # Prompt separators for input and output.
276 # Prompt separators for input and output.
277 # Use \n for newline explicitly, without quotes.
277 # Use \n for newline explicitly, without quotes.
278 # Use 0 (like at the cmd line) to turn off a given separator.
278 # Use 0 (like at the cmd line) to turn off a given separator.
279
279
280 # The structure of prompt printing is:
280 # The structure of prompt printing is:
281 # (SeparateIn)Input....
281 # (SeparateIn)Input....
282 # (SeparateOut)Output...
282 # (SeparateOut)Output...
283 # (SeparateOut2), # that is, no newline is printed after Out2
283 # (SeparateOut2), # that is, no newline is printed after Out2
284 # By choosing these you can organize your output any way you want.
284 # By choosing these you can organize your output any way you want.
285
285
286 separate_in \n
286 separate_in \n
287 separate_out 0
287 separate_out 0
288 separate_out2 0
288 separate_out2 0
289
289
290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
291 # Simply removes all input/output separators, overriding the choices above.
291 # Simply removes all input/output separators, overriding the choices above.
292 nosep 0
292 nosep 0
293
293
294 # Wildcard searches - IPython has a system for searching names using
294 # Wildcard searches - IPython has a system for searching names using
295 # shell-like wildcards; type %psearch? for details. This variables sets
295 # shell-like wildcards; type %psearch? for details. This variables sets
296 # whether by default such searches should be case sensitive or not. You can
296 # whether by default such searches should be case sensitive or not. You can
297 # always override the default at the system command line or the IPython
297 # always override the default at the system command line or the IPython
298 # prompt.
298 # prompt.
299
299
300 wildcards_case_sensitive 1
300 wildcards_case_sensitive 1
301
301
302 # Object information: at what level of detail to display the string form of an
302 # Object information: at what level of detail to display the string form of an
303 # object. If set to 0, ipython will compute the string form of any object X,
303 # object. If set to 0, ipython will compute the string form of any object X,
304 # by calling str(X), when X? is typed. If set to 1, str(X) will only be
304 # by calling str(X), when X? is typed. If set to 1, str(X) will only be
305 # computed when X?? is given, and if set to 2 or higher, it will never be
305 # computed when X?? is given, and if set to 2 or higher, it will never be
306 # computed (there is no X??? level of detail). This is mostly of use to
306 # computed (there is no X??? level of detail). This is mostly of use to
307 # people who frequently manipulate objects whose string representation is
307 # people who frequently manipulate objects whose string representation is
308 # extremely expensive to compute.
308 # extremely expensive to compute.
309
309
310 object_info_string_level 0
310 object_info_string_level 0
311
311
312 # xmode - Exception reporting mode.
312 # xmode - Exception reporting mode.
313
313
314 # Valid modes: Plain, Context and Verbose.
314 # Valid modes: Plain, Context and Verbose.
315
315
316 # Plain: similar to python's normal traceback printing.
316 # Plain: similar to python's normal traceback printing.
317
317
318 # Context: prints 5 lines of context source code around each line in the
318 # Context: prints 5 lines of context source code around each line in the
319 # traceback.
319 # traceback.
320
320
321 # Verbose: similar to Context, but additionally prints the variables currently
321 # Verbose: similar to Context, but additionally prints the variables currently
322 # visible where the exception happened (shortening their strings if too
322 # visible where the exception happened (shortening their strings if too
323 # long). This can potentially be very slow, if you happen to have a huge data
323 # long). This can potentially be very slow, if you happen to have a huge data
324 # structure whose string representation is complex to compute. Your computer
324 # structure whose string representation is complex to compute. Your computer
325 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
325 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
326 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
326 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
327
327
328 #xmode Plain
328 #xmode Plain
329 xmode Context
329 xmode Context
330 #xmode Verbose
330 #xmode Verbose
331
331
332 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
332 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
333 # !cmd) to be used in multi-line input (like for loops). For example, if you
333 # !cmd) to be used in multi-line input (like for loops). For example, if you
334 # have this active, the following is valid in IPython:
334 # have this active, the following is valid in IPython:
335 #
335 #
336 #In [17]: for i in range(3):
336 #In [17]: for i in range(3):
337 # ....: mkdir $i
337 # ....: mkdir $i
338 # ....: !touch $i/hello
338 # ....: !touch $i/hello
339 # ....: ls -l $i
339 # ....: ls -l $i
340
340
341 multi_line_specials 1
341 multi_line_specials 1
342
342
343
344 # System calls: When IPython makes system calls (e.g. via special syntax like
345 # !cmd or !!cmd, or magics like %sc or %sx), it can print the command it is
346 # executing to standard output, prefixed by a header string.
347
348 system_header "IPython system call: "
349
350 system_verbose 1
351
343 # wxversion: request a specific wxPython version (used for -wthread)
352 # wxversion: request a specific wxPython version (used for -wthread)
344
353
345 # Set this to the value of wxPython you want to use, but note that this
354 # Set this to the value of wxPython you want to use, but note that this
346 # feature requires you to have the wxversion Python module to work. If you
355 # feature requires you to have the wxversion Python module to work. If you
347 # don't have the wxversion module (try 'import wxversion' at the prompt to
356 # don't have the wxversion module (try 'import wxversion' at the prompt to
348 # check) or simply want to leave the system to pick up the default, leave this
357 # check) or simply want to leave the system to pick up the default, leave this
349 # variable at 0.
358 # variable at 0.
350
359
351 wxversion 0
360 wxversion 0
352
361
353 #---------------------------------------------------------------------------
362 #---------------------------------------------------------------------------
354 # Section: Readline configuration (readline is not available for MS-Windows)
363 # Section: Readline configuration (readline is not available for MS-Windows)
355
364
356 # This is done via the following options:
365 # This is done via the following options:
357
366
358 # (i) readline_parse_and_bind: this option can appear as many times as you
367 # (i) readline_parse_and_bind: this option can appear as many times as you
359 # want, each time defining a string to be executed via a
368 # want, each time defining a string to be executed via a
360 # readline.parse_and_bind() command. The syntax for valid commands of this
369 # readline.parse_and_bind() command. The syntax for valid commands of this
361 # kind can be found by reading the documentation for the GNU readline library,
370 # kind can be found by reading the documentation for the GNU readline library,
362 # as these commands are of the kind which readline accepts in its
371 # as these commands are of the kind which readline accepts in its
363 # configuration file.
372 # configuration file.
364
373
365 # The TAB key can be used to complete names at the command line in one of two
374 # The TAB key can be used to complete names at the command line in one of two
366 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
375 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
367 # completes as much as possible while 'menu-complete' cycles through all
376 # completes as much as possible while 'menu-complete' cycles through all
368 # possible completions. Leave the one you prefer uncommented.
377 # possible completions. Leave the one you prefer uncommented.
369
378
370 readline_parse_and_bind tab: complete
379 readline_parse_and_bind tab: complete
371 #readline_parse_and_bind tab: menu-complete
380 #readline_parse_and_bind tab: menu-complete
372
381
373 # This binds Control-l to printing the list of all possible completions when
382 # This binds Control-l to printing the list of all possible completions when
374 # there is more than one (what 'complete' does when hitting TAB twice, or at
383 # there is more than one (what 'complete' does when hitting TAB twice, or at
375 # the first TAB if show-all-if-ambiguous is on)
384 # the first TAB if show-all-if-ambiguous is on)
376 readline_parse_and_bind "\C-l": possible-completions
385 readline_parse_and_bind "\C-l": possible-completions
377
386
378 # This forces readline to automatically print the above list when tab
387 # This forces readline to automatically print the above list when tab
379 # completion is set to 'complete'. You can still get this list manually by
388 # completion is set to 'complete'. You can still get this list manually by
380 # using the key bound to 'possible-completions' (Control-l by default) or by
389 # using the key bound to 'possible-completions' (Control-l by default) or by
381 # hitting TAB twice. Turning this on makes the printing happen at the first
390 # hitting TAB twice. Turning this on makes the printing happen at the first
382 # TAB.
391 # TAB.
383 readline_parse_and_bind set show-all-if-ambiguous on
392 readline_parse_and_bind set show-all-if-ambiguous on
384
393
385 # If you have TAB set to complete names, you can rebind any key (Control-o by
394 # If you have TAB set to complete names, you can rebind any key (Control-o by
386 # default) to insert a true TAB character.
395 # default) to insert a true TAB character.
387 readline_parse_and_bind "\C-o": tab-insert
396 readline_parse_and_bind "\C-o": tab-insert
388
397
389 # These commands allow you to indent/unindent easily, with the 4-space
398 # These commands allow you to indent/unindent easily, with the 4-space
390 # convention of the Python coding standards. Since IPython's internal
399 # convention of the Python coding standards. Since IPython's internal
391 # auto-indent system also uses 4 spaces, you should not change the number of
400 # auto-indent system also uses 4 spaces, you should not change the number of
392 # spaces in the code below.
401 # spaces in the code below.
393 readline_parse_and_bind "\M-i": " "
402 readline_parse_and_bind "\M-i": " "
394 readline_parse_and_bind "\M-o": "\d\d\d\d"
403 readline_parse_and_bind "\M-o": "\d\d\d\d"
395 readline_parse_and_bind "\M-I": "\d\d\d\d"
404 readline_parse_and_bind "\M-I": "\d\d\d\d"
396
405
397 # Bindings for incremental searches in the history. These searches use the
406 # Bindings for incremental searches in the history. These searches use the
398 # string typed so far on the command line and search anything in the previous
407 # string typed so far on the command line and search anything in the previous
399 # input history containing them.
408 # input history containing them.
400 readline_parse_and_bind "\C-r": reverse-search-history
409 readline_parse_and_bind "\C-r": reverse-search-history
401 readline_parse_and_bind "\C-s": forward-search-history
410 readline_parse_and_bind "\C-s": forward-search-history
402
411
403 # Bindings for completing the current line in the history of previous
412 # Bindings for completing the current line in the history of previous
404 # commands. This allows you to recall any previous command by typing its first
413 # commands. This allows you to recall any previous command by typing its first
405 # few letters and hitting Control-p, bypassing all intermediate commands which
414 # few letters and hitting Control-p, bypassing all intermediate commands which
406 # may be in the history (much faster than hitting up-arrow 50 times!)
415 # may be in the history (much faster than hitting up-arrow 50 times!)
407 readline_parse_and_bind "\C-p": history-search-backward
416 readline_parse_and_bind "\C-p": history-search-backward
408 readline_parse_and_bind "\C-n": history-search-forward
417 readline_parse_and_bind "\C-n": history-search-forward
409
418
410 # I also like to have the same functionality on the plain arrow keys. If you'd
419 # I also like to have the same functionality on the plain arrow keys. If you'd
411 # rather have the arrows use all the history (and not just match what you've
420 # rather have the arrows use all the history (and not just match what you've
412 # typed so far), comment out or delete the next two lines.
421 # typed so far), comment out or delete the next two lines.
413 readline_parse_and_bind "\e[A": history-search-backward
422 readline_parse_and_bind "\e[A": history-search-backward
414 readline_parse_and_bind "\e[B": history-search-forward
423 readline_parse_and_bind "\e[B": history-search-forward
415
424
416 # These are typically on by default under *nix, but not win32.
425 # These are typically on by default under *nix, but not win32.
417 readline_parse_and_bind "\C-k": kill-line
426 readline_parse_and_bind "\C-k": kill-line
418 readline_parse_and_bind "\C-u": unix-line-discard
427 readline_parse_and_bind "\C-u": unix-line-discard
419
428
420 # (ii) readline_remove_delims: a string of characters to be removed from the
429 # (ii) readline_remove_delims: a string of characters to be removed from the
421 # default word-delimiters list used by readline, so that completions may be
430 # default word-delimiters list used by readline, so that completions may be
422 # performed on strings which contain them.
431 # performed on strings which contain them.
423
432
424 readline_remove_delims -/~
433 readline_remove_delims -/~
425
434
426 # (iii) readline_merge_completions: whether to merge the result of all
435 # (iii) readline_merge_completions: whether to merge the result of all
427 # possible completions or not. If true, IPython will complete filenames,
436 # possible completions or not. If true, IPython will complete filenames,
428 # python names and aliases and return all possible completions. If you set it
437 # python names and aliases and return all possible completions. If you set it
429 # to false, each completer is used at a time, and only if it doesn't return
438 # to false, each completer is used at a time, and only if it doesn't return
430 # any completions is the next one used.
439 # any completions is the next one used.
431
440
432 # The default order is: [python_matches, file_matches, alias_matches]
441 # The default order is: [python_matches, file_matches, alias_matches]
433
442
434 readline_merge_completions 1
443 readline_merge_completions 1
435
444
436 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
445 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
437 # will complete all attributes of an object, including all the special methods
446 # will complete all attributes of an object, including all the special methods
438 # whose names start with single or double underscores (like __getitem__ or
447 # whose names start with single or double underscores (like __getitem__ or
439 # __class__).
448 # __class__).
440
449
441 # This variable allows you to control this completion behavior:
450 # This variable allows you to control this completion behavior:
442
451
443 # readline_omit__names 1 -> completion will omit showing any names starting
452 # readline_omit__names 1 -> completion will omit showing any names starting
444 # with two __, but it will still show names starting with one _.
453 # with two __, but it will still show names starting with one _.
445
454
446 # readline_omit__names 2 -> completion will omit all names beginning with one
455 # readline_omit__names 2 -> completion will omit all names beginning with one
447 # _ (which obviously means filtering out the double __ ones).
456 # _ (which obviously means filtering out the double __ ones).
448
457
449 # Even when this option is set, you can still see those names by explicitly
458 # Even when this option is set, you can still see those names by explicitly
450 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
459 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
451 # complete attribute names starting with '_'.
460 # complete attribute names starting with '_'.
452
461
453 # This option is off by default so that new users see all attributes of any
462 # This option is off by default so that new users see all attributes of any
454 # objects they are dealing with.
463 # objects they are dealing with.
455
464
456 readline_omit__names 0
465 readline_omit__names 0
457
466
458 #---------------------------------------------------------------------------
467 #---------------------------------------------------------------------------
459 # Section: modules to be loaded with 'import ...'
468 # Section: modules to be loaded with 'import ...'
460
469
461 # List, separated by spaces, the names of the modules you want to import
470 # List, separated by spaces, the names of the modules you want to import
462
471
463 # Example:
472 # Example:
464 # import_mod sys os
473 # import_mod sys os
465 # will produce internally the statements
474 # will produce internally the statements
466 # import sys
475 # import sys
467 # import os
476 # import os
468
477
469 # Each import is executed in its own try/except block, so if one module
478 # Each import is executed in its own try/except block, so if one module
470 # fails to load the others will still be ok.
479 # fails to load the others will still be ok.
471
480
472 import_mod
481 import_mod
473
482
474 #---------------------------------------------------------------------------
483 #---------------------------------------------------------------------------
475 # Section: modules to import some functions from: 'from ... import ...'
484 # Section: modules to import some functions from: 'from ... import ...'
476
485
477 # List, one per line, the modules for which you want only to import some
486 # List, one per line, the modules for which you want only to import some
478 # functions. Give the module name first and then the name of functions to be
487 # functions. Give the module name first and then the name of functions to be
479 # imported from that module.
488 # imported from that module.
480
489
481 # Example:
490 # Example:
482
491
483 # import_some IPython.genutils timing timings
492 # import_some IPython.genutils timing timings
484 # will produce internally the statement
493 # will produce internally the statement
485 # from IPython.genutils import timing, timings
494 # from IPython.genutils import timing, timings
486
495
487 # timing() and timings() are two IPython utilities for timing the execution of
496 # timing() and timings() are two IPython utilities for timing the execution of
488 # your own functions, which you may find useful. Just commment out the above
497 # your own functions, which you may find useful. Just commment out the above
489 # line if you want to test them.
498 # line if you want to test them.
490
499
491 # If you have more than one modules_some line, each gets its own try/except
500 # If you have more than one modules_some line, each gets its own try/except
492 # block (like modules, see above).
501 # block (like modules, see above).
493
502
494 import_some
503 import_some
495
504
496 #---------------------------------------------------------------------------
505 #---------------------------------------------------------------------------
497 # Section: modules to import all from : 'from ... import *'
506 # Section: modules to import all from : 'from ... import *'
498
507
499 # List (same syntax as import_mod above) those modules for which you want to
508 # List (same syntax as import_mod above) those modules for which you want to
500 # import all functions. Remember, this is a potentially dangerous thing to do,
509 # import all functions. Remember, this is a potentially dangerous thing to do,
501 # since it is very easy to overwrite names of things you need. Use with
510 # since it is very easy to overwrite names of things you need. Use with
502 # caution.
511 # caution.
503
512
504 # Example:
513 # Example:
505 # import_all sys os
514 # import_all sys os
506 # will produce internally the statements
515 # will produce internally the statements
507 # from sys import *
516 # from sys import *
508 # from os import *
517 # from os import *
509
518
510 # As before, each will be called in a separate try/except block.
519 # As before, each will be called in a separate try/except block.
511
520
512 import_all
521 import_all
513
522
514 #---------------------------------------------------------------------------
523 #---------------------------------------------------------------------------
515 # Section: Python code to execute.
524 # Section: Python code to execute.
516
525
517 # Put here code to be explicitly executed (keep it simple!)
526 # Put here code to be explicitly executed (keep it simple!)
518 # Put one line of python code per line. All whitespace is removed (this is a
527 # Put one line of python code per line. All whitespace is removed (this is a
519 # feature, not a bug), so don't get fancy building loops here.
528 # feature, not a bug), so don't get fancy building loops here.
520 # This is just for quick convenient creation of things you want available.
529 # This is just for quick convenient creation of things you want available.
521
530
522 # Example:
531 # Example:
523 # execute x = 1
532 # execute x = 1
524 # execute print 'hello world'; y = z = 'a'
533 # execute print 'hello world'; y = z = 'a'
525 # will produce internally
534 # will produce internally
526 # x = 1
535 # x = 1
527 # print 'hello world'; y = z = 'a'
536 # print 'hello world'; y = z = 'a'
528 # and each *line* (not each statement, we don't do python syntax parsing) is
537 # and each *line* (not each statement, we don't do python syntax parsing) is
529 # executed in its own try/except block.
538 # executed in its own try/except block.
530
539
531 execute
540 execute
532
541
533 # Note for the adventurous: you can use this to define your own names for the
542 # Note for the adventurous: you can use this to define your own names for the
534 # magic functions, by playing some namespace tricks:
543 # magic functions, by playing some namespace tricks:
535
544
536 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
545 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
537
546
538 # defines %pf as a new name for %profile.
547 # defines %pf as a new name for %profile.
539
548
540 #---------------------------------------------------------------------------
549 #---------------------------------------------------------------------------
541 # Section: Pyhton files to load and execute.
550 # Section: Pyhton files to load and execute.
542
551
543 # Put here the full names of files you want executed with execfile(file). If
552 # Put here the full names of files you want executed with execfile(file). If
544 # you want complicated initialization, just write whatever you want in a
553 # you want complicated initialization, just write whatever you want in a
545 # regular python file and load it from here.
554 # regular python file and load it from here.
546
555
547 # Filenames defined here (which *must* include the extension) are searched for
556 # Filenames defined here (which *must* include the extension) are searched for
548 # through all of sys.path. Since IPython adds your .ipython directory to
557 # through all of sys.path. Since IPython adds your .ipython directory to
549 # sys.path, they can also be placed in your .ipython dir and will be
558 # sys.path, they can also be placed in your .ipython dir and will be
550 # found. Otherwise (if you want to execute things not in .ipyton nor in
559 # found. Otherwise (if you want to execute things not in .ipyton nor in
551 # sys.path) give a full path (you can use ~, it gets expanded)
560 # sys.path) give a full path (you can use ~, it gets expanded)
552
561
553 # Example:
562 # Example:
554 # execfile file1.py ~/file2.py
563 # execfile file1.py ~/file2.py
555 # will generate
564 # will generate
556 # execfile('file1.py')
565 # execfile('file1.py')
557 # execfile('_path_to_your_home/file2.py')
566 # execfile('_path_to_your_home/file2.py')
558
567
559 # As before, each file gets its own try/except block.
568 # As before, each file gets its own try/except block.
560
569
561 execfile
570 execfile
562
571
563 # If you are feeling adventurous, you can even add functionality to IPython
572 # If you are feeling adventurous, you can even add functionality to IPython
564 # through here. IPython works through a global variable called __ip which
573 # through here. IPython works through a global variable called __ip which
565 # exists at the time when these files are read. If you know what you are doing
574 # exists at the time when these files are read. If you know what you are doing
566 # (read the source) you can add functions to __ip in files loaded here.
575 # (read the source) you can add functions to __ip in files loaded here.
567
576
568 # The file example-magic.py contains a simple but correct example. Try it:
577 # The file example-magic.py contains a simple but correct example. Try it:
569
578
570 # execfile example-magic.py
579 # execfile example-magic.py
571
580
572 # Look at the examples in IPython/iplib.py for more details on how these magic
581 # Look at the examples in IPython/iplib.py for more details on how these magic
573 # functions need to process their arguments.
582 # functions need to process their arguments.
574
583
575 #---------------------------------------------------------------------------
584 #---------------------------------------------------------------------------
576 # Section: aliases for system shell commands
585 # Section: aliases for system shell commands
577
586
578 # Here you can define your own names for system commands. The syntax is
587 # Here you can define your own names for system commands. The syntax is
579 # similar to that of the builtin %alias function:
588 # similar to that of the builtin %alias function:
580
589
581 # alias alias_name command_string
590 # alias alias_name command_string
582
591
583 # The resulting aliases are auto-generated magic functions (hence usable as
592 # The resulting aliases are auto-generated magic functions (hence usable as
584 # %alias_name)
593 # %alias_name)
585
594
586 # For example:
595 # For example:
587
596
588 # alias myls ls -la
597 # alias myls ls -la
589
598
590 # will define 'myls' as an alias for executing the system command 'ls -la'.
599 # will define 'myls' as an alias for executing the system command 'ls -la'.
591 # This allows you to customize IPython's environment to have the same aliases
600 # This allows you to customize IPython's environment to have the same aliases
592 # you are accustomed to from your own shell.
601 # you are accustomed to from your own shell.
593
602
594 # You can also define aliases with parameters using %s specifiers (one per
603 # You can also define aliases with parameters using %s specifiers (one per
595 # parameter):
604 # parameter):
596
605
597 # alias parts echo first %s second %s
606 # alias parts echo first %s second %s
598
607
599 # will give you in IPython:
608 # will give you in IPython:
600 # >>> %parts A B
609 # >>> %parts A B
601 # first A second B
610 # first A second B
602
611
603 # Use one 'alias' statement per alias you wish to define.
612 # Use one 'alias' statement per alias you wish to define.
604
613
605 # alias
614 # alias
606
615
607 #************************* end of file <ipythonrc> ************************
616 #************************* end of file <ipythonrc> ************************
@@ -1,2489 +1,2515 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.3 or newer.
5 Requires Python 2.3 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 1878 2006-11-03 23:00:22Z fptest $
9 $Id: iplib.py 1879 2006-11-04 00:34:34Z fptest $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import StringIO
40 import StringIO
41 import bdb
41 import bdb
42 import cPickle as pickle
42 import cPickle as pickle
43 import codeop
43 import codeop
44 import exceptions
44 import exceptions
45 import glob
45 import glob
46 import inspect
46 import inspect
47 import keyword
47 import keyword
48 import new
48 import new
49 import os
49 import os
50 import pydoc
50 import pydoc
51 import re
51 import re
52 import shutil
52 import shutil
53 import string
53 import string
54 import sys
54 import sys
55 import tempfile
55 import tempfile
56 import traceback
56 import traceback
57 import types
57 import types
58 import pickleshare
58 import pickleshare
59 from sets import Set
59 from sets import Set
60 from pprint import pprint, pformat
60 from pprint import pprint, pformat
61
61
62 # IPython's own modules
62 # IPython's own modules
63 import IPython
63 import IPython
64 from IPython import OInspect,PyColorize,ultraTB
64 from IPython import OInspect,PyColorize,ultraTB
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.FakeModule import FakeModule
66 from IPython.FakeModule import FakeModule
67 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
67 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Logger import Logger
68 from IPython.Logger import Logger
69 from IPython.Magic import Magic
69 from IPython.Magic import Magic
70 from IPython.Prompts import CachedOutput
70 from IPython.Prompts import CachedOutput
71 from IPython.ipstruct import Struct
71 from IPython.ipstruct import Struct
72 from IPython.background_jobs import BackgroundJobManager
72 from IPython.background_jobs import BackgroundJobManager
73 from IPython.usage import cmd_line_usage,interactive_usage
73 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.genutils import *
74 from IPython.genutils import *
75 from IPython.strdispatch import StrDispatch
75 from IPython.strdispatch import StrDispatch
76 import IPython.ipapi
76 import IPython.ipapi
77
77
78 # Globals
78 # Globals
79
79
80 # store the builtin raw_input globally, and use this always, in case user code
80 # store the builtin raw_input globally, and use this always, in case user code
81 # overwrites it (like wx.py.PyShell does)
81 # overwrites it (like wx.py.PyShell does)
82 raw_input_original = raw_input
82 raw_input_original = raw_input
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87
87
88 #****************************************************************************
88 #****************************************************************************
89 # Some utility function definitions
89 # Some utility function definitions
90
90
91 ini_spaces_re = re.compile(r'^(\s+)')
91 ini_spaces_re = re.compile(r'^(\s+)')
92
92
93 def num_ini_spaces(strng):
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
94 """Return the number of initial spaces in a string"""
95
95
96 ini_spaces = ini_spaces_re.match(strng)
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
97 if ini_spaces:
98 return ini_spaces.end()
98 return ini_spaces.end()
99 else:
99 else:
100 return 0
100 return 0
101
101
102 def softspace(file, newvalue):
102 def softspace(file, newvalue):
103 """Copied from code.py, to remove the dependency"""
103 """Copied from code.py, to remove the dependency"""
104
104
105 oldvalue = 0
105 oldvalue = 0
106 try:
106 try:
107 oldvalue = file.softspace
107 oldvalue = file.softspace
108 except AttributeError:
108 except AttributeError:
109 pass
109 pass
110 try:
110 try:
111 file.softspace = newvalue
111 file.softspace = newvalue
112 except (AttributeError, TypeError):
112 except (AttributeError, TypeError):
113 # "attribute-less object" or "read-only attributes"
113 # "attribute-less object" or "read-only attributes"
114 pass
114 pass
115 return oldvalue
115 return oldvalue
116
116
117
117
118 #****************************************************************************
118 #****************************************************************************
119 # Local use exceptions
119 # Local use exceptions
120 class SpaceInInput(exceptions.Exception): pass
120 class SpaceInInput(exceptions.Exception): pass
121
121
122
122
123 #****************************************************************************
123 #****************************************************************************
124 # Local use classes
124 # Local use classes
125 class Bunch: pass
125 class Bunch: pass
126
126
127 class Undefined: pass
127 class Undefined: pass
128
128
129 class Quitter(object):
129 class Quitter(object):
130 """Simple class to handle exit, similar to Python 2.5's.
130 """Simple class to handle exit, similar to Python 2.5's.
131
131
132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
133 doesn't do (obviously, since it doesn't know about ipython)."""
133 doesn't do (obviously, since it doesn't know about ipython)."""
134
134
135 def __init__(self,shell,name):
135 def __init__(self,shell,name):
136 self.shell = shell
136 self.shell = shell
137 self.name = name
137 self.name = name
138
138
139 def __repr__(self):
139 def __repr__(self):
140 return 'Type %s() to exit.' % self.name
140 return 'Type %s() to exit.' % self.name
141 __str__ = __repr__
141 __str__ = __repr__
142
142
143 def __call__(self):
143 def __call__(self):
144 self.shell.exit()
144 self.shell.exit()
145
145
146 class InputList(list):
146 class InputList(list):
147 """Class to store user input.
147 """Class to store user input.
148
148
149 It's basically a list, but slices return a string instead of a list, thus
149 It's basically a list, but slices return a string instead of a list, thus
150 allowing things like (assuming 'In' is an instance):
150 allowing things like (assuming 'In' is an instance):
151
151
152 exec In[4:7]
152 exec In[4:7]
153
153
154 or
154 or
155
155
156 exec In[5:9] + In[14] + In[21:25]"""
156 exec In[5:9] + In[14] + In[21:25]"""
157
157
158 def __getslice__(self,i,j):
158 def __getslice__(self,i,j):
159 return ''.join(list.__getslice__(self,i,j))
159 return ''.join(list.__getslice__(self,i,j))
160
160
161 class SyntaxTB(ultraTB.ListTB):
161 class SyntaxTB(ultraTB.ListTB):
162 """Extension which holds some state: the last exception value"""
162 """Extension which holds some state: the last exception value"""
163
163
164 def __init__(self,color_scheme = 'NoColor'):
164 def __init__(self,color_scheme = 'NoColor'):
165 ultraTB.ListTB.__init__(self,color_scheme)
165 ultraTB.ListTB.__init__(self,color_scheme)
166 self.last_syntax_error = None
166 self.last_syntax_error = None
167
167
168 def __call__(self, etype, value, elist):
168 def __call__(self, etype, value, elist):
169 self.last_syntax_error = value
169 self.last_syntax_error = value
170 ultraTB.ListTB.__call__(self,etype,value,elist)
170 ultraTB.ListTB.__call__(self,etype,value,elist)
171
171
172 def clear_err_state(self):
172 def clear_err_state(self):
173 """Return the current error state and clear it"""
173 """Return the current error state and clear it"""
174 e = self.last_syntax_error
174 e = self.last_syntax_error
175 self.last_syntax_error = None
175 self.last_syntax_error = None
176 return e
176 return e
177
177
178 #****************************************************************************
178 #****************************************************************************
179 # Main IPython class
179 # Main IPython class
180
180
181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
182 # until a full rewrite is made. I've cleaned all cross-class uses of
182 # until a full rewrite is made. I've cleaned all cross-class uses of
183 # attributes and methods, but too much user code out there relies on the
183 # attributes and methods, but too much user code out there relies on the
184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
185 #
185 #
186 # But at least now, all the pieces have been separated and we could, in
186 # But at least now, all the pieces have been separated and we could, in
187 # principle, stop using the mixin. This will ease the transition to the
187 # principle, stop using the mixin. This will ease the transition to the
188 # chainsaw branch.
188 # chainsaw branch.
189
189
190 # For reference, the following is the list of 'self.foo' uses in the Magic
190 # For reference, the following is the list of 'self.foo' uses in the Magic
191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
192 # class, to prevent clashes.
192 # class, to prevent clashes.
193
193
194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
197 # 'self.value']
197 # 'self.value']
198
198
199 class InteractiveShell(object,Magic):
199 class InteractiveShell(object,Magic):
200 """An enhanced console for Python."""
200 """An enhanced console for Python."""
201
201
202 # class attribute to indicate whether the class supports threads or not.
202 # class attribute to indicate whether the class supports threads or not.
203 # Subclasses with thread support should override this as needed.
203 # Subclasses with thread support should override this as needed.
204 isthreaded = False
204 isthreaded = False
205
205
206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
207 user_ns = None,user_global_ns=None,banner2='',
207 user_ns = None,user_global_ns=None,banner2='',
208 custom_exceptions=((),None),embedded=False):
208 custom_exceptions=((),None),embedded=False):
209
209
210 # log system
210 # log system
211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
212
212
213 # some minimal strict typechecks. For some core data structures, I
213 # some minimal strict typechecks. For some core data structures, I
214 # want actual basic python types, not just anything that looks like
214 # want actual basic python types, not just anything that looks like
215 # one. This is especially true for namespaces.
215 # one. This is especially true for namespaces.
216 for ns in (user_ns,user_global_ns):
216 for ns in (user_ns,user_global_ns):
217 if ns is not None and type(ns) != types.DictType:
217 if ns is not None and type(ns) != types.DictType:
218 raise TypeError,'namespace must be a dictionary'
218 raise TypeError,'namespace must be a dictionary'
219
219
220 # Job manager (for jobs run as background threads)
220 # Job manager (for jobs run as background threads)
221 self.jobs = BackgroundJobManager()
221 self.jobs = BackgroundJobManager()
222
222
223 # Store the actual shell's name
223 # Store the actual shell's name
224 self.name = name
224 self.name = name
225
225
226 # We need to know whether the instance is meant for embedding, since
226 # We need to know whether the instance is meant for embedding, since
227 # global/local namespaces need to be handled differently in that case
227 # global/local namespaces need to be handled differently in that case
228 self.embedded = embedded
228 self.embedded = embedded
229
229
230 # command compiler
230 # command compiler
231 self.compile = codeop.CommandCompiler()
231 self.compile = codeop.CommandCompiler()
232
232
233 # User input buffer
233 # User input buffer
234 self.buffer = []
234 self.buffer = []
235
235
236 # Default name given in compilation of code
236 # Default name given in compilation of code
237 self.filename = '<ipython console>'
237 self.filename = '<ipython console>'
238
238
239 # Install our own quitter instead of the builtins. For python2.3-2.4,
239 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 # this brings in behavior like 2.5, and for 2.5 it's identical.
240 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 __builtin__.exit = Quitter(self,'exit')
241 __builtin__.exit = Quitter(self,'exit')
242 __builtin__.quit = Quitter(self,'quit')
242 __builtin__.quit = Quitter(self,'quit')
243
243
244 # Make an empty namespace, which extension writers can rely on both
244 # Make an empty namespace, which extension writers can rely on both
245 # existing and NEVER being used by ipython itself. This gives them a
245 # existing and NEVER being used by ipython itself. This gives them a
246 # convenient location for storing additional information and state
246 # convenient location for storing additional information and state
247 # their extensions may require, without fear of collisions with other
247 # their extensions may require, without fear of collisions with other
248 # ipython names that may develop later.
248 # ipython names that may develop later.
249 self.meta = Struct()
249 self.meta = Struct()
250
250
251 # Create the namespace where the user will operate. user_ns is
251 # Create the namespace where the user will operate. user_ns is
252 # normally the only one used, and it is passed to the exec calls as
252 # normally the only one used, and it is passed to the exec calls as
253 # the locals argument. But we do carry a user_global_ns namespace
253 # the locals argument. But we do carry a user_global_ns namespace
254 # given as the exec 'globals' argument, This is useful in embedding
254 # given as the exec 'globals' argument, This is useful in embedding
255 # situations where the ipython shell opens in a context where the
255 # situations where the ipython shell opens in a context where the
256 # distinction between locals and globals is meaningful.
256 # distinction between locals and globals is meaningful.
257
257
258 # FIXME. For some strange reason, __builtins__ is showing up at user
258 # FIXME. For some strange reason, __builtins__ is showing up at user
259 # level as a dict instead of a module. This is a manual fix, but I
259 # level as a dict instead of a module. This is a manual fix, but I
260 # should really track down where the problem is coming from. Alex
260 # should really track down where the problem is coming from. Alex
261 # Schmolck reported this problem first.
261 # Schmolck reported this problem first.
262
262
263 # A useful post by Alex Martelli on this topic:
263 # A useful post by Alex Martelli on this topic:
264 # Re: inconsistent value from __builtins__
264 # Re: inconsistent value from __builtins__
265 # Von: Alex Martelli <aleaxit@yahoo.com>
265 # Von: Alex Martelli <aleaxit@yahoo.com>
266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
267 # Gruppen: comp.lang.python
267 # Gruppen: comp.lang.python
268
268
269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
271 # > <type 'dict'>
271 # > <type 'dict'>
272 # > >>> print type(__builtins__)
272 # > >>> print type(__builtins__)
273 # > <type 'module'>
273 # > <type 'module'>
274 # > Is this difference in return value intentional?
274 # > Is this difference in return value intentional?
275
275
276 # Well, it's documented that '__builtins__' can be either a dictionary
276 # Well, it's documented that '__builtins__' can be either a dictionary
277 # or a module, and it's been that way for a long time. Whether it's
277 # or a module, and it's been that way for a long time. Whether it's
278 # intentional (or sensible), I don't know. In any case, the idea is
278 # intentional (or sensible), I don't know. In any case, the idea is
279 # that if you need to access the built-in namespace directly, you
279 # that if you need to access the built-in namespace directly, you
280 # should start with "import __builtin__" (note, no 's') which will
280 # should start with "import __builtin__" (note, no 's') which will
281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
282
282
283 # These routines return properly built dicts as needed by the rest of
283 # These routines return properly built dicts as needed by the rest of
284 # the code, and can also be used by extension writers to generate
284 # the code, and can also be used by extension writers to generate
285 # properly initialized namespaces.
285 # properly initialized namespaces.
286 user_ns = IPython.ipapi.make_user_ns(user_ns)
286 user_ns = IPython.ipapi.make_user_ns(user_ns)
287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
288
288
289 # Assign namespaces
289 # Assign namespaces
290 # This is the namespace where all normal user variables live
290 # This is the namespace where all normal user variables live
291 self.user_ns = user_ns
291 self.user_ns = user_ns
292 # Embedded instances require a separate namespace for globals.
292 # Embedded instances require a separate namespace for globals.
293 # Normally this one is unused by non-embedded instances.
293 # Normally this one is unused by non-embedded instances.
294 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
295 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
296 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
297 self.internal_ns = {}
297 self.internal_ns = {}
298
298
299 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
300 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
301 # of positional arguments of the alias.
301 # of positional arguments of the alias.
302 self.alias_table = {}
302 self.alias_table = {}
303
303
304 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
305 # introspection facilities can search easily.
305 # introspection facilities can search easily.
306 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
307 'user_global':user_global_ns,
307 'user_global':user_global_ns,
308 'alias':self.alias_table,
308 'alias':self.alias_table,
309 'internal':self.internal_ns,
309 'internal':self.internal_ns,
310 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
311 }
311 }
312
312
313 # The user namespace MUST have a pointer to the shell itself.
313 # The user namespace MUST have a pointer to the shell itself.
314 self.user_ns[name] = self
314 self.user_ns[name] = self
315
315
316 # We need to insert into sys.modules something that looks like a
316 # We need to insert into sys.modules something that looks like a
317 # module but which accesses the IPython namespace, for shelve and
317 # module but which accesses the IPython namespace, for shelve and
318 # pickle to work interactively. Normally they rely on getting
318 # pickle to work interactively. Normally they rely on getting
319 # everything out of __main__, but for embedding purposes each IPython
319 # everything out of __main__, but for embedding purposes each IPython
320 # instance has its own private namespace, so we can't go shoving
320 # instance has its own private namespace, so we can't go shoving
321 # everything into __main__.
321 # everything into __main__.
322
322
323 # note, however, that we should only do this for non-embedded
323 # note, however, that we should only do this for non-embedded
324 # ipythons, which really mimic the __main__.__dict__ with their own
324 # ipythons, which really mimic the __main__.__dict__ with their own
325 # namespace. Embedded instances, on the other hand, should not do
325 # namespace. Embedded instances, on the other hand, should not do
326 # this because they need to manage the user local/global namespaces
326 # this because they need to manage the user local/global namespaces
327 # only, but they live within a 'normal' __main__ (meaning, they
327 # only, but they live within a 'normal' __main__ (meaning, they
328 # shouldn't overtake the execution environment of the script they're
328 # shouldn't overtake the execution environment of the script they're
329 # embedded in).
329 # embedded in).
330
330
331 if not embedded:
331 if not embedded:
332 try:
332 try:
333 main_name = self.user_ns['__name__']
333 main_name = self.user_ns['__name__']
334 except KeyError:
334 except KeyError:
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 else:
336 else:
337 #print "pickle hack in place" # dbg
337 #print "pickle hack in place" # dbg
338 #print 'main_name:',main_name # dbg
338 #print 'main_name:',main_name # dbg
339 sys.modules[main_name] = FakeModule(self.user_ns)
339 sys.modules[main_name] = FakeModule(self.user_ns)
340
340
341 # List of input with multi-line handling.
341 # List of input with multi-line handling.
342 # Fill its zero entry, user counter starts at 1
342 # Fill its zero entry, user counter starts at 1
343 self.input_hist = InputList(['\n'])
343 self.input_hist = InputList(['\n'])
344 # This one will hold the 'raw' input history, without any
344 # This one will hold the 'raw' input history, without any
345 # pre-processing. This will allow users to retrieve the input just as
345 # pre-processing. This will allow users to retrieve the input just as
346 # it was exactly typed in by the user, with %hist -r.
346 # it was exactly typed in by the user, with %hist -r.
347 self.input_hist_raw = InputList(['\n'])
347 self.input_hist_raw = InputList(['\n'])
348
348
349 # list of visited directories
349 # list of visited directories
350 try:
350 try:
351 self.dir_hist = [os.getcwd()]
351 self.dir_hist = [os.getcwd()]
352 except IOError, e:
352 except IOError, e:
353 self.dir_hist = []
353 self.dir_hist = []
354
354
355 # dict of output history
355 # dict of output history
356 self.output_hist = {}
356 self.output_hist = {}
357
357
358 # dict of things NOT to alias (keywords, builtins and some magics)
358 # dict of things NOT to alias (keywords, builtins and some magics)
359 no_alias = {}
359 no_alias = {}
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
361 for key in keyword.kwlist + no_alias_magics:
361 for key in keyword.kwlist + no_alias_magics:
362 no_alias[key] = 1
362 no_alias[key] = 1
363 no_alias.update(__builtin__.__dict__)
363 no_alias.update(__builtin__.__dict__)
364 self.no_alias = no_alias
364 self.no_alias = no_alias
365
365
366 # make global variables for user access to these
366 # make global variables for user access to these
367 self.user_ns['_ih'] = self.input_hist
367 self.user_ns['_ih'] = self.input_hist
368 self.user_ns['_oh'] = self.output_hist
368 self.user_ns['_oh'] = self.output_hist
369 self.user_ns['_dh'] = self.dir_hist
369 self.user_ns['_dh'] = self.dir_hist
370
370
371 # user aliases to input and output histories
371 # user aliases to input and output histories
372 self.user_ns['In'] = self.input_hist
372 self.user_ns['In'] = self.input_hist
373 self.user_ns['Out'] = self.output_hist
373 self.user_ns['Out'] = self.output_hist
374
374
375 # Object variable to store code object waiting execution. This is
375 # Object variable to store code object waiting execution. This is
376 # used mainly by the multithreaded shells, but it can come in handy in
376 # used mainly by the multithreaded shells, but it can come in handy in
377 # other situations. No need to use a Queue here, since it's a single
377 # other situations. No need to use a Queue here, since it's a single
378 # item which gets cleared once run.
378 # item which gets cleared once run.
379 self.code_to_run = None
379 self.code_to_run = None
380
380
381 # escapes for automatic behavior on the command line
381 # escapes for automatic behavior on the command line
382 self.ESC_SHELL = '!'
382 self.ESC_SHELL = '!'
383 self.ESC_HELP = '?'
383 self.ESC_HELP = '?'
384 self.ESC_MAGIC = '%'
384 self.ESC_MAGIC = '%'
385 self.ESC_QUOTE = ','
385 self.ESC_QUOTE = ','
386 self.ESC_QUOTE2 = ';'
386 self.ESC_QUOTE2 = ';'
387 self.ESC_PAREN = '/'
387 self.ESC_PAREN = '/'
388
388
389 # And their associated handlers
389 # And their associated handlers
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
393 self.ESC_MAGIC : self.handle_magic,
393 self.ESC_MAGIC : self.handle_magic,
394 self.ESC_HELP : self.handle_help,
394 self.ESC_HELP : self.handle_help,
395 self.ESC_SHELL : self.handle_shell_escape,
395 self.ESC_SHELL : self.handle_shell_escape,
396 }
396 }
397
397
398 # class initializations
398 # class initializations
399 Magic.__init__(self,self)
399 Magic.__init__(self,self)
400
400
401 # Python source parser/formatter for syntax highlighting
401 # Python source parser/formatter for syntax highlighting
402 pyformat = PyColorize.Parser().format
402 pyformat = PyColorize.Parser().format
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
404
404
405 # hooks holds pointers used for user-side customizations
405 # hooks holds pointers used for user-side customizations
406 self.hooks = Struct()
406 self.hooks = Struct()
407
407
408 self.strdispatchers = {}
408 self.strdispatchers = {}
409
409
410 # Set all default hooks, defined in the IPython.hooks module.
410 # Set all default hooks, defined in the IPython.hooks module.
411 hooks = IPython.hooks
411 hooks = IPython.hooks
412 for hook_name in hooks.__all__:
412 for hook_name in hooks.__all__:
413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
415 #print "bound hook",hook_name
415 #print "bound hook",hook_name
416
416
417 # Flag to mark unconditional exit
417 # Flag to mark unconditional exit
418 self.exit_now = False
418 self.exit_now = False
419
419
420 self.usage_min = """\
420 self.usage_min = """\
421 An enhanced console for Python.
421 An enhanced console for Python.
422 Some of its features are:
422 Some of its features are:
423 - Readline support if the readline library is present.
423 - Readline support if the readline library is present.
424 - Tab completion in the local namespace.
424 - Tab completion in the local namespace.
425 - Logging of input, see command-line options.
425 - Logging of input, see command-line options.
426 - System shell escape via ! , eg !ls.
426 - System shell escape via ! , eg !ls.
427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
428 - Keeps track of locally defined variables via %who, %whos.
428 - Keeps track of locally defined variables via %who, %whos.
429 - Show object information with a ? eg ?x or x? (use ?? for more info).
429 - Show object information with a ? eg ?x or x? (use ?? for more info).
430 """
430 """
431 if usage: self.usage = usage
431 if usage: self.usage = usage
432 else: self.usage = self.usage_min
432 else: self.usage = self.usage_min
433
433
434 # Storage
434 # Storage
435 self.rc = rc # This will hold all configuration information
435 self.rc = rc # This will hold all configuration information
436 self.pager = 'less'
436 self.pager = 'less'
437 # temporary files used for various purposes. Deleted at exit.
437 # temporary files used for various purposes. Deleted at exit.
438 self.tempfiles = []
438 self.tempfiles = []
439
439
440 # Keep track of readline usage (later set by init_readline)
440 # Keep track of readline usage (later set by init_readline)
441 self.has_readline = False
441 self.has_readline = False
442
442
443 # template for logfile headers. It gets resolved at runtime by the
443 # template for logfile headers. It gets resolved at runtime by the
444 # logstart method.
444 # logstart method.
445 self.loghead_tpl = \
445 self.loghead_tpl = \
446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
448 #log# opts = %s
448 #log# opts = %s
449 #log# args = %s
449 #log# args = %s
450 #log# It is safe to make manual edits below here.
450 #log# It is safe to make manual edits below here.
451 #log#-----------------------------------------------------------------------
451 #log#-----------------------------------------------------------------------
452 """
452 """
453 # for pushd/popd management
453 # for pushd/popd management
454 try:
454 try:
455 self.home_dir = get_home_dir()
455 self.home_dir = get_home_dir()
456 except HomeDirError,msg:
456 except HomeDirError,msg:
457 fatal(msg)
457 fatal(msg)
458
458
459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
460
460
461 # Functions to call the underlying shell.
461 # Functions to call the underlying shell.
462
462
463 # The first is similar to os.system, but it doesn't return a value,
463 # The first is similar to os.system, but it doesn't return a value,
464 # and it allows interpolation of variables in the user's namespace.
464 # and it allows interpolation of variables in the user's namespace.
465 self.system = lambda cmd: \
465 self.system = lambda cmd: \
466 shell(self.var_expand(cmd,depth=2),
466 shell(self.var_expand(cmd,depth=2),
467 header='IPython system call: ',
467 header=self.rc.system_header,
468 verbose=self.rc.system_verbose)
468 verbose=self.rc.system_verbose)
469
469 # These are for getoutput and getoutputerror:
470 # These are for getoutput and getoutputerror:
470 self.getoutput = lambda cmd: \
471 self.getoutput = lambda cmd: \
471 getoutput(self.var_expand(cmd,depth=2),
472 getoutput(self.var_expand(cmd,depth=2),
472 header='IPython system call: ',
473 header=self.rc.system_header,
473 verbose=self.rc.system_verbose)
474 verbose=self.rc.system_verbose)
475
474 self.getoutputerror = lambda cmd: \
476 self.getoutputerror = lambda cmd: \
475 getoutputerror(self.var_expand(cmd,depth=2),
477 getoutputerror(self.var_expand(cmd,depth=2),
476 header='IPython system call: ',
478 header=self.rc.system_header,
477 verbose=self.rc.system_verbose)
479 verbose=self.rc.system_verbose)
478
480
479 # RegExp for splitting line contents into pre-char//first
481 # RegExp for splitting line contents into pre-char//first
480 # word-method//rest. For clarity, each group in on one line.
482 # word-method//rest. For clarity, each group in on one line.
481
483
482 # WARNING: update the regexp if the above escapes are changed, as they
484 # WARNING: update the regexp if the above escapes are changed, as they
483 # are hardwired in.
485 # are hardwired in.
484
486
485 # Don't get carried away with trying to make the autocalling catch too
487 # Don't get carried away with trying to make the autocalling catch too
486 # much: it's better to be conservative rather than to trigger hidden
488 # much: it's better to be conservative rather than to trigger hidden
487 # evals() somewhere and end up causing side effects.
489 # evals() somewhere and end up causing side effects.
488
490
489 self.line_split = re.compile(r'^([\s*,;/])'
491 self.line_split = re.compile(r'^([\s*,;/])'
490 r'([\?\w\.]+\w*\s*)'
492 r'([\?\w\.]+\w*\s*)'
491 r'(\(?.*$)')
493 r'(\(?.*$)')
492
494
493 # Original re, keep around for a while in case changes break something
495 # Original re, keep around for a while in case changes break something
494 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
496 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
495 # r'(\s*[\?\w\.]+\w*\s*)'
497 # r'(\s*[\?\w\.]+\w*\s*)'
496 # r'(\(?.*$)')
498 # r'(\(?.*$)')
497
499
498 # RegExp to identify potential function names
500 # RegExp to identify potential function names
499 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
501 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
500
502
501 # RegExp to exclude strings with this start from autocalling. In
503 # RegExp to exclude strings with this start from autocalling. In
502 # particular, all binary operators should be excluded, so that if foo
504 # particular, all binary operators should be excluded, so that if foo
503 # is callable, foo OP bar doesn't become foo(OP bar), which is
505 # is callable, foo OP bar doesn't become foo(OP bar), which is
504 # invalid. The characters '!=()' don't need to be checked for, as the
506 # invalid. The characters '!=()' don't need to be checked for, as the
505 # _prefilter routine explicitely does so, to catch direct calls and
507 # _prefilter routine explicitely does so, to catch direct calls and
506 # rebindings of existing names.
508 # rebindings of existing names.
507
509
508 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
510 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
509 # it affects the rest of the group in square brackets.
511 # it affects the rest of the group in square brackets.
510 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
512 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
511 '|^is |^not |^in |^and |^or ')
513 '|^is |^not |^in |^and |^or ')
512
514
513 # try to catch also methods for stuff in lists/tuples/dicts: off
515 # try to catch also methods for stuff in lists/tuples/dicts: off
514 # (experimental). For this to work, the line_split regexp would need
516 # (experimental). For this to work, the line_split regexp would need
515 # to be modified so it wouldn't break things at '['. That line is
517 # to be modified so it wouldn't break things at '['. That line is
516 # nasty enough that I shouldn't change it until I can test it _well_.
518 # nasty enough that I shouldn't change it until I can test it _well_.
517 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
519 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
518
520
519 # keep track of where we started running (mainly for crash post-mortem)
521 # keep track of where we started running (mainly for crash post-mortem)
520 self.starting_dir = os.getcwd()
522 self.starting_dir = os.getcwd()
521
523
522 # Various switches which can be set
524 # Various switches which can be set
523 self.CACHELENGTH = 5000 # this is cheap, it's just text
525 self.CACHELENGTH = 5000 # this is cheap, it's just text
524 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
526 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
525 self.banner2 = banner2
527 self.banner2 = banner2
526
528
527 # TraceBack handlers:
529 # TraceBack handlers:
528
530
529 # Syntax error handler.
531 # Syntax error handler.
530 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
532 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
531
533
532 # The interactive one is initialized with an offset, meaning we always
534 # The interactive one is initialized with an offset, meaning we always
533 # want to remove the topmost item in the traceback, which is our own
535 # want to remove the topmost item in the traceback, which is our own
534 # internal code. Valid modes: ['Plain','Context','Verbose']
536 # internal code. Valid modes: ['Plain','Context','Verbose']
535 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
537 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
536 color_scheme='NoColor',
538 color_scheme='NoColor',
537 tb_offset = 1)
539 tb_offset = 1)
538
540
539 # IPython itself shouldn't crash. This will produce a detailed
541 # IPython itself shouldn't crash. This will produce a detailed
540 # post-mortem if it does. But we only install the crash handler for
542 # post-mortem if it does. But we only install the crash handler for
541 # non-threaded shells, the threaded ones use a normal verbose reporter
543 # non-threaded shells, the threaded ones use a normal verbose reporter
542 # and lose the crash handler. This is because exceptions in the main
544 # and lose the crash handler. This is because exceptions in the main
543 # thread (such as in GUI code) propagate directly to sys.excepthook,
545 # thread (such as in GUI code) propagate directly to sys.excepthook,
544 # and there's no point in printing crash dumps for every user exception.
546 # and there's no point in printing crash dumps for every user exception.
545 if self.isthreaded:
547 if self.isthreaded:
546 ipCrashHandler = ultraTB.FormattedTB()
548 ipCrashHandler = ultraTB.FormattedTB()
547 else:
549 else:
548 from IPython import CrashHandler
550 from IPython import CrashHandler
549 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
551 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
550 self.set_crash_handler(ipCrashHandler)
552 self.set_crash_handler(ipCrashHandler)
551
553
552 # and add any custom exception handlers the user may have specified
554 # and add any custom exception handlers the user may have specified
553 self.set_custom_exc(*custom_exceptions)
555 self.set_custom_exc(*custom_exceptions)
554
556
555 # indentation management
557 # indentation management
556 self.autoindent = False
558 self.autoindent = False
557 self.indent_current_nsp = 0
559 self.indent_current_nsp = 0
558
560
559 # Make some aliases automatically
561 # Make some aliases automatically
560 # Prepare list of shell aliases to auto-define
562 # Prepare list of shell aliases to auto-define
561 if os.name == 'posix':
563 if os.name == 'posix':
562 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
564 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
563 'mv mv -i','rm rm -i','cp cp -i',
565 'mv mv -i','rm rm -i','cp cp -i',
564 'cat cat','less less','clear clear',
566 'cat cat','less less','clear clear',
565 # a better ls
567 # a better ls
566 'ls ls -F',
568 'ls ls -F',
567 # long ls
569 # long ls
568 'll ls -lF')
570 'll ls -lF')
569 # Extra ls aliases with color, which need special treatment on BSD
571 # Extra ls aliases with color, which need special treatment on BSD
570 # variants
572 # variants
571 ls_extra = ( # color ls
573 ls_extra = ( # color ls
572 'lc ls -F -o --color',
574 'lc ls -F -o --color',
573 # ls normal files only
575 # ls normal files only
574 'lf ls -F -o --color %l | grep ^-',
576 'lf ls -F -o --color %l | grep ^-',
575 # ls symbolic links
577 # ls symbolic links
576 'lk ls -F -o --color %l | grep ^l',
578 'lk ls -F -o --color %l | grep ^l',
577 # directories or links to directories,
579 # directories or links to directories,
578 'ldir ls -F -o --color %l | grep /$',
580 'ldir ls -F -o --color %l | grep /$',
579 # things which are executable
581 # things which are executable
580 'lx ls -F -o --color %l | grep ^-..x',
582 'lx ls -F -o --color %l | grep ^-..x',
581 )
583 )
582 # The BSDs don't ship GNU ls, so they don't understand the
584 # The BSDs don't ship GNU ls, so they don't understand the
583 # --color switch out of the box
585 # --color switch out of the box
584 if 'bsd' in sys.platform:
586 if 'bsd' in sys.platform:
585 ls_extra = ( # ls normal files only
587 ls_extra = ( # ls normal files only
586 'lf ls -lF | grep ^-',
588 'lf ls -lF | grep ^-',
587 # ls symbolic links
589 # ls symbolic links
588 'lk ls -lF | grep ^l',
590 'lk ls -lF | grep ^l',
589 # directories or links to directories,
591 # directories or links to directories,
590 'ldir ls -lF | grep /$',
592 'ldir ls -lF | grep /$',
591 # things which are executable
593 # things which are executable
592 'lx ls -lF | grep ^-..x',
594 'lx ls -lF | grep ^-..x',
593 )
595 )
594 auto_alias = auto_alias + ls_extra
596 auto_alias = auto_alias + ls_extra
595 elif os.name in ['nt','dos']:
597 elif os.name in ['nt','dos']:
596 auto_alias = ('dir dir /on', 'ls dir /on',
598 auto_alias = ('dir dir /on', 'ls dir /on',
597 'ddir dir /ad /on', 'ldir dir /ad /on',
599 'ddir dir /ad /on', 'ldir dir /ad /on',
598 'mkdir mkdir','rmdir rmdir','echo echo',
600 'mkdir mkdir','rmdir rmdir','echo echo',
599 'ren ren','cls cls','copy copy')
601 'ren ren','cls cls','copy copy')
600 else:
602 else:
601 auto_alias = ()
603 auto_alias = ()
602 self.auto_alias = [s.split(None,1) for s in auto_alias]
604 self.auto_alias = [s.split(None,1) for s in auto_alias]
603 # Call the actual (public) initializer
605 # Call the actual (public) initializer
604 self.init_auto_alias()
606 self.init_auto_alias()
605
607
606 # Produce a public API instance
608 # Produce a public API instance
607 self.api = IPython.ipapi.IPApi(self)
609 self.api = IPython.ipapi.IPApi(self)
608
610
609 # track which builtins we add, so we can clean up later
611 # track which builtins we add, so we can clean up later
610 self.builtins_added = {}
612 self.builtins_added = {}
611 # This method will add the necessary builtins for operation, but
613 # This method will add the necessary builtins for operation, but
612 # tracking what it did via the builtins_added dict.
614 # tracking what it did via the builtins_added dict.
613 self.add_builtins()
615 self.add_builtins()
614
616
615 # end __init__
617 # end __init__
616
618
617 def var_expand(self,cmd,depth=0):
619 def var_expand(self,cmd,depth=0):
618 """Expand python variables in a string.
620 """Expand python variables in a string.
619
621
620 The depth argument indicates how many frames above the caller should
622 The depth argument indicates how many frames above the caller should
621 be walked to look for the local namespace where to expand variables.
623 be walked to look for the local namespace where to expand variables.
622
624
623 The global namespace for expansion is always the user's interactive
625 The global namespace for expansion is always the user's interactive
624 namespace.
626 namespace.
625 """
627 """
626
628
627 return str(ItplNS(cmd.replace('#','\#'),
629 return str(ItplNS(cmd.replace('#','\#'),
628 self.user_ns, # globals
630 self.user_ns, # globals
629 # Skip our own frame in searching for locals:
631 # Skip our own frame in searching for locals:
630 sys._getframe(depth+1).f_locals # locals
632 sys._getframe(depth+1).f_locals # locals
631 ))
633 ))
632
634
633 def pre_config_initialization(self):
635 def pre_config_initialization(self):
634 """Pre-configuration init method
636 """Pre-configuration init method
635
637
636 This is called before the configuration files are processed to
638 This is called before the configuration files are processed to
637 prepare the services the config files might need.
639 prepare the services the config files might need.
638
640
639 self.rc already has reasonable default values at this point.
641 self.rc already has reasonable default values at this point.
640 """
642 """
641 rc = self.rc
643 rc = self.rc
642
644
643 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
645 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
644
646
645 def post_config_initialization(self):
647 def post_config_initialization(self):
646 """Post configuration init method
648 """Post configuration init method
647
649
648 This is called after the configuration files have been processed to
650 This is called after the configuration files have been processed to
649 'finalize' the initialization."""
651 'finalize' the initialization."""
650
652
651 rc = self.rc
653 rc = self.rc
652
654
653 # Object inspector
655 # Object inspector
654 self.inspector = OInspect.Inspector(OInspect.InspectColors,
656 self.inspector = OInspect.Inspector(OInspect.InspectColors,
655 PyColorize.ANSICodeColors,
657 PyColorize.ANSICodeColors,
656 'NoColor',
658 'NoColor',
657 rc.object_info_string_level)
659 rc.object_info_string_level)
658
660
659 # Load readline proper
661 # Load readline proper
660 if rc.readline:
662 if rc.readline:
661 self.init_readline()
663 self.init_readline()
662
664
663 # local shortcut, this is used a LOT
665 # local shortcut, this is used a LOT
664 self.log = self.logger.log
666 self.log = self.logger.log
665
667
666 # Initialize cache, set in/out prompts and printing system
668 # Initialize cache, set in/out prompts and printing system
667 self.outputcache = CachedOutput(self,
669 self.outputcache = CachedOutput(self,
668 rc.cache_size,
670 rc.cache_size,
669 rc.pprint,
671 rc.pprint,
670 input_sep = rc.separate_in,
672 input_sep = rc.separate_in,
671 output_sep = rc.separate_out,
673 output_sep = rc.separate_out,
672 output_sep2 = rc.separate_out2,
674 output_sep2 = rc.separate_out2,
673 ps1 = rc.prompt_in1,
675 ps1 = rc.prompt_in1,
674 ps2 = rc.prompt_in2,
676 ps2 = rc.prompt_in2,
675 ps_out = rc.prompt_out,
677 ps_out = rc.prompt_out,
676 pad_left = rc.prompts_pad_left)
678 pad_left = rc.prompts_pad_left)
677
679
678 # user may have over-ridden the default print hook:
680 # user may have over-ridden the default print hook:
679 try:
681 try:
680 self.outputcache.__class__.display = self.hooks.display
682 self.outputcache.__class__.display = self.hooks.display
681 except AttributeError:
683 except AttributeError:
682 pass
684 pass
683
685
684 # I don't like assigning globally to sys, because it means when
686 # I don't like assigning globally to sys, because it means when
685 # embedding instances, each embedded instance overrides the previous
687 # embedding instances, each embedded instance overrides the previous
686 # choice. But sys.displayhook seems to be called internally by exec,
688 # choice. But sys.displayhook seems to be called internally by exec,
687 # so I don't see a way around it. We first save the original and then
689 # so I don't see a way around it. We first save the original and then
688 # overwrite it.
690 # overwrite it.
689 self.sys_displayhook = sys.displayhook
691 self.sys_displayhook = sys.displayhook
690 sys.displayhook = self.outputcache
692 sys.displayhook = self.outputcache
691
693
692 # Set user colors (don't do it in the constructor above so that it
694 # Set user colors (don't do it in the constructor above so that it
693 # doesn't crash if colors option is invalid)
695 # doesn't crash if colors option is invalid)
694 self.magic_colors(rc.colors)
696 self.magic_colors(rc.colors)
695
697
696 # Set calling of pdb on exceptions
698 # Set calling of pdb on exceptions
697 self.call_pdb = rc.pdb
699 self.call_pdb = rc.pdb
698
700
699 # Load user aliases
701 # Load user aliases
700 for alias in rc.alias:
702 for alias in rc.alias:
701 self.magic_alias(alias)
703 self.magic_alias(alias)
702 self.hooks.late_startup_hook()
704 self.hooks.late_startup_hook()
703
705
704 batchrun = False
706 batchrun = False
705 for batchfile in [path(arg) for arg in self.rc.args
707 for batchfile in [path(arg) for arg in self.rc.args
706 if arg.lower().endswith('.ipy')]:
708 if arg.lower().endswith('.ipy')]:
707 if not batchfile.isfile():
709 if not batchfile.isfile():
708 print "No such batch file:", batchfile
710 print "No such batch file:", batchfile
709 continue
711 continue
710 self.api.runlines(batchfile.text())
712 self.api.runlines(batchfile.text())
711 batchrun = True
713 batchrun = True
712 if batchrun:
714 if batchrun:
713 self.exit_now = True
715 self.exit_now = True
714
716
715 def add_builtins(self):
717 def add_builtins(self):
716 """Store ipython references into the builtin namespace.
718 """Store ipython references into the builtin namespace.
717
719
718 Some parts of ipython operate via builtins injected here, which hold a
720 Some parts of ipython operate via builtins injected here, which hold a
719 reference to IPython itself."""
721 reference to IPython itself."""
720
722
721 # TODO: deprecate all except _ip; 'jobs' should be installed
723 # TODO: deprecate all except _ip; 'jobs' should be installed
722 # by an extension and the rest are under _ip, ipalias is redundant
724 # by an extension and the rest are under _ip, ipalias is redundant
723 builtins_new = dict(__IPYTHON__ = self,
725 builtins_new = dict(__IPYTHON__ = self,
724 ip_set_hook = self.set_hook,
726 ip_set_hook = self.set_hook,
725 jobs = self.jobs,
727 jobs = self.jobs,
726 ipmagic = self.ipmagic,
728 ipmagic = self.ipmagic,
727 ipalias = self.ipalias,
729 ipalias = self.ipalias,
728 ipsystem = self.ipsystem,
730 ipsystem = self.ipsystem,
731 ipconfig = self.ipconfig,
729 _ip = self.api
732 _ip = self.api
730 )
733 )
731 for biname,bival in builtins_new.items():
734 for biname,bival in builtins_new.items():
732 try:
735 try:
733 # store the orignal value so we can restore it
736 # store the orignal value so we can restore it
734 self.builtins_added[biname] = __builtin__.__dict__[biname]
737 self.builtins_added[biname] = __builtin__.__dict__[biname]
735 except KeyError:
738 except KeyError:
736 # or mark that it wasn't defined, and we'll just delete it at
739 # or mark that it wasn't defined, and we'll just delete it at
737 # cleanup
740 # cleanup
738 self.builtins_added[biname] = Undefined
741 self.builtins_added[biname] = Undefined
739 __builtin__.__dict__[biname] = bival
742 __builtin__.__dict__[biname] = bival
740
743
741 # Keep in the builtins a flag for when IPython is active. We set it
744 # Keep in the builtins a flag for when IPython is active. We set it
742 # with setdefault so that multiple nested IPythons don't clobber one
745 # with setdefault so that multiple nested IPythons don't clobber one
743 # another. Each will increase its value by one upon being activated,
746 # another. Each will increase its value by one upon being activated,
744 # which also gives us a way to determine the nesting level.
747 # which also gives us a way to determine the nesting level.
745 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
748 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
746
749
747 def clean_builtins(self):
750 def clean_builtins(self):
748 """Remove any builtins which might have been added by add_builtins, or
751 """Remove any builtins which might have been added by add_builtins, or
749 restore overwritten ones to their previous values."""
752 restore overwritten ones to their previous values."""
750 for biname,bival in self.builtins_added.items():
753 for biname,bival in self.builtins_added.items():
751 if bival is Undefined:
754 if bival is Undefined:
752 del __builtin__.__dict__[biname]
755 del __builtin__.__dict__[biname]
753 else:
756 else:
754 __builtin__.__dict__[biname] = bival
757 __builtin__.__dict__[biname] = bival
755 self.builtins_added.clear()
758 self.builtins_added.clear()
756
759
757 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
760 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
758 """set_hook(name,hook) -> sets an internal IPython hook.
761 """set_hook(name,hook) -> sets an internal IPython hook.
759
762
760 IPython exposes some of its internal API as user-modifiable hooks. By
763 IPython exposes some of its internal API as user-modifiable hooks. By
761 adding your function to one of these hooks, you can modify IPython's
764 adding your function to one of these hooks, you can modify IPython's
762 behavior to call at runtime your own routines."""
765 behavior to call at runtime your own routines."""
763
766
764 # At some point in the future, this should validate the hook before it
767 # At some point in the future, this should validate the hook before it
765 # accepts it. Probably at least check that the hook takes the number
768 # accepts it. Probably at least check that the hook takes the number
766 # of args it's supposed to.
769 # of args it's supposed to.
767
770
768 f = new.instancemethod(hook,self,self.__class__)
771 f = new.instancemethod(hook,self,self.__class__)
769
772
770 # check if the hook is for strdispatcher first
773 # check if the hook is for strdispatcher first
771 if str_key is not None:
774 if str_key is not None:
772 sdp = self.strdispatchers.get(name, StrDispatch())
775 sdp = self.strdispatchers.get(name, StrDispatch())
773 sdp.add_s(str_key, f, priority )
776 sdp.add_s(str_key, f, priority )
774 self.strdispatchers[name] = sdp
777 self.strdispatchers[name] = sdp
775 return
778 return
776 if re_key is not None:
779 if re_key is not None:
777 sdp = self.strdispatchers.get(name, StrDispatch())
780 sdp = self.strdispatchers.get(name, StrDispatch())
778 sdp.add_re(re.compile(re_key), f, priority )
781 sdp.add_re(re.compile(re_key), f, priority )
779 self.strdispatchers[name] = sdp
782 self.strdispatchers[name] = sdp
780 return
783 return
781
784
782 dp = getattr(self.hooks, name, None)
785 dp = getattr(self.hooks, name, None)
783 if name not in IPython.hooks.__all__:
786 if name not in IPython.hooks.__all__:
784 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
787 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
785 if not dp:
788 if not dp:
786 dp = IPython.hooks.CommandChainDispatcher()
789 dp = IPython.hooks.CommandChainDispatcher()
787
790
788 try:
791 try:
789 dp.add(f,priority)
792 dp.add(f,priority)
790 except AttributeError:
793 except AttributeError:
791 # it was not commandchain, plain old func - replace
794 # it was not commandchain, plain old func - replace
792 dp = f
795 dp = f
793
796
794 setattr(self.hooks,name, dp)
797 setattr(self.hooks,name, dp)
795
798
796
799
797 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
800 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
798
801
799 def set_crash_handler(self,crashHandler):
802 def set_crash_handler(self,crashHandler):
800 """Set the IPython crash handler.
803 """Set the IPython crash handler.
801
804
802 This must be a callable with a signature suitable for use as
805 This must be a callable with a signature suitable for use as
803 sys.excepthook."""
806 sys.excepthook."""
804
807
805 # Install the given crash handler as the Python exception hook
808 # Install the given crash handler as the Python exception hook
806 sys.excepthook = crashHandler
809 sys.excepthook = crashHandler
807
810
808 # The instance will store a pointer to this, so that runtime code
811 # The instance will store a pointer to this, so that runtime code
809 # (such as magics) can access it. This is because during the
812 # (such as magics) can access it. This is because during the
810 # read-eval loop, it gets temporarily overwritten (to deal with GUI
813 # read-eval loop, it gets temporarily overwritten (to deal with GUI
811 # frameworks).
814 # frameworks).
812 self.sys_excepthook = sys.excepthook
815 self.sys_excepthook = sys.excepthook
813
816
814
817
815 def set_custom_exc(self,exc_tuple,handler):
818 def set_custom_exc(self,exc_tuple,handler):
816 """set_custom_exc(exc_tuple,handler)
819 """set_custom_exc(exc_tuple,handler)
817
820
818 Set a custom exception handler, which will be called if any of the
821 Set a custom exception handler, which will be called if any of the
819 exceptions in exc_tuple occur in the mainloop (specifically, in the
822 exceptions in exc_tuple occur in the mainloop (specifically, in the
820 runcode() method.
823 runcode() method.
821
824
822 Inputs:
825 Inputs:
823
826
824 - exc_tuple: a *tuple* of valid exceptions to call the defined
827 - exc_tuple: a *tuple* of valid exceptions to call the defined
825 handler for. It is very important that you use a tuple, and NOT A
828 handler for. It is very important that you use a tuple, and NOT A
826 LIST here, because of the way Python's except statement works. If
829 LIST here, because of the way Python's except statement works. If
827 you only want to trap a single exception, use a singleton tuple:
830 you only want to trap a single exception, use a singleton tuple:
828
831
829 exc_tuple == (MyCustomException,)
832 exc_tuple == (MyCustomException,)
830
833
831 - handler: this must be defined as a function with the following
834 - handler: this must be defined as a function with the following
832 basic interface: def my_handler(self,etype,value,tb).
835 basic interface: def my_handler(self,etype,value,tb).
833
836
834 This will be made into an instance method (via new.instancemethod)
837 This will be made into an instance method (via new.instancemethod)
835 of IPython itself, and it will be called if any of the exceptions
838 of IPython itself, and it will be called if any of the exceptions
836 listed in the exc_tuple are caught. If the handler is None, an
839 listed in the exc_tuple are caught. If the handler is None, an
837 internal basic one is used, which just prints basic info.
840 internal basic one is used, which just prints basic info.
838
841
839 WARNING: by putting in your own exception handler into IPython's main
842 WARNING: by putting in your own exception handler into IPython's main
840 execution loop, you run a very good chance of nasty crashes. This
843 execution loop, you run a very good chance of nasty crashes. This
841 facility should only be used if you really know what you are doing."""
844 facility should only be used if you really know what you are doing."""
842
845
843 assert type(exc_tuple)==type(()) , \
846 assert type(exc_tuple)==type(()) , \
844 "The custom exceptions must be given AS A TUPLE."
847 "The custom exceptions must be given AS A TUPLE."
845
848
846 def dummy_handler(self,etype,value,tb):
849 def dummy_handler(self,etype,value,tb):
847 print '*** Simple custom exception handler ***'
850 print '*** Simple custom exception handler ***'
848 print 'Exception type :',etype
851 print 'Exception type :',etype
849 print 'Exception value:',value
852 print 'Exception value:',value
850 print 'Traceback :',tb
853 print 'Traceback :',tb
851 print 'Source code :','\n'.join(self.buffer)
854 print 'Source code :','\n'.join(self.buffer)
852
855
853 if handler is None: handler = dummy_handler
856 if handler is None: handler = dummy_handler
854
857
855 self.CustomTB = new.instancemethod(handler,self,self.__class__)
858 self.CustomTB = new.instancemethod(handler,self,self.__class__)
856 self.custom_exceptions = exc_tuple
859 self.custom_exceptions = exc_tuple
857
860
858 def set_custom_completer(self,completer,pos=0):
861 def set_custom_completer(self,completer,pos=0):
859 """set_custom_completer(completer,pos=0)
862 """set_custom_completer(completer,pos=0)
860
863
861 Adds a new custom completer function.
864 Adds a new custom completer function.
862
865
863 The position argument (defaults to 0) is the index in the completers
866 The position argument (defaults to 0) is the index in the completers
864 list where you want the completer to be inserted."""
867 list where you want the completer to be inserted."""
865
868
866 newcomp = new.instancemethod(completer,self.Completer,
869 newcomp = new.instancemethod(completer,self.Completer,
867 self.Completer.__class__)
870 self.Completer.__class__)
868 self.Completer.matchers.insert(pos,newcomp)
871 self.Completer.matchers.insert(pos,newcomp)
869
872
870 def _get_call_pdb(self):
873 def _get_call_pdb(self):
871 return self._call_pdb
874 return self._call_pdb
872
875
873 def _set_call_pdb(self,val):
876 def _set_call_pdb(self,val):
874
877
875 if val not in (0,1,False,True):
878 if val not in (0,1,False,True):
876 raise ValueError,'new call_pdb value must be boolean'
879 raise ValueError,'new call_pdb value must be boolean'
877
880
878 # store value in instance
881 # store value in instance
879 self._call_pdb = val
882 self._call_pdb = val
880
883
881 # notify the actual exception handlers
884 # notify the actual exception handlers
882 self.InteractiveTB.call_pdb = val
885 self.InteractiveTB.call_pdb = val
883 if self.isthreaded:
886 if self.isthreaded:
884 try:
887 try:
885 self.sys_excepthook.call_pdb = val
888 self.sys_excepthook.call_pdb = val
886 except:
889 except:
887 warn('Failed to activate pdb for threaded exception handler')
890 warn('Failed to activate pdb for threaded exception handler')
888
891
889 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
892 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
890 'Control auto-activation of pdb at exceptions')
893 'Control auto-activation of pdb at exceptions')
891
894
892
895
893 # These special functions get installed in the builtin namespace, to
896 # These special functions get installed in the builtin namespace, to
894 # provide programmatic (pure python) access to magics, aliases and system
897 # provide programmatic (pure python) access to magics, aliases and system
895 # calls. This is important for logging, user scripting, and more.
898 # calls. This is important for logging, user scripting, and more.
896
899
897 # We are basically exposing, via normal python functions, the three
900 # We are basically exposing, via normal python functions, the three
898 # mechanisms in which ipython offers special call modes (magics for
901 # mechanisms in which ipython offers special call modes (magics for
899 # internal control, aliases for direct system access via pre-selected
902 # internal control, aliases for direct system access via pre-selected
900 # names, and !cmd for calling arbitrary system commands).
903 # names, and !cmd for calling arbitrary system commands).
901
904
902 def ipmagic(self,arg_s):
905 def ipmagic(self,arg_s):
903 """Call a magic function by name.
906 """Call a magic function by name.
904
907
905 Input: a string containing the name of the magic function to call and any
908 Input: a string containing the name of the magic function to call and any
906 additional arguments to be passed to the magic.
909 additional arguments to be passed to the magic.
907
910
908 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
911 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
909 prompt:
912 prompt:
910
913
911 In[1]: %name -opt foo bar
914 In[1]: %name -opt foo bar
912
915
913 To call a magic without arguments, simply use ipmagic('name').
916 To call a magic without arguments, simply use ipmagic('name').
914
917
915 This provides a proper Python function to call IPython's magics in any
918 This provides a proper Python function to call IPython's magics in any
916 valid Python code you can type at the interpreter, including loops and
919 valid Python code you can type at the interpreter, including loops and
917 compound statements. It is added by IPython to the Python builtin
920 compound statements. It is added by IPython to the Python builtin
918 namespace upon initialization."""
921 namespace upon initialization."""
919
922
920 args = arg_s.split(' ',1)
923 args = arg_s.split(' ',1)
921 magic_name = args[0]
924 magic_name = args[0]
922 magic_name = magic_name.lstrip(self.ESC_MAGIC)
925 magic_name = magic_name.lstrip(self.ESC_MAGIC)
923
926
924 try:
927 try:
925 magic_args = args[1]
928 magic_args = args[1]
926 except IndexError:
929 except IndexError:
927 magic_args = ''
930 magic_args = ''
928 fn = getattr(self,'magic_'+magic_name,None)
931 fn = getattr(self,'magic_'+magic_name,None)
929 if fn is None:
932 if fn is None:
930 error("Magic function `%s` not found." % magic_name)
933 error("Magic function `%s` not found." % magic_name)
931 else:
934 else:
932 magic_args = self.var_expand(magic_args,1)
935 magic_args = self.var_expand(magic_args,1)
933 return fn(magic_args)
936 return fn(magic_args)
934
937
935 def ipalias(self,arg_s):
938 def ipalias(self,arg_s):
936 """Call an alias by name.
939 """Call an alias by name.
937
940
938 Input: a string containing the name of the alias to call and any
941 Input: a string containing the name of the alias to call and any
939 additional arguments to be passed to the magic.
942 additional arguments to be passed to the magic.
940
943
941 ipalias('name -opt foo bar') is equivalent to typing at the ipython
944 ipalias('name -opt foo bar') is equivalent to typing at the ipython
942 prompt:
945 prompt:
943
946
944 In[1]: name -opt foo bar
947 In[1]: name -opt foo bar
945
948
946 To call an alias without arguments, simply use ipalias('name').
949 To call an alias without arguments, simply use ipalias('name').
947
950
948 This provides a proper Python function to call IPython's aliases in any
951 This provides a proper Python function to call IPython's aliases in any
949 valid Python code you can type at the interpreter, including loops and
952 valid Python code you can type at the interpreter, including loops and
950 compound statements. It is added by IPython to the Python builtin
953 compound statements. It is added by IPython to the Python builtin
951 namespace upon initialization."""
954 namespace upon initialization."""
952
955
953 args = arg_s.split(' ',1)
956 args = arg_s.split(' ',1)
954 alias_name = args[0]
957 alias_name = args[0]
955 try:
958 try:
956 alias_args = args[1]
959 alias_args = args[1]
957 except IndexError:
960 except IndexError:
958 alias_args = ''
961 alias_args = ''
959 if alias_name in self.alias_table:
962 if alias_name in self.alias_table:
960 self.call_alias(alias_name,alias_args)
963 self.call_alias(alias_name,alias_args)
961 else:
964 else:
962 error("Alias `%s` not found." % alias_name)
965 error("Alias `%s` not found." % alias_name)
963
966
967 def ipconfig(self,key=None,value=None):
968 """Manipulate the IPython config.
969
970 This provides a python interface to
971 If called with no arguments, it prints the internal IPython config
972
973 Optional arguments:
974
975 - key(None): if given, what key of the rc structure to return.
976
977 - value(None): if given, set the key to this value."""
978
979 if key is None:
980 page('Current configuration structure:\n'+
981 pformat(self.rc.dict()))
982 else:
983 if value is None:
984 print '%s -> %s' % (key,self.rc[key])
985 else:
986 if key not in self.rc:
987 raise KeyError(str(key))
988 self.rc[key] = value
989
964 def ipsystem(self,arg_s):
990 def ipsystem(self,arg_s):
965 """Make a system call, using IPython."""
991 """Make a system call, using IPython."""
966
992
967 self.system(arg_s)
993 self.system(arg_s)
968
994
969 def complete(self,text):
995 def complete(self,text):
970 """Return a sorted list of all possible completions on text.
996 """Return a sorted list of all possible completions on text.
971
997
972 Inputs:
998 Inputs:
973
999
974 - text: a string of text to be completed on.
1000 - text: a string of text to be completed on.
975
1001
976 This is a wrapper around the completion mechanism, similar to what
1002 This is a wrapper around the completion mechanism, similar to what
977 readline does at the command line when the TAB key is hit. By
1003 readline does at the command line when the TAB key is hit. By
978 exposing it as a method, it can be used by other non-readline
1004 exposing it as a method, it can be used by other non-readline
979 environments (such as GUIs) for text completion.
1005 environments (such as GUIs) for text completion.
980
1006
981 Simple usage example:
1007 Simple usage example:
982
1008
983 In [1]: x = 'hello'
1009 In [1]: x = 'hello'
984
1010
985 In [2]: __IP.complete('x.l')
1011 In [2]: __IP.complete('x.l')
986 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1012 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
987
1013
988 complete = self.Completer.complete
1014 complete = self.Completer.complete
989 state = 0
1015 state = 0
990 # use a dict so we get unique keys, since ipyhton's multiple
1016 # use a dict so we get unique keys, since ipyhton's multiple
991 # completers can return duplicates.
1017 # completers can return duplicates.
992 comps = {}
1018 comps = {}
993 while True:
1019 while True:
994 newcomp = complete(text,state)
1020 newcomp = complete(text,state)
995 if newcomp is None:
1021 if newcomp is None:
996 break
1022 break
997 comps[newcomp] = 1
1023 comps[newcomp] = 1
998 state += 1
1024 state += 1
999 outcomps = comps.keys()
1025 outcomps = comps.keys()
1000 outcomps.sort()
1026 outcomps.sort()
1001 return outcomps
1027 return outcomps
1002
1028
1003 def set_completer_frame(self, frame=None):
1029 def set_completer_frame(self, frame=None):
1004 if frame:
1030 if frame:
1005 self.Completer.namespace = frame.f_locals
1031 self.Completer.namespace = frame.f_locals
1006 self.Completer.global_namespace = frame.f_globals
1032 self.Completer.global_namespace = frame.f_globals
1007 else:
1033 else:
1008 self.Completer.namespace = self.user_ns
1034 self.Completer.namespace = self.user_ns
1009 self.Completer.global_namespace = self.user_global_ns
1035 self.Completer.global_namespace = self.user_global_ns
1010
1036
1011 def init_auto_alias(self):
1037 def init_auto_alias(self):
1012 """Define some aliases automatically.
1038 """Define some aliases automatically.
1013
1039
1014 These are ALL parameter-less aliases"""
1040 These are ALL parameter-less aliases"""
1015
1041
1016 for alias,cmd in self.auto_alias:
1042 for alias,cmd in self.auto_alias:
1017 self.alias_table[alias] = (0,cmd)
1043 self.alias_table[alias] = (0,cmd)
1018
1044
1019 def alias_table_validate(self,verbose=0):
1045 def alias_table_validate(self,verbose=0):
1020 """Update information about the alias table.
1046 """Update information about the alias table.
1021
1047
1022 In particular, make sure no Python keywords/builtins are in it."""
1048 In particular, make sure no Python keywords/builtins are in it."""
1023
1049
1024 no_alias = self.no_alias
1050 no_alias = self.no_alias
1025 for k in self.alias_table.keys():
1051 for k in self.alias_table.keys():
1026 if k in no_alias:
1052 if k in no_alias:
1027 del self.alias_table[k]
1053 del self.alias_table[k]
1028 if verbose:
1054 if verbose:
1029 print ("Deleting alias <%s>, it's a Python "
1055 print ("Deleting alias <%s>, it's a Python "
1030 "keyword or builtin." % k)
1056 "keyword or builtin." % k)
1031
1057
1032 def set_autoindent(self,value=None):
1058 def set_autoindent(self,value=None):
1033 """Set the autoindent flag, checking for readline support.
1059 """Set the autoindent flag, checking for readline support.
1034
1060
1035 If called with no arguments, it acts as a toggle."""
1061 If called with no arguments, it acts as a toggle."""
1036
1062
1037 if not self.has_readline:
1063 if not self.has_readline:
1038 if os.name == 'posix':
1064 if os.name == 'posix':
1039 warn("The auto-indent feature requires the readline library")
1065 warn("The auto-indent feature requires the readline library")
1040 self.autoindent = 0
1066 self.autoindent = 0
1041 return
1067 return
1042 if value is None:
1068 if value is None:
1043 self.autoindent = not self.autoindent
1069 self.autoindent = not self.autoindent
1044 else:
1070 else:
1045 self.autoindent = value
1071 self.autoindent = value
1046
1072
1047 def rc_set_toggle(self,rc_field,value=None):
1073 def rc_set_toggle(self,rc_field,value=None):
1048 """Set or toggle a field in IPython's rc config. structure.
1074 """Set or toggle a field in IPython's rc config. structure.
1049
1075
1050 If called with no arguments, it acts as a toggle.
1076 If called with no arguments, it acts as a toggle.
1051
1077
1052 If called with a non-existent field, the resulting AttributeError
1078 If called with a non-existent field, the resulting AttributeError
1053 exception will propagate out."""
1079 exception will propagate out."""
1054
1080
1055 rc_val = getattr(self.rc,rc_field)
1081 rc_val = getattr(self.rc,rc_field)
1056 if value is None:
1082 if value is None:
1057 value = not rc_val
1083 value = not rc_val
1058 setattr(self.rc,rc_field,value)
1084 setattr(self.rc,rc_field,value)
1059
1085
1060 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1086 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1061 """Install the user configuration directory.
1087 """Install the user configuration directory.
1062
1088
1063 Can be called when running for the first time or to upgrade the user's
1089 Can be called when running for the first time or to upgrade the user's
1064 .ipython/ directory with the mode parameter. Valid modes are 'install'
1090 .ipython/ directory with the mode parameter. Valid modes are 'install'
1065 and 'upgrade'."""
1091 and 'upgrade'."""
1066
1092
1067 def wait():
1093 def wait():
1068 try:
1094 try:
1069 raw_input("Please press <RETURN> to start IPython.")
1095 raw_input("Please press <RETURN> to start IPython.")
1070 except EOFError:
1096 except EOFError:
1071 print >> Term.cout
1097 print >> Term.cout
1072 print '*'*70
1098 print '*'*70
1073
1099
1074 cwd = os.getcwd() # remember where we started
1100 cwd = os.getcwd() # remember where we started
1075 glb = glob.glob
1101 glb = glob.glob
1076 print '*'*70
1102 print '*'*70
1077 if mode == 'install':
1103 if mode == 'install':
1078 print \
1104 print \
1079 """Welcome to IPython. I will try to create a personal configuration directory
1105 """Welcome to IPython. I will try to create a personal configuration directory
1080 where you can customize many aspects of IPython's functionality in:\n"""
1106 where you can customize many aspects of IPython's functionality in:\n"""
1081 else:
1107 else:
1082 print 'I am going to upgrade your configuration in:'
1108 print 'I am going to upgrade your configuration in:'
1083
1109
1084 print ipythondir
1110 print ipythondir
1085
1111
1086 rcdirend = os.path.join('IPython','UserConfig')
1112 rcdirend = os.path.join('IPython','UserConfig')
1087 cfg = lambda d: os.path.join(d,rcdirend)
1113 cfg = lambda d: os.path.join(d,rcdirend)
1088 try:
1114 try:
1089 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1115 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1090 except IOError:
1116 except IOError:
1091 warning = """
1117 warning = """
1092 Installation error. IPython's directory was not found.
1118 Installation error. IPython's directory was not found.
1093
1119
1094 Check the following:
1120 Check the following:
1095
1121
1096 The ipython/IPython directory should be in a directory belonging to your
1122 The ipython/IPython directory should be in a directory belonging to your
1097 PYTHONPATH environment variable (that is, it should be in a directory
1123 PYTHONPATH environment variable (that is, it should be in a directory
1098 belonging to sys.path). You can copy it explicitly there or just link to it.
1124 belonging to sys.path). You can copy it explicitly there or just link to it.
1099
1125
1100 IPython will proceed with builtin defaults.
1126 IPython will proceed with builtin defaults.
1101 """
1127 """
1102 warn(warning)
1128 warn(warning)
1103 wait()
1129 wait()
1104 return
1130 return
1105
1131
1106 if mode == 'install':
1132 if mode == 'install':
1107 try:
1133 try:
1108 shutil.copytree(rcdir,ipythondir)
1134 shutil.copytree(rcdir,ipythondir)
1109 os.chdir(ipythondir)
1135 os.chdir(ipythondir)
1110 rc_files = glb("ipythonrc*")
1136 rc_files = glb("ipythonrc*")
1111 for rc_file in rc_files:
1137 for rc_file in rc_files:
1112 os.rename(rc_file,rc_file+rc_suffix)
1138 os.rename(rc_file,rc_file+rc_suffix)
1113 except:
1139 except:
1114 warning = """
1140 warning = """
1115
1141
1116 There was a problem with the installation:
1142 There was a problem with the installation:
1117 %s
1143 %s
1118 Try to correct it or contact the developers if you think it's a bug.
1144 Try to correct it or contact the developers if you think it's a bug.
1119 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1145 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1120 warn(warning)
1146 warn(warning)
1121 wait()
1147 wait()
1122 return
1148 return
1123
1149
1124 elif mode == 'upgrade':
1150 elif mode == 'upgrade':
1125 try:
1151 try:
1126 os.chdir(ipythondir)
1152 os.chdir(ipythondir)
1127 except:
1153 except:
1128 print """
1154 print """
1129 Can not upgrade: changing to directory %s failed. Details:
1155 Can not upgrade: changing to directory %s failed. Details:
1130 %s
1156 %s
1131 """ % (ipythondir,sys.exc_info()[1])
1157 """ % (ipythondir,sys.exc_info()[1])
1132 wait()
1158 wait()
1133 return
1159 return
1134 else:
1160 else:
1135 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1161 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1136 for new_full_path in sources:
1162 for new_full_path in sources:
1137 new_filename = os.path.basename(new_full_path)
1163 new_filename = os.path.basename(new_full_path)
1138 if new_filename.startswith('ipythonrc'):
1164 if new_filename.startswith('ipythonrc'):
1139 new_filename = new_filename + rc_suffix
1165 new_filename = new_filename + rc_suffix
1140 # The config directory should only contain files, skip any
1166 # The config directory should only contain files, skip any
1141 # directories which may be there (like CVS)
1167 # directories which may be there (like CVS)
1142 if os.path.isdir(new_full_path):
1168 if os.path.isdir(new_full_path):
1143 continue
1169 continue
1144 if os.path.exists(new_filename):
1170 if os.path.exists(new_filename):
1145 old_file = new_filename+'.old'
1171 old_file = new_filename+'.old'
1146 if os.path.exists(old_file):
1172 if os.path.exists(old_file):
1147 os.remove(old_file)
1173 os.remove(old_file)
1148 os.rename(new_filename,old_file)
1174 os.rename(new_filename,old_file)
1149 shutil.copy(new_full_path,new_filename)
1175 shutil.copy(new_full_path,new_filename)
1150 else:
1176 else:
1151 raise ValueError,'unrecognized mode for install:',`mode`
1177 raise ValueError,'unrecognized mode for install:',`mode`
1152
1178
1153 # Fix line-endings to those native to each platform in the config
1179 # Fix line-endings to those native to each platform in the config
1154 # directory.
1180 # directory.
1155 try:
1181 try:
1156 os.chdir(ipythondir)
1182 os.chdir(ipythondir)
1157 except:
1183 except:
1158 print """
1184 print """
1159 Problem: changing to directory %s failed.
1185 Problem: changing to directory %s failed.
1160 Details:
1186 Details:
1161 %s
1187 %s
1162
1188
1163 Some configuration files may have incorrect line endings. This should not
1189 Some configuration files may have incorrect line endings. This should not
1164 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1190 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1165 wait()
1191 wait()
1166 else:
1192 else:
1167 for fname in glb('ipythonrc*'):
1193 for fname in glb('ipythonrc*'):
1168 try:
1194 try:
1169 native_line_ends(fname,backup=0)
1195 native_line_ends(fname,backup=0)
1170 except IOError:
1196 except IOError:
1171 pass
1197 pass
1172
1198
1173 if mode == 'install':
1199 if mode == 'install':
1174 print """
1200 print """
1175 Successful installation!
1201 Successful installation!
1176
1202
1177 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1203 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1178 IPython manual (there are both HTML and PDF versions supplied with the
1204 IPython manual (there are both HTML and PDF versions supplied with the
1179 distribution) to make sure that your system environment is properly configured
1205 distribution) to make sure that your system environment is properly configured
1180 to take advantage of IPython's features.
1206 to take advantage of IPython's features.
1181
1207
1182 Important note: the configuration system has changed! The old system is
1208 Important note: the configuration system has changed! The old system is
1183 still in place, but its setting may be partly overridden by the settings in
1209 still in place, but its setting may be partly overridden by the settings in
1184 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1210 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1185 if some of the new settings bother you.
1211 if some of the new settings bother you.
1186
1212
1187 """
1213 """
1188 else:
1214 else:
1189 print """
1215 print """
1190 Successful upgrade!
1216 Successful upgrade!
1191
1217
1192 All files in your directory:
1218 All files in your directory:
1193 %(ipythondir)s
1219 %(ipythondir)s
1194 which would have been overwritten by the upgrade were backed up with a .old
1220 which would have been overwritten by the upgrade were backed up with a .old
1195 extension. If you had made particular customizations in those files you may
1221 extension. If you had made particular customizations in those files you may
1196 want to merge them back into the new files.""" % locals()
1222 want to merge them back into the new files.""" % locals()
1197 wait()
1223 wait()
1198 os.chdir(cwd)
1224 os.chdir(cwd)
1199 # end user_setup()
1225 # end user_setup()
1200
1226
1201 def atexit_operations(self):
1227 def atexit_operations(self):
1202 """This will be executed at the time of exit.
1228 """This will be executed at the time of exit.
1203
1229
1204 Saving of persistent data should be performed here. """
1230 Saving of persistent data should be performed here. """
1205
1231
1206 #print '*** IPython exit cleanup ***' # dbg
1232 #print '*** IPython exit cleanup ***' # dbg
1207 # input history
1233 # input history
1208 self.savehist()
1234 self.savehist()
1209
1235
1210 # Cleanup all tempfiles left around
1236 # Cleanup all tempfiles left around
1211 for tfile in self.tempfiles:
1237 for tfile in self.tempfiles:
1212 try:
1238 try:
1213 os.unlink(tfile)
1239 os.unlink(tfile)
1214 except OSError:
1240 except OSError:
1215 pass
1241 pass
1216
1242
1217 # save the "persistent data" catch-all dictionary
1243 # save the "persistent data" catch-all dictionary
1218 self.hooks.shutdown_hook()
1244 self.hooks.shutdown_hook()
1219
1245
1220 def savehist(self):
1246 def savehist(self):
1221 """Save input history to a file (via readline library)."""
1247 """Save input history to a file (via readline library)."""
1222 try:
1248 try:
1223 self.readline.write_history_file(self.histfile)
1249 self.readline.write_history_file(self.histfile)
1224 except:
1250 except:
1225 print 'Unable to save IPython command history to file: ' + \
1251 print 'Unable to save IPython command history to file: ' + \
1226 `self.histfile`
1252 `self.histfile`
1227
1253
1228 def history_saving_wrapper(self, func):
1254 def history_saving_wrapper(self, func):
1229 """ Wrap func for readline history saving
1255 """ Wrap func for readline history saving
1230
1256
1231 Convert func into callable that saves & restores
1257 Convert func into callable that saves & restores
1232 history around the call """
1258 history around the call """
1233
1259
1234 if not self.has_readline:
1260 if not self.has_readline:
1235 return func
1261 return func
1236
1262
1237 def wrapper():
1263 def wrapper():
1238 self.savehist()
1264 self.savehist()
1239 try:
1265 try:
1240 func()
1266 func()
1241 finally:
1267 finally:
1242 readline.read_history_file(self.histfile)
1268 readline.read_history_file(self.histfile)
1243 return wrapper
1269 return wrapper
1244
1270
1245
1271
1246 def pre_readline(self):
1272 def pre_readline(self):
1247 """readline hook to be used at the start of each line.
1273 """readline hook to be used at the start of each line.
1248
1274
1249 Currently it handles auto-indent only."""
1275 Currently it handles auto-indent only."""
1250
1276
1251 #debugx('self.indent_current_nsp','pre_readline:')
1277 #debugx('self.indent_current_nsp','pre_readline:')
1252 self.readline.insert_text(self.indent_current_str())
1278 self.readline.insert_text(self.indent_current_str())
1253
1279
1254 def init_readline(self):
1280 def init_readline(self):
1255 """Command history completion/saving/reloading."""
1281 """Command history completion/saving/reloading."""
1256
1282
1257 import IPython.rlineimpl as readline
1283 import IPython.rlineimpl as readline
1258 if not readline.have_readline:
1284 if not readline.have_readline:
1259 self.has_readline = 0
1285 self.has_readline = 0
1260 self.readline = None
1286 self.readline = None
1261 # no point in bugging windows users with this every time:
1287 # no point in bugging windows users with this every time:
1262 warn('Readline services not available on this platform.')
1288 warn('Readline services not available on this platform.')
1263 else:
1289 else:
1264 sys.modules['readline'] = readline
1290 sys.modules['readline'] = readline
1265 import atexit
1291 import atexit
1266 from IPython.completer import IPCompleter
1292 from IPython.completer import IPCompleter
1267 self.Completer = IPCompleter(self,
1293 self.Completer = IPCompleter(self,
1268 self.user_ns,
1294 self.user_ns,
1269 self.user_global_ns,
1295 self.user_global_ns,
1270 self.rc.readline_omit__names,
1296 self.rc.readline_omit__names,
1271 self.alias_table)
1297 self.alias_table)
1272 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1298 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1273 self.strdispatchers['complete_command'] = sdisp
1299 self.strdispatchers['complete_command'] = sdisp
1274 self.Completer.custom_completers = sdisp
1300 self.Completer.custom_completers = sdisp
1275 # Platform-specific configuration
1301 # Platform-specific configuration
1276 if os.name == 'nt':
1302 if os.name == 'nt':
1277 self.readline_startup_hook = readline.set_pre_input_hook
1303 self.readline_startup_hook = readline.set_pre_input_hook
1278 else:
1304 else:
1279 self.readline_startup_hook = readline.set_startup_hook
1305 self.readline_startup_hook = readline.set_startup_hook
1280
1306
1281 # Load user's initrc file (readline config)
1307 # Load user's initrc file (readline config)
1282 inputrc_name = os.environ.get('INPUTRC')
1308 inputrc_name = os.environ.get('INPUTRC')
1283 if inputrc_name is None:
1309 if inputrc_name is None:
1284 home_dir = get_home_dir()
1310 home_dir = get_home_dir()
1285 if home_dir is not None:
1311 if home_dir is not None:
1286 inputrc_name = os.path.join(home_dir,'.inputrc')
1312 inputrc_name = os.path.join(home_dir,'.inputrc')
1287 if os.path.isfile(inputrc_name):
1313 if os.path.isfile(inputrc_name):
1288 try:
1314 try:
1289 readline.read_init_file(inputrc_name)
1315 readline.read_init_file(inputrc_name)
1290 except:
1316 except:
1291 warn('Problems reading readline initialization file <%s>'
1317 warn('Problems reading readline initialization file <%s>'
1292 % inputrc_name)
1318 % inputrc_name)
1293
1319
1294 self.has_readline = 1
1320 self.has_readline = 1
1295 self.readline = readline
1321 self.readline = readline
1296 # save this in sys so embedded copies can restore it properly
1322 # save this in sys so embedded copies can restore it properly
1297 sys.ipcompleter = self.Completer.complete
1323 sys.ipcompleter = self.Completer.complete
1298 readline.set_completer(self.Completer.complete)
1324 readline.set_completer(self.Completer.complete)
1299
1325
1300 # Configure readline according to user's prefs
1326 # Configure readline according to user's prefs
1301 for rlcommand in self.rc.readline_parse_and_bind:
1327 for rlcommand in self.rc.readline_parse_and_bind:
1302 readline.parse_and_bind(rlcommand)
1328 readline.parse_and_bind(rlcommand)
1303
1329
1304 # remove some chars from the delimiters list
1330 # remove some chars from the delimiters list
1305 delims = readline.get_completer_delims()
1331 delims = readline.get_completer_delims()
1306 delims = delims.translate(string._idmap,
1332 delims = delims.translate(string._idmap,
1307 self.rc.readline_remove_delims)
1333 self.rc.readline_remove_delims)
1308 readline.set_completer_delims(delims)
1334 readline.set_completer_delims(delims)
1309 # otherwise we end up with a monster history after a while:
1335 # otherwise we end up with a monster history after a while:
1310 readline.set_history_length(1000)
1336 readline.set_history_length(1000)
1311 try:
1337 try:
1312 #print '*** Reading readline history' # dbg
1338 #print '*** Reading readline history' # dbg
1313 readline.read_history_file(self.histfile)
1339 readline.read_history_file(self.histfile)
1314 except IOError:
1340 except IOError:
1315 pass # It doesn't exist yet.
1341 pass # It doesn't exist yet.
1316
1342
1317 atexit.register(self.atexit_operations)
1343 atexit.register(self.atexit_operations)
1318 del atexit
1344 del atexit
1319
1345
1320 # Configure auto-indent for all platforms
1346 # Configure auto-indent for all platforms
1321 self.set_autoindent(self.rc.autoindent)
1347 self.set_autoindent(self.rc.autoindent)
1322
1348
1323 def ask_yes_no(self,prompt,default=True):
1349 def ask_yes_no(self,prompt,default=True):
1324 if self.rc.quiet:
1350 if self.rc.quiet:
1325 return True
1351 return True
1326 return ask_yes_no(prompt,default)
1352 return ask_yes_no(prompt,default)
1327
1353
1328 def _should_recompile(self,e):
1354 def _should_recompile(self,e):
1329 """Utility routine for edit_syntax_error"""
1355 """Utility routine for edit_syntax_error"""
1330
1356
1331 if e.filename in ('<ipython console>','<input>','<string>',
1357 if e.filename in ('<ipython console>','<input>','<string>',
1332 '<console>','<BackgroundJob compilation>',
1358 '<console>','<BackgroundJob compilation>',
1333 None):
1359 None):
1334
1360
1335 return False
1361 return False
1336 try:
1362 try:
1337 if (self.rc.autoedit_syntax and
1363 if (self.rc.autoedit_syntax and
1338 not self.ask_yes_no('Return to editor to correct syntax error? '
1364 not self.ask_yes_no('Return to editor to correct syntax error? '
1339 '[Y/n] ','y')):
1365 '[Y/n] ','y')):
1340 return False
1366 return False
1341 except EOFError:
1367 except EOFError:
1342 return False
1368 return False
1343
1369
1344 def int0(x):
1370 def int0(x):
1345 try:
1371 try:
1346 return int(x)
1372 return int(x)
1347 except TypeError:
1373 except TypeError:
1348 return 0
1374 return 0
1349 # always pass integer line and offset values to editor hook
1375 # always pass integer line and offset values to editor hook
1350 self.hooks.fix_error_editor(e.filename,
1376 self.hooks.fix_error_editor(e.filename,
1351 int0(e.lineno),int0(e.offset),e.msg)
1377 int0(e.lineno),int0(e.offset),e.msg)
1352 return True
1378 return True
1353
1379
1354 def edit_syntax_error(self):
1380 def edit_syntax_error(self):
1355 """The bottom half of the syntax error handler called in the main loop.
1381 """The bottom half of the syntax error handler called in the main loop.
1356
1382
1357 Loop until syntax error is fixed or user cancels.
1383 Loop until syntax error is fixed or user cancels.
1358 """
1384 """
1359
1385
1360 while self.SyntaxTB.last_syntax_error:
1386 while self.SyntaxTB.last_syntax_error:
1361 # copy and clear last_syntax_error
1387 # copy and clear last_syntax_error
1362 err = self.SyntaxTB.clear_err_state()
1388 err = self.SyntaxTB.clear_err_state()
1363 if not self._should_recompile(err):
1389 if not self._should_recompile(err):
1364 return
1390 return
1365 try:
1391 try:
1366 # may set last_syntax_error again if a SyntaxError is raised
1392 # may set last_syntax_error again if a SyntaxError is raised
1367 self.safe_execfile(err.filename,self.user_ns)
1393 self.safe_execfile(err.filename,self.user_ns)
1368 except:
1394 except:
1369 self.showtraceback()
1395 self.showtraceback()
1370 else:
1396 else:
1371 try:
1397 try:
1372 f = file(err.filename)
1398 f = file(err.filename)
1373 try:
1399 try:
1374 sys.displayhook(f.read())
1400 sys.displayhook(f.read())
1375 finally:
1401 finally:
1376 f.close()
1402 f.close()
1377 except:
1403 except:
1378 self.showtraceback()
1404 self.showtraceback()
1379
1405
1380 def showsyntaxerror(self, filename=None):
1406 def showsyntaxerror(self, filename=None):
1381 """Display the syntax error that just occurred.
1407 """Display the syntax error that just occurred.
1382
1408
1383 This doesn't display a stack trace because there isn't one.
1409 This doesn't display a stack trace because there isn't one.
1384
1410
1385 If a filename is given, it is stuffed in the exception instead
1411 If a filename is given, it is stuffed in the exception instead
1386 of what was there before (because Python's parser always uses
1412 of what was there before (because Python's parser always uses
1387 "<string>" when reading from a string).
1413 "<string>" when reading from a string).
1388 """
1414 """
1389 etype, value, last_traceback = sys.exc_info()
1415 etype, value, last_traceback = sys.exc_info()
1390
1416
1391 # See note about these variables in showtraceback() below
1417 # See note about these variables in showtraceback() below
1392 sys.last_type = etype
1418 sys.last_type = etype
1393 sys.last_value = value
1419 sys.last_value = value
1394 sys.last_traceback = last_traceback
1420 sys.last_traceback = last_traceback
1395
1421
1396 if filename and etype is SyntaxError:
1422 if filename and etype is SyntaxError:
1397 # Work hard to stuff the correct filename in the exception
1423 # Work hard to stuff the correct filename in the exception
1398 try:
1424 try:
1399 msg, (dummy_filename, lineno, offset, line) = value
1425 msg, (dummy_filename, lineno, offset, line) = value
1400 except:
1426 except:
1401 # Not the format we expect; leave it alone
1427 # Not the format we expect; leave it alone
1402 pass
1428 pass
1403 else:
1429 else:
1404 # Stuff in the right filename
1430 # Stuff in the right filename
1405 try:
1431 try:
1406 # Assume SyntaxError is a class exception
1432 # Assume SyntaxError is a class exception
1407 value = SyntaxError(msg, (filename, lineno, offset, line))
1433 value = SyntaxError(msg, (filename, lineno, offset, line))
1408 except:
1434 except:
1409 # If that failed, assume SyntaxError is a string
1435 # If that failed, assume SyntaxError is a string
1410 value = msg, (filename, lineno, offset, line)
1436 value = msg, (filename, lineno, offset, line)
1411 self.SyntaxTB(etype,value,[])
1437 self.SyntaxTB(etype,value,[])
1412
1438
1413 def debugger(self):
1439 def debugger(self):
1414 """Call the pydb/pdb debugger."""
1440 """Call the pydb/pdb debugger."""
1415
1441
1416 if not self.rc.pdb:
1442 if not self.rc.pdb:
1417 return
1443 return
1418 have_pydb = False
1444 have_pydb = False
1419 if sys.version[:3] >= '2.5':
1445 if sys.version[:3] >= '2.5':
1420 try:
1446 try:
1421 from pydb import pm
1447 from pydb import pm
1422 have_pydb = True
1448 have_pydb = True
1423 except ImportError:
1449 except ImportError:
1424 pass
1450 pass
1425 if not have_pydb:
1451 if not have_pydb:
1426 from pdb import pm
1452 from pdb import pm
1427 self.history_saving_wrapper(pm)()
1453 self.history_saving_wrapper(pm)()
1428
1454
1429 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1455 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1430 """Display the exception that just occurred.
1456 """Display the exception that just occurred.
1431
1457
1432 If nothing is known about the exception, this is the method which
1458 If nothing is known about the exception, this is the method which
1433 should be used throughout the code for presenting user tracebacks,
1459 should be used throughout the code for presenting user tracebacks,
1434 rather than directly invoking the InteractiveTB object.
1460 rather than directly invoking the InteractiveTB object.
1435
1461
1436 A specific showsyntaxerror() also exists, but this method can take
1462 A specific showsyntaxerror() also exists, but this method can take
1437 care of calling it if needed, so unless you are explicitly catching a
1463 care of calling it if needed, so unless you are explicitly catching a
1438 SyntaxError exception, don't try to analyze the stack manually and
1464 SyntaxError exception, don't try to analyze the stack manually and
1439 simply call this method."""
1465 simply call this method."""
1440
1466
1441 # Though this won't be called by syntax errors in the input line,
1467 # Though this won't be called by syntax errors in the input line,
1442 # there may be SyntaxError cases whith imported code.
1468 # there may be SyntaxError cases whith imported code.
1443 if exc_tuple is None:
1469 if exc_tuple is None:
1444 etype, value, tb = sys.exc_info()
1470 etype, value, tb = sys.exc_info()
1445 else:
1471 else:
1446 etype, value, tb = exc_tuple
1472 etype, value, tb = exc_tuple
1447 if etype is SyntaxError:
1473 if etype is SyntaxError:
1448 self.showsyntaxerror(filename)
1474 self.showsyntaxerror(filename)
1449 else:
1475 else:
1450 # WARNING: these variables are somewhat deprecated and not
1476 # WARNING: these variables are somewhat deprecated and not
1451 # necessarily safe to use in a threaded environment, but tools
1477 # necessarily safe to use in a threaded environment, but tools
1452 # like pdb depend on their existence, so let's set them. If we
1478 # like pdb depend on their existence, so let's set them. If we
1453 # find problems in the field, we'll need to revisit their use.
1479 # find problems in the field, we'll need to revisit their use.
1454 sys.last_type = etype
1480 sys.last_type = etype
1455 sys.last_value = value
1481 sys.last_value = value
1456 sys.last_traceback = tb
1482 sys.last_traceback = tb
1457
1483
1458 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1484 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1459 if self.InteractiveTB.call_pdb and self.has_readline:
1485 if self.InteractiveTB.call_pdb and self.has_readline:
1460 # pdb mucks up readline, fix it back
1486 # pdb mucks up readline, fix it back
1461 self.readline.set_completer(self.Completer.complete)
1487 self.readline.set_completer(self.Completer.complete)
1462
1488
1463 def mainloop(self,banner=None):
1489 def mainloop(self,banner=None):
1464 """Creates the local namespace and starts the mainloop.
1490 """Creates the local namespace and starts the mainloop.
1465
1491
1466 If an optional banner argument is given, it will override the
1492 If an optional banner argument is given, it will override the
1467 internally created default banner."""
1493 internally created default banner."""
1468
1494
1469 if self.rc.c: # Emulate Python's -c option
1495 if self.rc.c: # Emulate Python's -c option
1470 self.exec_init_cmd()
1496 self.exec_init_cmd()
1471 if banner is None:
1497 if banner is None:
1472 if not self.rc.banner:
1498 if not self.rc.banner:
1473 banner = ''
1499 banner = ''
1474 # banner is string? Use it directly!
1500 # banner is string? Use it directly!
1475 elif isinstance(self.rc.banner,basestring):
1501 elif isinstance(self.rc.banner,basestring):
1476 banner = self.rc.banner
1502 banner = self.rc.banner
1477 else:
1503 else:
1478 banner = self.BANNER+self.banner2
1504 banner = self.BANNER+self.banner2
1479
1505
1480 self.interact(banner)
1506 self.interact(banner)
1481
1507
1482 def exec_init_cmd(self):
1508 def exec_init_cmd(self):
1483 """Execute a command given at the command line.
1509 """Execute a command given at the command line.
1484
1510
1485 This emulates Python's -c option."""
1511 This emulates Python's -c option."""
1486
1512
1487 #sys.argv = ['-c']
1513 #sys.argv = ['-c']
1488 self.push(self.rc.c)
1514 self.push(self.rc.c)
1489
1515
1490 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1516 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1491 """Embeds IPython into a running python program.
1517 """Embeds IPython into a running python program.
1492
1518
1493 Input:
1519 Input:
1494
1520
1495 - header: An optional header message can be specified.
1521 - header: An optional header message can be specified.
1496
1522
1497 - local_ns, global_ns: working namespaces. If given as None, the
1523 - local_ns, global_ns: working namespaces. If given as None, the
1498 IPython-initialized one is updated with __main__.__dict__, so that
1524 IPython-initialized one is updated with __main__.__dict__, so that
1499 program variables become visible but user-specific configuration
1525 program variables become visible but user-specific configuration
1500 remains possible.
1526 remains possible.
1501
1527
1502 - stack_depth: specifies how many levels in the stack to go to
1528 - stack_depth: specifies how many levels in the stack to go to
1503 looking for namespaces (when local_ns and global_ns are None). This
1529 looking for namespaces (when local_ns and global_ns are None). This
1504 allows an intermediate caller to make sure that this function gets
1530 allows an intermediate caller to make sure that this function gets
1505 the namespace from the intended level in the stack. By default (0)
1531 the namespace from the intended level in the stack. By default (0)
1506 it will get its locals and globals from the immediate caller.
1532 it will get its locals and globals from the immediate caller.
1507
1533
1508 Warning: it's possible to use this in a program which is being run by
1534 Warning: it's possible to use this in a program which is being run by
1509 IPython itself (via %run), but some funny things will happen (a few
1535 IPython itself (via %run), but some funny things will happen (a few
1510 globals get overwritten). In the future this will be cleaned up, as
1536 globals get overwritten). In the future this will be cleaned up, as
1511 there is no fundamental reason why it can't work perfectly."""
1537 there is no fundamental reason why it can't work perfectly."""
1512
1538
1513 # Get locals and globals from caller
1539 # Get locals and globals from caller
1514 if local_ns is None or global_ns is None:
1540 if local_ns is None or global_ns is None:
1515 call_frame = sys._getframe(stack_depth).f_back
1541 call_frame = sys._getframe(stack_depth).f_back
1516
1542
1517 if local_ns is None:
1543 if local_ns is None:
1518 local_ns = call_frame.f_locals
1544 local_ns = call_frame.f_locals
1519 if global_ns is None:
1545 if global_ns is None:
1520 global_ns = call_frame.f_globals
1546 global_ns = call_frame.f_globals
1521
1547
1522 # Update namespaces and fire up interpreter
1548 # Update namespaces and fire up interpreter
1523
1549
1524 # The global one is easy, we can just throw it in
1550 # The global one is easy, we can just throw it in
1525 self.user_global_ns = global_ns
1551 self.user_global_ns = global_ns
1526
1552
1527 # but the user/local one is tricky: ipython needs it to store internal
1553 # but the user/local one is tricky: ipython needs it to store internal
1528 # data, but we also need the locals. We'll copy locals in the user
1554 # data, but we also need the locals. We'll copy locals in the user
1529 # one, but will track what got copied so we can delete them at exit.
1555 # one, but will track what got copied so we can delete them at exit.
1530 # This is so that a later embedded call doesn't see locals from a
1556 # This is so that a later embedded call doesn't see locals from a
1531 # previous call (which most likely existed in a separate scope).
1557 # previous call (which most likely existed in a separate scope).
1532 local_varnames = local_ns.keys()
1558 local_varnames = local_ns.keys()
1533 self.user_ns.update(local_ns)
1559 self.user_ns.update(local_ns)
1534
1560
1535 # Patch for global embedding to make sure that things don't overwrite
1561 # Patch for global embedding to make sure that things don't overwrite
1536 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1562 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1537 # FIXME. Test this a bit more carefully (the if.. is new)
1563 # FIXME. Test this a bit more carefully (the if.. is new)
1538 if local_ns is None and global_ns is None:
1564 if local_ns is None and global_ns is None:
1539 self.user_global_ns.update(__main__.__dict__)
1565 self.user_global_ns.update(__main__.__dict__)
1540
1566
1541 # make sure the tab-completer has the correct frame information, so it
1567 # make sure the tab-completer has the correct frame information, so it
1542 # actually completes using the frame's locals/globals
1568 # actually completes using the frame's locals/globals
1543 self.set_completer_frame()
1569 self.set_completer_frame()
1544
1570
1545 # before activating the interactive mode, we need to make sure that
1571 # before activating the interactive mode, we need to make sure that
1546 # all names in the builtin namespace needed by ipython point to
1572 # all names in the builtin namespace needed by ipython point to
1547 # ourselves, and not to other instances.
1573 # ourselves, and not to other instances.
1548 self.add_builtins()
1574 self.add_builtins()
1549
1575
1550 self.interact(header)
1576 self.interact(header)
1551
1577
1552 # now, purge out the user namespace from anything we might have added
1578 # now, purge out the user namespace from anything we might have added
1553 # from the caller's local namespace
1579 # from the caller's local namespace
1554 delvar = self.user_ns.pop
1580 delvar = self.user_ns.pop
1555 for var in local_varnames:
1581 for var in local_varnames:
1556 delvar(var,None)
1582 delvar(var,None)
1557 # and clean builtins we may have overridden
1583 # and clean builtins we may have overridden
1558 self.clean_builtins()
1584 self.clean_builtins()
1559
1585
1560 def interact(self, banner=None):
1586 def interact(self, banner=None):
1561 """Closely emulate the interactive Python console.
1587 """Closely emulate the interactive Python console.
1562
1588
1563 The optional banner argument specify the banner to print
1589 The optional banner argument specify the banner to print
1564 before the first interaction; by default it prints a banner
1590 before the first interaction; by default it prints a banner
1565 similar to the one printed by the real Python interpreter,
1591 similar to the one printed by the real Python interpreter,
1566 followed by the current class name in parentheses (so as not
1592 followed by the current class name in parentheses (so as not
1567 to confuse this with the real interpreter -- since it's so
1593 to confuse this with the real interpreter -- since it's so
1568 close!).
1594 close!).
1569
1595
1570 """
1596 """
1571
1597
1572 if self.exit_now:
1598 if self.exit_now:
1573 # batch run -> do not interact
1599 # batch run -> do not interact
1574 return
1600 return
1575 cprt = 'Type "copyright", "credits" or "license" for more information.'
1601 cprt = 'Type "copyright", "credits" or "license" for more information.'
1576 if banner is None:
1602 if banner is None:
1577 self.write("Python %s on %s\n%s\n(%s)\n" %
1603 self.write("Python %s on %s\n%s\n(%s)\n" %
1578 (sys.version, sys.platform, cprt,
1604 (sys.version, sys.platform, cprt,
1579 self.__class__.__name__))
1605 self.__class__.__name__))
1580 else:
1606 else:
1581 self.write(banner)
1607 self.write(banner)
1582
1608
1583 more = 0
1609 more = 0
1584
1610
1585 # Mark activity in the builtins
1611 # Mark activity in the builtins
1586 __builtin__.__dict__['__IPYTHON__active'] += 1
1612 __builtin__.__dict__['__IPYTHON__active'] += 1
1587
1613
1588 # exit_now is set by a call to %Exit or %Quit
1614 # exit_now is set by a call to %Exit or %Quit
1589 while not self.exit_now:
1615 while not self.exit_now:
1590 if more:
1616 if more:
1591 prompt = self.hooks.generate_prompt(True)
1617 prompt = self.hooks.generate_prompt(True)
1592 if self.autoindent:
1618 if self.autoindent:
1593 self.readline_startup_hook(self.pre_readline)
1619 self.readline_startup_hook(self.pre_readline)
1594 else:
1620 else:
1595 prompt = self.hooks.generate_prompt(False)
1621 prompt = self.hooks.generate_prompt(False)
1596 try:
1622 try:
1597 line = self.raw_input(prompt,more)
1623 line = self.raw_input(prompt,more)
1598 if self.exit_now:
1624 if self.exit_now:
1599 # quick exit on sys.std[in|out] close
1625 # quick exit on sys.std[in|out] close
1600 break
1626 break
1601 if self.autoindent:
1627 if self.autoindent:
1602 self.readline_startup_hook(None)
1628 self.readline_startup_hook(None)
1603 except KeyboardInterrupt:
1629 except KeyboardInterrupt:
1604 self.write('\nKeyboardInterrupt\n')
1630 self.write('\nKeyboardInterrupt\n')
1605 self.resetbuffer()
1631 self.resetbuffer()
1606 # keep cache in sync with the prompt counter:
1632 # keep cache in sync with the prompt counter:
1607 self.outputcache.prompt_count -= 1
1633 self.outputcache.prompt_count -= 1
1608
1634
1609 if self.autoindent:
1635 if self.autoindent:
1610 self.indent_current_nsp = 0
1636 self.indent_current_nsp = 0
1611 more = 0
1637 more = 0
1612 except EOFError:
1638 except EOFError:
1613 if self.autoindent:
1639 if self.autoindent:
1614 self.readline_startup_hook(None)
1640 self.readline_startup_hook(None)
1615 self.write('\n')
1641 self.write('\n')
1616 self.exit()
1642 self.exit()
1617 except bdb.BdbQuit:
1643 except bdb.BdbQuit:
1618 warn('The Python debugger has exited with a BdbQuit exception.\n'
1644 warn('The Python debugger has exited with a BdbQuit exception.\n'
1619 'Because of how pdb handles the stack, it is impossible\n'
1645 'Because of how pdb handles the stack, it is impossible\n'
1620 'for IPython to properly format this particular exception.\n'
1646 'for IPython to properly format this particular exception.\n'
1621 'IPython will resume normal operation.')
1647 'IPython will resume normal operation.')
1622 except:
1648 except:
1623 # exceptions here are VERY RARE, but they can be triggered
1649 # exceptions here are VERY RARE, but they can be triggered
1624 # asynchronously by signal handlers, for example.
1650 # asynchronously by signal handlers, for example.
1625 self.showtraceback()
1651 self.showtraceback()
1626 else:
1652 else:
1627 more = self.push(line)
1653 more = self.push(line)
1628 if (self.SyntaxTB.last_syntax_error and
1654 if (self.SyntaxTB.last_syntax_error and
1629 self.rc.autoedit_syntax):
1655 self.rc.autoedit_syntax):
1630 self.edit_syntax_error()
1656 self.edit_syntax_error()
1631
1657
1632 # We are off again...
1658 # We are off again...
1633 __builtin__.__dict__['__IPYTHON__active'] -= 1
1659 __builtin__.__dict__['__IPYTHON__active'] -= 1
1634
1660
1635 def excepthook(self, etype, value, tb):
1661 def excepthook(self, etype, value, tb):
1636 """One more defense for GUI apps that call sys.excepthook.
1662 """One more defense for GUI apps that call sys.excepthook.
1637
1663
1638 GUI frameworks like wxPython trap exceptions and call
1664 GUI frameworks like wxPython trap exceptions and call
1639 sys.excepthook themselves. I guess this is a feature that
1665 sys.excepthook themselves. I guess this is a feature that
1640 enables them to keep running after exceptions that would
1666 enables them to keep running after exceptions that would
1641 otherwise kill their mainloop. This is a bother for IPython
1667 otherwise kill their mainloop. This is a bother for IPython
1642 which excepts to catch all of the program exceptions with a try:
1668 which excepts to catch all of the program exceptions with a try:
1643 except: statement.
1669 except: statement.
1644
1670
1645 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1671 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1646 any app directly invokes sys.excepthook, it will look to the user like
1672 any app directly invokes sys.excepthook, it will look to the user like
1647 IPython crashed. In order to work around this, we can disable the
1673 IPython crashed. In order to work around this, we can disable the
1648 CrashHandler and replace it with this excepthook instead, which prints a
1674 CrashHandler and replace it with this excepthook instead, which prints a
1649 regular traceback using our InteractiveTB. In this fashion, apps which
1675 regular traceback using our InteractiveTB. In this fashion, apps which
1650 call sys.excepthook will generate a regular-looking exception from
1676 call sys.excepthook will generate a regular-looking exception from
1651 IPython, and the CrashHandler will only be triggered by real IPython
1677 IPython, and the CrashHandler will only be triggered by real IPython
1652 crashes.
1678 crashes.
1653
1679
1654 This hook should be used sparingly, only in places which are not likely
1680 This hook should be used sparingly, only in places which are not likely
1655 to be true IPython errors.
1681 to be true IPython errors.
1656 """
1682 """
1657 self.showtraceback((etype,value,tb),tb_offset=0)
1683 self.showtraceback((etype,value,tb),tb_offset=0)
1658
1684
1659 def expand_aliases(self,fn,rest):
1685 def expand_aliases(self,fn,rest):
1660 """ Expand multiple levels of aliases:
1686 """ Expand multiple levels of aliases:
1661
1687
1662 if:
1688 if:
1663
1689
1664 alias foo bar /tmp
1690 alias foo bar /tmp
1665 alias baz foo
1691 alias baz foo
1666
1692
1667 then:
1693 then:
1668
1694
1669 baz huhhahhei -> bar /tmp huhhahhei
1695 baz huhhahhei -> bar /tmp huhhahhei
1670
1696
1671 """
1697 """
1672 line = fn + " " + rest
1698 line = fn + " " + rest
1673
1699
1674 done = Set()
1700 done = Set()
1675 while 1:
1701 while 1:
1676 pre,fn,rest = self.split_user_input(line)
1702 pre,fn,rest = self.split_user_input(line)
1677 if fn in self.alias_table:
1703 if fn in self.alias_table:
1678 if fn in done:
1704 if fn in done:
1679 warn("Cyclic alias definition, repeated '%s'" % fn)
1705 warn("Cyclic alias definition, repeated '%s'" % fn)
1680 return ""
1706 return ""
1681 done.add(fn)
1707 done.add(fn)
1682
1708
1683 l2 = self.transform_alias(fn,rest)
1709 l2 = self.transform_alias(fn,rest)
1684 # dir -> dir
1710 # dir -> dir
1685 # print "alias",line, "->",l2 #dbg
1711 # print "alias",line, "->",l2 #dbg
1686 if l2 == line:
1712 if l2 == line:
1687 break
1713 break
1688 # ls -> ls -F should not recurse forever
1714 # ls -> ls -F should not recurse forever
1689 if l2.split(None,1)[0] == line.split(None,1)[0]:
1715 if l2.split(None,1)[0] == line.split(None,1)[0]:
1690 line = l2
1716 line = l2
1691 break
1717 break
1692
1718
1693 line=l2
1719 line=l2
1694
1720
1695
1721
1696 # print "al expand to",line #dbg
1722 # print "al expand to",line #dbg
1697 else:
1723 else:
1698 break
1724 break
1699
1725
1700 return line
1726 return line
1701
1727
1702 def transform_alias(self, alias,rest=''):
1728 def transform_alias(self, alias,rest=''):
1703 """ Transform alias to system command string.
1729 """ Transform alias to system command string.
1704 """
1730 """
1705 nargs,cmd = self.alias_table[alias]
1731 nargs,cmd = self.alias_table[alias]
1706 if ' ' in cmd and os.path.isfile(cmd):
1732 if ' ' in cmd and os.path.isfile(cmd):
1707 cmd = '"%s"' % cmd
1733 cmd = '"%s"' % cmd
1708
1734
1709 # Expand the %l special to be the user's input line
1735 # Expand the %l special to be the user's input line
1710 if cmd.find('%l') >= 0:
1736 if cmd.find('%l') >= 0:
1711 cmd = cmd.replace('%l',rest)
1737 cmd = cmd.replace('%l',rest)
1712 rest = ''
1738 rest = ''
1713 if nargs==0:
1739 if nargs==0:
1714 # Simple, argument-less aliases
1740 # Simple, argument-less aliases
1715 cmd = '%s %s' % (cmd,rest)
1741 cmd = '%s %s' % (cmd,rest)
1716 else:
1742 else:
1717 # Handle aliases with positional arguments
1743 # Handle aliases with positional arguments
1718 args = rest.split(None,nargs)
1744 args = rest.split(None,nargs)
1719 if len(args)< nargs:
1745 if len(args)< nargs:
1720 error('Alias <%s> requires %s arguments, %s given.' %
1746 error('Alias <%s> requires %s arguments, %s given.' %
1721 (alias,nargs,len(args)))
1747 (alias,nargs,len(args)))
1722 return None
1748 return None
1723 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1749 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1724 # Now call the macro, evaluating in the user's namespace
1750 # Now call the macro, evaluating in the user's namespace
1725 #print 'new command: <%r>' % cmd # dbg
1751 #print 'new command: <%r>' % cmd # dbg
1726 return cmd
1752 return cmd
1727
1753
1728 def call_alias(self,alias,rest=''):
1754 def call_alias(self,alias,rest=''):
1729 """Call an alias given its name and the rest of the line.
1755 """Call an alias given its name and the rest of the line.
1730
1756
1731 This is only used to provide backwards compatibility for users of
1757 This is only used to provide backwards compatibility for users of
1732 ipalias(), use of which is not recommended for anymore."""
1758 ipalias(), use of which is not recommended for anymore."""
1733
1759
1734 # Now call the macro, evaluating in the user's namespace
1760 # Now call the macro, evaluating in the user's namespace
1735 cmd = self.transform_alias(alias, rest)
1761 cmd = self.transform_alias(alias, rest)
1736 try:
1762 try:
1737 self.system(cmd)
1763 self.system(cmd)
1738 except:
1764 except:
1739 self.showtraceback()
1765 self.showtraceback()
1740
1766
1741 def indent_current_str(self):
1767 def indent_current_str(self):
1742 """return the current level of indentation as a string"""
1768 """return the current level of indentation as a string"""
1743 return self.indent_current_nsp * ' '
1769 return self.indent_current_nsp * ' '
1744
1770
1745 def autoindent_update(self,line):
1771 def autoindent_update(self,line):
1746 """Keep track of the indent level."""
1772 """Keep track of the indent level."""
1747
1773
1748 #debugx('line')
1774 #debugx('line')
1749 #debugx('self.indent_current_nsp')
1775 #debugx('self.indent_current_nsp')
1750 if self.autoindent:
1776 if self.autoindent:
1751 if line:
1777 if line:
1752 inisp = num_ini_spaces(line)
1778 inisp = num_ini_spaces(line)
1753 if inisp < self.indent_current_nsp:
1779 if inisp < self.indent_current_nsp:
1754 self.indent_current_nsp = inisp
1780 self.indent_current_nsp = inisp
1755
1781
1756 if line[-1] == ':':
1782 if line[-1] == ':':
1757 self.indent_current_nsp += 4
1783 self.indent_current_nsp += 4
1758 elif dedent_re.match(line):
1784 elif dedent_re.match(line):
1759 self.indent_current_nsp -= 4
1785 self.indent_current_nsp -= 4
1760 else:
1786 else:
1761 self.indent_current_nsp = 0
1787 self.indent_current_nsp = 0
1762
1788
1763 def runlines(self,lines):
1789 def runlines(self,lines):
1764 """Run a string of one or more lines of source.
1790 """Run a string of one or more lines of source.
1765
1791
1766 This method is capable of running a string containing multiple source
1792 This method is capable of running a string containing multiple source
1767 lines, as if they had been entered at the IPython prompt. Since it
1793 lines, as if they had been entered at the IPython prompt. Since it
1768 exposes IPython's processing machinery, the given strings can contain
1794 exposes IPython's processing machinery, the given strings can contain
1769 magic calls (%magic), special shell access (!cmd), etc."""
1795 magic calls (%magic), special shell access (!cmd), etc."""
1770
1796
1771 # We must start with a clean buffer, in case this is run from an
1797 # We must start with a clean buffer, in case this is run from an
1772 # interactive IPython session (via a magic, for example).
1798 # interactive IPython session (via a magic, for example).
1773 self.resetbuffer()
1799 self.resetbuffer()
1774 lines = lines.split('\n')
1800 lines = lines.split('\n')
1775 more = 0
1801 more = 0
1776 for line in lines:
1802 for line in lines:
1777 # skip blank lines so we don't mess up the prompt counter, but do
1803 # skip blank lines so we don't mess up the prompt counter, but do
1778 # NOT skip even a blank line if we are in a code block (more is
1804 # NOT skip even a blank line if we are in a code block (more is
1779 # true)
1805 # true)
1780 if line or more:
1806 if line or more:
1781 more = self.push(self.prefilter(line,more))
1807 more = self.push(self.prefilter(line,more))
1782 # IPython's runsource returns None if there was an error
1808 # IPython's runsource returns None if there was an error
1783 # compiling the code. This allows us to stop processing right
1809 # compiling the code. This allows us to stop processing right
1784 # away, so the user gets the error message at the right place.
1810 # away, so the user gets the error message at the right place.
1785 if more is None:
1811 if more is None:
1786 break
1812 break
1787 # final newline in case the input didn't have it, so that the code
1813 # final newline in case the input didn't have it, so that the code
1788 # actually does get executed
1814 # actually does get executed
1789 if more:
1815 if more:
1790 self.push('\n')
1816 self.push('\n')
1791
1817
1792 def runsource(self, source, filename='<input>', symbol='single'):
1818 def runsource(self, source, filename='<input>', symbol='single'):
1793 """Compile and run some source in the interpreter.
1819 """Compile and run some source in the interpreter.
1794
1820
1795 Arguments are as for compile_command().
1821 Arguments are as for compile_command().
1796
1822
1797 One several things can happen:
1823 One several things can happen:
1798
1824
1799 1) The input is incorrect; compile_command() raised an
1825 1) The input is incorrect; compile_command() raised an
1800 exception (SyntaxError or OverflowError). A syntax traceback
1826 exception (SyntaxError or OverflowError). A syntax traceback
1801 will be printed by calling the showsyntaxerror() method.
1827 will be printed by calling the showsyntaxerror() method.
1802
1828
1803 2) The input is incomplete, and more input is required;
1829 2) The input is incomplete, and more input is required;
1804 compile_command() returned None. Nothing happens.
1830 compile_command() returned None. Nothing happens.
1805
1831
1806 3) The input is complete; compile_command() returned a code
1832 3) The input is complete; compile_command() returned a code
1807 object. The code is executed by calling self.runcode() (which
1833 object. The code is executed by calling self.runcode() (which
1808 also handles run-time exceptions, except for SystemExit).
1834 also handles run-time exceptions, except for SystemExit).
1809
1835
1810 The return value is:
1836 The return value is:
1811
1837
1812 - True in case 2
1838 - True in case 2
1813
1839
1814 - False in the other cases, unless an exception is raised, where
1840 - False in the other cases, unless an exception is raised, where
1815 None is returned instead. This can be used by external callers to
1841 None is returned instead. This can be used by external callers to
1816 know whether to continue feeding input or not.
1842 know whether to continue feeding input or not.
1817
1843
1818 The return value can be used to decide whether to use sys.ps1 or
1844 The return value can be used to decide whether to use sys.ps1 or
1819 sys.ps2 to prompt the next line."""
1845 sys.ps2 to prompt the next line."""
1820
1846
1821 try:
1847 try:
1822 code = self.compile(source,filename,symbol)
1848 code = self.compile(source,filename,symbol)
1823 except (OverflowError, SyntaxError, ValueError):
1849 except (OverflowError, SyntaxError, ValueError):
1824 # Case 1
1850 # Case 1
1825 self.showsyntaxerror(filename)
1851 self.showsyntaxerror(filename)
1826 return None
1852 return None
1827
1853
1828 if code is None:
1854 if code is None:
1829 # Case 2
1855 # Case 2
1830 return True
1856 return True
1831
1857
1832 # Case 3
1858 # Case 3
1833 # We store the code object so that threaded shells and
1859 # We store the code object so that threaded shells and
1834 # custom exception handlers can access all this info if needed.
1860 # custom exception handlers can access all this info if needed.
1835 # The source corresponding to this can be obtained from the
1861 # The source corresponding to this can be obtained from the
1836 # buffer attribute as '\n'.join(self.buffer).
1862 # buffer attribute as '\n'.join(self.buffer).
1837 self.code_to_run = code
1863 self.code_to_run = code
1838 # now actually execute the code object
1864 # now actually execute the code object
1839 if self.runcode(code) == 0:
1865 if self.runcode(code) == 0:
1840 return False
1866 return False
1841 else:
1867 else:
1842 return None
1868 return None
1843
1869
1844 def runcode(self,code_obj):
1870 def runcode(self,code_obj):
1845 """Execute a code object.
1871 """Execute a code object.
1846
1872
1847 When an exception occurs, self.showtraceback() is called to display a
1873 When an exception occurs, self.showtraceback() is called to display a
1848 traceback.
1874 traceback.
1849
1875
1850 Return value: a flag indicating whether the code to be run completed
1876 Return value: a flag indicating whether the code to be run completed
1851 successfully:
1877 successfully:
1852
1878
1853 - 0: successful execution.
1879 - 0: successful execution.
1854 - 1: an error occurred.
1880 - 1: an error occurred.
1855 """
1881 """
1856
1882
1857 # Set our own excepthook in case the user code tries to call it
1883 # Set our own excepthook in case the user code tries to call it
1858 # directly, so that the IPython crash handler doesn't get triggered
1884 # directly, so that the IPython crash handler doesn't get triggered
1859 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1885 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1860
1886
1861 # we save the original sys.excepthook in the instance, in case config
1887 # we save the original sys.excepthook in the instance, in case config
1862 # code (such as magics) needs access to it.
1888 # code (such as magics) needs access to it.
1863 self.sys_excepthook = old_excepthook
1889 self.sys_excepthook = old_excepthook
1864 outflag = 1 # happens in more places, so it's easier as default
1890 outflag = 1 # happens in more places, so it's easier as default
1865 try:
1891 try:
1866 try:
1892 try:
1867 # Embedded instances require separate global/local namespaces
1893 # Embedded instances require separate global/local namespaces
1868 # so they can see both the surrounding (local) namespace and
1894 # so they can see both the surrounding (local) namespace and
1869 # the module-level globals when called inside another function.
1895 # the module-level globals when called inside another function.
1870 if self.embedded:
1896 if self.embedded:
1871 exec code_obj in self.user_global_ns, self.user_ns
1897 exec code_obj in self.user_global_ns, self.user_ns
1872 # Normal (non-embedded) instances should only have a single
1898 # Normal (non-embedded) instances should only have a single
1873 # namespace for user code execution, otherwise functions won't
1899 # namespace for user code execution, otherwise functions won't
1874 # see interactive top-level globals.
1900 # see interactive top-level globals.
1875 else:
1901 else:
1876 exec code_obj in self.user_ns
1902 exec code_obj in self.user_ns
1877 finally:
1903 finally:
1878 # Reset our crash handler in place
1904 # Reset our crash handler in place
1879 sys.excepthook = old_excepthook
1905 sys.excepthook = old_excepthook
1880 except SystemExit:
1906 except SystemExit:
1881 self.resetbuffer()
1907 self.resetbuffer()
1882 self.showtraceback()
1908 self.showtraceback()
1883 warn("Type %exit or %quit to exit IPython "
1909 warn("Type %exit or %quit to exit IPython "
1884 "(%Exit or %Quit do so unconditionally).",level=1)
1910 "(%Exit or %Quit do so unconditionally).",level=1)
1885 except self.custom_exceptions:
1911 except self.custom_exceptions:
1886 etype,value,tb = sys.exc_info()
1912 etype,value,tb = sys.exc_info()
1887 self.CustomTB(etype,value,tb)
1913 self.CustomTB(etype,value,tb)
1888 except:
1914 except:
1889 self.showtraceback()
1915 self.showtraceback()
1890 else:
1916 else:
1891 outflag = 0
1917 outflag = 0
1892 if softspace(sys.stdout, 0):
1918 if softspace(sys.stdout, 0):
1893 print
1919 print
1894 # Flush out code object which has been run (and source)
1920 # Flush out code object which has been run (and source)
1895 self.code_to_run = None
1921 self.code_to_run = None
1896 return outflag
1922 return outflag
1897
1923
1898 def push(self, line):
1924 def push(self, line):
1899 """Push a line to the interpreter.
1925 """Push a line to the interpreter.
1900
1926
1901 The line should not have a trailing newline; it may have
1927 The line should not have a trailing newline; it may have
1902 internal newlines. The line is appended to a buffer and the
1928 internal newlines. The line is appended to a buffer and the
1903 interpreter's runsource() method is called with the
1929 interpreter's runsource() method is called with the
1904 concatenated contents of the buffer as source. If this
1930 concatenated contents of the buffer as source. If this
1905 indicates that the command was executed or invalid, the buffer
1931 indicates that the command was executed or invalid, the buffer
1906 is reset; otherwise, the command is incomplete, and the buffer
1932 is reset; otherwise, the command is incomplete, and the buffer
1907 is left as it was after the line was appended. The return
1933 is left as it was after the line was appended. The return
1908 value is 1 if more input is required, 0 if the line was dealt
1934 value is 1 if more input is required, 0 if the line was dealt
1909 with in some way (this is the same as runsource()).
1935 with in some way (this is the same as runsource()).
1910 """
1936 """
1911
1937
1912 # autoindent management should be done here, and not in the
1938 # autoindent management should be done here, and not in the
1913 # interactive loop, since that one is only seen by keyboard input. We
1939 # interactive loop, since that one is only seen by keyboard input. We
1914 # need this done correctly even for code run via runlines (which uses
1940 # need this done correctly even for code run via runlines (which uses
1915 # push).
1941 # push).
1916
1942
1917 #print 'push line: <%s>' % line # dbg
1943 #print 'push line: <%s>' % line # dbg
1918 for subline in line.splitlines():
1944 for subline in line.splitlines():
1919 self.autoindent_update(subline)
1945 self.autoindent_update(subline)
1920 self.buffer.append(line)
1946 self.buffer.append(line)
1921 more = self.runsource('\n'.join(self.buffer), self.filename)
1947 more = self.runsource('\n'.join(self.buffer), self.filename)
1922 if not more:
1948 if not more:
1923 self.resetbuffer()
1949 self.resetbuffer()
1924 return more
1950 return more
1925
1951
1926 def resetbuffer(self):
1952 def resetbuffer(self):
1927 """Reset the input buffer."""
1953 """Reset the input buffer."""
1928 self.buffer[:] = []
1954 self.buffer[:] = []
1929
1955
1930 def raw_input(self,prompt='',continue_prompt=False):
1956 def raw_input(self,prompt='',continue_prompt=False):
1931 """Write a prompt and read a line.
1957 """Write a prompt and read a line.
1932
1958
1933 The returned line does not include the trailing newline.
1959 The returned line does not include the trailing newline.
1934 When the user enters the EOF key sequence, EOFError is raised.
1960 When the user enters the EOF key sequence, EOFError is raised.
1935
1961
1936 Optional inputs:
1962 Optional inputs:
1937
1963
1938 - prompt(''): a string to be printed to prompt the user.
1964 - prompt(''): a string to be printed to prompt the user.
1939
1965
1940 - continue_prompt(False): whether this line is the first one or a
1966 - continue_prompt(False): whether this line is the first one or a
1941 continuation in a sequence of inputs.
1967 continuation in a sequence of inputs.
1942 """
1968 """
1943
1969
1944 try:
1970 try:
1945 line = raw_input_original(prompt)
1971 line = raw_input_original(prompt)
1946 except ValueError:
1972 except ValueError:
1947 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1973 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1948 self.exit_now = True
1974 self.exit_now = True
1949 return ""
1975 return ""
1950
1976
1951
1977
1952 # Try to be reasonably smart about not re-indenting pasted input more
1978 # Try to be reasonably smart about not re-indenting pasted input more
1953 # than necessary. We do this by trimming out the auto-indent initial
1979 # than necessary. We do this by trimming out the auto-indent initial
1954 # spaces, if the user's actual input started itself with whitespace.
1980 # spaces, if the user's actual input started itself with whitespace.
1955 #debugx('self.buffer[-1]')
1981 #debugx('self.buffer[-1]')
1956
1982
1957 if self.autoindent:
1983 if self.autoindent:
1958 if num_ini_spaces(line) > self.indent_current_nsp:
1984 if num_ini_spaces(line) > self.indent_current_nsp:
1959 line = line[self.indent_current_nsp:]
1985 line = line[self.indent_current_nsp:]
1960 self.indent_current_nsp = 0
1986 self.indent_current_nsp = 0
1961
1987
1962 # store the unfiltered input before the user has any chance to modify
1988 # store the unfiltered input before the user has any chance to modify
1963 # it.
1989 # it.
1964 if line.strip():
1990 if line.strip():
1965 if continue_prompt:
1991 if continue_prompt:
1966 self.input_hist_raw[-1] += '%s\n' % line
1992 self.input_hist_raw[-1] += '%s\n' % line
1967 if self.has_readline: # and some config option is set?
1993 if self.has_readline: # and some config option is set?
1968 try:
1994 try:
1969 histlen = self.readline.get_current_history_length()
1995 histlen = self.readline.get_current_history_length()
1970 newhist = self.input_hist_raw[-1].rstrip()
1996 newhist = self.input_hist_raw[-1].rstrip()
1971 self.readline.remove_history_item(histlen-1)
1997 self.readline.remove_history_item(histlen-1)
1972 self.readline.replace_history_item(histlen-2,newhist)
1998 self.readline.replace_history_item(histlen-2,newhist)
1973 except AttributeError:
1999 except AttributeError:
1974 pass # re{move,place}_history_item are new in 2.4.
2000 pass # re{move,place}_history_item are new in 2.4.
1975 else:
2001 else:
1976 self.input_hist_raw.append('%s\n' % line)
2002 self.input_hist_raw.append('%s\n' % line)
1977
2003
1978 try:
2004 try:
1979 lineout = self.prefilter(line,continue_prompt)
2005 lineout = self.prefilter(line,continue_prompt)
1980 except:
2006 except:
1981 # blanket except, in case a user-defined prefilter crashes, so it
2007 # blanket except, in case a user-defined prefilter crashes, so it
1982 # can't take all of ipython with it.
2008 # can't take all of ipython with it.
1983 self.showtraceback()
2009 self.showtraceback()
1984 return ''
2010 return ''
1985 else:
2011 else:
1986 return lineout
2012 return lineout
1987
2013
1988 def split_user_input(self,line):
2014 def split_user_input(self,line):
1989 """Split user input into pre-char, function part and rest."""
2015 """Split user input into pre-char, function part and rest."""
1990
2016
1991 lsplit = self.line_split.match(line)
2017 lsplit = self.line_split.match(line)
1992 if lsplit is None: # no regexp match returns None
2018 if lsplit is None: # no regexp match returns None
1993 try:
2019 try:
1994 iFun,theRest = line.split(None,1)
2020 iFun,theRest = line.split(None,1)
1995 except ValueError:
2021 except ValueError:
1996 iFun,theRest = line,''
2022 iFun,theRest = line,''
1997 pre = re.match('^(\s*)(.*)',line).groups()[0]
2023 pre = re.match('^(\s*)(.*)',line).groups()[0]
1998 else:
2024 else:
1999 pre,iFun,theRest = lsplit.groups()
2025 pre,iFun,theRest = lsplit.groups()
2000
2026
2001 #print 'line:<%s>' % line # dbg
2027 #print 'line:<%s>' % line # dbg
2002 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2028 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2003 return pre,iFun.strip(),theRest
2029 return pre,iFun.strip(),theRest
2004
2030
2005 def _prefilter(self, line, continue_prompt):
2031 def _prefilter(self, line, continue_prompt):
2006 """Calls different preprocessors, depending on the form of line."""
2032 """Calls different preprocessors, depending on the form of line."""
2007
2033
2008 # All handlers *must* return a value, even if it's blank ('').
2034 # All handlers *must* return a value, even if it's blank ('').
2009
2035
2010 # Lines are NOT logged here. Handlers should process the line as
2036 # Lines are NOT logged here. Handlers should process the line as
2011 # needed, update the cache AND log it (so that the input cache array
2037 # needed, update the cache AND log it (so that the input cache array
2012 # stays synced).
2038 # stays synced).
2013
2039
2014 # This function is _very_ delicate, and since it's also the one which
2040 # This function is _very_ delicate, and since it's also the one which
2015 # determines IPython's response to user input, it must be as efficient
2041 # determines IPython's response to user input, it must be as efficient
2016 # as possible. For this reason it has _many_ returns in it, trying
2042 # as possible. For this reason it has _many_ returns in it, trying
2017 # always to exit as quickly as it can figure out what it needs to do.
2043 # always to exit as quickly as it can figure out what it needs to do.
2018
2044
2019 # This function is the main responsible for maintaining IPython's
2045 # This function is the main responsible for maintaining IPython's
2020 # behavior respectful of Python's semantics. So be _very_ careful if
2046 # behavior respectful of Python's semantics. So be _very_ careful if
2021 # making changes to anything here.
2047 # making changes to anything here.
2022
2048
2023 #.....................................................................
2049 #.....................................................................
2024 # Code begins
2050 # Code begins
2025
2051
2026 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2052 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2027
2053
2028 # save the line away in case we crash, so the post-mortem handler can
2054 # save the line away in case we crash, so the post-mortem handler can
2029 # record it
2055 # record it
2030 self._last_input_line = line
2056 self._last_input_line = line
2031
2057
2032 #print '***line: <%s>' % line # dbg
2058 #print '***line: <%s>' % line # dbg
2033
2059
2034 # the input history needs to track even empty lines
2060 # the input history needs to track even empty lines
2035 stripped = line.strip()
2061 stripped = line.strip()
2036
2062
2037 if not stripped:
2063 if not stripped:
2038 if not continue_prompt:
2064 if not continue_prompt:
2039 self.outputcache.prompt_count -= 1
2065 self.outputcache.prompt_count -= 1
2040 return self.handle_normal(line,continue_prompt)
2066 return self.handle_normal(line,continue_prompt)
2041 #return self.handle_normal('',continue_prompt)
2067 #return self.handle_normal('',continue_prompt)
2042
2068
2043 # print '***cont',continue_prompt # dbg
2069 # print '***cont',continue_prompt # dbg
2044 # special handlers are only allowed for single line statements
2070 # special handlers are only allowed for single line statements
2045 if continue_prompt and not self.rc.multi_line_specials:
2071 if continue_prompt and not self.rc.multi_line_specials:
2046 return self.handle_normal(line,continue_prompt)
2072 return self.handle_normal(line,continue_prompt)
2047
2073
2048
2074
2049 # For the rest, we need the structure of the input
2075 # For the rest, we need the structure of the input
2050 pre,iFun,theRest = self.split_user_input(line)
2076 pre,iFun,theRest = self.split_user_input(line)
2051
2077
2052 # See whether any pre-existing handler can take care of it
2078 # See whether any pre-existing handler can take care of it
2053
2079
2054 rewritten = self.hooks.input_prefilter(stripped)
2080 rewritten = self.hooks.input_prefilter(stripped)
2055 if rewritten != stripped: # ok, some prefilter did something
2081 if rewritten != stripped: # ok, some prefilter did something
2056 rewritten = pre + rewritten # add indentation
2082 rewritten = pre + rewritten # add indentation
2057 return self.handle_normal(rewritten)
2083 return self.handle_normal(rewritten)
2058
2084
2059 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2085 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2060
2086
2061 # First check for explicit escapes in the last/first character
2087 # First check for explicit escapes in the last/first character
2062 handler = None
2088 handler = None
2063 if line[-1] == self.ESC_HELP:
2089 if line[-1] == self.ESC_HELP:
2064 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2090 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2065 if handler is None:
2091 if handler is None:
2066 # look at the first character of iFun, NOT of line, so we skip
2092 # look at the first character of iFun, NOT of line, so we skip
2067 # leading whitespace in multiline input
2093 # leading whitespace in multiline input
2068 handler = self.esc_handlers.get(iFun[0:1])
2094 handler = self.esc_handlers.get(iFun[0:1])
2069 if handler is not None:
2095 if handler is not None:
2070 return handler(line,continue_prompt,pre,iFun,theRest)
2096 return handler(line,continue_prompt,pre,iFun,theRest)
2071 # Emacs ipython-mode tags certain input lines
2097 # Emacs ipython-mode tags certain input lines
2072 if line.endswith('# PYTHON-MODE'):
2098 if line.endswith('# PYTHON-MODE'):
2073 return self.handle_emacs(line,continue_prompt)
2099 return self.handle_emacs(line,continue_prompt)
2074
2100
2075 # Next, check if we can automatically execute this thing
2101 # Next, check if we can automatically execute this thing
2076
2102
2077 # Allow ! in multi-line statements if multi_line_specials is on:
2103 # Allow ! in multi-line statements if multi_line_specials is on:
2078 if continue_prompt and self.rc.multi_line_specials and \
2104 if continue_prompt and self.rc.multi_line_specials and \
2079 iFun.startswith(self.ESC_SHELL):
2105 iFun.startswith(self.ESC_SHELL):
2080 return self.handle_shell_escape(line,continue_prompt,
2106 return self.handle_shell_escape(line,continue_prompt,
2081 pre=pre,iFun=iFun,
2107 pre=pre,iFun=iFun,
2082 theRest=theRest)
2108 theRest=theRest)
2083
2109
2084 # Let's try to find if the input line is a magic fn
2110 # Let's try to find if the input line is a magic fn
2085 oinfo = None
2111 oinfo = None
2086 if hasattr(self,'magic_'+iFun):
2112 if hasattr(self,'magic_'+iFun):
2087 # WARNING: _ofind uses getattr(), so it can consume generators and
2113 # WARNING: _ofind uses getattr(), so it can consume generators and
2088 # cause other side effects.
2114 # cause other side effects.
2089 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2115 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2090 if oinfo['ismagic']:
2116 if oinfo['ismagic']:
2091 # Be careful not to call magics when a variable assignment is
2117 # Be careful not to call magics when a variable assignment is
2092 # being made (ls='hi', for example)
2118 # being made (ls='hi', for example)
2093 if self.rc.automagic and \
2119 if self.rc.automagic and \
2094 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2120 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2095 (self.rc.multi_line_specials or not continue_prompt):
2121 (self.rc.multi_line_specials or not continue_prompt):
2096 return self.handle_magic(line,continue_prompt,
2122 return self.handle_magic(line,continue_prompt,
2097 pre,iFun,theRest)
2123 pre,iFun,theRest)
2098 else:
2124 else:
2099 return self.handle_normal(line,continue_prompt)
2125 return self.handle_normal(line,continue_prompt)
2100
2126
2101 # If the rest of the line begins with an (in)equality, assginment or
2127 # If the rest of the line begins with an (in)equality, assginment or
2102 # function call, we should not call _ofind but simply execute it.
2128 # function call, we should not call _ofind but simply execute it.
2103 # This avoids spurious geattr() accesses on objects upon assignment.
2129 # This avoids spurious geattr() accesses on objects upon assignment.
2104 #
2130 #
2105 # It also allows users to assign to either alias or magic names true
2131 # It also allows users to assign to either alias or magic names true
2106 # python variables (the magic/alias systems always take second seat to
2132 # python variables (the magic/alias systems always take second seat to
2107 # true python code).
2133 # true python code).
2108 if theRest and theRest[0] in '!=()':
2134 if theRest and theRest[0] in '!=()':
2109 return self.handle_normal(line,continue_prompt)
2135 return self.handle_normal(line,continue_prompt)
2110
2136
2111 if oinfo is None:
2137 if oinfo is None:
2112 # let's try to ensure that _oinfo is ONLY called when autocall is
2138 # let's try to ensure that _oinfo is ONLY called when autocall is
2113 # on. Since it has inevitable potential side effects, at least
2139 # on. Since it has inevitable potential side effects, at least
2114 # having autocall off should be a guarantee to the user that no
2140 # having autocall off should be a guarantee to the user that no
2115 # weird things will happen.
2141 # weird things will happen.
2116
2142
2117 if self.rc.autocall:
2143 if self.rc.autocall:
2118 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2144 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2119 else:
2145 else:
2120 # in this case, all that's left is either an alias or
2146 # in this case, all that's left is either an alias or
2121 # processing the line normally.
2147 # processing the line normally.
2122 if iFun in self.alias_table:
2148 if iFun in self.alias_table:
2123 # if autocall is off, by not running _ofind we won't know
2149 # if autocall is off, by not running _ofind we won't know
2124 # whether the given name may also exist in one of the
2150 # whether the given name may also exist in one of the
2125 # user's namespace. At this point, it's best to do a
2151 # user's namespace. At this point, it's best to do a
2126 # quick check just to be sure that we don't let aliases
2152 # quick check just to be sure that we don't let aliases
2127 # shadow variables.
2153 # shadow variables.
2128 head = iFun.split('.',1)[0]
2154 head = iFun.split('.',1)[0]
2129 if head in self.user_ns or head in self.internal_ns \
2155 if head in self.user_ns or head in self.internal_ns \
2130 or head in __builtin__.__dict__:
2156 or head in __builtin__.__dict__:
2131 return self.handle_normal(line,continue_prompt)
2157 return self.handle_normal(line,continue_prompt)
2132 else:
2158 else:
2133 return self.handle_alias(line,continue_prompt,
2159 return self.handle_alias(line,continue_prompt,
2134 pre,iFun,theRest)
2160 pre,iFun,theRest)
2135
2161
2136 else:
2162 else:
2137 return self.handle_normal(line,continue_prompt)
2163 return self.handle_normal(line,continue_prompt)
2138
2164
2139 if not oinfo['found']:
2165 if not oinfo['found']:
2140 return self.handle_normal(line,continue_prompt)
2166 return self.handle_normal(line,continue_prompt)
2141 else:
2167 else:
2142 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2168 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2143 if oinfo['isalias']:
2169 if oinfo['isalias']:
2144 return self.handle_alias(line,continue_prompt,
2170 return self.handle_alias(line,continue_prompt,
2145 pre,iFun,theRest)
2171 pre,iFun,theRest)
2146
2172
2147 if (self.rc.autocall
2173 if (self.rc.autocall
2148 and
2174 and
2149 (
2175 (
2150 #only consider exclusion re if not "," or ";" autoquoting
2176 #only consider exclusion re if not "," or ";" autoquoting
2151 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2177 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2152 or pre == self.ESC_PAREN) or
2178 or pre == self.ESC_PAREN) or
2153 (not self.re_exclude_auto.match(theRest)))
2179 (not self.re_exclude_auto.match(theRest)))
2154 and
2180 and
2155 self.re_fun_name.match(iFun) and
2181 self.re_fun_name.match(iFun) and
2156 callable(oinfo['obj'])) :
2182 callable(oinfo['obj'])) :
2157 #print 'going auto' # dbg
2183 #print 'going auto' # dbg
2158 return self.handle_auto(line,continue_prompt,
2184 return self.handle_auto(line,continue_prompt,
2159 pre,iFun,theRest,oinfo['obj'])
2185 pre,iFun,theRest,oinfo['obj'])
2160 else:
2186 else:
2161 #print 'was callable?', callable(oinfo['obj']) # dbg
2187 #print 'was callable?', callable(oinfo['obj']) # dbg
2162 return self.handle_normal(line,continue_prompt)
2188 return self.handle_normal(line,continue_prompt)
2163
2189
2164 # If we get here, we have a normal Python line. Log and return.
2190 # If we get here, we have a normal Python line. Log and return.
2165 return self.handle_normal(line,continue_prompt)
2191 return self.handle_normal(line,continue_prompt)
2166
2192
2167 def _prefilter_dumb(self, line, continue_prompt):
2193 def _prefilter_dumb(self, line, continue_prompt):
2168 """simple prefilter function, for debugging"""
2194 """simple prefilter function, for debugging"""
2169 return self.handle_normal(line,continue_prompt)
2195 return self.handle_normal(line,continue_prompt)
2170
2196
2171
2197
2172 def multiline_prefilter(self, line, continue_prompt):
2198 def multiline_prefilter(self, line, continue_prompt):
2173 """ Run _prefilter for each line of input
2199 """ Run _prefilter for each line of input
2174
2200
2175 Covers cases where there are multiple lines in the user entry,
2201 Covers cases where there are multiple lines in the user entry,
2176 which is the case when the user goes back to a multiline history
2202 which is the case when the user goes back to a multiline history
2177 entry and presses enter.
2203 entry and presses enter.
2178
2204
2179 """
2205 """
2180 out = []
2206 out = []
2181 for l in line.rstrip('\n').split('\n'):
2207 for l in line.rstrip('\n').split('\n'):
2182 out.append(self._prefilter(l, continue_prompt))
2208 out.append(self._prefilter(l, continue_prompt))
2183 return '\n'.join(out)
2209 return '\n'.join(out)
2184
2210
2185 # Set the default prefilter() function (this can be user-overridden)
2211 # Set the default prefilter() function (this can be user-overridden)
2186 prefilter = multiline_prefilter
2212 prefilter = multiline_prefilter
2187
2213
2188 def handle_normal(self,line,continue_prompt=None,
2214 def handle_normal(self,line,continue_prompt=None,
2189 pre=None,iFun=None,theRest=None):
2215 pre=None,iFun=None,theRest=None):
2190 """Handle normal input lines. Use as a template for handlers."""
2216 """Handle normal input lines. Use as a template for handlers."""
2191
2217
2192 # With autoindent on, we need some way to exit the input loop, and I
2218 # With autoindent on, we need some way to exit the input loop, and I
2193 # don't want to force the user to have to backspace all the way to
2219 # don't want to force the user to have to backspace all the way to
2194 # clear the line. The rule will be in this case, that either two
2220 # clear the line. The rule will be in this case, that either two
2195 # lines of pure whitespace in a row, or a line of pure whitespace but
2221 # lines of pure whitespace in a row, or a line of pure whitespace but
2196 # of a size different to the indent level, will exit the input loop.
2222 # of a size different to the indent level, will exit the input loop.
2197
2223
2198 if (continue_prompt and self.autoindent and line.isspace() and
2224 if (continue_prompt and self.autoindent and line.isspace() and
2199 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2225 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2200 (self.buffer[-1]).isspace() )):
2226 (self.buffer[-1]).isspace() )):
2201 line = ''
2227 line = ''
2202
2228
2203 self.log(line,line,continue_prompt)
2229 self.log(line,line,continue_prompt)
2204 return line
2230 return line
2205
2231
2206 def handle_alias(self,line,continue_prompt=None,
2232 def handle_alias(self,line,continue_prompt=None,
2207 pre=None,iFun=None,theRest=None):
2233 pre=None,iFun=None,theRest=None):
2208 """Handle alias input lines. """
2234 """Handle alias input lines. """
2209
2235
2210 # pre is needed, because it carries the leading whitespace. Otherwise
2236 # pre is needed, because it carries the leading whitespace. Otherwise
2211 # aliases won't work in indented sections.
2237 # aliases won't work in indented sections.
2212 transformed = self.expand_aliases(iFun, theRest)
2238 transformed = self.expand_aliases(iFun, theRest)
2213 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2239 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2214 self.log(line,line_out,continue_prompt)
2240 self.log(line,line_out,continue_prompt)
2215 #print 'line out:',line_out # dbg
2241 #print 'line out:',line_out # dbg
2216 return line_out
2242 return line_out
2217
2243
2218 def handle_shell_escape(self, line, continue_prompt=None,
2244 def handle_shell_escape(self, line, continue_prompt=None,
2219 pre=None,iFun=None,theRest=None):
2245 pre=None,iFun=None,theRest=None):
2220 """Execute the line in a shell, empty return value"""
2246 """Execute the line in a shell, empty return value"""
2221
2247
2222 #print 'line in :', `line` # dbg
2248 #print 'line in :', `line` # dbg
2223 # Example of a special handler. Others follow a similar pattern.
2249 # Example of a special handler. Others follow a similar pattern.
2224 if line.lstrip().startswith('!!'):
2250 if line.lstrip().startswith('!!'):
2225 # rewrite iFun/theRest to properly hold the call to %sx and
2251 # rewrite iFun/theRest to properly hold the call to %sx and
2226 # the actual command to be executed, so handle_magic can work
2252 # the actual command to be executed, so handle_magic can work
2227 # correctly
2253 # correctly
2228 theRest = '%s %s' % (iFun[2:],theRest)
2254 theRest = '%s %s' % (iFun[2:],theRest)
2229 iFun = 'sx'
2255 iFun = 'sx'
2230 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2256 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2231 line.lstrip()[2:]),
2257 line.lstrip()[2:]),
2232 continue_prompt,pre,iFun,theRest)
2258 continue_prompt,pre,iFun,theRest)
2233 else:
2259 else:
2234 cmd=line.lstrip().lstrip('!')
2260 cmd=line.lstrip().lstrip('!')
2235 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2261 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2236 # update cache/log and return
2262 # update cache/log and return
2237 self.log(line,line_out,continue_prompt)
2263 self.log(line,line_out,continue_prompt)
2238 return line_out
2264 return line_out
2239
2265
2240 def handle_magic(self, line, continue_prompt=None,
2266 def handle_magic(self, line, continue_prompt=None,
2241 pre=None,iFun=None,theRest=None):
2267 pre=None,iFun=None,theRest=None):
2242 """Execute magic functions."""
2268 """Execute magic functions."""
2243
2269
2244
2270
2245 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2271 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2246 self.log(line,cmd,continue_prompt)
2272 self.log(line,cmd,continue_prompt)
2247 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2273 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2248 return cmd
2274 return cmd
2249
2275
2250 def handle_auto(self, line, continue_prompt=None,
2276 def handle_auto(self, line, continue_prompt=None,
2251 pre=None,iFun=None,theRest=None,obj=None):
2277 pre=None,iFun=None,theRest=None,obj=None):
2252 """Hande lines which can be auto-executed, quoting if requested."""
2278 """Hande lines which can be auto-executed, quoting if requested."""
2253
2279
2254 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2280 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2255
2281
2256 # This should only be active for single-line input!
2282 # This should only be active for single-line input!
2257 if continue_prompt:
2283 if continue_prompt:
2258 self.log(line,line,continue_prompt)
2284 self.log(line,line,continue_prompt)
2259 return line
2285 return line
2260
2286
2261 auto_rewrite = True
2287 auto_rewrite = True
2262
2288
2263 if pre == self.ESC_QUOTE:
2289 if pre == self.ESC_QUOTE:
2264 # Auto-quote splitting on whitespace
2290 # Auto-quote splitting on whitespace
2265 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2291 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2266 elif pre == self.ESC_QUOTE2:
2292 elif pre == self.ESC_QUOTE2:
2267 # Auto-quote whole string
2293 # Auto-quote whole string
2268 newcmd = '%s("%s")' % (iFun,theRest)
2294 newcmd = '%s("%s")' % (iFun,theRest)
2269 elif pre == self.ESC_PAREN:
2295 elif pre == self.ESC_PAREN:
2270 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2296 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2271 else:
2297 else:
2272 # Auto-paren.
2298 # Auto-paren.
2273 # We only apply it to argument-less calls if the autocall
2299 # We only apply it to argument-less calls if the autocall
2274 # parameter is set to 2. We only need to check that autocall is <
2300 # parameter is set to 2. We only need to check that autocall is <
2275 # 2, since this function isn't called unless it's at least 1.
2301 # 2, since this function isn't called unless it's at least 1.
2276 if not theRest and (self.rc.autocall < 2):
2302 if not theRest and (self.rc.autocall < 2):
2277 newcmd = '%s %s' % (iFun,theRest)
2303 newcmd = '%s %s' % (iFun,theRest)
2278 auto_rewrite = False
2304 auto_rewrite = False
2279 else:
2305 else:
2280 if theRest.startswith('['):
2306 if theRest.startswith('['):
2281 if hasattr(obj,'__getitem__'):
2307 if hasattr(obj,'__getitem__'):
2282 # Don't autocall in this case: item access for an object
2308 # Don't autocall in this case: item access for an object
2283 # which is BOTH callable and implements __getitem__.
2309 # which is BOTH callable and implements __getitem__.
2284 newcmd = '%s %s' % (iFun,theRest)
2310 newcmd = '%s %s' % (iFun,theRest)
2285 auto_rewrite = False
2311 auto_rewrite = False
2286 else:
2312 else:
2287 # if the object doesn't support [] access, go ahead and
2313 # if the object doesn't support [] access, go ahead and
2288 # autocall
2314 # autocall
2289 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2315 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2290 elif theRest.endswith(';'):
2316 elif theRest.endswith(';'):
2291 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2317 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2292 else:
2318 else:
2293 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2319 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2294
2320
2295 if auto_rewrite:
2321 if auto_rewrite:
2296 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2322 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2297 # log what is now valid Python, not the actual user input (without the
2323 # log what is now valid Python, not the actual user input (without the
2298 # final newline)
2324 # final newline)
2299 self.log(line,newcmd,continue_prompt)
2325 self.log(line,newcmd,continue_prompt)
2300 return newcmd
2326 return newcmd
2301
2327
2302 def handle_help(self, line, continue_prompt=None,
2328 def handle_help(self, line, continue_prompt=None,
2303 pre=None,iFun=None,theRest=None):
2329 pre=None,iFun=None,theRest=None):
2304 """Try to get some help for the object.
2330 """Try to get some help for the object.
2305
2331
2306 obj? or ?obj -> basic information.
2332 obj? or ?obj -> basic information.
2307 obj?? or ??obj -> more details.
2333 obj?? or ??obj -> more details.
2308 """
2334 """
2309
2335
2310 # We need to make sure that we don't process lines which would be
2336 # We need to make sure that we don't process lines which would be
2311 # otherwise valid python, such as "x=1 # what?"
2337 # otherwise valid python, such as "x=1 # what?"
2312 try:
2338 try:
2313 codeop.compile_command(line)
2339 codeop.compile_command(line)
2314 except SyntaxError:
2340 except SyntaxError:
2315 # We should only handle as help stuff which is NOT valid syntax
2341 # We should only handle as help stuff which is NOT valid syntax
2316 if line[0]==self.ESC_HELP:
2342 if line[0]==self.ESC_HELP:
2317 line = line[1:]
2343 line = line[1:]
2318 elif line[-1]==self.ESC_HELP:
2344 elif line[-1]==self.ESC_HELP:
2319 line = line[:-1]
2345 line = line[:-1]
2320 self.log(line,'#?'+line,continue_prompt)
2346 self.log(line,'#?'+line,continue_prompt)
2321 if line:
2347 if line:
2322 self.magic_pinfo(line)
2348 self.magic_pinfo(line)
2323 else:
2349 else:
2324 page(self.usage,screen_lines=self.rc.screen_length)
2350 page(self.usage,screen_lines=self.rc.screen_length)
2325 return '' # Empty string is needed here!
2351 return '' # Empty string is needed here!
2326 except:
2352 except:
2327 # Pass any other exceptions through to the normal handler
2353 # Pass any other exceptions through to the normal handler
2328 return self.handle_normal(line,continue_prompt)
2354 return self.handle_normal(line,continue_prompt)
2329 else:
2355 else:
2330 # If the code compiles ok, we should handle it normally
2356 # If the code compiles ok, we should handle it normally
2331 return self.handle_normal(line,continue_prompt)
2357 return self.handle_normal(line,continue_prompt)
2332
2358
2333 def getapi(self):
2359 def getapi(self):
2334 """ Get an IPApi object for this shell instance
2360 """ Get an IPApi object for this shell instance
2335
2361
2336 Getting an IPApi object is always preferable to accessing the shell
2362 Getting an IPApi object is always preferable to accessing the shell
2337 directly, but this holds true especially for extensions.
2363 directly, but this holds true especially for extensions.
2338
2364
2339 It should always be possible to implement an extension with IPApi
2365 It should always be possible to implement an extension with IPApi
2340 alone. If not, contact maintainer to request an addition.
2366 alone. If not, contact maintainer to request an addition.
2341
2367
2342 """
2368 """
2343 return self.api
2369 return self.api
2344
2370
2345 def handle_emacs(self,line,continue_prompt=None,
2371 def handle_emacs(self,line,continue_prompt=None,
2346 pre=None,iFun=None,theRest=None):
2372 pre=None,iFun=None,theRest=None):
2347 """Handle input lines marked by python-mode."""
2373 """Handle input lines marked by python-mode."""
2348
2374
2349 # Currently, nothing is done. Later more functionality can be added
2375 # Currently, nothing is done. Later more functionality can be added
2350 # here if needed.
2376 # here if needed.
2351
2377
2352 # The input cache shouldn't be updated
2378 # The input cache shouldn't be updated
2353
2379
2354 return line
2380 return line
2355
2381
2356 def mktempfile(self,data=None):
2382 def mktempfile(self,data=None):
2357 """Make a new tempfile and return its filename.
2383 """Make a new tempfile and return its filename.
2358
2384
2359 This makes a call to tempfile.mktemp, but it registers the created
2385 This makes a call to tempfile.mktemp, but it registers the created
2360 filename internally so ipython cleans it up at exit time.
2386 filename internally so ipython cleans it up at exit time.
2361
2387
2362 Optional inputs:
2388 Optional inputs:
2363
2389
2364 - data(None): if data is given, it gets written out to the temp file
2390 - data(None): if data is given, it gets written out to the temp file
2365 immediately, and the file is closed again."""
2391 immediately, and the file is closed again."""
2366
2392
2367 filename = tempfile.mktemp('.py','ipython_edit_')
2393 filename = tempfile.mktemp('.py','ipython_edit_')
2368 self.tempfiles.append(filename)
2394 self.tempfiles.append(filename)
2369
2395
2370 if data:
2396 if data:
2371 tmp_file = open(filename,'w')
2397 tmp_file = open(filename,'w')
2372 tmp_file.write(data)
2398 tmp_file.write(data)
2373 tmp_file.close()
2399 tmp_file.close()
2374 return filename
2400 return filename
2375
2401
2376 def write(self,data):
2402 def write(self,data):
2377 """Write a string to the default output"""
2403 """Write a string to the default output"""
2378 Term.cout.write(data)
2404 Term.cout.write(data)
2379
2405
2380 def write_err(self,data):
2406 def write_err(self,data):
2381 """Write a string to the default error output"""
2407 """Write a string to the default error output"""
2382 Term.cerr.write(data)
2408 Term.cerr.write(data)
2383
2409
2384 def exit(self):
2410 def exit(self):
2385 """Handle interactive exit.
2411 """Handle interactive exit.
2386
2412
2387 This method sets the exit_now attribute."""
2413 This method sets the exit_now attribute."""
2388
2414
2389 if self.rc.confirm_exit:
2415 if self.rc.confirm_exit:
2390 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2416 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2391 self.exit_now = True
2417 self.exit_now = True
2392 else:
2418 else:
2393 self.exit_now = True
2419 self.exit_now = True
2394
2420
2395 def safe_execfile(self,fname,*where,**kw):
2421 def safe_execfile(self,fname,*where,**kw):
2396 fname = os.path.expanduser(fname)
2422 fname = os.path.expanduser(fname)
2397
2423
2398 try:
2424 try:
2399 xfile = open(fname)
2425 xfile = open(fname)
2400 except:
2426 except:
2401 print >> Term.cerr, \
2427 print >> Term.cerr, \
2402 'Could not open file <%s> for safe execution.' % fname
2428 'Could not open file <%s> for safe execution.' % fname
2403 return None
2429 return None
2404
2430
2405 kw.setdefault('islog',0)
2431 kw.setdefault('islog',0)
2406 kw.setdefault('quiet',1)
2432 kw.setdefault('quiet',1)
2407 kw.setdefault('exit_ignore',0)
2433 kw.setdefault('exit_ignore',0)
2408 first = xfile.readline()
2434 first = xfile.readline()
2409 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2435 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2410 xfile.close()
2436 xfile.close()
2411 # line by line execution
2437 # line by line execution
2412 if first.startswith(loghead) or kw['islog']:
2438 if first.startswith(loghead) or kw['islog']:
2413 print 'Loading log file <%s> one line at a time...' % fname
2439 print 'Loading log file <%s> one line at a time...' % fname
2414 if kw['quiet']:
2440 if kw['quiet']:
2415 stdout_save = sys.stdout
2441 stdout_save = sys.stdout
2416 sys.stdout = StringIO.StringIO()
2442 sys.stdout = StringIO.StringIO()
2417 try:
2443 try:
2418 globs,locs = where[0:2]
2444 globs,locs = where[0:2]
2419 except:
2445 except:
2420 try:
2446 try:
2421 globs = locs = where[0]
2447 globs = locs = where[0]
2422 except:
2448 except:
2423 globs = locs = globals()
2449 globs = locs = globals()
2424 badblocks = []
2450 badblocks = []
2425
2451
2426 # we also need to identify indented blocks of code when replaying
2452 # we also need to identify indented blocks of code when replaying
2427 # logs and put them together before passing them to an exec
2453 # logs and put them together before passing them to an exec
2428 # statement. This takes a bit of regexp and look-ahead work in the
2454 # statement. This takes a bit of regexp and look-ahead work in the
2429 # file. It's easiest if we swallow the whole thing in memory
2455 # file. It's easiest if we swallow the whole thing in memory
2430 # first, and manually walk through the lines list moving the
2456 # first, and manually walk through the lines list moving the
2431 # counter ourselves.
2457 # counter ourselves.
2432 indent_re = re.compile('\s+\S')
2458 indent_re = re.compile('\s+\S')
2433 xfile = open(fname)
2459 xfile = open(fname)
2434 filelines = xfile.readlines()
2460 filelines = xfile.readlines()
2435 xfile.close()
2461 xfile.close()
2436 nlines = len(filelines)
2462 nlines = len(filelines)
2437 lnum = 0
2463 lnum = 0
2438 while lnum < nlines:
2464 while lnum < nlines:
2439 line = filelines[lnum]
2465 line = filelines[lnum]
2440 lnum += 1
2466 lnum += 1
2441 # don't re-insert logger status info into cache
2467 # don't re-insert logger status info into cache
2442 if line.startswith('#log#'):
2468 if line.startswith('#log#'):
2443 continue
2469 continue
2444 else:
2470 else:
2445 # build a block of code (maybe a single line) for execution
2471 # build a block of code (maybe a single line) for execution
2446 block = line
2472 block = line
2447 try:
2473 try:
2448 next = filelines[lnum] # lnum has already incremented
2474 next = filelines[lnum] # lnum has already incremented
2449 except:
2475 except:
2450 next = None
2476 next = None
2451 while next and indent_re.match(next):
2477 while next and indent_re.match(next):
2452 block += next
2478 block += next
2453 lnum += 1
2479 lnum += 1
2454 try:
2480 try:
2455 next = filelines[lnum]
2481 next = filelines[lnum]
2456 except:
2482 except:
2457 next = None
2483 next = None
2458 # now execute the block of one or more lines
2484 # now execute the block of one or more lines
2459 try:
2485 try:
2460 exec block in globs,locs
2486 exec block in globs,locs
2461 except SystemExit:
2487 except SystemExit:
2462 pass
2488 pass
2463 except:
2489 except:
2464 badblocks.append(block.rstrip())
2490 badblocks.append(block.rstrip())
2465 if kw['quiet']: # restore stdout
2491 if kw['quiet']: # restore stdout
2466 sys.stdout.close()
2492 sys.stdout.close()
2467 sys.stdout = stdout_save
2493 sys.stdout = stdout_save
2468 print 'Finished replaying log file <%s>' % fname
2494 print 'Finished replaying log file <%s>' % fname
2469 if badblocks:
2495 if badblocks:
2470 print >> sys.stderr, ('\nThe following lines/blocks in file '
2496 print >> sys.stderr, ('\nThe following lines/blocks in file '
2471 '<%s> reported errors:' % fname)
2497 '<%s> reported errors:' % fname)
2472
2498
2473 for badline in badblocks:
2499 for badline in badblocks:
2474 print >> sys.stderr, badline
2500 print >> sys.stderr, badline
2475 else: # regular file execution
2501 else: # regular file execution
2476 try:
2502 try:
2477 execfile(fname,*where)
2503 execfile(fname,*where)
2478 except SyntaxError:
2504 except SyntaxError:
2479 self.showsyntaxerror()
2505 self.showsyntaxerror()
2480 warn('Failure executing file: <%s>' % fname)
2506 warn('Failure executing file: <%s>' % fname)
2481 except SystemExit,status:
2507 except SystemExit,status:
2482 if not kw['exit_ignore']:
2508 if not kw['exit_ignore']:
2483 self.showtraceback()
2509 self.showtraceback()
2484 warn('Failure executing file: <%s>' % fname)
2510 warn('Failure executing file: <%s>' % fname)
2485 except:
2511 except:
2486 self.showtraceback()
2512 self.showtraceback()
2487 warn('Failure executing file: <%s>' % fname)
2513 warn('Failure executing file: <%s>' % fname)
2488
2514
2489 #************************* end of file <iplib.py> *****************************
2515 #************************* end of file <iplib.py> *****************************
@@ -1,754 +1,755 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 better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 1384 2006-06-29 20:04:37Z vivainio $"""
9 $Id: ipmaker.py 1879 2006-11-04 00:34:34Z fptest $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 from IPython import Release
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
20 __license__ = Release.license
21 __version__ = Release.version
21 __version__ = Release.version
22
22
23 credits._Printer__data = """
23 credits._Printer__data = """
24 Python: %s
24 Python: %s
25
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
28 % credits._Printer__data
29
29
30 copyright._Printer__data += """
30 copyright._Printer__data += """
31
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
33 All Rights Reserved."""
34
34
35 #****************************************************************************
35 #****************************************************************************
36 # Required modules
36 # Required modules
37
37
38 # From the standard library
38 # From the standard library
39 import __main__
39 import __main__
40 import __builtin__
40 import __builtin__
41 import os
41 import os
42 import re
42 import re
43 import sys
43 import sys
44 import types
44 import types
45 from pprint import pprint,pformat
45 from pprint import pprint,pformat
46
46
47 # Our own
47 # Our own
48 from IPython import DPyGetOpt
48 from IPython import DPyGetOpt
49 from IPython.ipstruct import Struct
49 from IPython.ipstruct import Struct
50 from IPython.OutputTrap import OutputTrap
50 from IPython.OutputTrap import OutputTrap
51 from IPython.ConfigLoader import ConfigLoader
51 from IPython.ConfigLoader import ConfigLoader
52 from IPython.iplib import InteractiveShell
52 from IPython.iplib import InteractiveShell
53 from IPython.usage import cmd_line_usage,interactive_usage
53 from IPython.usage import cmd_line_usage,interactive_usage
54 from IPython.genutils import *
54 from IPython.genutils import *
55
55
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 rc_override=None,shell_class=InteractiveShell,
58 rc_override=None,shell_class=InteractiveShell,
59 embedded=False,**kw):
59 embedded=False,**kw):
60 """This is a dump of IPython into a single function.
60 """This is a dump of IPython into a single function.
61
61
62 Later it will have to be broken up in a sensible manner.
62 Later it will have to be broken up in a sensible manner.
63
63
64 Arguments:
64 Arguments:
65
65
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 script name, b/c DPyGetOpt strips the first argument only for the real
67 script name, b/c DPyGetOpt strips the first argument only for the real
68 sys.argv.
68 sys.argv.
69
69
70 - user_ns: a dict to be used as the user's namespace."""
70 - user_ns: a dict to be used as the user's namespace."""
71
71
72 #----------------------------------------------------------------------
72 #----------------------------------------------------------------------
73 # Defaults and initialization
73 # Defaults and initialization
74
74
75 # For developer debugging, deactivates crash handler and uses pdb.
75 # For developer debugging, deactivates crash handler and uses pdb.
76 DEVDEBUG = False
76 DEVDEBUG = False
77
77
78 if argv is None:
78 if argv is None:
79 argv = sys.argv
79 argv = sys.argv
80
80
81 # __IP is the main global that lives throughout and represents the whole
81 # __IP is the main global that lives throughout and represents the whole
82 # application. If the user redefines it, all bets are off as to what
82 # application. If the user redefines it, all bets are off as to what
83 # happens.
83 # happens.
84
84
85 # __IP is the name of he global which the caller will have accessible as
85 # __IP is the name of he global which the caller will have accessible as
86 # __IP.name. We set its name via the first parameter passed to
86 # __IP.name. We set its name via the first parameter passed to
87 # InteractiveShell:
87 # InteractiveShell:
88
88
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 embedded=embedded,**kw)
90 embedded=embedded,**kw)
91
91
92 # Put 'help' in the user namespace
92 # Put 'help' in the user namespace
93 from site import _Helper
93 from site import _Helper
94 IP.user_ns['help'] = _Helper()
94 IP.user_ns['help'] = _Helper()
95
95
96
96
97 if DEVDEBUG:
97 if DEVDEBUG:
98 # For developer debugging only (global flag)
98 # For developer debugging only (global flag)
99 from IPython import ultraTB
99 from IPython import ultraTB
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101
101
102 IP.BANNER_PARTS = ['Python %s\n'
102 IP.BANNER_PARTS = ['Python %s\n'
103 'Type "copyright", "credits" or "license" '
103 'Type "copyright", "credits" or "license" '
104 'for more information.\n'
104 'for more information.\n'
105 % (sys.version.split('\n')[0],),
105 % (sys.version.split('\n')[0],),
106 "IPython %s -- An enhanced Interactive Python."
106 "IPython %s -- An enhanced Interactive Python."
107 % (__version__,),
107 % (__version__,),
108 """? -> Introduction to IPython's features.
108 """? -> Introduction to IPython's features.
109 %magic -> Information about IPython's 'magic' % functions.
109 %magic -> Information about IPython's 'magic' % functions.
110 help -> Python's own help system.
110 help -> Python's own help system.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 """ ]
112 """ ]
113
113
114 IP.usage = interactive_usage
114 IP.usage = interactive_usage
115
115
116 # Platform-dependent suffix and directory names. We use _ipython instead
116 # Platform-dependent suffix and directory names. We use _ipython instead
117 # of .ipython under win32 b/c there's software that breaks with .named
117 # of .ipython under win32 b/c there's software that breaks with .named
118 # directories on that platform.
118 # directories on that platform.
119 if os.name == 'posix':
119 if os.name == 'posix':
120 rc_suffix = ''
120 rc_suffix = ''
121 ipdir_def = '.ipython'
121 ipdir_def = '.ipython'
122 else:
122 else:
123 rc_suffix = '.ini'
123 rc_suffix = '.ini'
124 ipdir_def = '_ipython'
124 ipdir_def = '_ipython'
125
125
126 # default directory for configuration
126 # default directory for configuration
127 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
127 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
128 os.path.join(IP.home_dir,ipdir_def)))
128 os.path.join(IP.home_dir,ipdir_def)))
129
129
130 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
130 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
131
131
132 # we need the directory where IPython itself is installed
132 # we need the directory where IPython itself is installed
133 import IPython
133 import IPython
134 IPython_dir = os.path.dirname(IPython.__file__)
134 IPython_dir = os.path.dirname(IPython.__file__)
135 del IPython
135 del IPython
136
136
137 #-------------------------------------------------------------------------
137 #-------------------------------------------------------------------------
138 # Command line handling
138 # Command line handling
139
139
140 # Valid command line options (uses DPyGetOpt syntax, like Perl's
140 # Valid command line options (uses DPyGetOpt syntax, like Perl's
141 # GetOpt::Long)
141 # GetOpt::Long)
142
142
143 # Any key not listed here gets deleted even if in the file (like session
143 # Any key not listed here gets deleted even if in the file (like session
144 # or profile). That's deliberate, to maintain the rc namespace clean.
144 # or profile). That's deliberate, to maintain the rc namespace clean.
145
145
146 # Each set of options appears twice: under _conv only the names are
146 # Each set of options appears twice: under _conv only the names are
147 # listed, indicating which type they must be converted to when reading the
147 # listed, indicating which type they must be converted to when reading the
148 # ipythonrc file. And under DPyGetOpt they are listed with the regular
148 # ipythonrc file. And under DPyGetOpt they are listed with the regular
149 # DPyGetOpt syntax (=s,=i,:f,etc).
149 # DPyGetOpt syntax (=s,=i,:f,etc).
150
150
151 # Make sure there's a space before each end of line (they get auto-joined!)
151 # Make sure there's a space before each end of line (they get auto-joined!)
152 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
152 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
153 'c=s classic|cl color_info! colors=s confirm_exit! '
153 'c=s classic|cl color_info! colors=s confirm_exit! '
154 'debug! deep_reload! editor=s log|l messages! nosep '
154 'debug! deep_reload! editor=s log|l messages! nosep '
155 'object_info_string_level=i pdb! '
155 'object_info_string_level=i pdb! '
156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
157 'quick screen_length|sl=i prompts_pad_left=i '
157 'quick screen_length|sl=i prompts_pad_left=i '
158 'logfile|lf=s logplay|lp=s profile|p=s '
158 'logfile|lf=s logplay|lp=s profile|p=s '
159 'readline! readline_merge_completions! '
159 'readline! readline_merge_completions! '
160 'readline_omit__names! '
160 'readline_omit__names! '
161 'rcfile=s separate_in|si=s separate_out|so=s '
161 'rcfile=s separate_in|si=s separate_out|so=s '
162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
163 'magic_docstrings system_verbose! '
163 'magic_docstrings system_verbose! '
164 'multi_line_specials! '
164 'multi_line_specials! '
165 'wxversion=s '
165 'wxversion=s '
166 'autoedit_syntax!')
166 'autoedit_syntax!')
167
167
168 # Options that can *only* appear at the cmd line (not in rcfiles).
168 # Options that can *only* appear at the cmd line (not in rcfiles).
169
169
170 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
170 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
171 # the 'C-c !' command in emacs automatically appends a -i option at the end.
171 # the 'C-c !' command in emacs automatically appends a -i option at the end.
172 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
172 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
173 'gthread! qthread! q4thread! wthread! pylab! tk!')
173 'gthread! qthread! q4thread! wthread! pylab! tk!')
174
174
175 # Build the actual name list to be used by DPyGetOpt
175 # Build the actual name list to be used by DPyGetOpt
176 opts_names = qw(cmdline_opts) + qw(cmdline_only)
176 opts_names = qw(cmdline_opts) + qw(cmdline_only)
177
177
178 # Set sensible command line defaults.
178 # Set sensible command line defaults.
179 # This should have everything from cmdline_opts and cmdline_only
179 # This should have everything from cmdline_opts and cmdline_only
180 opts_def = Struct(autocall = 1,
180 opts_def = Struct(autocall = 1,
181 autoedit_syntax = 0,
181 autoedit_syntax = 0,
182 autoindent = 0,
182 autoindent = 0,
183 automagic = 1,
183 automagic = 1,
184 banner = 1,
184 banner = 1,
185 cache_size = 1000,
185 cache_size = 1000,
186 c = '',
186 c = '',
187 classic = 0,
187 classic = 0,
188 colors = 'NoColor',
188 colors = 'NoColor',
189 color_info = 0,
189 color_info = 0,
190 confirm_exit = 1,
190 confirm_exit = 1,
191 debug = 0,
191 debug = 0,
192 deep_reload = 0,
192 deep_reload = 0,
193 editor = '0',
193 editor = '0',
194 help = 0,
194 help = 0,
195 ignore = 0,
195 ignore = 0,
196 ipythondir = ipythondir_def,
196 ipythondir = ipythondir_def,
197 log = 0,
197 log = 0,
198 logfile = '',
198 logfile = '',
199 logplay = '',
199 logplay = '',
200 multi_line_specials = 1,
200 multi_line_specials = 1,
201 messages = 1,
201 messages = 1,
202 object_info_string_level = 0,
202 object_info_string_level = 0,
203 nosep = 0,
203 nosep = 0,
204 pdb = 0,
204 pdb = 0,
205 pprint = 0,
205 pprint = 0,
206 profile = '',
206 profile = '',
207 prompt_in1 = 'In [\\#]: ',
207 prompt_in1 = 'In [\\#]: ',
208 prompt_in2 = ' .\\D.: ',
208 prompt_in2 = ' .\\D.: ',
209 prompt_out = 'Out[\\#]: ',
209 prompt_out = 'Out[\\#]: ',
210 prompts_pad_left = 1,
210 prompts_pad_left = 1,
211 quiet = 0,
211 quiet = 0,
212 quick = 0,
212 quick = 0,
213 readline = 1,
213 readline = 1,
214 readline_merge_completions = 1,
214 readline_merge_completions = 1,
215 readline_omit__names = 0,
215 readline_omit__names = 0,
216 rcfile = 'ipythonrc' + rc_suffix,
216 rcfile = 'ipythonrc' + rc_suffix,
217 screen_length = 0,
217 screen_length = 0,
218 separate_in = '\n',
218 separate_in = '\n',
219 separate_out = '\n',
219 separate_out = '\n',
220 separate_out2 = '',
220 separate_out2 = '',
221 system_header = 'IPython system call: ',
221 system_verbose = 0,
222 system_verbose = 0,
222 gthread = 0,
223 gthread = 0,
223 qthread = 0,
224 qthread = 0,
224 q4thread = 0,
225 q4thread = 0,
225 wthread = 0,
226 wthread = 0,
226 pylab = 0,
227 pylab = 0,
227 tk = 0,
228 tk = 0,
228 upgrade = 0,
229 upgrade = 0,
229 Version = 0,
230 Version = 0,
230 xmode = 'Verbose',
231 xmode = 'Verbose',
231 wildcards_case_sensitive = 1,
232 wildcards_case_sensitive = 1,
232 wxversion = '0',
233 wxversion = '0',
233 magic_docstrings = 0, # undocumented, for doc generation
234 magic_docstrings = 0, # undocumented, for doc generation
234 )
235 )
235
236
236 # Things that will *only* appear in rcfiles (not at the command line).
237 # Things that will *only* appear in rcfiles (not at the command line).
237 # Make sure there's a space before each end of line (they get auto-joined!)
238 # Make sure there's a space before each end of line (they get auto-joined!)
238 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
239 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
239 qw_lol: 'import_some ',
240 qw_lol: 'import_some ',
240 # for things with embedded whitespace:
241 # for things with embedded whitespace:
241 list_strings:'execute alias readline_parse_and_bind ',
242 list_strings:'execute alias readline_parse_and_bind ',
242 # Regular strings need no conversion:
243 # Regular strings need no conversion:
243 None:'readline_remove_delims ',
244 None:'readline_remove_delims ',
244 }
245 }
245 # Default values for these
246 # Default values for these
246 rc_def = Struct(include = [],
247 rc_def = Struct(include = [],
247 import_mod = [],
248 import_mod = [],
248 import_all = [],
249 import_all = [],
249 import_some = [[]],
250 import_some = [[]],
250 execute = [],
251 execute = [],
251 execfile = [],
252 execfile = [],
252 alias = [],
253 alias = [],
253 readline_parse_and_bind = [],
254 readline_parse_and_bind = [],
254 readline_remove_delims = '',
255 readline_remove_delims = '',
255 )
256 )
256
257
257 # Build the type conversion dictionary from the above tables:
258 # Build the type conversion dictionary from the above tables:
258 typeconv = rcfile_opts.copy()
259 typeconv = rcfile_opts.copy()
259 typeconv.update(optstr2types(cmdline_opts))
260 typeconv.update(optstr2types(cmdline_opts))
260
261
261 # FIXME: the None key appears in both, put that back together by hand. Ugly!
262 # FIXME: the None key appears in both, put that back together by hand. Ugly!
262 typeconv[None] += ' ' + rcfile_opts[None]
263 typeconv[None] += ' ' + rcfile_opts[None]
263
264
264 # Remove quotes at ends of all strings (used to protect spaces)
265 # Remove quotes at ends of all strings (used to protect spaces)
265 typeconv[unquote_ends] = typeconv[None]
266 typeconv[unquote_ends] = typeconv[None]
266 del typeconv[None]
267 del typeconv[None]
267
268
268 # Build the list we'll use to make all config decisions with defaults:
269 # Build the list we'll use to make all config decisions with defaults:
269 opts_all = opts_def.copy()
270 opts_all = opts_def.copy()
270 opts_all.update(rc_def)
271 opts_all.update(rc_def)
271
272
272 # Build conflict resolver for recursive loading of config files:
273 # Build conflict resolver for recursive loading of config files:
273 # - preserve means the outermost file maintains the value, it is not
274 # - preserve means the outermost file maintains the value, it is not
274 # overwritten if an included file has the same key.
275 # overwritten if an included file has the same key.
275 # - add_flip applies + to the two values, so it better make sense to add
276 # - add_flip applies + to the two values, so it better make sense to add
276 # those types of keys. But it flips them first so that things loaded
277 # those types of keys. But it flips them first so that things loaded
277 # deeper in the inclusion chain have lower precedence.
278 # deeper in the inclusion chain have lower precedence.
278 conflict = {'preserve': ' '.join([ typeconv[int],
279 conflict = {'preserve': ' '.join([ typeconv[int],
279 typeconv[unquote_ends] ]),
280 typeconv[unquote_ends] ]),
280 'add_flip': ' '.join([ typeconv[qwflat],
281 'add_flip': ' '.join([ typeconv[qwflat],
281 typeconv[qw_lol],
282 typeconv[qw_lol],
282 typeconv[list_strings] ])
283 typeconv[list_strings] ])
283 }
284 }
284
285
285 # Now actually process the command line
286 # Now actually process the command line
286 getopt = DPyGetOpt.DPyGetOpt()
287 getopt = DPyGetOpt.DPyGetOpt()
287 getopt.setIgnoreCase(0)
288 getopt.setIgnoreCase(0)
288
289
289 getopt.parseConfiguration(opts_names)
290 getopt.parseConfiguration(opts_names)
290
291
291 try:
292 try:
292 getopt.processArguments(argv)
293 getopt.processArguments(argv)
293 except:
294 except:
294 print cmd_line_usage
295 print cmd_line_usage
295 warn('\nError in Arguments: ' + `sys.exc_value`)
296 warn('\nError in Arguments: ' + `sys.exc_value`)
296 sys.exit(1)
297 sys.exit(1)
297
298
298 # convert the options dict to a struct for much lighter syntax later
299 # convert the options dict to a struct for much lighter syntax later
299 opts = Struct(getopt.optionValues)
300 opts = Struct(getopt.optionValues)
300 args = getopt.freeValues
301 args = getopt.freeValues
301
302
302 # this is the struct (which has default values at this point) with which
303 # this is the struct (which has default values at this point) with which
303 # we make all decisions:
304 # we make all decisions:
304 opts_all.update(opts)
305 opts_all.update(opts)
305
306
306 # Options that force an immediate exit
307 # Options that force an immediate exit
307 if opts_all.help:
308 if opts_all.help:
308 page(cmd_line_usage)
309 page(cmd_line_usage)
309 sys.exit()
310 sys.exit()
310
311
311 if opts_all.Version:
312 if opts_all.Version:
312 print __version__
313 print __version__
313 sys.exit()
314 sys.exit()
314
315
315 if opts_all.magic_docstrings:
316 if opts_all.magic_docstrings:
316 IP.magic_magic('-latex')
317 IP.magic_magic('-latex')
317 sys.exit()
318 sys.exit()
318
319
319 # add personal ipythondir to sys.path so that users can put things in
320 # add personal ipythondir to sys.path so that users can put things in
320 # there for customization
321 # there for customization
321 sys.path.append(os.path.abspath(opts_all.ipythondir))
322 sys.path.append(os.path.abspath(opts_all.ipythondir))
322
323
323 # Create user config directory if it doesn't exist. This must be done
324 # Create user config directory if it doesn't exist. This must be done
324 # *after* getting the cmd line options.
325 # *after* getting the cmd line options.
325 if not os.path.isdir(opts_all.ipythondir):
326 if not os.path.isdir(opts_all.ipythondir):
326 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
327 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
327
328
328 # upgrade user config files while preserving a copy of the originals
329 # upgrade user config files while preserving a copy of the originals
329 if opts_all.upgrade:
330 if opts_all.upgrade:
330 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
331 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
331
332
332 # check mutually exclusive options in the *original* command line
333 # check mutually exclusive options in the *original* command line
333 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
334 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
334 qw('classic profile'),qw('classic rcfile')])
335 qw('classic profile'),qw('classic rcfile')])
335
336
336 #---------------------------------------------------------------------------
337 #---------------------------------------------------------------------------
337 # Log replay
338 # Log replay
338
339
339 # if -logplay, we need to 'become' the other session. That basically means
340 # if -logplay, we need to 'become' the other session. That basically means
340 # replacing the current command line environment with that of the old
341 # replacing the current command line environment with that of the old
341 # session and moving on.
342 # session and moving on.
342
343
343 # this is needed so that later we know we're in session reload mode, as
344 # this is needed so that later we know we're in session reload mode, as
344 # opts_all will get overwritten:
345 # opts_all will get overwritten:
345 load_logplay = 0
346 load_logplay = 0
346
347
347 if opts_all.logplay:
348 if opts_all.logplay:
348 load_logplay = opts_all.logplay
349 load_logplay = opts_all.logplay
349 opts_debug_save = opts_all.debug
350 opts_debug_save = opts_all.debug
350 try:
351 try:
351 logplay = open(opts_all.logplay)
352 logplay = open(opts_all.logplay)
352 except IOError:
353 except IOError:
353 if opts_all.debug: IP.InteractiveTB()
354 if opts_all.debug: IP.InteractiveTB()
354 warn('Could not open logplay file '+`opts_all.logplay`)
355 warn('Could not open logplay file '+`opts_all.logplay`)
355 # restore state as if nothing had happened and move on, but make
356 # restore state as if nothing had happened and move on, but make
356 # sure that later we don't try to actually load the session file
357 # sure that later we don't try to actually load the session file
357 logplay = None
358 logplay = None
358 load_logplay = 0
359 load_logplay = 0
359 del opts_all.logplay
360 del opts_all.logplay
360 else:
361 else:
361 try:
362 try:
362 logplay.readline()
363 logplay.readline()
363 logplay.readline();
364 logplay.readline();
364 # this reloads that session's command line
365 # this reloads that session's command line
365 cmd = logplay.readline()[6:]
366 cmd = logplay.readline()[6:]
366 exec cmd
367 exec cmd
367 # restore the true debug flag given so that the process of
368 # restore the true debug flag given so that the process of
368 # session loading itself can be monitored.
369 # session loading itself can be monitored.
369 opts.debug = opts_debug_save
370 opts.debug = opts_debug_save
370 # save the logplay flag so later we don't overwrite the log
371 # save the logplay flag so later we don't overwrite the log
371 opts.logplay = load_logplay
372 opts.logplay = load_logplay
372 # now we must update our own structure with defaults
373 # now we must update our own structure with defaults
373 opts_all.update(opts)
374 opts_all.update(opts)
374 # now load args
375 # now load args
375 cmd = logplay.readline()[6:]
376 cmd = logplay.readline()[6:]
376 exec cmd
377 exec cmd
377 logplay.close()
378 logplay.close()
378 except:
379 except:
379 logplay.close()
380 logplay.close()
380 if opts_all.debug: IP.InteractiveTB()
381 if opts_all.debug: IP.InteractiveTB()
381 warn("Logplay file lacking full configuration information.\n"
382 warn("Logplay file lacking full configuration information.\n"
382 "I'll try to read it, but some things may not work.")
383 "I'll try to read it, but some things may not work.")
383
384
384 #-------------------------------------------------------------------------
385 #-------------------------------------------------------------------------
385 # set up output traps: catch all output from files, being run, modules
386 # set up output traps: catch all output from files, being run, modules
386 # loaded, etc. Then give it to the user in a clean form at the end.
387 # loaded, etc. Then give it to the user in a clean form at the end.
387
388
388 msg_out = 'Output messages. '
389 msg_out = 'Output messages. '
389 msg_err = 'Error messages. '
390 msg_err = 'Error messages. '
390 msg_sep = '\n'
391 msg_sep = '\n'
391 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
392 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
392 msg_err,msg_sep,debug,
393 msg_err,msg_sep,debug,
393 quiet_out=1),
394 quiet_out=1),
394 user_exec = OutputTrap('User File Execution',msg_out,
395 user_exec = OutputTrap('User File Execution',msg_out,
395 msg_err,msg_sep,debug),
396 msg_err,msg_sep,debug),
396 logplay = OutputTrap('Log Loader',msg_out,
397 logplay = OutputTrap('Log Loader',msg_out,
397 msg_err,msg_sep,debug),
398 msg_err,msg_sep,debug),
398 summary = ''
399 summary = ''
399 )
400 )
400
401
401 #-------------------------------------------------------------------------
402 #-------------------------------------------------------------------------
402 # Process user ipythonrc-type configuration files
403 # Process user ipythonrc-type configuration files
403
404
404 # turn on output trapping and log to msg.config
405 # turn on output trapping and log to msg.config
405 # remember that with debug on, trapping is actually disabled
406 # remember that with debug on, trapping is actually disabled
406 msg.config.trap_all()
407 msg.config.trap_all()
407
408
408 # look for rcfile in current or default directory
409 # look for rcfile in current or default directory
409 try:
410 try:
410 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
411 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
411 except IOError:
412 except IOError:
412 if opts_all.debug: IP.InteractiveTB()
413 if opts_all.debug: IP.InteractiveTB()
413 warn('Configuration file %s not found. Ignoring request.'
414 warn('Configuration file %s not found. Ignoring request.'
414 % (opts_all.rcfile) )
415 % (opts_all.rcfile) )
415
416
416 # 'profiles' are a shorthand notation for config filenames
417 # 'profiles' are a shorthand notation for config filenames
417 if opts_all.profile:
418 if opts_all.profile:
418
419
419 try:
420 try:
420 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
421 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
421 + rc_suffix,
422 + rc_suffix,
422 opts_all.ipythondir)
423 opts_all.ipythondir)
423 except IOError:
424 except IOError:
424 if opts_all.debug: IP.InteractiveTB()
425 if opts_all.debug: IP.InteractiveTB()
425 opts.profile = '' # remove profile from options if invalid
426 opts.profile = '' # remove profile from options if invalid
426 # We won't warn anymore, primary method is ipy_profile_PROFNAME
427 # We won't warn anymore, primary method is ipy_profile_PROFNAME
427 # which does trigger a warning.
428 # which does trigger a warning.
428
429
429 # load the config file
430 # load the config file
430 rcfiledata = None
431 rcfiledata = None
431 if opts_all.quick:
432 if opts_all.quick:
432 print 'Launching IPython in quick mode. No config file read.'
433 print 'Launching IPython in quick mode. No config file read.'
433 elif opts_all.classic:
434 elif opts_all.classic:
434 print 'Launching IPython in classic mode. No config file read.'
435 print 'Launching IPython in classic mode. No config file read.'
435 elif opts_all.rcfile:
436 elif opts_all.rcfile:
436 try:
437 try:
437 cfg_loader = ConfigLoader(conflict)
438 cfg_loader = ConfigLoader(conflict)
438 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
439 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
439 'include',opts_all.ipythondir,
440 'include',opts_all.ipythondir,
440 purge = 1,
441 purge = 1,
441 unique = conflict['preserve'])
442 unique = conflict['preserve'])
442 except:
443 except:
443 IP.InteractiveTB()
444 IP.InteractiveTB()
444 warn('Problems loading configuration file '+
445 warn('Problems loading configuration file '+
445 `opts_all.rcfile`+
446 `opts_all.rcfile`+
446 '\nStarting with default -bare bones- configuration.')
447 '\nStarting with default -bare bones- configuration.')
447 else:
448 else:
448 warn('No valid configuration file found in either currrent directory\n'+
449 warn('No valid configuration file found in either currrent directory\n'+
449 'or in the IPython config. directory: '+`opts_all.ipythondir`+
450 'or in the IPython config. directory: '+`opts_all.ipythondir`+
450 '\nProceeding with internal defaults.')
451 '\nProceeding with internal defaults.')
451
452
452 #------------------------------------------------------------------------
453 #------------------------------------------------------------------------
453 # Set exception handlers in mode requested by user.
454 # Set exception handlers in mode requested by user.
454 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
455 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
455 IP.magic_xmode(opts_all.xmode)
456 IP.magic_xmode(opts_all.xmode)
456 otrap.release_out()
457 otrap.release_out()
457
458
458 #------------------------------------------------------------------------
459 #------------------------------------------------------------------------
459 # Execute user config
460 # Execute user config
460
461
461 # Create a valid config structure with the right precedence order:
462 # Create a valid config structure with the right precedence order:
462 # defaults < rcfile < command line. This needs to be in the instance, so
463 # defaults < rcfile < command line. This needs to be in the instance, so
463 # that method calls below that rely on it find it.
464 # that method calls below that rely on it find it.
464 IP.rc = rc_def.copy()
465 IP.rc = rc_def.copy()
465
466
466 # Work with a local alias inside this routine to avoid unnecessary
467 # Work with a local alias inside this routine to avoid unnecessary
467 # attribute lookups.
468 # attribute lookups.
468 IP_rc = IP.rc
469 IP_rc = IP.rc
469
470
470 IP_rc.update(opts_def)
471 IP_rc.update(opts_def)
471 if rcfiledata:
472 if rcfiledata:
472 # now we can update
473 # now we can update
473 IP_rc.update(rcfiledata)
474 IP_rc.update(rcfiledata)
474 IP_rc.update(opts)
475 IP_rc.update(opts)
475 IP_rc.update(rc_override)
476 IP_rc.update(rc_override)
476
477
477 # Store the original cmd line for reference:
478 # Store the original cmd line for reference:
478 IP_rc.opts = opts
479 IP_rc.opts = opts
479 IP_rc.args = args
480 IP_rc.args = args
480
481
481 # create a *runtime* Struct like rc for holding parameters which may be
482 # create a *runtime* Struct like rc for holding parameters which may be
482 # created and/or modified by runtime user extensions.
483 # created and/or modified by runtime user extensions.
483 IP.runtime_rc = Struct()
484 IP.runtime_rc = Struct()
484
485
485 # from this point on, all config should be handled through IP_rc,
486 # from this point on, all config should be handled through IP_rc,
486 # opts* shouldn't be used anymore.
487 # opts* shouldn't be used anymore.
487
488
488
489
489 # update IP_rc with some special things that need manual
490 # update IP_rc with some special things that need manual
490 # tweaks. Basically options which affect other options. I guess this
491 # tweaks. Basically options which affect other options. I guess this
491 # should just be written so that options are fully orthogonal and we
492 # should just be written so that options are fully orthogonal and we
492 # wouldn't worry about this stuff!
493 # wouldn't worry about this stuff!
493
494
494 if IP_rc.classic:
495 if IP_rc.classic:
495 IP_rc.quick = 1
496 IP_rc.quick = 1
496 IP_rc.cache_size = 0
497 IP_rc.cache_size = 0
497 IP_rc.pprint = 0
498 IP_rc.pprint = 0
498 IP_rc.prompt_in1 = '>>> '
499 IP_rc.prompt_in1 = '>>> '
499 IP_rc.prompt_in2 = '... '
500 IP_rc.prompt_in2 = '... '
500 IP_rc.prompt_out = ''
501 IP_rc.prompt_out = ''
501 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
502 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
502 IP_rc.colors = 'NoColor'
503 IP_rc.colors = 'NoColor'
503 IP_rc.xmode = 'Plain'
504 IP_rc.xmode = 'Plain'
504
505
505 IP.pre_config_initialization()
506 IP.pre_config_initialization()
506 # configure readline
507 # configure readline
507 # Define the history file for saving commands in between sessions
508 # Define the history file for saving commands in between sessions
508 if IP_rc.profile:
509 if IP_rc.profile:
509 histfname = 'history-%s' % IP_rc.profile
510 histfname = 'history-%s' % IP_rc.profile
510 else:
511 else:
511 histfname = 'history'
512 histfname = 'history'
512 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
513 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
513
514
514 # update exception handlers with rc file status
515 # update exception handlers with rc file status
515 otrap.trap_out() # I don't want these messages ever.
516 otrap.trap_out() # I don't want these messages ever.
516 IP.magic_xmode(IP_rc.xmode)
517 IP.magic_xmode(IP_rc.xmode)
517 otrap.release_out()
518 otrap.release_out()
518
519
519 # activate logging if requested and not reloading a log
520 # activate logging if requested and not reloading a log
520 if IP_rc.logplay:
521 if IP_rc.logplay:
521 IP.magic_logstart(IP_rc.logplay + ' append')
522 IP.magic_logstart(IP_rc.logplay + ' append')
522 elif IP_rc.logfile:
523 elif IP_rc.logfile:
523 IP.magic_logstart(IP_rc.logfile)
524 IP.magic_logstart(IP_rc.logfile)
524 elif IP_rc.log:
525 elif IP_rc.log:
525 IP.magic_logstart()
526 IP.magic_logstart()
526
527
527 # find user editor so that it we don't have to look it up constantly
528 # find user editor so that it we don't have to look it up constantly
528 if IP_rc.editor.strip()=='0':
529 if IP_rc.editor.strip()=='0':
529 try:
530 try:
530 ed = os.environ['EDITOR']
531 ed = os.environ['EDITOR']
531 except KeyError:
532 except KeyError:
532 if os.name == 'posix':
533 if os.name == 'posix':
533 ed = 'vi' # the only one guaranteed to be there!
534 ed = 'vi' # the only one guaranteed to be there!
534 else:
535 else:
535 ed = 'notepad' # same in Windows!
536 ed = 'notepad' # same in Windows!
536 IP_rc.editor = ed
537 IP_rc.editor = ed
537
538
538 # Keep track of whether this is an embedded instance or not (useful for
539 # Keep track of whether this is an embedded instance or not (useful for
539 # post-mortems).
540 # post-mortems).
540 IP_rc.embedded = IP.embedded
541 IP_rc.embedded = IP.embedded
541
542
542 # Recursive reload
543 # Recursive reload
543 try:
544 try:
544 from IPython import deep_reload
545 from IPython import deep_reload
545 if IP_rc.deep_reload:
546 if IP_rc.deep_reload:
546 __builtin__.reload = deep_reload.reload
547 __builtin__.reload = deep_reload.reload
547 else:
548 else:
548 __builtin__.dreload = deep_reload.reload
549 __builtin__.dreload = deep_reload.reload
549 del deep_reload
550 del deep_reload
550 except ImportError:
551 except ImportError:
551 pass
552 pass
552
553
553 # Save the current state of our namespace so that the interactive shell
554 # Save the current state of our namespace so that the interactive shell
554 # can later know which variables have been created by us from config files
555 # can later know which variables have been created by us from config files
555 # and loading. This way, loading a file (in any way) is treated just like
556 # and loading. This way, loading a file (in any way) is treated just like
556 # defining things on the command line, and %who works as expected.
557 # defining things on the command line, and %who works as expected.
557
558
558 # DON'T do anything that affects the namespace beyond this point!
559 # DON'T do anything that affects the namespace beyond this point!
559 IP.internal_ns.update(__main__.__dict__)
560 IP.internal_ns.update(__main__.__dict__)
560
561
561 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
562 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
562
563
563 # Now run through the different sections of the users's config
564 # Now run through the different sections of the users's config
564 if IP_rc.debug:
565 if IP_rc.debug:
565 print 'Trying to execute the following configuration structure:'
566 print 'Trying to execute the following configuration structure:'
566 print '(Things listed first are deeper in the inclusion tree and get'
567 print '(Things listed first are deeper in the inclusion tree and get'
567 print 'loaded first).\n'
568 print 'loaded first).\n'
568 pprint(IP_rc.__dict__)
569 pprint(IP_rc.__dict__)
569
570
570 for mod in IP_rc.import_mod:
571 for mod in IP_rc.import_mod:
571 try:
572 try:
572 exec 'import '+mod in IP.user_ns
573 exec 'import '+mod in IP.user_ns
573 except :
574 except :
574 IP.InteractiveTB()
575 IP.InteractiveTB()
575 import_fail_info(mod)
576 import_fail_info(mod)
576
577
577 for mod_fn in IP_rc.import_some:
578 for mod_fn in IP_rc.import_some:
578 if mod_fn == []: break
579 if mod_fn == []: break
579 mod,fn = mod_fn[0],','.join(mod_fn[1:])
580 mod,fn = mod_fn[0],','.join(mod_fn[1:])
580 try:
581 try:
581 exec 'from '+mod+' import '+fn in IP.user_ns
582 exec 'from '+mod+' import '+fn in IP.user_ns
582 except :
583 except :
583 IP.InteractiveTB()
584 IP.InteractiveTB()
584 import_fail_info(mod,fn)
585 import_fail_info(mod,fn)
585
586
586 for mod in IP_rc.import_all:
587 for mod in IP_rc.import_all:
587 try:
588 try:
588 exec 'from '+mod+' import *' in IP.user_ns
589 exec 'from '+mod+' import *' in IP.user_ns
589 except :
590 except :
590 IP.InteractiveTB()
591 IP.InteractiveTB()
591 import_fail_info(mod)
592 import_fail_info(mod)
592
593
593 for code in IP_rc.execute:
594 for code in IP_rc.execute:
594 try:
595 try:
595 exec code in IP.user_ns
596 exec code in IP.user_ns
596 except:
597 except:
597 IP.InteractiveTB()
598 IP.InteractiveTB()
598 warn('Failure executing code: ' + `code`)
599 warn('Failure executing code: ' + `code`)
599
600
600 # Execute the files the user wants in ipythonrc
601 # Execute the files the user wants in ipythonrc
601 for file in IP_rc.execfile:
602 for file in IP_rc.execfile:
602 try:
603 try:
603 file = filefind(file,sys.path+[IPython_dir])
604 file = filefind(file,sys.path+[IPython_dir])
604 except IOError:
605 except IOError:
605 warn(itpl('File $file not found. Skipping it.'))
606 warn(itpl('File $file not found. Skipping it.'))
606 else:
607 else:
607 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
608 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
608
609
609 # finally, try importing ipy_*_conf for final configuration
610 # finally, try importing ipy_*_conf for final configuration
610 try:
611 try:
611 import ipy_system_conf
612 import ipy_system_conf
612 except ImportError:
613 except ImportError:
613 if opts_all.debug: IP.InteractiveTB()
614 if opts_all.debug: IP.InteractiveTB()
614 warn("Could not import 'ipy_system_conf'")
615 warn("Could not import 'ipy_system_conf'")
615 except:
616 except:
616 IP.InteractiveTB()
617 IP.InteractiveTB()
617 import_fail_info('ipy_system_conf')
618 import_fail_info('ipy_system_conf')
618
619
619 if opts_all.profile:
620 if opts_all.profile:
620 profmodname = 'ipy_profile_' + opts_all.profile
621 profmodname = 'ipy_profile_' + opts_all.profile
621 try:
622 try:
622 __import__(profmodname)
623 __import__(profmodname)
623 except ImportError:
624 except ImportError:
624 # only warn if ipythonrc-PROFNAME didn't exist
625 # only warn if ipythonrc-PROFNAME didn't exist
625 if opts.profile =='':
626 if opts.profile =='':
626 warn("Could not start with profile '%s'!\n"
627 warn("Could not start with profile '%s'!\n"
627 "('%s/%s.py' does not exist? run '%%upgrade')" %
628 "('%s/%s.py' does not exist? run '%%upgrade')" %
628 (opts_all.profile, opts_all.ipythondir, profmodname) )
629 (opts_all.profile, opts_all.ipythondir, profmodname) )
629 except:
630 except:
630 print "Error importing",profmodname
631 print "Error importing",profmodname
631 IP.InteractiveTB()
632 IP.InteractiveTB()
632 import_fail_info(profmodname)
633 import_fail_info(profmodname)
633
634
634 try:
635 try:
635 import ipy_user_conf
636 import ipy_user_conf
636 except ImportError:
637 except ImportError:
637 if opts_all.debug: IP.InteractiveTB()
638 if opts_all.debug: IP.InteractiveTB()
638 warn("Could not import user config!\n "
639 warn("Could not import user config!\n "
639 "('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n"
640 "('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n"
640 % opts_all.ipythondir)
641 % opts_all.ipythondir)
641 except:
642 except:
642 print "Error importing ipy_user_conf"
643 print "Error importing ipy_user_conf"
643 IP.InteractiveTB()
644 IP.InteractiveTB()
644 import_fail_info("ipy_user_conf")
645 import_fail_info("ipy_user_conf")
645
646
646 # release stdout and stderr and save config log into a global summary
647 # release stdout and stderr and save config log into a global summary
647 msg.config.release_all()
648 msg.config.release_all()
648 if IP_rc.messages:
649 if IP_rc.messages:
649 msg.summary += msg.config.summary_all()
650 msg.summary += msg.config.summary_all()
650
651
651 #------------------------------------------------------------------------
652 #------------------------------------------------------------------------
652 # Setup interactive session
653 # Setup interactive session
653
654
654 # Now we should be fully configured. We can then execute files or load
655 # Now we should be fully configured. We can then execute files or load
655 # things only needed for interactive use. Then we'll open the shell.
656 # things only needed for interactive use. Then we'll open the shell.
656
657
657 # Take a snapshot of the user namespace before opening the shell. That way
658 # Take a snapshot of the user namespace before opening the shell. That way
658 # we'll be able to identify which things were interactively defined and
659 # we'll be able to identify which things were interactively defined and
659 # which were defined through config files.
660 # which were defined through config files.
660 IP.user_config_ns = IP.user_ns.copy()
661 IP.user_config_ns = IP.user_ns.copy()
661
662
662 # Force reading a file as if it were a session log. Slower but safer.
663 # Force reading a file as if it were a session log. Slower but safer.
663 if load_logplay:
664 if load_logplay:
664 print 'Replaying log...'
665 print 'Replaying log...'
665 try:
666 try:
666 if IP_rc.debug:
667 if IP_rc.debug:
667 logplay_quiet = 0
668 logplay_quiet = 0
668 else:
669 else:
669 logplay_quiet = 1
670 logplay_quiet = 1
670
671
671 msg.logplay.trap_all()
672 msg.logplay.trap_all()
672 IP.safe_execfile(load_logplay,IP.user_ns,
673 IP.safe_execfile(load_logplay,IP.user_ns,
673 islog = 1, quiet = logplay_quiet)
674 islog = 1, quiet = logplay_quiet)
674 msg.logplay.release_all()
675 msg.logplay.release_all()
675 if IP_rc.messages:
676 if IP_rc.messages:
676 msg.summary += msg.logplay.summary_all()
677 msg.summary += msg.logplay.summary_all()
677 except:
678 except:
678 warn('Problems replaying logfile %s.' % load_logplay)
679 warn('Problems replaying logfile %s.' % load_logplay)
679 IP.InteractiveTB()
680 IP.InteractiveTB()
680
681
681 # Load remaining files in command line
682 # Load remaining files in command line
682 msg.user_exec.trap_all()
683 msg.user_exec.trap_all()
683
684
684 # Do NOT execute files named in the command line as scripts to be loaded
685 # Do NOT execute files named in the command line as scripts to be loaded
685 # by embedded instances. Doing so has the potential for an infinite
686 # by embedded instances. Doing so has the potential for an infinite
686 # recursion if there are exceptions thrown in the process.
687 # recursion if there are exceptions thrown in the process.
687
688
688 # XXX FIXME: the execution of user files should be moved out to after
689 # XXX FIXME: the execution of user files should be moved out to after
689 # ipython is fully initialized, just as if they were run via %run at the
690 # ipython is fully initialized, just as if they were run via %run at the
690 # ipython prompt. This would also give them the benefit of ipython's
691 # ipython prompt. This would also give them the benefit of ipython's
691 # nice tracebacks.
692 # nice tracebacks.
692
693
693 if (not embedded and IP_rc.args and
694 if (not embedded and IP_rc.args and
694 not IP_rc.args[0].lower().endswith('.ipy')):
695 not IP_rc.args[0].lower().endswith('.ipy')):
695 name_save = IP.user_ns['__name__']
696 name_save = IP.user_ns['__name__']
696 IP.user_ns['__name__'] = '__main__'
697 IP.user_ns['__name__'] = '__main__'
697 # Set our own excepthook in case the user code tries to call it
698 # Set our own excepthook in case the user code tries to call it
698 # directly. This prevents triggering the IPython crash handler.
699 # directly. This prevents triggering the IPython crash handler.
699 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
700 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
700
701
701 save_argv = sys.argv[1:] # save it for later restoring
702 save_argv = sys.argv[1:] # save it for later restoring
702
703
703 sys.argv = args
704 sys.argv = args
704
705
705 try:
706 try:
706 IP.safe_execfile(args[0], IP.user_ns)
707 IP.safe_execfile(args[0], IP.user_ns)
707 finally:
708 finally:
708 # Reset our crash handler in place
709 # Reset our crash handler in place
709 sys.excepthook = old_excepthook
710 sys.excepthook = old_excepthook
710 sys.argv[:] = save_argv
711 sys.argv[:] = save_argv
711 IP.user_ns['__name__'] = name_save
712 IP.user_ns['__name__'] = name_save
712
713
713 msg.user_exec.release_all()
714 msg.user_exec.release_all()
714
715
715 if IP_rc.messages:
716 if IP_rc.messages:
716 msg.summary += msg.user_exec.summary_all()
717 msg.summary += msg.user_exec.summary_all()
717
718
718 # since we can't specify a null string on the cmd line, 0 is the equivalent:
719 # since we can't specify a null string on the cmd line, 0 is the equivalent:
719 if IP_rc.nosep:
720 if IP_rc.nosep:
720 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
721 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
721 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
722 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
722 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
723 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
723 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
724 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
724 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
725 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
725 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
726 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
726 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
727 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
727
728
728 # Determine how many lines at the bottom of the screen are needed for
729 # Determine how many lines at the bottom of the screen are needed for
729 # showing prompts, so we can know wheter long strings are to be printed or
730 # showing prompts, so we can know wheter long strings are to be printed or
730 # paged:
731 # paged:
731 num_lines_bot = IP_rc.separate_in.count('\n')+1
732 num_lines_bot = IP_rc.separate_in.count('\n')+1
732 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
733 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
733
734
734 # configure startup banner
735 # configure startup banner
735 if IP_rc.c: # regular python doesn't print the banner with -c
736 if IP_rc.c: # regular python doesn't print the banner with -c
736 IP_rc.banner = 0
737 IP_rc.banner = 0
737 if IP_rc.banner:
738 if IP_rc.banner:
738 BANN_P = IP.BANNER_PARTS
739 BANN_P = IP.BANNER_PARTS
739 else:
740 else:
740 BANN_P = []
741 BANN_P = []
741
742
742 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
743 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
743
744
744 # add message log (possibly empty)
745 # add message log (possibly empty)
745 if msg.summary: BANN_P.append(msg.summary)
746 if msg.summary: BANN_P.append(msg.summary)
746 # Final banner is a string
747 # Final banner is a string
747 IP.BANNER = '\n'.join(BANN_P)
748 IP.BANNER = '\n'.join(BANN_P)
748
749
749 # Finalize the IPython instance. This assumes the rc structure is fully
750 # Finalize the IPython instance. This assumes the rc structure is fully
750 # in place.
751 # in place.
751 IP.post_config_initialization()
752 IP.post_config_initialization()
752
753
753 return IP
754 return IP
754 #************************ end of file <ipmaker.py> **************************
755 #************************ end of file <ipmaker.py> **************************
@@ -1,305 +1,314 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Module for interactively running scripts.
2 """Module for interactively running scripts.
3
3
4 This module implements classes for interactively running scripts written for
4 This module implements classes for interactively running scripts written for
5 any system with a prompt which can be matched by a regexp suitable for
5 any system with a prompt which can be matched by a regexp suitable for
6 pexpect. It can be used to run as if they had been typed up interactively, an
6 pexpect. It can be used to run as if they had been typed up interactively, an
7 arbitrary series of commands for the target system.
7 arbitrary series of commands for the target system.
8
8
9 The module includes classes ready for IPython (with the default prompts),
9 The module includes classes ready for IPython (with the default prompts),
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 simply run the module as a script:
11 simply run the module as a script:
12
12
13 ./irunner.py --help
13 ./irunner.py --help
14
14
15
15
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 contributed on the ipython-user list:
17 contributed on the ipython-user list:
18
18
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20
20
21
21
22 NOTES:
22 NOTES:
23
23
24 - This module requires pexpect, available in most linux distros, or which can
24 - This module requires pexpect, available in most linux distros, or which can
25 be downloaded from
25 be downloaded from
26
26
27 http://pexpect.sourceforge.net
27 http://pexpect.sourceforge.net
28
28
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 limitations. This means that it will NOT work under native windows Python.
30 limitations. This means that it will NOT work under native windows Python.
31 """
31 """
32
32
33 # Stdlib imports
33 # Stdlib imports
34 import optparse
34 import optparse
35 import os
35 import os
36 import sys
36 import sys
37
37
38 # Third-party modules.
38 # Third-party modules.
39 import pexpect
39 import pexpect
40
40
41 # Global usage strings, to avoid indentation issues when typing it below.
41 # Global usage strings, to avoid indentation issues when typing it below.
42 USAGE = """
42 USAGE = """
43 Interactive script runner, type: %s
43 Interactive script runner, type: %s
44
44
45 runner [opts] script_name
45 runner [opts] script_name
46 """
46 """
47
47
48 # The generic runner class
48 # The generic runner class
49 class InteractiveRunner(object):
49 class InteractiveRunner(object):
50 """Class to run a sequence of commands through an interactive program."""
50 """Class to run a sequence of commands through an interactive program."""
51
51
52 def __init__(self,program,prompts,args=None):
52 def __init__(self,program,prompts,args=None):
53 """Construct a runner.
53 """Construct a runner.
54
54
55 Inputs:
55 Inputs:
56
56
57 - program: command to execute the given program.
57 - program: command to execute the given program.
58
58
59 - prompts: a list of patterns to match as valid prompts, in the
59 - prompts: a list of patterns to match as valid prompts, in the
60 format used by pexpect. This basically means that it can be either
60 format used by pexpect. This basically means that it can be either
61 a string (to be compiled as a regular expression) or a list of such
61 a string (to be compiled as a regular expression) or a list of such
62 (it must be a true list, as pexpect does type checks).
62 (it must be a true list, as pexpect does type checks).
63
63
64 If more than one prompt is given, the first is treated as the main
64 If more than one prompt is given, the first is treated as the main
65 program prompt and the others as 'continuation' prompts, like
65 program prompt and the others as 'continuation' prompts, like
66 python's. This means that blank lines in the input source are
66 python's. This means that blank lines in the input source are
67 ommitted when the first prompt is matched, but are NOT ommitted when
67 ommitted when the first prompt is matched, but are NOT ommitted when
68 the continuation one matches, since this is how python signals the
68 the continuation one matches, since this is how python signals the
69 end of multiline input interactively.
69 end of multiline input interactively.
70
70
71 Optional inputs:
71 Optional inputs:
72
72
73 - args(None): optional list of strings to pass as arguments to the
73 - args(None): optional list of strings to pass as arguments to the
74 child program.
74 child program.
75
75
76 Public members not parameterized in the constructor:
76 Public members not parameterized in the constructor:
77
77
78 - delaybeforesend(0): Newer versions of pexpect have a delay before
78 - delaybeforesend(0): Newer versions of pexpect have a delay before
79 sending each new input. For our purposes here, it's typically best
79 sending each new input. For our purposes here, it's typically best
80 to just set this to zero, but if you encounter reliability problems
80 to just set this to zero, but if you encounter reliability problems
81 or want an interactive run to pause briefly at each prompt, just
81 or want an interactive run to pause briefly at each prompt, just
82 increase this value (it is measured in seconds). Note that this
82 increase this value (it is measured in seconds). Note that this
83 variable is not honored at all by older versions of pexpect.
83 variable is not honored at all by older versions of pexpect.
84 """
84 """
85
85
86 self.program = program
86 self.program = program
87 self.prompts = prompts
87 self.prompts = prompts
88 if args is None: args = []
88 if args is None: args = []
89 self.args = args
89 self.args = args
90 # Other public members which we don't make as parameters, but which
90 # Other public members which we don't make as parameters, but which
91 # users may occasionally want to tweak
91 # users may occasionally want to tweak
92 self.delaybeforesend = 0
92 self.delaybeforesend = 0
93
93
94 def run_file(self,fname,interact=False):
94 def run_file(self,fname,interact=False):
95 """Run the given file interactively.
95 """Run the given file interactively.
96
96
97 Inputs:
97 Inputs:
98
98
99 -fname: name of the file to execute.
99 -fname: name of the file to execute.
100
100
101 See the run_source docstring for the meaning of the optional
101 See the run_source docstring for the meaning of the optional
102 arguments."""
102 arguments."""
103
103
104 fobj = open(fname,'r')
104 fobj = open(fname,'r')
105 try:
105 try:
106 self.run_source(fobj,interact)
106 self.run_source(fobj,interact)
107 finally:
107 finally:
108 fobj.close()
108 fobj.close()
109
109
110 def run_source(self,source,interact=False):
110 def run_source(self,source,interact=False):
111 """Run the given source code interactively.
111 """Run the given source code interactively.
112
112
113 Inputs:
113 Inputs:
114
114
115 - source: a string of code to be executed, or an open file object we
115 - source: a string of code to be executed, or an open file object we
116 can iterate over.
116 can iterate over.
117
117
118 Optional inputs:
118 Optional inputs:
119
119
120 - interact(False): if true, start to interact with the running
120 - interact(False): if true, start to interact with the running
121 program at the end of the script. Otherwise, just exit.
121 program at the end of the script. Otherwise, just exit.
122 """
122 """
123
123
124 # if the source is a string, chop it up in lines so we can iterate
124 # if the source is a string, chop it up in lines so we can iterate
125 # over it just as if it were an open file.
125 # over it just as if it were an open file.
126 if not isinstance(source,file):
126 if not isinstance(source,file):
127 source = source.splitlines(True)
127 source = source.splitlines(True)
128
128
129 # grab the true write method of stdout, in case anything later
129 # grab the true write method of stdout, in case anything later
130 # reassigns sys.stdout, so that we really are writing to the true
130 # reassigns sys.stdout, so that we really are writing to the true
131 # stdout and not to something else. We also normalize all strings we
131 # stdout and not to something else. We also normalize all strings we
132 # write to use the native OS line separators.
132 # write to use the native OS line separators.
133 linesep = os.linesep
133 linesep = os.linesep
134 stdwrite = sys.stdout.write
134 stdwrite = sys.stdout.write
135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
136
136
137 c = pexpect.spawn(self.program,self.args,timeout=None)
137 c = pexpect.spawn(self.program,self.args,timeout=None)
138 c.delaybeforesend = self.delaybeforesend
138 c.delaybeforesend = self.delaybeforesend
139
139
140 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
140 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
141 # This causes problems because any line longer than 80 characters gets
141 # This causes problems because any line longer than 80 characters gets
142 # completely overwrapped on the printed outptut (even though
142 # completely overwrapped on the printed outptut (even though
143 # internally the code runs fine). We reset this to 99 rows X 200
143 # internally the code runs fine). We reset this to 99 rows X 200
144 # columns (arbitrarily chosen), which should avoid problems in all
144 # columns (arbitrarily chosen), which should avoid problems in all
145 # reasonable cases.
145 # reasonable cases.
146 c.setwinsize(99,200)
146 c.setwinsize(99,200)
147
147
148 prompts = c.compile_pattern_list(self.prompts)
148 prompts = c.compile_pattern_list(self.prompts)
149
149
150 prompt_idx = c.expect_list(prompts)
150 prompt_idx = c.expect_list(prompts)
151 # Flag whether the script ends normally or not, to know whether we can
151 # Flag whether the script ends normally or not, to know whether we can
152 # do anything further with the underlying process.
152 # do anything further with the underlying process.
153 end_normal = True
153 end_normal = True
154 for cmd in source:
154 for cmd in source:
155 # skip blank lines for all matches to the 'main' prompt, while the
155 # skip blank lines for all matches to the 'main' prompt, while the
156 # secondary prompts do not
156 # secondary prompts do not
157 if prompt_idx==0 and \
157 if prompt_idx==0 and \
158 (cmd.isspace() or cmd.lstrip().startswith('#')):
158 (cmd.isspace() or cmd.lstrip().startswith('#')):
159 print cmd,
159 print cmd,
160 continue
160 continue
161
161
162 write(c.after)
162 write(c.after)
163 c.send(cmd)
163 c.send(cmd)
164 try:
164 try:
165 prompt_idx = c.expect_list(prompts)
165 prompt_idx = c.expect_list(prompts)
166 except pexpect.EOF:
166 except pexpect.EOF:
167 # this will happen if the child dies unexpectedly
167 # this will happen if the child dies unexpectedly
168 write(c.before)
168 write(c.before)
169 end_normal = False
169 end_normal = False
170 break
170 break
171 write(c.before)
171 write(c.before)
172
172
173 if end_normal:
173 if end_normal:
174 if interact:
174 if interact:
175 c.send('\n')
175 c.send('\n')
176 print '<< Starting interactive mode >>',
176 print '<< Starting interactive mode >>',
177 try:
177 try:
178 c.interact()
178 c.interact()
179 except OSError:
179 except OSError:
180 # This is what fires when the child stops. Simply print a
180 # This is what fires when the child stops. Simply print a
181 # newline so the system prompt is aligned. The extra
181 # newline so the system prompt is aligned. The extra
182 # space is there to make sure it gets printed, otherwise
182 # space is there to make sure it gets printed, otherwise
183 # OS buffering sometimes just suppresses it.
183 # OS buffering sometimes just suppresses it.
184 write(' \n')
184 write(' \n')
185 sys.stdout.flush()
185 sys.stdout.flush()
186 else:
186 else:
187 c.close()
187 c.close()
188 else:
188 else:
189 if interact:
189 if interact:
190 e="Further interaction is not possible: child process is dead."
190 e="Further interaction is not possible: child process is dead."
191 print >> sys.stderr, e
191 print >> sys.stderr, e
192
192
193 def main(self,argv=None):
193 def main(self,argv=None):
194 """Run as a command-line script."""
194 """Run as a command-line script."""
195
195
196 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
196 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
197 newopt = parser.add_option
197 newopt = parser.add_option
198 newopt('-i','--interact',action='store_true',default=False,
198 newopt('-i','--interact',action='store_true',default=False,
199 help='Interact with the program after the script is run.')
199 help='Interact with the program after the script is run.')
200
200
201 opts,args = parser.parse_args(argv)
201 opts,args = parser.parse_args(argv)
202
202
203 if len(args) != 1:
203 if len(args) != 1:
204 print >> sys.stderr,"You must supply exactly one file to run."
204 print >> sys.stderr,"You must supply exactly one file to run."
205 sys.exit(1)
205 sys.exit(1)
206
206
207 self.run_file(args[0],opts.interact)
207 self.run_file(args[0],opts.interact)
208
208
209
209
210 # Specific runners for particular programs
210 # Specific runners for particular programs
211 class IPythonRunner(InteractiveRunner):
211 class IPythonRunner(InteractiveRunner):
212 """Interactive IPython runner.
212 """Interactive IPython runner.
213
213
214 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
214 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
215 avoid having to write a regexp that matches ANSI sequences, though pexpect
215 avoid having to write a regexp that matches ANSI sequences, though pexpect
216 does support them. If anyone contributes patches for ANSI color support,
216 does support them. If anyone contributes patches for ANSI color support,
217 they will be welcome.
217 they will be welcome.
218
218
219 It also sets the prompts manually, since the prompt regexps for
219 It also sets the prompts manually, since the prompt regexps for
220 pexpect need to be matched to the actual prompts, so user-customized
220 pexpect need to be matched to the actual prompts, so user-customized
221 prompts would break this.
221 prompts would break this.
222 """
222 """
223
223
224 def __init__(self,program = 'ipython',args=None):
224 def __init__(self,program = 'ipython',args=None):
225 """New runner, optionally passing the ipython command to use."""
225 """New runner, optionally passing the ipython command to use."""
226
226
227 args0 = ['-colors','NoColor',
227 args0 = ['-colors','NoColor',
228 '-pi1','In [\\#]: ',
228 '-pi1','In [\\#]: ',
229 '-pi2',' .\\D.: ']
229 '-pi2',' .\\D.: ']
230 if args is None: args = args0
230 if args is None: args = args0
231 else: args = args0 + args
231 else: args = args0 + args
232 prompts = [r'In \[\d+\]: ',r' \.*: ']
232 prompts = [r'In \[\d+\]: ',r' \.*: ']
233 InteractiveRunner.__init__(self,program,prompts,args)
233 InteractiveRunner.__init__(self,program,prompts,args)
234
234
235
235
236 class PythonRunner(InteractiveRunner):
236 class PythonRunner(InteractiveRunner):
237 """Interactive Python runner."""
237 """Interactive Python runner."""
238
238
239 def __init__(self,program='python',args=None):
239 def __init__(self,program='python',args=None):
240 """New runner, optionally passing the python command to use."""
240 """New runner, optionally passing the python command to use."""
241
241
242 prompts = [r'>>> ',r'\.\.\. ']
242 prompts = [r'>>> ',r'\.\.\. ']
243 InteractiveRunner.__init__(self,program,prompts,args)
243 InteractiveRunner.__init__(self,program,prompts,args)
244
244
245
245
246 class SAGERunner(InteractiveRunner):
246 class SAGERunner(InteractiveRunner):
247 """Interactive SAGE runner.
247 """Interactive SAGE runner.
248
248
249 WARNING: this runner only works if you manually configure your SAGE copy
249 WARNING: this runner only works if you manually configure your SAGE copy
250 to use 'colors NoColor' in the ipythonrc config file, since currently the
250 to use 'colors NoColor' in the ipythonrc config file, since currently the
251 prompt matching regexp does not identify color sequences."""
251 prompt matching regexp does not identify color sequences."""
252
252
253 def __init__(self,program='sage',args=None):
253 def __init__(self,program='sage',args=None):
254 """New runner, optionally passing the sage command to use."""
254 """New runner, optionally passing the sage command to use."""
255
255
256 prompts = ['sage: ',r'\s*\.\.\. ']
256 prompts = ['sage: ',r'\s*\.\.\. ']
257 InteractiveRunner.__init__(self,program,prompts,args)
257 InteractiveRunner.__init__(self,program,prompts,args)
258
258
259 # Global usage string, to avoid indentation issues if typed in a function def.
259 # Global usage string, to avoid indentation issues if typed in a function def.
260 MAIN_USAGE = """
260 MAIN_USAGE = """
261 %prog [options] file_to_run
261 %prog [options] file_to_run
262
262
263 This is an interface to the various interactive runners available in this
263 This is an interface to the various interactive runners available in this
264 module. If you want to pass specific options to one of the runners, you need
264 module. If you want to pass specific options to one of the runners, you need
265 to first terminate the main options with a '--', and then provide the runner's
265 to first terminate the main options with a '--', and then provide the runner's
266 options. For example:
266 options. For example:
267
267
268 irunner.py --python -- --help
268 irunner.py --python -- --help
269
269
270 will pass --help to the python runner. Similarly,
270 will pass --help to the python runner. Similarly,
271
271
272 irunner.py --ipython -- --interact script.ipy
272 irunner.py --ipython -- --interact script.ipy
273
273
274 will run the script.ipy file under the IPython runner, and then will start to
274 will run the script.ipy file under the IPython runner, and then will start to
275 interact with IPython at the end of the script (instead of exiting).
275 interact with IPython at the end of the script (instead of exiting).
276
276
277 The already implemented runners are listed below; adding one for a new program
277 The already implemented runners are listed below; adding one for a new program
278 is a trivial task, see the source for examples.
278 is a trivial task, see the source for examples.
279
279
280 WARNING: the SAGE runner only works if you manually configure your SAGE copy
280 WARNING: the SAGE runner only works if you manually configure your SAGE copy
281 to use 'colors NoColor' in the ipythonrc config file, since currently the
281 to use 'colors NoColor' in the ipythonrc config file, since currently the
282 prompt matching regexp does not identify color sequences.
282 prompt matching regexp does not identify color sequences.
283 """
283 """
284
284
285 def main():
285 def main():
286 """Run as a command-line script."""
286 """Run as a command-line script."""
287
287
288 parser = optparse.OptionParser(usage=MAIN_USAGE)
288 parser = optparse.OptionParser(usage=MAIN_USAGE)
289 newopt = parser.add_option
289 newopt = parser.add_option
290 parser.set_defaults(mode='ipython')
290 parser.set_defaults(mode='ipython')
291 newopt('--ipython',action='store_const',dest='mode',const='ipython',
291 newopt('--ipython',action='store_const',dest='mode',const='ipython',
292 help='IPython interactive runner (default).')
292 help='IPython interactive runner (default).')
293 newopt('--python',action='store_const',dest='mode',const='python',
293 newopt('--python',action='store_const',dest='mode',const='python',
294 help='Python interactive runner.')
294 help='Python interactive runner.')
295 newopt('--sage',action='store_const',dest='mode',const='sage',
295 newopt('--sage',action='store_const',dest='mode',const='sage',
296 help='SAGE interactive runner.')
296 help='SAGE interactive runner.')
297
297
298 opts,args = parser.parse_args()
298 opts,args = parser.parse_args()
299 runners = dict(ipython=IPythonRunner,
299 runners = dict(ipython=IPythonRunner,
300 python=PythonRunner,
300 python=PythonRunner,
301 sage=SAGERunner)
301 sage=SAGERunner)
302 runners[opts.mode]().main(args)
302
303 try:
304 ext = os.path.splitext(args[0])
305 except IndexError:
306 ext = ''
307 modes = {'.ipy':'ipython',
308 '.py':'python',
309 '.sage':'sage'}
310 mode = modes.get(ext,opts.mode)
311 runners[mode]().main(args)
303
312
304 if __name__ == '__main__':
313 if __name__ == '__main__':
305 main()
314 main()
@@ -1,5910 +1,5923 b''
1 2006-11-03 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/iplib.py (InteractiveShell.ipconfig): new builtin, also
4 visible in ipapi as ip.config(), to programatically control the
5 internal rc object. There's an accompanying %config magic for
6 interactive use, which has been enhanced to match the
7 funtionality in ipconfig.
8
9 * IPython/Magic.py (magic_system_verbose): Change %system_verbose
10 so it's not just a toggle, it now takes an argument. Add support
11 for a customizable header when making system calls, as the new
12 system_header variable in the ipythonrc file.
13
1 2006-11-03 Walter Doerwald <walter@livinglogic.de>
14 2006-11-03 Walter Doerwald <walter@livinglogic.de>
2
15
3 * IPython/Extensions/ipipe.py: xrepr(), xiter() and xattrs() are now
16 * IPython/Extensions/ipipe.py: xrepr(), xiter() and xattrs() are now
4 generic functions (using Philip J. Eby's simplegeneric package).
17 generic functions (using Philip J. Eby's simplegeneric package).
5 This makes it possible to customize the display of third-party classes
18 This makes it possible to customize the display of third-party classes
6 without having to monkeypatch them. xiter() no longer supports a mode
19 without having to monkeypatch them. xiter() no longer supports a mode
7 argument and the XMode class has been removed. The same functionality can
20 argument and the XMode class has been removed. The same functionality can
8 be implemented via IterAttributeDescriptor and IterMethodDescriptor.
21 be implemented via IterAttributeDescriptor and IterMethodDescriptor.
9 One consequence of the switch to generic functions is that xrepr() and
22 One consequence of the switch to generic functions is that xrepr() and
10 xattrs() implementation must define the default value for the mode
23 xattrs() implementation must define the default value for the mode
11 argument themselves and xattrs() implementations must return real
24 argument themselves and xattrs() implementations must return real
12 descriptors.
25 descriptors.
13
26
14 * IPython/external: This new subpackage will contain all third-party
27 * IPython/external: This new subpackage will contain all third-party
15 packages that are bundled with IPython. (The first one is simplegeneric).
28 packages that are bundled with IPython. (The first one is simplegeneric).
16
29
17 * IPython/Extensions/ipipe.py (ifile/ils): Readd output of the parent
30 * IPython/Extensions/ipipe.py (ifile/ils): Readd output of the parent
18 directory which as been dropped in r1703.
31 directory which as been dropped in r1703.
19
32
20 * IPython/Extensions/ipipe.py (iless): Fixed.
33 * IPython/Extensions/ipipe.py (iless): Fixed.
21
34
22 * IPython/Extensions/ibrowse: Fixed sorting under Python 2.3.
35 * IPython/Extensions/ibrowse: Fixed sorting under Python 2.3.
23
36
24 2006-11-03 Fernando Perez <Fernando.Perez@colorado.edu>
37 2006-11-03 Fernando Perez <Fernando.Perez@colorado.edu>
25
38
26 * IPython/iplib.py (InteractiveShell.var_expand): fix stack
39 * IPython/iplib.py (InteractiveShell.var_expand): fix stack
27 handling in variable expansion so that shells and magics recognize
40 handling in variable expansion so that shells and magics recognize
28 function local scopes correctly. Bug reported by Brian.
41 function local scopes correctly. Bug reported by Brian.
29
42
30 * scripts/ipython: remove the very first entry in sys.path which
43 * scripts/ipython: remove the very first entry in sys.path which
31 Python auto-inserts for scripts, so that sys.path under IPython is
44 Python auto-inserts for scripts, so that sys.path under IPython is
32 as similar as possible to that under plain Python.
45 as similar as possible to that under plain Python.
33
46
34 * IPython/completer.py (IPCompleter.file_matches): Fix
47 * IPython/completer.py (IPCompleter.file_matches): Fix
35 tab-completion so that quotes are not closed unless the completion
48 tab-completion so that quotes are not closed unless the completion
36 is unambiguous. After a request by Stefan. Minor cleanups in
49 is unambiguous. After a request by Stefan. Minor cleanups in
37 ipy_stock_completers.
50 ipy_stock_completers.
38
51
39 2006-11-02 Ville Vainio <vivainio@gmail.com>
52 2006-11-02 Ville Vainio <vivainio@gmail.com>
40
53
41 * ipy_stock_completers.py: Add %run and %cd completers.
54 * ipy_stock_completers.py: Add %run and %cd completers.
42
55
43 * completer.py: Try running custom completer for both
56 * completer.py: Try running custom completer for both
44 "foo" and "%foo" if the command is just "foo". Ignore case
57 "foo" and "%foo" if the command is just "foo". Ignore case
45 when filtering possible completions.
58 when filtering possible completions.
46
59
47 * UserConfig/ipy_user_conf.py: install stock completers as default
60 * UserConfig/ipy_user_conf.py: install stock completers as default
48
61
49 * iplib.py (history_saving_wrapper), debugger(), ipy_pydb.py:
62 * iplib.py (history_saving_wrapper), debugger(), ipy_pydb.py:
50 simplified readline history save / restore through a wrapper
63 simplified readline history save / restore through a wrapper
51 function
64 function
52
65
53
66
54 2006-10-31 Ville Vainio <vivainio@gmail.com>
67 2006-10-31 Ville Vainio <vivainio@gmail.com>
55
68
56 * strdispatch.py, completer.py, ipy_stock_completers.py:
69 * strdispatch.py, completer.py, ipy_stock_completers.py:
57 Allow str_key ("command") in completer hooks. Implement
70 Allow str_key ("command") in completer hooks. Implement
58 trivial completer for 'import' (stdlib modules only). Rename
71 trivial completer for 'import' (stdlib modules only). Rename
59 ipy_linux_package_managers.py to ipy_stock_completers.py.
72 ipy_linux_package_managers.py to ipy_stock_completers.py.
60 SVN completer.
73 SVN completer.
61
74
62 * Extensions/ledit.py: %magic line editor for easily and
75 * Extensions/ledit.py: %magic line editor for easily and
63 incrementally manipulating lists of strings. The magic command
76 incrementally manipulating lists of strings. The magic command
64 name is %led.
77 name is %led.
65
78
66 2006-10-30 Ville Vainio <vivainio@gmail.com>
79 2006-10-30 Ville Vainio <vivainio@gmail.com>
67
80
68 * Debugger.py, iplib.py (debugger()): Add last set of Rocky
81 * Debugger.py, iplib.py (debugger()): Add last set of Rocky
69 Bernsteins's patches for pydb integration.
82 Bernsteins's patches for pydb integration.
70 http://bashdb.sourceforge.net/pydb/
83 http://bashdb.sourceforge.net/pydb/
71
84
72 * strdispatch.py, iplib.py, completer.py, IPython/__init__.py,
85 * strdispatch.py, iplib.py, completer.py, IPython/__init__.py,
73 Extensions/ipy_linux_package_managers.py, hooks.py: Implement
86 Extensions/ipy_linux_package_managers.py, hooks.py: Implement
74 custom completer hook to allow the users to implement their own
87 custom completer hook to allow the users to implement their own
75 completers. See ipy_linux_package_managers.py for example. The
88 completers. See ipy_linux_package_managers.py for example. The
76 hook name is 'complete_command'.
89 hook name is 'complete_command'.
77
90
78 2006-10-28 Fernando Perez <Fernando.Perez@colorado.edu>
91 2006-10-28 Fernando Perez <Fernando.Perez@colorado.edu>
79
92
80 * IPython/UserConfig/ipythonrc-scipy: minor cleanups to remove old
93 * IPython/UserConfig/ipythonrc-scipy: minor cleanups to remove old
81 Numeric leftovers.
94 Numeric leftovers.
82
95
83 * ipython.el (py-execute-region): apply Stefan's patch to fix
96 * ipython.el (py-execute-region): apply Stefan's patch to fix
84 garbled results if the python shell hasn't been previously started.
97 garbled results if the python shell hasn't been previously started.
85
98
86 * IPython/genutils.py (arg_split): moved to genutils, since it's a
99 * IPython/genutils.py (arg_split): moved to genutils, since it's a
87 pretty generic function and useful for other things.
100 pretty generic function and useful for other things.
88
101
89 * IPython/OInspect.py (getsource): Add customizable source
102 * IPython/OInspect.py (getsource): Add customizable source
90 extractor. After a request/patch form W. Stein (SAGE).
103 extractor. After a request/patch form W. Stein (SAGE).
91
104
92 * IPython/irunner.py (InteractiveRunner.run_source): reset tty
105 * IPython/irunner.py (InteractiveRunner.run_source): reset tty
93 window size to a more reasonable value from what pexpect does,
106 window size to a more reasonable value from what pexpect does,
94 since their choice causes wrapping bugs with long input lines.
107 since their choice causes wrapping bugs with long input lines.
95
108
96 2006-10-28 Ville Vainio <vivainio@gmail.com>
109 2006-10-28 Ville Vainio <vivainio@gmail.com>
97
110
98 * Magic.py (%run): Save and restore the readline history from
111 * Magic.py (%run): Save and restore the readline history from
99 file around %run commands to prevent side effects from
112 file around %run commands to prevent side effects from
100 %runned programs that might use readline (e.g. pydb).
113 %runned programs that might use readline (e.g. pydb).
101
114
102 * extensions/ipy_pydb.py: Adds %pydb magic when imported, for
115 * extensions/ipy_pydb.py: Adds %pydb magic when imported, for
103 invoking the pydb enhanced debugger.
116 invoking the pydb enhanced debugger.
104
117
105 2006-10-23 Walter Doerwald <walter@livinglogic.de>
118 2006-10-23 Walter Doerwald <walter@livinglogic.de>
106
119
107 * IPython/Extensions/ipipe.py (ifile): Remove all methods that
120 * IPython/Extensions/ipipe.py (ifile): Remove all methods that
108 call the base class method and propagate the return value to
121 call the base class method and propagate the return value to
109 ifile. This is now done by path itself.
122 ifile. This is now done by path itself.
110
123
111 2006-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
124 2006-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
112
125
113 * IPython/ipapi.py (IPApi.__init__): Added new entry to public
126 * IPython/ipapi.py (IPApi.__init__): Added new entry to public
114 api: set_crash_handler(), to expose the ability to change the
127 api: set_crash_handler(), to expose the ability to change the
115 internal crash handler.
128 internal crash handler.
116
129
117 * IPython/CrashHandler.py (CrashHandler.__init__): abstract out
130 * IPython/CrashHandler.py (CrashHandler.__init__): abstract out
118 the various parameters of the crash handler so that apps using
131 the various parameters of the crash handler so that apps using
119 IPython as their engine can customize crash handling. Ipmlemented
132 IPython as their engine can customize crash handling. Ipmlemented
120 at the request of SAGE.
133 at the request of SAGE.
121
134
122 2006-10-14 Ville Vainio <vivainio@gmail.com>
135 2006-10-14 Ville Vainio <vivainio@gmail.com>
123
136
124 * Magic.py, ipython.el: applied first "safe" part of Rocky
137 * Magic.py, ipython.el: applied first "safe" part of Rocky
125 Bernstein's patch set for pydb integration.
138 Bernstein's patch set for pydb integration.
126
139
127 * Magic.py (%unalias, %alias): %store'd aliases can now be
140 * Magic.py (%unalias, %alias): %store'd aliases can now be
128 removed with '%unalias'. %alias w/o args now shows most
141 removed with '%unalias'. %alias w/o args now shows most
129 interesting (stored / manually defined) aliases last
142 interesting (stored / manually defined) aliases last
130 where they catch the eye w/o scrolling.
143 where they catch the eye w/o scrolling.
131
144
132 * Magic.py (%rehashx), ext_rehashdir.py: files with
145 * Magic.py (%rehashx), ext_rehashdir.py: files with
133 'py' extension are always considered executable, even
146 'py' extension are always considered executable, even
134 when not in PATHEXT environment variable.
147 when not in PATHEXT environment variable.
135
148
136 2006-10-12 Ville Vainio <vivainio@gmail.com>
149 2006-10-12 Ville Vainio <vivainio@gmail.com>
137
150
138 * jobctrl.py: Add new "jobctrl" extension for spawning background
151 * jobctrl.py: Add new "jobctrl" extension for spawning background
139 processes with "&find /". 'import jobctrl' to try it out. Requires
152 processes with "&find /". 'import jobctrl' to try it out. Requires
140 'subprocess' module, standard in python 2.4+.
153 'subprocess' module, standard in python 2.4+.
141
154
142 * iplib.py (expand_aliases, handle_alias): Aliases expand transitively,
155 * iplib.py (expand_aliases, handle_alias): Aliases expand transitively,
143 so if foo -> bar and bar -> baz, then foo -> baz.
156 so if foo -> bar and bar -> baz, then foo -> baz.
144
157
145 2006-10-09 Fernando Perez <Fernando.Perez@colorado.edu>
158 2006-10-09 Fernando Perez <Fernando.Perez@colorado.edu>
146
159
147 * IPython/Magic.py (Magic.parse_options): add a new posix option
160 * IPython/Magic.py (Magic.parse_options): add a new posix option
148 to allow parsing of input args in magics that doesn't strip quotes
161 to allow parsing of input args in magics that doesn't strip quotes
149 (if posix=False). This also closes %timeit bug reported by
162 (if posix=False). This also closes %timeit bug reported by
150 Stefan.
163 Stefan.
151
164
152 2006-10-03 Ville Vainio <vivainio@gmail.com>
165 2006-10-03 Ville Vainio <vivainio@gmail.com>
153
166
154 * iplib.py (raw_input, interact): Return ValueError catching for
167 * iplib.py (raw_input, interact): Return ValueError catching for
155 raw_input. Fixes infinite loop for sys.stdin.close() or
168 raw_input. Fixes infinite loop for sys.stdin.close() or
156 sys.stdout.close().
169 sys.stdout.close().
157
170
158 2006-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
171 2006-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
159
172
160 * IPython/irunner.py (InteractiveRunner.run_source): small fixes
173 * IPython/irunner.py (InteractiveRunner.run_source): small fixes
161 to help in handling doctests. irunner is now pretty useful for
174 to help in handling doctests. irunner is now pretty useful for
162 running standalone scripts and simulate a full interactive session
175 running standalone scripts and simulate a full interactive session
163 in a format that can be then pasted as a doctest.
176 in a format that can be then pasted as a doctest.
164
177
165 * IPython/iplib.py (InteractiveShell.__init__): Install exit/quit
178 * IPython/iplib.py (InteractiveShell.__init__): Install exit/quit
166 on top of the default (useless) ones. This also fixes the nasty
179 on top of the default (useless) ones. This also fixes the nasty
167 way in which 2.5's Quitter() exits (reverted [1785]).
180 way in which 2.5's Quitter() exits (reverted [1785]).
168
181
169 * IPython/Debugger.py (Pdb.__init__): Fix ipdb to work with python
182 * IPython/Debugger.py (Pdb.__init__): Fix ipdb to work with python
170 2.5.
183 2.5.
171
184
172 * IPython/ultraTB.py (TBTools.set_colors): Make sure that ipdb
185 * IPython/ultraTB.py (TBTools.set_colors): Make sure that ipdb
173 color scheme is updated as well when color scheme is changed
186 color scheme is updated as well when color scheme is changed
174 interactively.
187 interactively.
175
188
176 2006-09-27 Ville Vainio <vivainio@gmail.com>
189 2006-09-27 Ville Vainio <vivainio@gmail.com>
177
190
178 * iplib.py (raw_input): python 2.5 closes stdin on quit -> avoid
191 * iplib.py (raw_input): python 2.5 closes stdin on quit -> avoid
179 infinite loop and just exit. It's a hack, but will do for a while.
192 infinite loop and just exit. It's a hack, but will do for a while.
180
193
181 2006-08-25 Walter Doerwald <walter@livinglogic.de>
194 2006-08-25 Walter Doerwald <walter@livinglogic.de>
182
195
183 * IPython/Extensions/ipipe.py (ils): Add arguments dirs and files to
196 * IPython/Extensions/ipipe.py (ils): Add arguments dirs and files to
184 the constructor, this makes it possible to get a list of only directories
197 the constructor, this makes it possible to get a list of only directories
185 or only files.
198 or only files.
186
199
187 2006-08-12 Ville Vainio <vivainio@gmail.com>
200 2006-08-12 Ville Vainio <vivainio@gmail.com>
188
201
189 * Fakemodule.py, OInspect.py: Reverted 2006-08-11 mods,
202 * Fakemodule.py, OInspect.py: Reverted 2006-08-11 mods,
190 they broke unittest
203 they broke unittest
191
204
192 2006-08-11 Ville Vainio <vivainio@gmail.com>
205 2006-08-11 Ville Vainio <vivainio@gmail.com>
193
206
194 * Fakemodule.py, OInspect.py: remove 2006-08-09 monkepatch
207 * Fakemodule.py, OInspect.py: remove 2006-08-09 monkepatch
195 by resolving issue properly, i.e. by inheriting FakeModule
208 by resolving issue properly, i.e. by inheriting FakeModule
196 from types.ModuleType. Pickling ipython interactive data
209 from types.ModuleType. Pickling ipython interactive data
197 should still work as usual (testing appreciated).
210 should still work as usual (testing appreciated).
198
211
199 2006-08-09 Fernando Perez <Fernando.Perez@colorado.edu>
212 2006-08-09 Fernando Perez <Fernando.Perez@colorado.edu>
200
213
201 * IPython/OInspect.py: monkeypatch inspect from the stdlib if
214 * IPython/OInspect.py: monkeypatch inspect from the stdlib if
202 running under python 2.3 with code from 2.4 to fix a bug with
215 running under python 2.3 with code from 2.4 to fix a bug with
203 help(). Reported by the Debian maintainers, Norbert Tretkowski
216 help(). Reported by the Debian maintainers, Norbert Tretkowski
204 <norbert-AT-tretkowski.de> and Alexandre Fayolle
217 <norbert-AT-tretkowski.de> and Alexandre Fayolle
205 <afayolle-AT-debian.org>.
218 <afayolle-AT-debian.org>.
206
219
207 2006-08-04 Walter Doerwald <walter@livinglogic.de>
220 2006-08-04 Walter Doerwald <walter@livinglogic.de>
208
221
209 * IPython/Extensions/ibrowse.py: Fixed the help message in the footer
222 * IPython/Extensions/ibrowse.py: Fixed the help message in the footer
210 (which was displaying "quit" twice).
223 (which was displaying "quit" twice).
211
224
212 2006-07-28 Walter Doerwald <walter@livinglogic.de>
225 2006-07-28 Walter Doerwald <walter@livinglogic.de>
213
226
214 * IPython/Extensions/ipipe.py: Fix isort.__iter__() (was still using
227 * IPython/Extensions/ipipe.py: Fix isort.__iter__() (was still using
215 the mode argument).
228 the mode argument).
216
229
217 2006-07-27 Walter Doerwald <walter@livinglogic.de>
230 2006-07-27 Walter Doerwald <walter@livinglogic.de>
218
231
219 * IPython/Extensions/ipipe.py: Fix getglobals() if we're
232 * IPython/Extensions/ipipe.py: Fix getglobals() if we're
220 not running under IPython.
233 not running under IPython.
221
234
222 * IPython/Extensions/ipipe.py: Rename XAttr to AttributeDetail
235 * IPython/Extensions/ipipe.py: Rename XAttr to AttributeDetail
223 and make it iterable (iterating over the attribute itself). Add two new
236 and make it iterable (iterating over the attribute itself). Add two new
224 magic strings for __xattrs__(): If the string starts with "-", the attribute
237 magic strings for __xattrs__(): If the string starts with "-", the attribute
225 will not be displayed in ibrowse's detail view (but it can still be
238 will not be displayed in ibrowse's detail view (but it can still be
226 iterated over). This makes it possible to add attributes that are large
239 iterated over). This makes it possible to add attributes that are large
227 lists or generator methods to the detail view. Replace magic attribute names
240 lists or generator methods to the detail view. Replace magic attribute names
228 and _attrname() and _getattr() with "descriptors": For each type of magic
241 and _attrname() and _getattr() with "descriptors": For each type of magic
229 attribute name there's a subclass of Descriptor: None -> SelfDescriptor();
242 attribute name there's a subclass of Descriptor: None -> SelfDescriptor();
230 "foo" -> AttributeDescriptor("foo"); "foo()" -> MethodDescriptor("foo");
243 "foo" -> AttributeDescriptor("foo"); "foo()" -> MethodDescriptor("foo");
231 "-foo" -> IterAttributeDescriptor("foo"); "-foo()" -> IterMethodDescriptor("foo");
244 "-foo" -> IterAttributeDescriptor("foo"); "-foo()" -> IterMethodDescriptor("foo");
232 foo() -> FunctionDescriptor(foo). Magic strings returned from __xattrs__()
245 foo() -> FunctionDescriptor(foo). Magic strings returned from __xattrs__()
233 are still supported.
246 are still supported.
234
247
235 * IPython/Extensions/ibrowse.py: If fetching the next row from the input
248 * IPython/Extensions/ibrowse.py: If fetching the next row from the input
236 fails in ibrowse.fetch(), the exception object is added as the last item
249 fails in ibrowse.fetch(), the exception object is added as the last item
237 and item fetching is canceled. This prevents ibrowse from aborting if e.g.
250 and item fetching is canceled. This prevents ibrowse from aborting if e.g.
238 a generator throws an exception midway through execution.
251 a generator throws an exception midway through execution.
239
252
240 * IPython/Extensions/ipipe.py: Turn ifile's properties mimetype and
253 * IPython/Extensions/ipipe.py: Turn ifile's properties mimetype and
241 encoding into methods.
254 encoding into methods.
242
255
243 2006-07-26 Ville Vainio <vivainio@gmail.com>
256 2006-07-26 Ville Vainio <vivainio@gmail.com>
244
257
245 * iplib.py: history now stores multiline input as single
258 * iplib.py: history now stores multiline input as single
246 history entries. Patch by Jorgen Cederlof.
259 history entries. Patch by Jorgen Cederlof.
247
260
248 2006-07-18 Walter Doerwald <walter@livinglogic.de>
261 2006-07-18 Walter Doerwald <walter@livinglogic.de>
249
262
250 * IPython/Extensions/ibrowse.py: Make cursor visible over
263 * IPython/Extensions/ibrowse.py: Make cursor visible over
251 non existing attributes.
264 non existing attributes.
252
265
253 2006-07-14 Walter Doerwald <walter@livinglogic.de>
266 2006-07-14 Walter Doerwald <walter@livinglogic.de>
254
267
255 * IPython/Extensions/ipipe.py (ix): Use os.popen4() so that the
268 * IPython/Extensions/ipipe.py (ix): Use os.popen4() so that the
256 error output of the running command doesn't mess up the screen.
269 error output of the running command doesn't mess up the screen.
257
270
258 2006-07-13 Walter Doerwald <walter@livinglogic.de>
271 2006-07-13 Walter Doerwald <walter@livinglogic.de>
259
272
260 * IPython/Extensions/ipipe.py (isort): Make isort usable without
273 * IPython/Extensions/ipipe.py (isort): Make isort usable without
261 argument. This sorts the items themselves.
274 argument. This sorts the items themselves.
262
275
263 2006-07-12 Walter Doerwald <walter@livinglogic.de>
276 2006-07-12 Walter Doerwald <walter@livinglogic.de>
264
277
265 * IPython/Extensions/ipipe.py (eval, ifilter, isort, ieval):
278 * IPython/Extensions/ipipe.py (eval, ifilter, isort, ieval):
266 Compile expression strings into code objects. This should speed
279 Compile expression strings into code objects. This should speed
267 up ifilter and friends somewhat.
280 up ifilter and friends somewhat.
268
281
269 2006-07-08 Ville Vainio <vivainio@gmail.com>
282 2006-07-08 Ville Vainio <vivainio@gmail.com>
270
283
271 * Magic.py: %cpaste now strips > from the beginning of lines
284 * Magic.py: %cpaste now strips > from the beginning of lines
272 to ease pasting quoted code from emails. Contributed by
285 to ease pasting quoted code from emails. Contributed by
273 Stefan van der Walt.
286 Stefan van der Walt.
274
287
275 2006-06-29 Ville Vainio <vivainio@gmail.com>
288 2006-06-29 Ville Vainio <vivainio@gmail.com>
276
289
277 * ipmaker.py, Shell.py: qt4agg matplotlib backend support for pylab
290 * ipmaker.py, Shell.py: qt4agg matplotlib backend support for pylab
278 mode, patch contributed by Darren Dale. NEEDS TESTING!
291 mode, patch contributed by Darren Dale. NEEDS TESTING!
279
292
280 2006-06-28 Walter Doerwald <walter@livinglogic.de>
293 2006-06-28 Walter Doerwald <walter@livinglogic.de>
281
294
282 * IPython/Extensions/ibrowse.py: Give the ibrowse cursor row
295 * IPython/Extensions/ibrowse.py: Give the ibrowse cursor row
283 a blue background. Fix fetching new display rows when the browser
296 a blue background. Fix fetching new display rows when the browser
284 scrolls more than a screenful (e.g. by using the goto command).
297 scrolls more than a screenful (e.g. by using the goto command).
285
298
286 2006-06-27 Ville Vainio <vivainio@gmail.com>
299 2006-06-27 Ville Vainio <vivainio@gmail.com>
287
300
288 * Magic.py (_inspect, _ofind) Apply David Huard's
301 * Magic.py (_inspect, _ofind) Apply David Huard's
289 patch for displaying the correct docstring for 'property'
302 patch for displaying the correct docstring for 'property'
290 attributes.
303 attributes.
291
304
292 2006-06-23 Walter Doerwald <walter@livinglogic.de>
305 2006-06-23 Walter Doerwald <walter@livinglogic.de>
293
306
294 * IPython/Extensions/ibrowse.py: Put the documentation of the keyboard
307 * IPython/Extensions/ibrowse.py: Put the documentation of the keyboard
295 commands into the methods implementing them.
308 commands into the methods implementing them.
296
309
297 2006-06-22 Fernando Perez <Fernando.Perez@colorado.edu>
310 2006-06-22 Fernando Perez <Fernando.Perez@colorado.edu>
298
311
299 * ipython.el (ipython-indentation-hook): cleanup patch, submitted
312 * ipython.el (ipython-indentation-hook): cleanup patch, submitted
300 by Kov Chai <tchaikov-AT-gmail.com>. He notes that the original
313 by Kov Chai <tchaikov-AT-gmail.com>. He notes that the original
301 autoindent support was authored by Jin Liu.
314 autoindent support was authored by Jin Liu.
302
315
303 2006-06-22 Walter Doerwald <walter@livinglogic.de>
316 2006-06-22 Walter Doerwald <walter@livinglogic.de>
304
317
305 * IPython/Extensions/ibrowse.py: Replace the plain dictionaries used
318 * IPython/Extensions/ibrowse.py: Replace the plain dictionaries used
306 for keymaps with a custom class that simplifies handling.
319 for keymaps with a custom class that simplifies handling.
307
320
308 2006-06-19 Walter Doerwald <walter@livinglogic.de>
321 2006-06-19 Walter Doerwald <walter@livinglogic.de>
309
322
310 * IPython/Extensions/ibrowse.py: ibrowse now properly handles terminal
323 * IPython/Extensions/ibrowse.py: ibrowse now properly handles terminal
311 resizing. This requires Python 2.5 to work.
324 resizing. This requires Python 2.5 to work.
312
325
313 2006-06-16 Walter Doerwald <walter@livinglogic.de>
326 2006-06-16 Walter Doerwald <walter@livinglogic.de>
314
327
315 * IPython/Extensions/ibrowse.py: Add two new commands to
328 * IPython/Extensions/ibrowse.py: Add two new commands to
316 ibrowse: "hideattr" (mapped to "h") hides the attribute under
329 ibrowse: "hideattr" (mapped to "h") hides the attribute under
317 the cursor. "unhiderattrs" (mapped to "H") reveals all hidden
330 the cursor. "unhiderattrs" (mapped to "H") reveals all hidden
318 attributes again. Remapped the help command to "?". Display
331 attributes again. Remapped the help command to "?". Display
319 keycodes in the range 0x01-0x1F as CTRL-xx. Add CTRL-a and CTRL-e
332 keycodes in the range 0x01-0x1F as CTRL-xx. Add CTRL-a and CTRL-e
320 as keys for the "home" and "end" commands. Add three new commands
333 as keys for the "home" and "end" commands. Add three new commands
321 to the input mode for "find" and friends: "delend" (CTRL-K)
334 to the input mode for "find" and friends: "delend" (CTRL-K)
322 deletes to the end of line. "incsearchup" searches upwards in the
335 deletes to the end of line. "incsearchup" searches upwards in the
323 command history for an input that starts with the text before the cursor.
336 command history for an input that starts with the text before the cursor.
324 "incsearchdown" does the same downwards. Removed a bogus mapping of
337 "incsearchdown" does the same downwards. Removed a bogus mapping of
325 the x key to "delete".
338 the x key to "delete".
326
339
327 2006-06-15 Ville Vainio <vivainio@gmail.com>
340 2006-06-15 Ville Vainio <vivainio@gmail.com>
328
341
329 * iplib.py, hooks.py: Added new generate_prompt hook that can be
342 * iplib.py, hooks.py: Added new generate_prompt hook that can be
330 used to create prompts dynamically, instead of the "old" way of
343 used to create prompts dynamically, instead of the "old" way of
331 assigning "magic" strings to prompt_in1 and prompt_in2. The old
344 assigning "magic" strings to prompt_in1 and prompt_in2. The old
332 way still works (it's invoked by the default hook), of course.
345 way still works (it's invoked by the default hook), of course.
333
346
334 * Prompts.py: added generate_output_prompt hook for altering output
347 * Prompts.py: added generate_output_prompt hook for altering output
335 prompt
348 prompt
336
349
337 * Release.py: Changed version string to 0.7.3.svn.
350 * Release.py: Changed version string to 0.7.3.svn.
338
351
339 2006-06-15 Walter Doerwald <walter@livinglogic.de>
352 2006-06-15 Walter Doerwald <walter@livinglogic.de>
340
353
341 * IPython/Extensions/ibrowse.py: Change _BrowserLevel.moveto() so that
354 * IPython/Extensions/ibrowse.py: Change _BrowserLevel.moveto() so that
342 the call to fetch() always tries to fetch enough data for at least one
355 the call to fetch() always tries to fetch enough data for at least one
343 full screen. This makes it possible to simply call moveto(0,0,True) in
356 full screen. This makes it possible to simply call moveto(0,0,True) in
344 the constructor. Fix typos and removed the obsolete goto attribute.
357 the constructor. Fix typos and removed the obsolete goto attribute.
345
358
346 2006-06-12 Ville Vainio <vivainio@gmail.com>
359 2006-06-12 Ville Vainio <vivainio@gmail.com>
347
360
348 * ipy_profile_sh.py: applied Krisha Mohan Gundu's patch for
361 * ipy_profile_sh.py: applied Krisha Mohan Gundu's patch for
349 allowing $variable interpolation within multiline statements,
362 allowing $variable interpolation within multiline statements,
350 though so far only with "sh" profile for a testing period.
363 though so far only with "sh" profile for a testing period.
351 The patch also enables splitting long commands with \ but it
364 The patch also enables splitting long commands with \ but it
352 doesn't work properly yet.
365 doesn't work properly yet.
353
366
354 2006-06-12 Walter Doerwald <walter@livinglogic.de>
367 2006-06-12 Walter Doerwald <walter@livinglogic.de>
355
368
356 * IPython/Extensions/ibrowse.py (_dodisplay): Display the length of the
369 * IPython/Extensions/ibrowse.py (_dodisplay): Display the length of the
357 input history and the position of the cursor in the input history for
370 input history and the position of the cursor in the input history for
358 the find, findbackwards and goto command.
371 the find, findbackwards and goto command.
359
372
360 2006-06-10 Walter Doerwald <walter@livinglogic.de>
373 2006-06-10 Walter Doerwald <walter@livinglogic.de>
361
374
362 * IPython/Extensions/ibrowse.py: Add a class _CommandInput that
375 * IPython/Extensions/ibrowse.py: Add a class _CommandInput that
363 implements the basic functionality of browser commands that require
376 implements the basic functionality of browser commands that require
364 input. Reimplement the goto, find and findbackwards commands as
377 input. Reimplement the goto, find and findbackwards commands as
365 subclasses of _CommandInput. Add an input history and keymaps to those
378 subclasses of _CommandInput. Add an input history and keymaps to those
366 commands. Add "\r" as a keyboard shortcut for the enterdefault and
379 commands. Add "\r" as a keyboard shortcut for the enterdefault and
367 execute commands.
380 execute commands.
368
381
369 2006-06-07 Ville Vainio <vivainio@gmail.com>
382 2006-06-07 Ville Vainio <vivainio@gmail.com>
370
383
371 * iplib.py: ipython mybatch.ipy exits ipython immediately after
384 * iplib.py: ipython mybatch.ipy exits ipython immediately after
372 running the batch files instead of leaving the session open.
385 running the batch files instead of leaving the session open.
373
386
374 2006-06-07 Fernando Perez <Fernando.Perez@colorado.edu>
387 2006-06-07 Fernando Perez <Fernando.Perez@colorado.edu>
375
388
376 * IPython/iplib.py (InteractiveShell.__init__): update BSD fix, as
389 * IPython/iplib.py (InteractiveShell.__init__): update BSD fix, as
377 the original fix was incomplete. Patch submitted by W. Maier.
390 the original fix was incomplete. Patch submitted by W. Maier.
378
391
379 2006-06-07 Ville Vainio <vivainio@gmail.com>
392 2006-06-07 Ville Vainio <vivainio@gmail.com>
380
393
381 * iplib.py,Magic.py, ipmaker.py (magic_rehashx):
394 * iplib.py,Magic.py, ipmaker.py (magic_rehashx):
382 Confirmation prompts can be supressed by 'quiet' option.
395 Confirmation prompts can be supressed by 'quiet' option.
383 _ip.options.quiet = 1 means "assume yes for all yes/no queries".
396 _ip.options.quiet = 1 means "assume yes for all yes/no queries".
384
397
385 2006-06-06 *** Released version 0.7.2
398 2006-06-06 *** Released version 0.7.2
386
399
387 2006-06-06 Fernando Perez <Fernando.Perez@colorado.edu>
400 2006-06-06 Fernando Perez <Fernando.Perez@colorado.edu>
388
401
389 * IPython/Release.py (version): Made 0.7.2 final for release.
402 * IPython/Release.py (version): Made 0.7.2 final for release.
390 Repo tagged and release cut.
403 Repo tagged and release cut.
391
404
392 2006-06-05 Ville Vainio <vivainio@gmail.com>
405 2006-06-05 Ville Vainio <vivainio@gmail.com>
393
406
394 * Magic.py (magic_rehashx): Honor no_alias list earlier in
407 * Magic.py (magic_rehashx): Honor no_alias list earlier in
395 %rehashx, to avoid clobbering builtins in ipy_profile_sh.py
408 %rehashx, to avoid clobbering builtins in ipy_profile_sh.py
396
409
397 * upgrade_dir.py: try import 'path' module a bit harder
410 * upgrade_dir.py: try import 'path' module a bit harder
398 (for %upgrade)
411 (for %upgrade)
399
412
400 2006-06-03 Fernando Perez <Fernando.Perez@colorado.edu>
413 2006-06-03 Fernando Perez <Fernando.Perez@colorado.edu>
401
414
402 * IPython/genutils.py (ask_yes_no): treat EOF as a default answer
415 * IPython/genutils.py (ask_yes_no): treat EOF as a default answer
403 instead of looping 20 times.
416 instead of looping 20 times.
404
417
405 * IPython/ipmaker.py (make_IPython): honor -ipythondir flag
418 * IPython/ipmaker.py (make_IPython): honor -ipythondir flag
406 correctly at initialization time. Bug reported by Krishna Mohan
419 correctly at initialization time. Bug reported by Krishna Mohan
407 Gundu <gkmohan-AT-gmail.com> on the user list.
420 Gundu <gkmohan-AT-gmail.com> on the user list.
408
421
409 * IPython/Release.py (version): Mark 0.7.2 version to start
422 * IPython/Release.py (version): Mark 0.7.2 version to start
410 testing for release on 06/06.
423 testing for release on 06/06.
411
424
412 2006-05-31 Fernando Perez <Fernando.Perez@colorado.edu>
425 2006-05-31 Fernando Perez <Fernando.Perez@colorado.edu>
413
426
414 * scripts/irunner: thin script interface so users don't have to
427 * scripts/irunner: thin script interface so users don't have to
415 find the module and call it as an executable, since modules rarely
428 find the module and call it as an executable, since modules rarely
416 live in people's PATH.
429 live in people's PATH.
417
430
418 * IPython/irunner.py (InteractiveRunner.__init__): added
431 * IPython/irunner.py (InteractiveRunner.__init__): added
419 delaybeforesend attribute to control delays with newer versions of
432 delaybeforesend attribute to control delays with newer versions of
420 pexpect. Thanks to detailed help from pexpect's author, Noah
433 pexpect. Thanks to detailed help from pexpect's author, Noah
421 Spurrier <noah-AT-noah.org>. Noted how to use the SAGE runner
434 Spurrier <noah-AT-noah.org>. Noted how to use the SAGE runner
422 correctly (it works in NoColor mode).
435 correctly (it works in NoColor mode).
423
436
424 * IPython/iplib.py (handle_normal): fix nasty crash reported on
437 * IPython/iplib.py (handle_normal): fix nasty crash reported on
425 SAGE list, from improper log() calls.
438 SAGE list, from improper log() calls.
426
439
427 2006-05-31 Ville Vainio <vivainio@gmail.com>
440 2006-05-31 Ville Vainio <vivainio@gmail.com>
428
441
429 * upgrade_dir.py, Magic.py (magic_upgrade): call upgrade_dir
442 * upgrade_dir.py, Magic.py (magic_upgrade): call upgrade_dir
430 with args in parens to work correctly with dirs that have spaces.
443 with args in parens to work correctly with dirs that have spaces.
431
444
432 2006-05-30 Fernando Perez <Fernando.Perez@colorado.edu>
445 2006-05-30 Fernando Perez <Fernando.Perez@colorado.edu>
433
446
434 * IPython/Logger.py (Logger.logstart): add option to log raw input
447 * IPython/Logger.py (Logger.logstart): add option to log raw input
435 instead of the processed one. A -r flag was added to the
448 instead of the processed one. A -r flag was added to the
436 %logstart magic used for controlling logging.
449 %logstart magic used for controlling logging.
437
450
438 2006-05-29 Fernando Perez <Fernando.Perez@colorado.edu>
451 2006-05-29 Fernando Perez <Fernando.Perez@colorado.edu>
439
452
440 * IPython/iplib.py (InteractiveShell.__init__): add check for the
453 * IPython/iplib.py (InteractiveShell.__init__): add check for the
441 *BSDs to omit --color from all 'ls' aliases, since *BSD ls doesn't
454 *BSDs to omit --color from all 'ls' aliases, since *BSD ls doesn't
442 recognize the option. After a bug report by Will Maier. This
455 recognize the option. After a bug report by Will Maier. This
443 closes #64 (will do it after confirmation from W. Maier).
456 closes #64 (will do it after confirmation from W. Maier).
444
457
445 * IPython/irunner.py: New module to run scripts as if manually
458 * IPython/irunner.py: New module to run scripts as if manually
446 typed into an interactive environment, based on pexpect. After a
459 typed into an interactive environment, based on pexpect. After a
447 submission by Ken Schutte <kschutte-AT-csail.mit.edu> on the
460 submission by Ken Schutte <kschutte-AT-csail.mit.edu> on the
448 ipython-user list. Simple unittests in the tests/ directory.
461 ipython-user list. Simple unittests in the tests/ directory.
449
462
450 * tools/release: add Will Maier, OpenBSD port maintainer, to
463 * tools/release: add Will Maier, OpenBSD port maintainer, to
451 recepients list. We are now officially part of the OpenBSD ports:
464 recepients list. We are now officially part of the OpenBSD ports:
452 http://www.openbsd.org/ports.html ! Many thanks to Will for the
465 http://www.openbsd.org/ports.html ! Many thanks to Will for the
453 work.
466 work.
454
467
455 2006-05-26 Fernando Perez <Fernando.Perez@colorado.edu>
468 2006-05-26 Fernando Perez <Fernando.Perez@colorado.edu>
456
469
457 * IPython/ipmaker.py (make_IPython): modify sys.argv fix (below)
470 * IPython/ipmaker.py (make_IPython): modify sys.argv fix (below)
458 so that it doesn't break tkinter apps.
471 so that it doesn't break tkinter apps.
459
472
460 * IPython/iplib.py (_prefilter): fix bug where aliases would
473 * IPython/iplib.py (_prefilter): fix bug where aliases would
461 shadow variables when autocall was fully off. Reported by SAGE
474 shadow variables when autocall was fully off. Reported by SAGE
462 author William Stein.
475 author William Stein.
463
476
464 * IPython/OInspect.py (Inspector.__init__): add a flag to control
477 * IPython/OInspect.py (Inspector.__init__): add a flag to control
465 at what detail level strings are computed when foo? is requested.
478 at what detail level strings are computed when foo? is requested.
466 This allows users to ask for example that the string form of an
479 This allows users to ask for example that the string form of an
467 object is only computed when foo?? is called, or even never, by
480 object is only computed when foo?? is called, or even never, by
468 setting the object_info_string_level >= 2 in the configuration
481 setting the object_info_string_level >= 2 in the configuration
469 file. This new option has been added and documented. After a
482 file. This new option has been added and documented. After a
470 request by SAGE to be able to control the printing of very large
483 request by SAGE to be able to control the printing of very large
471 objects more easily.
484 objects more easily.
472
485
473 2006-05-25 Fernando Perez <Fernando.Perez@colorado.edu>
486 2006-05-25 Fernando Perez <Fernando.Perez@colorado.edu>
474
487
475 * IPython/ipmaker.py (make_IPython): remove the ipython call path
488 * IPython/ipmaker.py (make_IPython): remove the ipython call path
476 from sys.argv, to be 100% consistent with how Python itself works
489 from sys.argv, to be 100% consistent with how Python itself works
477 (as seen for example with python -i file.py). After a bug report
490 (as seen for example with python -i file.py). After a bug report
478 by Jeffrey Collins.
491 by Jeffrey Collins.
479
492
480 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix
493 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix
481 nasty bug which was preventing custom namespaces with -pylab,
494 nasty bug which was preventing custom namespaces with -pylab,
482 reported by M. Foord. Minor cleanup, remove old matplotlib.matlab
495 reported by M. Foord. Minor cleanup, remove old matplotlib.matlab
483 compatibility (long gone from mpl).
496 compatibility (long gone from mpl).
484
497
485 * IPython/ipapi.py (make_session): name change: create->make. We
498 * IPython/ipapi.py (make_session): name change: create->make. We
486 use make in other places (ipmaker,...), it's shorter and easier to
499 use make in other places (ipmaker,...), it's shorter and easier to
487 type and say, etc. I'm trying to clean things before 0.7.2 so
500 type and say, etc. I'm trying to clean things before 0.7.2 so
488 that I can keep things stable wrt to ipapi in the chainsaw branch.
501 that I can keep things stable wrt to ipapi in the chainsaw branch.
489
502
490 * ipython.el: fix the py-pdbtrack-input-prompt variable so that
503 * ipython.el: fix the py-pdbtrack-input-prompt variable so that
491 python-mode recognizes our debugger mode. Add support for
504 python-mode recognizes our debugger mode. Add support for
492 autoindent inside (X)emacs. After a patch sent in by Jin Liu
505 autoindent inside (X)emacs. After a patch sent in by Jin Liu
493 <m.liu.jin-AT-gmail.com> originally written by
506 <m.liu.jin-AT-gmail.com> originally written by
494 doxgen-AT-newsmth.net (with minor modifications for xemacs
507 doxgen-AT-newsmth.net (with minor modifications for xemacs
495 compatibility)
508 compatibility)
496
509
497 * IPython/Debugger.py (Pdb.format_stack_entry): fix formatting of
510 * IPython/Debugger.py (Pdb.format_stack_entry): fix formatting of
498 tracebacks when walking the stack so that the stack tracking system
511 tracebacks when walking the stack so that the stack tracking system
499 in emacs' python-mode can identify the frames correctly.
512 in emacs' python-mode can identify the frames correctly.
500
513
501 * IPython/ipmaker.py (make_IPython): make the internal (and
514 * IPython/ipmaker.py (make_IPython): make the internal (and
502 default config) autoedit_syntax value false by default. Too many
515 default config) autoedit_syntax value false by default. Too many
503 users have complained to me (both on and off-list) about problems
516 users have complained to me (both on and off-list) about problems
504 with this option being on by default, so I'm making it default to
517 with this option being on by default, so I'm making it default to
505 off. It can still be enabled by anyone via the usual mechanisms.
518 off. It can still be enabled by anyone via the usual mechanisms.
506
519
507 * IPython/completer.py (Completer.attr_matches): add support for
520 * IPython/completer.py (Completer.attr_matches): add support for
508 PyCrust-style _getAttributeNames magic method. Patch contributed
521 PyCrust-style _getAttributeNames magic method. Patch contributed
509 by <mscott-AT-goldenspud.com>. Closes #50.
522 by <mscott-AT-goldenspud.com>. Closes #50.
510
523
511 * IPython/iplib.py (InteractiveShell.__init__): remove the
524 * IPython/iplib.py (InteractiveShell.__init__): remove the
512 deletion of exit/quit from __builtin__, which can break
525 deletion of exit/quit from __builtin__, which can break
513 third-party tools like the Zope debugging console. The
526 third-party tools like the Zope debugging console. The
514 %exit/%quit magics remain. In general, it's probably a good idea
527 %exit/%quit magics remain. In general, it's probably a good idea
515 not to delete anything from __builtin__, since we never know what
528 not to delete anything from __builtin__, since we never know what
516 that will break. In any case, python now (for 2.5) will support
529 that will break. In any case, python now (for 2.5) will support
517 'real' exit/quit, so this issue is moot. Closes #55.
530 'real' exit/quit, so this issue is moot. Closes #55.
518
531
519 * IPython/genutils.py (with_obj): rename the 'with' function to
532 * IPython/genutils.py (with_obj): rename the 'with' function to
520 'withobj' to avoid incompatibilities with Python 2.5, where 'with'
533 'withobj' to avoid incompatibilities with Python 2.5, where 'with'
521 becomes a language keyword. Closes #53.
534 becomes a language keyword. Closes #53.
522
535
523 * IPython/FakeModule.py (FakeModule.__init__): add a proper
536 * IPython/FakeModule.py (FakeModule.__init__): add a proper
524 __file__ attribute to this so it fools more things into thinking
537 __file__ attribute to this so it fools more things into thinking
525 it is a real module. Closes #59.
538 it is a real module. Closes #59.
526
539
527 * IPython/Magic.py (magic_edit): add -n option to open the editor
540 * IPython/Magic.py (magic_edit): add -n option to open the editor
528 at a specific line number. After a patch by Stefan van der Walt.
541 at a specific line number. After a patch by Stefan van der Walt.
529
542
530 2006-05-23 Fernando Perez <Fernando.Perez@colorado.edu>
543 2006-05-23 Fernando Perez <Fernando.Perez@colorado.edu>
531
544
532 * IPython/iplib.py (edit_syntax_error): fix crash when for some
545 * IPython/iplib.py (edit_syntax_error): fix crash when for some
533 reason the file could not be opened. After automatic crash
546 reason the file could not be opened. After automatic crash
534 reports sent by James Graham <jgraham-AT-ast.cam.ac.uk> and
547 reports sent by James Graham <jgraham-AT-ast.cam.ac.uk> and
535 Charles Dolan <charlespatrickdolan-AT-yahoo.com>.
548 Charles Dolan <charlespatrickdolan-AT-yahoo.com>.
536 (_should_recompile): Don't fire editor if using %bg, since there
549 (_should_recompile): Don't fire editor if using %bg, since there
537 is no file in the first place. From the same report as above.
550 is no file in the first place. From the same report as above.
538 (raw_input): protect against faulty third-party prefilters. After
551 (raw_input): protect against faulty third-party prefilters. After
539 an automatic crash report sent by Dirk Laurie <dirk-AT-sun.ac.za>
552 an automatic crash report sent by Dirk Laurie <dirk-AT-sun.ac.za>
540 while running under SAGE.
553 while running under SAGE.
541
554
542 2006-05-23 Ville Vainio <vivainio@gmail.com>
555 2006-05-23 Ville Vainio <vivainio@gmail.com>
543
556
544 * ipapi.py: Stripped down ip.to_user_ns() to work only as
557 * ipapi.py: Stripped down ip.to_user_ns() to work only as
545 ip.to_user_ns("x1 y1"), which exposes vars x1 and y1. ipapi.get()
558 ip.to_user_ns("x1 y1"), which exposes vars x1 and y1. ipapi.get()
546 now returns None (again), unless dummy is specifically allowed by
559 now returns None (again), unless dummy is specifically allowed by
547 ipapi.get(allow_dummy=True).
560 ipapi.get(allow_dummy=True).
548
561
549 2006-05-18 Fernando Perez <Fernando.Perez@colorado.edu>
562 2006-05-18 Fernando Perez <Fernando.Perez@colorado.edu>
550
563
551 * IPython: remove all 2.2-compatibility objects and hacks from
564 * IPython: remove all 2.2-compatibility objects and hacks from
552 everywhere, since we only support 2.3 at this point. Docs
565 everywhere, since we only support 2.3 at this point. Docs
553 updated.
566 updated.
554
567
555 * IPython/ipapi.py (IPApi.__init__): Cleanup of all getters.
568 * IPython/ipapi.py (IPApi.__init__): Cleanup of all getters.
556 Anything requiring extra validation can be turned into a Python
569 Anything requiring extra validation can be turned into a Python
557 property in the future. I used a property for the db one b/c
570 property in the future. I used a property for the db one b/c
558 there was a nasty circularity problem with the initialization
571 there was a nasty circularity problem with the initialization
559 order, which right now I don't have time to clean up.
572 order, which right now I don't have time to clean up.
560
573
561 * IPython/Shell.py (MTInteractiveShell.runcode): Fix, I think,
574 * IPython/Shell.py (MTInteractiveShell.runcode): Fix, I think,
562 another locking bug reported by Jorgen. I'm not 100% sure though,
575 another locking bug reported by Jorgen. I'm not 100% sure though,
563 so more testing is needed...
576 so more testing is needed...
564
577
565 2006-05-17 Fernando Perez <Fernando.Perez@colorado.edu>
578 2006-05-17 Fernando Perez <Fernando.Perez@colorado.edu>
566
579
567 * IPython/ipapi.py (IPApi.to_user_ns): New function to inject
580 * IPython/ipapi.py (IPApi.to_user_ns): New function to inject
568 local variables from any routine in user code (typically executed
581 local variables from any routine in user code (typically executed
569 with %run) directly into the interactive namespace. Very useful
582 with %run) directly into the interactive namespace. Very useful
570 when doing complex debugging.
583 when doing complex debugging.
571 (IPythonNotRunning): Changed the default None object to a dummy
584 (IPythonNotRunning): Changed the default None object to a dummy
572 whose attributes can be queried as well as called without
585 whose attributes can be queried as well as called without
573 exploding, to ease writing code which works transparently both in
586 exploding, to ease writing code which works transparently both in
574 and out of ipython and uses some of this API.
587 and out of ipython and uses some of this API.
575
588
576 2006-05-16 Fernando Perez <Fernando.Perez@colorado.edu>
589 2006-05-16 Fernando Perez <Fernando.Perez@colorado.edu>
577
590
578 * IPython/hooks.py (result_display): Fix the fact that our display
591 * IPython/hooks.py (result_display): Fix the fact that our display
579 hook was using str() instead of repr(), as the default python
592 hook was using str() instead of repr(), as the default python
580 console does. This had gone unnoticed b/c it only happened if
593 console does. This had gone unnoticed b/c it only happened if
581 %Pprint was off, but the inconsistency was there.
594 %Pprint was off, but the inconsistency was there.
582
595
583 2006-05-15 Ville Vainio <vivainio@gmail.com>
596 2006-05-15 Ville Vainio <vivainio@gmail.com>
584
597
585 * Oinspect.py: Only show docstring for nonexisting/binary files
598 * Oinspect.py: Only show docstring for nonexisting/binary files
586 when doing object??, closing ticket #62
599 when doing object??, closing ticket #62
587
600
588 2006-05-13 Fernando Perez <Fernando.Perez@colorado.edu>
601 2006-05-13 Fernando Perez <Fernando.Perez@colorado.edu>
589
602
590 * IPython/Shell.py (MTInteractiveShell.runsource): Fix threading
603 * IPython/Shell.py (MTInteractiveShell.runsource): Fix threading
591 bug, closes http://www.scipy.net/roundup/ipython/issue55. A lock
604 bug, closes http://www.scipy.net/roundup/ipython/issue55. A lock
592 was being released in a routine which hadn't checked if it had
605 was being released in a routine which hadn't checked if it had
593 been the one to acquire it.
606 been the one to acquire it.
594
607
595 2006-05-07 Fernando Perez <Fernando.Perez@colorado.edu>
608 2006-05-07 Fernando Perez <Fernando.Perez@colorado.edu>
596
609
597 * IPython/Release.py (version): put out 0.7.2.rc1 for testing.
610 * IPython/Release.py (version): put out 0.7.2.rc1 for testing.
598
611
599 2006-04-11 Ville Vainio <vivainio@gmail.com>
612 2006-04-11 Ville Vainio <vivainio@gmail.com>
600
613
601 * iplib.py, ipmaker.py: .ipy extension now means "ipython batch file"
614 * iplib.py, ipmaker.py: .ipy extension now means "ipython batch file"
602 in command line. E.g. "ipython test.ipy" runs test.ipy with ipython
615 in command line. E.g. "ipython test.ipy" runs test.ipy with ipython
603 prefilters, allowing stuff like magics and aliases in the file.
616 prefilters, allowing stuff like magics and aliases in the file.
604
617
605 * Prompts.py, Extensions/clearcmd.py, ipy_system_conf.py: %clear magic
618 * Prompts.py, Extensions/clearcmd.py, ipy_system_conf.py: %clear magic
606 added. Supported now are "%clear in" and "%clear out" (clear input and
619 added. Supported now are "%clear in" and "%clear out" (clear input and
607 output history, respectively). Also fixed CachedOutput.flush to
620 output history, respectively). Also fixed CachedOutput.flush to
608 properly flush the output cache.
621 properly flush the output cache.
609
622
610 * Extensions/pspersistence.py: Fix %store to avoid "%store obj.attr"
623 * Extensions/pspersistence.py: Fix %store to avoid "%store obj.attr"
611 half-success (and fail explicitly).
624 half-success (and fail explicitly).
612
625
613 2006-03-28 Ville Vainio <vivainio@gmail.com>
626 2006-03-28 Ville Vainio <vivainio@gmail.com>
614
627
615 * iplib.py: Fix quoting of aliases so that only argless ones
628 * iplib.py: Fix quoting of aliases so that only argless ones
616 are quoted
629 are quoted
617
630
618 2006-03-28 Ville Vainio <vivainio@gmail.com>
631 2006-03-28 Ville Vainio <vivainio@gmail.com>
619
632
620 * iplib.py: Quote aliases with spaces in the name.
633 * iplib.py: Quote aliases with spaces in the name.
621 "c:\program files\blah\bin" is now legal alias target.
634 "c:\program files\blah\bin" is now legal alias target.
622
635
623 * ext_rehashdir.py: Space no longer allowed as arg
636 * ext_rehashdir.py: Space no longer allowed as arg
624 separator, since space is legal in path names.
637 separator, since space is legal in path names.
625
638
626 2006-03-16 Ville Vainio <vivainio@gmail.com>
639 2006-03-16 Ville Vainio <vivainio@gmail.com>
627
640
628 * upgrade_dir.py: Take path.py from Extensions, correcting
641 * upgrade_dir.py: Take path.py from Extensions, correcting
629 %upgrade magic
642 %upgrade magic
630
643
631 * ipmaker.py: Suggest using %upgrade if ipy_user_conf.py isn't found.
644 * ipmaker.py: Suggest using %upgrade if ipy_user_conf.py isn't found.
632
645
633 * hooks.py: Only enclose editor binary in quotes if legal and
646 * hooks.py: Only enclose editor binary in quotes if legal and
634 necessary (space in the name, and is an existing file). Fixes a bug
647 necessary (space in the name, and is an existing file). Fixes a bug
635 reported by Zachary Pincus.
648 reported by Zachary Pincus.
636
649
637 2006-03-13 Fernando Perez <Fernando.Perez@colorado.edu>
650 2006-03-13 Fernando Perez <Fernando.Perez@colorado.edu>
638
651
639 * Manual: thanks to a tip on proper color handling for Emacs, by
652 * Manual: thanks to a tip on proper color handling for Emacs, by
640 Eric J Haywiser <ejh1-AT-MIT.EDU>.
653 Eric J Haywiser <ejh1-AT-MIT.EDU>.
641
654
642 * ipython.el: close http://www.scipy.net/roundup/ipython/issue57
655 * ipython.el: close http://www.scipy.net/roundup/ipython/issue57
643 by applying the provided patch. Thanks to Liu Jin
656 by applying the provided patch. Thanks to Liu Jin
644 <m.liu.jin-AT-gmail.com> for the contribution. No problems under
657 <m.liu.jin-AT-gmail.com> for the contribution. No problems under
645 XEmacs/Linux, I'm trusting the submitter that it actually helps
658 XEmacs/Linux, I'm trusting the submitter that it actually helps
646 under win32/GNU Emacs. Will revisit if any problems are reported.
659 under win32/GNU Emacs. Will revisit if any problems are reported.
647
660
648 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
661 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
649
662
650 * IPython/Gnuplot2.py (_FileClass): update for current Gnuplot.py
663 * IPython/Gnuplot2.py (_FileClass): update for current Gnuplot.py
651 from SVN, thanks to a patch by Ryan Woodard <rywo@bas.ac.uk>.
664 from SVN, thanks to a patch by Ryan Woodard <rywo@bas.ac.uk>.
652
665
653 2006-03-12 Ville Vainio <vivainio@gmail.com>
666 2006-03-12 Ville Vainio <vivainio@gmail.com>
654
667
655 * Magic.py (magic_timeit): Added %timeit magic, contributed by
668 * Magic.py (magic_timeit): Added %timeit magic, contributed by
656 Torsten Marek.
669 Torsten Marek.
657
670
658 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
671 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
659
672
660 * IPython/Magic.py (magic_macro): fix so that the n1-n2 syntax for
673 * IPython/Magic.py (magic_macro): fix so that the n1-n2 syntax for
661 line ranges works again.
674 line ranges works again.
662
675
663 2006-03-11 Fernando Perez <Fernando.Perez@colorado.edu>
676 2006-03-11 Fernando Perez <Fernando.Perez@colorado.edu>
664
677
665 * IPython/iplib.py (showtraceback): add back sys.last_traceback
678 * IPython/iplib.py (showtraceback): add back sys.last_traceback
666 and friends, after a discussion with Zach Pincus on ipython-user.
679 and friends, after a discussion with Zach Pincus on ipython-user.
667 I'm not 100% sure, but after thinking about it quite a bit, it may
680 I'm not 100% sure, but after thinking about it quite a bit, it may
668 be OK. Testing with the multithreaded shells didn't reveal any
681 be OK. Testing with the multithreaded shells didn't reveal any
669 problems, but let's keep an eye out.
682 problems, but let's keep an eye out.
670
683
671 In the process, I fixed a few things which were calling
684 In the process, I fixed a few things which were calling
672 self.InteractiveTB() directly (like safe_execfile), which is a
685 self.InteractiveTB() directly (like safe_execfile), which is a
673 mistake: ALL exception reporting should be done by calling
686 mistake: ALL exception reporting should be done by calling
674 self.showtraceback(), which handles state and tab-completion and
687 self.showtraceback(), which handles state and tab-completion and
675 more.
688 more.
676
689
677 2006-03-01 Ville Vainio <vivainio@gmail.com>
690 2006-03-01 Ville Vainio <vivainio@gmail.com>
678
691
679 * Extensions/ipipe.py: Added Walter Doerwald's "ipipe" module.
692 * Extensions/ipipe.py: Added Walter Doerwald's "ipipe" module.
680 To use, do "from ipipe import *".
693 To use, do "from ipipe import *".
681
694
682 2006-02-24 Ville Vainio <vivainio@gmail.com>
695 2006-02-24 Ville Vainio <vivainio@gmail.com>
683
696
684 * Magic.py, upgrade_dir.py: %upgrade magic added. Does things more
697 * Magic.py, upgrade_dir.py: %upgrade magic added. Does things more
685 "cleanly" and safely than the older upgrade mechanism.
698 "cleanly" and safely than the older upgrade mechanism.
686
699
687 2006-02-21 Ville Vainio <vivainio@gmail.com>
700 2006-02-21 Ville Vainio <vivainio@gmail.com>
688
701
689 * Magic.py: %save works again.
702 * Magic.py: %save works again.
690
703
691 2006-02-15 Ville Vainio <vivainio@gmail.com>
704 2006-02-15 Ville Vainio <vivainio@gmail.com>
692
705
693 * Magic.py: %Pprint works again
706 * Magic.py: %Pprint works again
694
707
695 * Extensions/ipy_sane_defaults.py: Provide everything provided
708 * Extensions/ipy_sane_defaults.py: Provide everything provided
696 in default ipythonrc, to make it possible to have a completely empty
709 in default ipythonrc, to make it possible to have a completely empty
697 ipythonrc (and thus completely rc-file free configuration)
710 ipythonrc (and thus completely rc-file free configuration)
698
711
699 2006-02-11 Fernando Perez <Fernando.Perez@colorado.edu>
712 2006-02-11 Fernando Perez <Fernando.Perez@colorado.edu>
700
713
701 * IPython/hooks.py (editor): quote the call to the editor command,
714 * IPython/hooks.py (editor): quote the call to the editor command,
702 to allow commands with spaces in them. Problem noted by watching
715 to allow commands with spaces in them. Problem noted by watching
703 Ian Oswald's video about textpad under win32 at
716 Ian Oswald's video about textpad under win32 at
704 http://showmedo.com/videoListPage?listKey=PythonIPythonSeries
717 http://showmedo.com/videoListPage?listKey=PythonIPythonSeries
705
718
706 * IPython/UserConfig/ipythonrc: Replace @ signs with % when
719 * IPython/UserConfig/ipythonrc: Replace @ signs with % when
707 describing magics (we haven't used @ for a loong time).
720 describing magics (we haven't used @ for a loong time).
708
721
709 * IPython/ultraTB.py (VerboseTB.text.text_repr): Added patch
722 * IPython/ultraTB.py (VerboseTB.text.text_repr): Added patch
710 contributed by marienz to close
723 contributed by marienz to close
711 http://www.scipy.net/roundup/ipython/issue53.
724 http://www.scipy.net/roundup/ipython/issue53.
712
725
713 2006-02-10 Ville Vainio <vivainio@gmail.com>
726 2006-02-10 Ville Vainio <vivainio@gmail.com>
714
727
715 * genutils.py: getoutput now works in win32 too
728 * genutils.py: getoutput now works in win32 too
716
729
717 * completer.py: alias and magic completion only invoked
730 * completer.py: alias and magic completion only invoked
718 at the first "item" in the line, to avoid "cd %store"
731 at the first "item" in the line, to avoid "cd %store"
719 nonsense.
732 nonsense.
720
733
721 2006-02-09 Ville Vainio <vivainio@gmail.com>
734 2006-02-09 Ville Vainio <vivainio@gmail.com>
722
735
723 * test/*: Added a unit testing framework (finally).
736 * test/*: Added a unit testing framework (finally).
724 '%run runtests.py' to run test_*.
737 '%run runtests.py' to run test_*.
725
738
726 * ipapi.py: Exposed runlines and set_custom_exc
739 * ipapi.py: Exposed runlines and set_custom_exc
727
740
728 2006-02-07 Ville Vainio <vivainio@gmail.com>
741 2006-02-07 Ville Vainio <vivainio@gmail.com>
729
742
730 * iplib.py: don't split "f 1 2" to "f(1,2)" in autocall,
743 * iplib.py: don't split "f 1 2" to "f(1,2)" in autocall,
731 instead use "f(1 2)" as before.
744 instead use "f(1 2)" as before.
732
745
733 2006-02-05 Fernando Perez <Fernando.Perez@colorado.edu>
746 2006-02-05 Fernando Perez <Fernando.Perez@colorado.edu>
734
747
735 * IPython/demo.py (IPythonDemo): Add new classes to the demo
748 * IPython/demo.py (IPythonDemo): Add new classes to the demo
736 facilities, for demos processed by the IPython input filter
749 facilities, for demos processed by the IPython input filter
737 (IPythonDemo), and for running a script one-line-at-a-time as a
750 (IPythonDemo), and for running a script one-line-at-a-time as a
738 demo, both for pure Python (LineDemo) and for IPython-processed
751 demo, both for pure Python (LineDemo) and for IPython-processed
739 input (IPythonLineDemo). After a request by Dave Kohel, from the
752 input (IPythonLineDemo). After a request by Dave Kohel, from the
740 SAGE team.
753 SAGE team.
741 (Demo.edit): added an edit() method to the demo objects, to edit
754 (Demo.edit): added an edit() method to the demo objects, to edit
742 the in-memory copy of the last executed block.
755 the in-memory copy of the last executed block.
743
756
744 * IPython/Magic.py (magic_edit): add '-r' option for 'raw'
757 * IPython/Magic.py (magic_edit): add '-r' option for 'raw'
745 processing to %edit, %macro and %save. These commands can now be
758 processing to %edit, %macro and %save. These commands can now be
746 invoked on the unprocessed input as it was typed by the user
759 invoked on the unprocessed input as it was typed by the user
747 (without any prefilters applied). After requests by the SAGE team
760 (without any prefilters applied). After requests by the SAGE team
748 at SAGE days 2006: http://modular.ucsd.edu/sage/days1/schedule.html.
761 at SAGE days 2006: http://modular.ucsd.edu/sage/days1/schedule.html.
749
762
750 2006-02-01 Ville Vainio <vivainio@gmail.com>
763 2006-02-01 Ville Vainio <vivainio@gmail.com>
751
764
752 * setup.py, eggsetup.py: easy_install ipython==dev works
765 * setup.py, eggsetup.py: easy_install ipython==dev works
753 correctly now (on Linux)
766 correctly now (on Linux)
754
767
755 * ipy_user_conf,ipmaker: user config changes, removed spurious
768 * ipy_user_conf,ipmaker: user config changes, removed spurious
756 warnings
769 warnings
757
770
758 * iplib: if rc.banner is string, use it as is.
771 * iplib: if rc.banner is string, use it as is.
759
772
760 * Magic: %pycat accepts a string argument and pages it's contents.
773 * Magic: %pycat accepts a string argument and pages it's contents.
761
774
762
775
763 2006-01-30 Ville Vainio <vivainio@gmail.com>
776 2006-01-30 Ville Vainio <vivainio@gmail.com>
764
777
765 * pickleshare,pspersistence,ipapi,Magic: persistence overhaul.
778 * pickleshare,pspersistence,ipapi,Magic: persistence overhaul.
766 Now %store and bookmarks work through PickleShare, meaning that
779 Now %store and bookmarks work through PickleShare, meaning that
767 concurrent access is possible and all ipython sessions see the
780 concurrent access is possible and all ipython sessions see the
768 same database situation all the time, instead of snapshot of
781 same database situation all the time, instead of snapshot of
769 the situation when the session was started. Hence, %bookmark
782 the situation when the session was started. Hence, %bookmark
770 results are immediately accessible from othes sessions. The database
783 results are immediately accessible from othes sessions. The database
771 is also available for use by user extensions. See:
784 is also available for use by user extensions. See:
772 http://www.python.org/pypi/pickleshare
785 http://www.python.org/pypi/pickleshare
773
786
774 * hooks.py: Two new hooks, 'shutdown_hook' and 'late_startup_hook'.
787 * hooks.py: Two new hooks, 'shutdown_hook' and 'late_startup_hook'.
775
788
776 * aliases can now be %store'd
789 * aliases can now be %store'd
777
790
778 * path.py moved to Extensions so that pickleshare does not need
791 * path.py moved to Extensions so that pickleshare does not need
779 IPython-specific import. Extensions added to pythonpath right
792 IPython-specific import. Extensions added to pythonpath right
780 at __init__.
793 at __init__.
781
794
782 * iplib.py: ipalias deprecated/redundant; aliases are converted and
795 * iplib.py: ipalias deprecated/redundant; aliases are converted and
783 called with _ip.system and the pre-transformed command string.
796 called with _ip.system and the pre-transformed command string.
784
797
785 2006-01-29 Fernando Perez <Fernando.Perez@colorado.edu>
798 2006-01-29 Fernando Perez <Fernando.Perez@colorado.edu>
786
799
787 * IPython/iplib.py (interact): Fix that we were not catching
800 * IPython/iplib.py (interact): Fix that we were not catching
788 KeyboardInterrupt exceptions properly. I'm not quite sure why the
801 KeyboardInterrupt exceptions properly. I'm not quite sure why the
789 logic here had to change, but it's fixed now.
802 logic here had to change, but it's fixed now.
790
803
791 2006-01-29 Ville Vainio <vivainio@gmail.com>
804 2006-01-29 Ville Vainio <vivainio@gmail.com>
792
805
793 * iplib.py: Try to import pyreadline on Windows.
806 * iplib.py: Try to import pyreadline on Windows.
794
807
795 2006-01-27 Ville Vainio <vivainio@gmail.com>
808 2006-01-27 Ville Vainio <vivainio@gmail.com>
796
809
797 * iplib.py: Expose ipapi as _ip in builtin namespace.
810 * iplib.py: Expose ipapi as _ip in builtin namespace.
798 Makes ipmagic (-> _ip.magic), ipsystem (-> _ip.system)
811 Makes ipmagic (-> _ip.magic), ipsystem (-> _ip.system)
799 and ip_set_hook (-> _ip.set_hook) redundant. % and !
812 and ip_set_hook (-> _ip.set_hook) redundant. % and !
800 syntax now produce _ip.* variant of the commands.
813 syntax now produce _ip.* variant of the commands.
801
814
802 * "_ip.options().autoedit_syntax = 2" automatically throws
815 * "_ip.options().autoedit_syntax = 2" automatically throws
803 user to editor for syntax error correction without prompting.
816 user to editor for syntax error correction without prompting.
804
817
805 2006-01-27 Ville Vainio <vivainio@gmail.com>
818 2006-01-27 Ville Vainio <vivainio@gmail.com>
806
819
807 * ipmaker.py: Give "realistic" sys.argv for scripts (without
820 * ipmaker.py: Give "realistic" sys.argv for scripts (without
808 'ipython' at argv[0]) executed through command line.
821 'ipython' at argv[0]) executed through command line.
809 NOTE: this DEPRECATES calling ipython with multiple scripts
822 NOTE: this DEPRECATES calling ipython with multiple scripts
810 ("ipython a.py b.py c.py")
823 ("ipython a.py b.py c.py")
811
824
812 * iplib.py, hooks.py: Added configurable input prefilter,
825 * iplib.py, hooks.py: Added configurable input prefilter,
813 named 'input_prefilter'. See ext_rescapture.py for example
826 named 'input_prefilter'. See ext_rescapture.py for example
814 usage.
827 usage.
815
828
816 * ext_rescapture.py, Magic.py: Better system command output capture
829 * ext_rescapture.py, Magic.py: Better system command output capture
817 through 'var = !ls' (deprecates user-visible %sc). Same notation
830 through 'var = !ls' (deprecates user-visible %sc). Same notation
818 applies for magics, 'var = %alias' assigns alias list to var.
831 applies for magics, 'var = %alias' assigns alias list to var.
819
832
820 * ipapi.py: added meta() for accessing extension-usable data store.
833 * ipapi.py: added meta() for accessing extension-usable data store.
821
834
822 * iplib.py: added InteractiveShell.getapi(). New magics should be
835 * iplib.py: added InteractiveShell.getapi(). New magics should be
823 written doing self.getapi() instead of using the shell directly.
836 written doing self.getapi() instead of using the shell directly.
824
837
825 * Magic.py: %store now allows doing %store foo > ~/myfoo.txt and
838 * Magic.py: %store now allows doing %store foo > ~/myfoo.txt and
826 %store foo >> ~/myfoo.txt to store variables to files (in clean
839 %store foo >> ~/myfoo.txt to store variables to files (in clean
827 textual form, not a restorable pickle).
840 textual form, not a restorable pickle).
828
841
829 * ipmaker.py: now import ipy_profile_PROFILENAME automatically
842 * ipmaker.py: now import ipy_profile_PROFILENAME automatically
830
843
831 * usage.py, Magic.py: added %quickref
844 * usage.py, Magic.py: added %quickref
832
845
833 * iplib.py: ESC_PAREN fixes: /f 1 2 -> f(1,2), not f(1 2).
846 * iplib.py: ESC_PAREN fixes: /f 1 2 -> f(1,2), not f(1 2).
834
847
835 * GetoptErrors when invoking magics etc. with wrong args
848 * GetoptErrors when invoking magics etc. with wrong args
836 are now more helpful:
849 are now more helpful:
837 GetoptError: option -l not recognized (allowed: "qb" )
850 GetoptError: option -l not recognized (allowed: "qb" )
838
851
839 2006-01-25 Fernando Perez <Fernando.Perez@colorado.edu>
852 2006-01-25 Fernando Perez <Fernando.Perez@colorado.edu>
840
853
841 * IPython/demo.py (Demo.show): Flush stdout after each block, so
854 * IPython/demo.py (Demo.show): Flush stdout after each block, so
842 computationally intensive blocks don't appear to stall the demo.
855 computationally intensive blocks don't appear to stall the demo.
843
856
844 2006-01-24 Ville Vainio <vivainio@gmail.com>
857 2006-01-24 Ville Vainio <vivainio@gmail.com>
845
858
846 * iplib.py, hooks.py: 'result_display' hook can return a non-None
859 * iplib.py, hooks.py: 'result_display' hook can return a non-None
847 value to manipulate resulting history entry.
860 value to manipulate resulting history entry.
848
861
849 * ipapi.py: Moved TryNext here from hooks.py. Moved functions
862 * ipapi.py: Moved TryNext here from hooks.py. Moved functions
850 to instance methods of IPApi class, to make extending an embedded
863 to instance methods of IPApi class, to make extending an embedded
851 IPython feasible. See ext_rehashdir.py for example usage.
864 IPython feasible. See ext_rehashdir.py for example usage.
852
865
853 * Merged 1071-1076 from branches/0.7.1
866 * Merged 1071-1076 from branches/0.7.1
854
867
855
868
856 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
869 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
857
870
858 * tools/release (daystamp): Fix build tools to use the new
871 * tools/release (daystamp): Fix build tools to use the new
859 eggsetup.py script to build lightweight eggs.
872 eggsetup.py script to build lightweight eggs.
860
873
861 * Applied changesets 1062 and 1064 before 0.7.1 release.
874 * Applied changesets 1062 and 1064 before 0.7.1 release.
862
875
863 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
876 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
864 see the raw input history (without conversions like %ls ->
877 see the raw input history (without conversions like %ls ->
865 ipmagic("ls")). After a request from W. Stein, SAGE
878 ipmagic("ls")). After a request from W. Stein, SAGE
866 (http://modular.ucsd.edu/sage) developer. This information is
879 (http://modular.ucsd.edu/sage) developer. This information is
867 stored in the input_hist_raw attribute of the IPython instance, so
880 stored in the input_hist_raw attribute of the IPython instance, so
868 developers can access it if needed (it's an InputList instance).
881 developers can access it if needed (it's an InputList instance).
869
882
870 * Versionstring = 0.7.2.svn
883 * Versionstring = 0.7.2.svn
871
884
872 * eggsetup.py: A separate script for constructing eggs, creates
885 * eggsetup.py: A separate script for constructing eggs, creates
873 proper launch scripts even on Windows (an .exe file in
886 proper launch scripts even on Windows (an .exe file in
874 \python24\scripts).
887 \python24\scripts).
875
888
876 * ipapi.py: launch_new_instance, launch entry point needed for the
889 * ipapi.py: launch_new_instance, launch entry point needed for the
877 egg.
890 egg.
878
891
879 2006-01-23 Ville Vainio <vivainio@gmail.com>
892 2006-01-23 Ville Vainio <vivainio@gmail.com>
880
893
881 * Added %cpaste magic for pasting python code
894 * Added %cpaste magic for pasting python code
882
895
883 2006-01-22 Ville Vainio <vivainio@gmail.com>
896 2006-01-22 Ville Vainio <vivainio@gmail.com>
884
897
885 * Merge from branches/0.7.1 into trunk, revs 1052-1057
898 * Merge from branches/0.7.1 into trunk, revs 1052-1057
886
899
887 * Versionstring = 0.7.2.svn
900 * Versionstring = 0.7.2.svn
888
901
889 * eggsetup.py: A separate script for constructing eggs, creates
902 * eggsetup.py: A separate script for constructing eggs, creates
890 proper launch scripts even on Windows (an .exe file in
903 proper launch scripts even on Windows (an .exe file in
891 \python24\scripts).
904 \python24\scripts).
892
905
893 * ipapi.py: launch_new_instance, launch entry point needed for the
906 * ipapi.py: launch_new_instance, launch entry point needed for the
894 egg.
907 egg.
895
908
896 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
909 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
897
910
898 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
911 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
899 %pfile foo would print the file for foo even if it was a binary.
912 %pfile foo would print the file for foo even if it was a binary.
900 Now, extensions '.so' and '.dll' are skipped.
913 Now, extensions '.so' and '.dll' are skipped.
901
914
902 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
915 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
903 bug, where macros would fail in all threaded modes. I'm not 100%
916 bug, where macros would fail in all threaded modes. I'm not 100%
904 sure, so I'm going to put out an rc instead of making a release
917 sure, so I'm going to put out an rc instead of making a release
905 today, and wait for feedback for at least a few days.
918 today, and wait for feedback for at least a few days.
906
919
907 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
920 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
908 it...) the handling of pasting external code with autoindent on.
921 it...) the handling of pasting external code with autoindent on.
909 To get out of a multiline input, the rule will appear for most
922 To get out of a multiline input, the rule will appear for most
910 users unchanged: two blank lines or change the indent level
923 users unchanged: two blank lines or change the indent level
911 proposed by IPython. But there is a twist now: you can
924 proposed by IPython. But there is a twist now: you can
912 add/subtract only *one or two spaces*. If you add/subtract three
925 add/subtract only *one or two spaces*. If you add/subtract three
913 or more (unless you completely delete the line), IPython will
926 or more (unless you completely delete the line), IPython will
914 accept that line, and you'll need to enter a second one of pure
927 accept that line, and you'll need to enter a second one of pure
915 whitespace. I know it sounds complicated, but I can't find a
928 whitespace. I know it sounds complicated, but I can't find a
916 different solution that covers all the cases, with the right
929 different solution that covers all the cases, with the right
917 heuristics. Hopefully in actual use, nobody will really notice
930 heuristics. Hopefully in actual use, nobody will really notice
918 all these strange rules and things will 'just work'.
931 all these strange rules and things will 'just work'.
919
932
920 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
933 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
921
934
922 * IPython/iplib.py (interact): catch exceptions which can be
935 * IPython/iplib.py (interact): catch exceptions which can be
923 triggered asynchronously by signal handlers. Thanks to an
936 triggered asynchronously by signal handlers. Thanks to an
924 automatic crash report, submitted by Colin Kingsley
937 automatic crash report, submitted by Colin Kingsley
925 <tercel-AT-gentoo.org>.
938 <tercel-AT-gentoo.org>.
926
939
927 2006-01-20 Ville Vainio <vivainio@gmail.com>
940 2006-01-20 Ville Vainio <vivainio@gmail.com>
928
941
929 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
942 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
930 (%rehashdir, very useful, try it out) of how to extend ipython
943 (%rehashdir, very useful, try it out) of how to extend ipython
931 with new magics. Also added Extensions dir to pythonpath to make
944 with new magics. Also added Extensions dir to pythonpath to make
932 importing extensions easy.
945 importing extensions easy.
933
946
934 * %store now complains when trying to store interactively declared
947 * %store now complains when trying to store interactively declared
935 classes / instances of those classes.
948 classes / instances of those classes.
936
949
937 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
950 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
938 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
951 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
939 if they exist, and ipy_user_conf.py with some defaults is created for
952 if they exist, and ipy_user_conf.py with some defaults is created for
940 the user.
953 the user.
941
954
942 * Startup rehashing done by the config file, not InterpreterExec.
955 * Startup rehashing done by the config file, not InterpreterExec.
943 This means system commands are available even without selecting the
956 This means system commands are available even without selecting the
944 pysh profile. It's the sensible default after all.
957 pysh profile. It's the sensible default after all.
945
958
946 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
959 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
947
960
948 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
961 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
949 multiline code with autoindent on working. But I am really not
962 multiline code with autoindent on working. But I am really not
950 sure, so this needs more testing. Will commit a debug-enabled
963 sure, so this needs more testing. Will commit a debug-enabled
951 version for now, while I test it some more, so that Ville and
964 version for now, while I test it some more, so that Ville and
952 others may also catch any problems. Also made
965 others may also catch any problems. Also made
953 self.indent_current_str() a method, to ensure that there's no
966 self.indent_current_str() a method, to ensure that there's no
954 chance of the indent space count and the corresponding string
967 chance of the indent space count and the corresponding string
955 falling out of sync. All code needing the string should just call
968 falling out of sync. All code needing the string should just call
956 the method.
969 the method.
957
970
958 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
971 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
959
972
960 * IPython/Magic.py (magic_edit): fix check for when users don't
973 * IPython/Magic.py (magic_edit): fix check for when users don't
961 save their output files, the try/except was in the wrong section.
974 save their output files, the try/except was in the wrong section.
962
975
963 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
976 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
964
977
965 * IPython/Magic.py (magic_run): fix __file__ global missing from
978 * IPython/Magic.py (magic_run): fix __file__ global missing from
966 script's namespace when executed via %run. After a report by
979 script's namespace when executed via %run. After a report by
967 Vivian.
980 Vivian.
968
981
969 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
982 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
970 when using python 2.4. The parent constructor changed in 2.4, and
983 when using python 2.4. The parent constructor changed in 2.4, and
971 we need to track it directly (we can't call it, as it messes up
984 we need to track it directly (we can't call it, as it messes up
972 readline and tab-completion inside our pdb would stop working).
985 readline and tab-completion inside our pdb would stop working).
973 After a bug report by R. Bernstein <rocky-AT-panix.com>.
986 After a bug report by R. Bernstein <rocky-AT-panix.com>.
974
987
975 2006-01-16 Ville Vainio <vivainio@gmail.com>
988 2006-01-16 Ville Vainio <vivainio@gmail.com>
976
989
977 * Ipython/magic.py: Reverted back to old %edit functionality
990 * Ipython/magic.py: Reverted back to old %edit functionality
978 that returns file contents on exit.
991 that returns file contents on exit.
979
992
980 * IPython/path.py: Added Jason Orendorff's "path" module to
993 * IPython/path.py: Added Jason Orendorff's "path" module to
981 IPython tree, http://www.jorendorff.com/articles/python/path/.
994 IPython tree, http://www.jorendorff.com/articles/python/path/.
982 You can get path objects conveniently through %sc, and !!, e.g.:
995 You can get path objects conveniently through %sc, and !!, e.g.:
983 sc files=ls
996 sc files=ls
984 for p in files.paths: # or files.p
997 for p in files.paths: # or files.p
985 print p,p.mtime
998 print p,p.mtime
986
999
987 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
1000 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
988 now work again without considering the exclusion regexp -
1001 now work again without considering the exclusion regexp -
989 hence, things like ',foo my/path' turn to 'foo("my/path")'
1002 hence, things like ',foo my/path' turn to 'foo("my/path")'
990 instead of syntax error.
1003 instead of syntax error.
991
1004
992
1005
993 2006-01-14 Ville Vainio <vivainio@gmail.com>
1006 2006-01-14 Ville Vainio <vivainio@gmail.com>
994
1007
995 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
1008 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
996 ipapi decorators for python 2.4 users, options() provides access to rc
1009 ipapi decorators for python 2.4 users, options() provides access to rc
997 data.
1010 data.
998
1011
999 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
1012 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
1000 as path separators (even on Linux ;-). Space character after
1013 as path separators (even on Linux ;-). Space character after
1001 backslash (as yielded by tab completer) is still space;
1014 backslash (as yielded by tab completer) is still space;
1002 "%cd long\ name" works as expected.
1015 "%cd long\ name" works as expected.
1003
1016
1004 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
1017 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
1005 as "chain of command", with priority. API stays the same,
1018 as "chain of command", with priority. API stays the same,
1006 TryNext exception raised by a hook function signals that
1019 TryNext exception raised by a hook function signals that
1007 current hook failed and next hook should try handling it, as
1020 current hook failed and next hook should try handling it, as
1008 suggested by Walter DΓΆrwald <walter@livinglogic.de>. Walter also
1021 suggested by Walter DΓΆrwald <walter@livinglogic.de>. Walter also
1009 requested configurable display hook, which is now implemented.
1022 requested configurable display hook, which is now implemented.
1010
1023
1011 2006-01-13 Ville Vainio <vivainio@gmail.com>
1024 2006-01-13 Ville Vainio <vivainio@gmail.com>
1012
1025
1013 * IPython/platutils*.py: platform specific utility functions,
1026 * IPython/platutils*.py: platform specific utility functions,
1014 so far only set_term_title is implemented (change terminal
1027 so far only set_term_title is implemented (change terminal
1015 label in windowing systems). %cd now changes the title to
1028 label in windowing systems). %cd now changes the title to
1016 current dir.
1029 current dir.
1017
1030
1018 * IPython/Release.py: Added myself to "authors" list,
1031 * IPython/Release.py: Added myself to "authors" list,
1019 had to create new files.
1032 had to create new files.
1020
1033
1021 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
1034 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
1022 shell escape; not a known bug but had potential to be one in the
1035 shell escape; not a known bug but had potential to be one in the
1023 future.
1036 future.
1024
1037
1025 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
1038 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
1026 extension API for IPython! See the module for usage example. Fix
1039 extension API for IPython! See the module for usage example. Fix
1027 OInspect for docstring-less magic functions.
1040 OInspect for docstring-less magic functions.
1028
1041
1029
1042
1030 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
1043 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
1031
1044
1032 * IPython/iplib.py (raw_input): temporarily deactivate all
1045 * IPython/iplib.py (raw_input): temporarily deactivate all
1033 attempts at allowing pasting of code with autoindent on. It
1046 attempts at allowing pasting of code with autoindent on. It
1034 introduced bugs (reported by Prabhu) and I can't seem to find a
1047 introduced bugs (reported by Prabhu) and I can't seem to find a
1035 robust combination which works in all cases. Will have to revisit
1048 robust combination which works in all cases. Will have to revisit
1036 later.
1049 later.
1037
1050
1038 * IPython/genutils.py: remove isspace() function. We've dropped
1051 * IPython/genutils.py: remove isspace() function. We've dropped
1039 2.2 compatibility, so it's OK to use the string method.
1052 2.2 compatibility, so it's OK to use the string method.
1040
1053
1041 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
1054 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
1042
1055
1043 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
1056 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
1044 matching what NOT to autocall on, to include all python binary
1057 matching what NOT to autocall on, to include all python binary
1045 operators (including things like 'and', 'or', 'is' and 'in').
1058 operators (including things like 'and', 'or', 'is' and 'in').
1046 Prompted by a bug report on 'foo & bar', but I realized we had
1059 Prompted by a bug report on 'foo & bar', but I realized we had
1047 many more potential bug cases with other operators. The regexp is
1060 many more potential bug cases with other operators. The regexp is
1048 self.re_exclude_auto, it's fairly commented.
1061 self.re_exclude_auto, it's fairly commented.
1049
1062
1050 2006-01-12 Ville Vainio <vivainio@gmail.com>
1063 2006-01-12 Ville Vainio <vivainio@gmail.com>
1051
1064
1052 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
1065 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
1053 Prettified and hardened string/backslash quoting with ipsystem(),
1066 Prettified and hardened string/backslash quoting with ipsystem(),
1054 ipalias() and ipmagic(). Now even \ characters are passed to
1067 ipalias() and ipmagic(). Now even \ characters are passed to
1055 %magics, !shell escapes and aliases exactly as they are in the
1068 %magics, !shell escapes and aliases exactly as they are in the
1056 ipython command line. Should improve backslash experience,
1069 ipython command line. Should improve backslash experience,
1057 particularly in Windows (path delimiter for some commands that
1070 particularly in Windows (path delimiter for some commands that
1058 won't understand '/'), but Unix benefits as well (regexps). %cd
1071 won't understand '/'), but Unix benefits as well (regexps). %cd
1059 magic still doesn't support backslash path delimiters, though. Also
1072 magic still doesn't support backslash path delimiters, though. Also
1060 deleted all pretense of supporting multiline command strings in
1073 deleted all pretense of supporting multiline command strings in
1061 !system or %magic commands. Thanks to Jerry McRae for suggestions.
1074 !system or %magic commands. Thanks to Jerry McRae for suggestions.
1062
1075
1063 * doc/build_doc_instructions.txt added. Documentation on how to
1076 * doc/build_doc_instructions.txt added. Documentation on how to
1064 use doc/update_manual.py, added yesterday. Both files contributed
1077 use doc/update_manual.py, added yesterday. Both files contributed
1065 by JΓΆrgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
1078 by JΓΆrgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
1066 doc/*.sh for deprecation at a later date.
1079 doc/*.sh for deprecation at a later date.
1067
1080
1068 * /ipython.py Added ipython.py to root directory for
1081 * /ipython.py Added ipython.py to root directory for
1069 zero-installation (tar xzvf ipython.tgz; cd ipython; python
1082 zero-installation (tar xzvf ipython.tgz; cd ipython; python
1070 ipython.py) and development convenience (no need to keep doing
1083 ipython.py) and development convenience (no need to keep doing
1071 "setup.py install" between changes).
1084 "setup.py install" between changes).
1072
1085
1073 * Made ! and !! shell escapes work (again) in multiline expressions:
1086 * Made ! and !! shell escapes work (again) in multiline expressions:
1074 if 1:
1087 if 1:
1075 !ls
1088 !ls
1076 !!ls
1089 !!ls
1077
1090
1078 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
1091 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
1079
1092
1080 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
1093 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
1081 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
1094 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
1082 module in case-insensitive installation. Was causing crashes
1095 module in case-insensitive installation. Was causing crashes
1083 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
1096 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
1084
1097
1085 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
1098 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
1086 <marienz-AT-gentoo.org>, closes
1099 <marienz-AT-gentoo.org>, closes
1087 http://www.scipy.net/roundup/ipython/issue51.
1100 http://www.scipy.net/roundup/ipython/issue51.
1088
1101
1089 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
1102 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
1090
1103
1091 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the
1104 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the
1092 problem of excessive CPU usage under *nix and keyboard lag under
1105 problem of excessive CPU usage under *nix and keyboard lag under
1093 win32.
1106 win32.
1094
1107
1095 2006-01-10 *** Released version 0.7.0
1108 2006-01-10 *** Released version 0.7.0
1096
1109
1097 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
1110 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
1098
1111
1099 * IPython/Release.py (revision): tag version number to 0.7.0,
1112 * IPython/Release.py (revision): tag version number to 0.7.0,
1100 ready for release.
1113 ready for release.
1101
1114
1102 * IPython/Magic.py (magic_edit): Add print statement to %edit so
1115 * IPython/Magic.py (magic_edit): Add print statement to %edit so
1103 it informs the user of the name of the temp. file used. This can
1116 it informs the user of the name of the temp. file used. This can
1104 help if you decide later to reuse that same file, so you know
1117 help if you decide later to reuse that same file, so you know
1105 where to copy the info from.
1118 where to copy the info from.
1106
1119
1107 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
1120 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
1108
1121
1109 * setup_bdist_egg.py: little script to build an egg. Added
1122 * setup_bdist_egg.py: little script to build an egg. Added
1110 support in the release tools as well.
1123 support in the release tools as well.
1111
1124
1112 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
1125 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
1113
1126
1114 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
1127 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
1115 version selection (new -wxversion command line and ipythonrc
1128 version selection (new -wxversion command line and ipythonrc
1116 parameter). Patch contributed by Arnd Baecker
1129 parameter). Patch contributed by Arnd Baecker
1117 <arnd.baecker-AT-web.de>.
1130 <arnd.baecker-AT-web.de>.
1118
1131
1119 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1132 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1120 embedded instances, for variables defined at the interactive
1133 embedded instances, for variables defined at the interactive
1121 prompt of the embedded ipython. Reported by Arnd.
1134 prompt of the embedded ipython. Reported by Arnd.
1122
1135
1123 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
1136 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
1124 it can be used as a (stateful) toggle, or with a direct parameter.
1137 it can be used as a (stateful) toggle, or with a direct parameter.
1125
1138
1126 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
1139 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
1127 could be triggered in certain cases and cause the traceback
1140 could be triggered in certain cases and cause the traceback
1128 printer not to work.
1141 printer not to work.
1129
1142
1130 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
1143 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
1131
1144
1132 * IPython/iplib.py (_should_recompile): Small fix, closes
1145 * IPython/iplib.py (_should_recompile): Small fix, closes
1133 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
1146 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
1134
1147
1135 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
1148 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
1136
1149
1137 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
1150 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
1138 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
1151 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
1139 Moad for help with tracking it down.
1152 Moad for help with tracking it down.
1140
1153
1141 * IPython/iplib.py (handle_auto): fix autocall handling for
1154 * IPython/iplib.py (handle_auto): fix autocall handling for
1142 objects which support BOTH __getitem__ and __call__ (so that f [x]
1155 objects which support BOTH __getitem__ and __call__ (so that f [x]
1143 is left alone, instead of becoming f([x]) automatically).
1156 is left alone, instead of becoming f([x]) automatically).
1144
1157
1145 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
1158 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
1146 Ville's patch.
1159 Ville's patch.
1147
1160
1148 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
1161 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
1149
1162
1150 * IPython/iplib.py (handle_auto): changed autocall semantics to
1163 * IPython/iplib.py (handle_auto): changed autocall semantics to
1151 include 'smart' mode, where the autocall transformation is NOT
1164 include 'smart' mode, where the autocall transformation is NOT
1152 applied if there are no arguments on the line. This allows you to
1165 applied if there are no arguments on the line. This allows you to
1153 just type 'foo' if foo is a callable to see its internal form,
1166 just type 'foo' if foo is a callable to see its internal form,
1154 instead of having it called with no arguments (typically a
1167 instead of having it called with no arguments (typically a
1155 mistake). The old 'full' autocall still exists: for that, you
1168 mistake). The old 'full' autocall still exists: for that, you
1156 need to set the 'autocall' parameter to 2 in your ipythonrc file.
1169 need to set the 'autocall' parameter to 2 in your ipythonrc file.
1157
1170
1158 * IPython/completer.py (Completer.attr_matches): add
1171 * IPython/completer.py (Completer.attr_matches): add
1159 tab-completion support for Enthoughts' traits. After a report by
1172 tab-completion support for Enthoughts' traits. After a report by
1160 Arnd and a patch by Prabhu.
1173 Arnd and a patch by Prabhu.
1161
1174
1162 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
1175 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
1163
1176
1164 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
1177 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
1165 Schmolck's patch to fix inspect.getinnerframes().
1178 Schmolck's patch to fix inspect.getinnerframes().
1166
1179
1167 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
1180 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
1168 for embedded instances, regarding handling of namespaces and items
1181 for embedded instances, regarding handling of namespaces and items
1169 added to the __builtin__ one. Multiple embedded instances and
1182 added to the __builtin__ one. Multiple embedded instances and
1170 recursive embeddings should work better now (though I'm not sure
1183 recursive embeddings should work better now (though I'm not sure
1171 I've got all the corner cases fixed, that code is a bit of a brain
1184 I've got all the corner cases fixed, that code is a bit of a brain
1172 twister).
1185 twister).
1173
1186
1174 * IPython/Magic.py (magic_edit): added support to edit in-memory
1187 * IPython/Magic.py (magic_edit): added support to edit in-memory
1175 macros (automatically creates the necessary temp files). %edit
1188 macros (automatically creates the necessary temp files). %edit
1176 also doesn't return the file contents anymore, it's just noise.
1189 also doesn't return the file contents anymore, it's just noise.
1177
1190
1178 * IPython/completer.py (Completer.attr_matches): revert change to
1191 * IPython/completer.py (Completer.attr_matches): revert change to
1179 complete only on attributes listed in __all__. I realized it
1192 complete only on attributes listed in __all__. I realized it
1180 cripples the tab-completion system as a tool for exploring the
1193 cripples the tab-completion system as a tool for exploring the
1181 internals of unknown libraries (it renders any non-__all__
1194 internals of unknown libraries (it renders any non-__all__
1182 attribute off-limits). I got bit by this when trying to see
1195 attribute off-limits). I got bit by this when trying to see
1183 something inside the dis module.
1196 something inside the dis module.
1184
1197
1185 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
1198 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
1186
1199
1187 * IPython/iplib.py (InteractiveShell.__init__): add .meta
1200 * IPython/iplib.py (InteractiveShell.__init__): add .meta
1188 namespace for users and extension writers to hold data in. This
1201 namespace for users and extension writers to hold data in. This
1189 follows the discussion in
1202 follows the discussion in
1190 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
1203 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
1191
1204
1192 * IPython/completer.py (IPCompleter.complete): small patch to help
1205 * IPython/completer.py (IPCompleter.complete): small patch to help
1193 tab-completion under Emacs, after a suggestion by John Barnard
1206 tab-completion under Emacs, after a suggestion by John Barnard
1194 <barnarj-AT-ccf.org>.
1207 <barnarj-AT-ccf.org>.
1195
1208
1196 * IPython/Magic.py (Magic.extract_input_slices): added support for
1209 * IPython/Magic.py (Magic.extract_input_slices): added support for
1197 the slice notation in magics to use N-M to represent numbers N...M
1210 the slice notation in magics to use N-M to represent numbers N...M
1198 (closed endpoints). This is used by %macro and %save.
1211 (closed endpoints). This is used by %macro and %save.
1199
1212
1200 * IPython/completer.py (Completer.attr_matches): for modules which
1213 * IPython/completer.py (Completer.attr_matches): for modules which
1201 define __all__, complete only on those. After a patch by Jeffrey
1214 define __all__, complete only on those. After a patch by Jeffrey
1202 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
1215 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
1203 speed up this routine.
1216 speed up this routine.
1204
1217
1205 * IPython/Logger.py (Logger.log): fix a history handling bug. I
1218 * IPython/Logger.py (Logger.log): fix a history handling bug. I
1206 don't know if this is the end of it, but the behavior now is
1219 don't know if this is the end of it, but the behavior now is
1207 certainly much more correct. Note that coupled with macros,
1220 certainly much more correct. Note that coupled with macros,
1208 slightly surprising (at first) behavior may occur: a macro will in
1221 slightly surprising (at first) behavior may occur: a macro will in
1209 general expand to multiple lines of input, so upon exiting, the
1222 general expand to multiple lines of input, so upon exiting, the
1210 in/out counters will both be bumped by the corresponding amount
1223 in/out counters will both be bumped by the corresponding amount
1211 (as if the macro's contents had been typed interactively). Typing
1224 (as if the macro's contents had been typed interactively). Typing
1212 %hist will reveal the intermediate (silently processed) lines.
1225 %hist will reveal the intermediate (silently processed) lines.
1213
1226
1214 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
1227 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
1215 pickle to fail (%run was overwriting __main__ and not restoring
1228 pickle to fail (%run was overwriting __main__ and not restoring
1216 it, but pickle relies on __main__ to operate).
1229 it, but pickle relies on __main__ to operate).
1217
1230
1218 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
1231 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
1219 using properties, but forgot to make the main InteractiveShell
1232 using properties, but forgot to make the main InteractiveShell
1220 class a new-style class. Properties fail silently, and
1233 class a new-style class. Properties fail silently, and
1221 mysteriously, with old-style class (getters work, but
1234 mysteriously, with old-style class (getters work, but
1222 setters don't do anything).
1235 setters don't do anything).
1223
1236
1224 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
1237 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
1225
1238
1226 * IPython/Magic.py (magic_history): fix history reporting bug (I
1239 * IPython/Magic.py (magic_history): fix history reporting bug (I
1227 know some nasties are still there, I just can't seem to find a
1240 know some nasties are still there, I just can't seem to find a
1228 reproducible test case to track them down; the input history is
1241 reproducible test case to track them down; the input history is
1229 falling out of sync...)
1242 falling out of sync...)
1230
1243
1231 * IPython/iplib.py (handle_shell_escape): fix bug where both
1244 * IPython/iplib.py (handle_shell_escape): fix bug where both
1232 aliases and system accesses where broken for indented code (such
1245 aliases and system accesses where broken for indented code (such
1233 as loops).
1246 as loops).
1234
1247
1235 * IPython/genutils.py (shell): fix small but critical bug for
1248 * IPython/genutils.py (shell): fix small but critical bug for
1236 win32 system access.
1249 win32 system access.
1237
1250
1238 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
1251 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
1239
1252
1240 * IPython/iplib.py (showtraceback): remove use of the
1253 * IPython/iplib.py (showtraceback): remove use of the
1241 sys.last_{type/value/traceback} structures, which are non
1254 sys.last_{type/value/traceback} structures, which are non
1242 thread-safe.
1255 thread-safe.
1243 (_prefilter): change control flow to ensure that we NEVER
1256 (_prefilter): change control flow to ensure that we NEVER
1244 introspect objects when autocall is off. This will guarantee that
1257 introspect objects when autocall is off. This will guarantee that
1245 having an input line of the form 'x.y', where access to attribute
1258 having an input line of the form 'x.y', where access to attribute
1246 'y' has side effects, doesn't trigger the side effect TWICE. It
1259 'y' has side effects, doesn't trigger the side effect TWICE. It
1247 is important to note that, with autocall on, these side effects
1260 is important to note that, with autocall on, these side effects
1248 can still happen.
1261 can still happen.
1249 (ipsystem): new builtin, to complete the ip{magic/alias/system}
1262 (ipsystem): new builtin, to complete the ip{magic/alias/system}
1250 trio. IPython offers these three kinds of special calls which are
1263 trio. IPython offers these three kinds of special calls which are
1251 not python code, and it's a good thing to have their call method
1264 not python code, and it's a good thing to have their call method
1252 be accessible as pure python functions (not just special syntax at
1265 be accessible as pure python functions (not just special syntax at
1253 the command line). It gives us a better internal implementation
1266 the command line). It gives us a better internal implementation
1254 structure, as well as exposing these for user scripting more
1267 structure, as well as exposing these for user scripting more
1255 cleanly.
1268 cleanly.
1256
1269
1257 * IPython/macro.py (Macro.__init__): moved macros to a standalone
1270 * IPython/macro.py (Macro.__init__): moved macros to a standalone
1258 file. Now that they'll be more likely to be used with the
1271 file. Now that they'll be more likely to be used with the
1259 persistance system (%store), I want to make sure their module path
1272 persistance system (%store), I want to make sure their module path
1260 doesn't change in the future, so that we don't break things for
1273 doesn't change in the future, so that we don't break things for
1261 users' persisted data.
1274 users' persisted data.
1262
1275
1263 * IPython/iplib.py (autoindent_update): move indentation
1276 * IPython/iplib.py (autoindent_update): move indentation
1264 management into the _text_ processing loop, not the keyboard
1277 management into the _text_ processing loop, not the keyboard
1265 interactive one. This is necessary to correctly process non-typed
1278 interactive one. This is necessary to correctly process non-typed
1266 multiline input (such as macros).
1279 multiline input (such as macros).
1267
1280
1268 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
1281 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
1269 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
1282 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
1270 which was producing problems in the resulting manual.
1283 which was producing problems in the resulting manual.
1271 (magic_whos): improve reporting of instances (show their class,
1284 (magic_whos): improve reporting of instances (show their class,
1272 instead of simply printing 'instance' which isn't terribly
1285 instead of simply printing 'instance' which isn't terribly
1273 informative).
1286 informative).
1274
1287
1275 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
1288 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
1276 (minor mods) to support network shares under win32.
1289 (minor mods) to support network shares under win32.
1277
1290
1278 * IPython/winconsole.py (get_console_size): add new winconsole
1291 * IPython/winconsole.py (get_console_size): add new winconsole
1279 module and fixes to page_dumb() to improve its behavior under
1292 module and fixes to page_dumb() to improve its behavior under
1280 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
1293 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
1281
1294
1282 * IPython/Magic.py (Macro): simplified Macro class to just
1295 * IPython/Magic.py (Macro): simplified Macro class to just
1283 subclass list. We've had only 2.2 compatibility for a very long
1296 subclass list. We've had only 2.2 compatibility for a very long
1284 time, yet I was still avoiding subclassing the builtin types. No
1297 time, yet I was still avoiding subclassing the builtin types. No
1285 more (I'm also starting to use properties, though I won't shift to
1298 more (I'm also starting to use properties, though I won't shift to
1286 2.3-specific features quite yet).
1299 2.3-specific features quite yet).
1287 (magic_store): added Ville's patch for lightweight variable
1300 (magic_store): added Ville's patch for lightweight variable
1288 persistence, after a request on the user list by Matt Wilkie
1301 persistence, after a request on the user list by Matt Wilkie
1289 <maphew-AT-gmail.com>. The new %store magic's docstring has full
1302 <maphew-AT-gmail.com>. The new %store magic's docstring has full
1290 details.
1303 details.
1291
1304
1292 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1305 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1293 changed the default logfile name from 'ipython.log' to
1306 changed the default logfile name from 'ipython.log' to
1294 'ipython_log.py'. These logs are real python files, and now that
1307 'ipython_log.py'. These logs are real python files, and now that
1295 we have much better multiline support, people are more likely to
1308 we have much better multiline support, people are more likely to
1296 want to use them as such. Might as well name them correctly.
1309 want to use them as such. Might as well name them correctly.
1297
1310
1298 * IPython/Magic.py: substantial cleanup. While we can't stop
1311 * IPython/Magic.py: substantial cleanup. While we can't stop
1299 using magics as mixins, due to the existing customizations 'out
1312 using magics as mixins, due to the existing customizations 'out
1300 there' which rely on the mixin naming conventions, at least I
1313 there' which rely on the mixin naming conventions, at least I
1301 cleaned out all cross-class name usage. So once we are OK with
1314 cleaned out all cross-class name usage. So once we are OK with
1302 breaking compatibility, the two systems can be separated.
1315 breaking compatibility, the two systems can be separated.
1303
1316
1304 * IPython/Logger.py: major cleanup. This one is NOT a mixin
1317 * IPython/Logger.py: major cleanup. This one is NOT a mixin
1305 anymore, and the class is a fair bit less hideous as well. New
1318 anymore, and the class is a fair bit less hideous as well. New
1306 features were also introduced: timestamping of input, and logging
1319 features were also introduced: timestamping of input, and logging
1307 of output results. These are user-visible with the -t and -o
1320 of output results. These are user-visible with the -t and -o
1308 options to %logstart. Closes
1321 options to %logstart. Closes
1309 http://www.scipy.net/roundup/ipython/issue11 and a request by
1322 http://www.scipy.net/roundup/ipython/issue11 and a request by
1310 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
1323 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
1311
1324
1312 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
1325 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
1313
1326
1314 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
1327 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
1315 better handle backslashes in paths. See the thread 'More Windows
1328 better handle backslashes in paths. See the thread 'More Windows
1316 questions part 2 - \/ characters revisited' on the iypthon user
1329 questions part 2 - \/ characters revisited' on the iypthon user
1317 list:
1330 list:
1318 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
1331 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
1319
1332
1320 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
1333 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
1321
1334
1322 (InteractiveShell.__init__): change threaded shells to not use the
1335 (InteractiveShell.__init__): change threaded shells to not use the
1323 ipython crash handler. This was causing more problems than not,
1336 ipython crash handler. This was causing more problems than not,
1324 as exceptions in the main thread (GUI code, typically) would
1337 as exceptions in the main thread (GUI code, typically) would
1325 always show up as a 'crash', when they really weren't.
1338 always show up as a 'crash', when they really weren't.
1326
1339
1327 The colors and exception mode commands (%colors/%xmode) have been
1340 The colors and exception mode commands (%colors/%xmode) have been
1328 synchronized to also take this into account, so users can get
1341 synchronized to also take this into account, so users can get
1329 verbose exceptions for their threaded code as well. I also added
1342 verbose exceptions for their threaded code as well. I also added
1330 support for activating pdb inside this exception handler as well,
1343 support for activating pdb inside this exception handler as well,
1331 so now GUI authors can use IPython's enhanced pdb at runtime.
1344 so now GUI authors can use IPython's enhanced pdb at runtime.
1332
1345
1333 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
1346 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
1334 true by default, and add it to the shipped ipythonrc file. Since
1347 true by default, and add it to the shipped ipythonrc file. Since
1335 this asks the user before proceeding, I think it's OK to make it
1348 this asks the user before proceeding, I think it's OK to make it
1336 true by default.
1349 true by default.
1337
1350
1338 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
1351 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
1339 of the previous special-casing of input in the eval loop. I think
1352 of the previous special-casing of input in the eval loop. I think
1340 this is cleaner, as they really are commands and shouldn't have
1353 this is cleaner, as they really are commands and shouldn't have
1341 a special role in the middle of the core code.
1354 a special role in the middle of the core code.
1342
1355
1343 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
1356 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
1344
1357
1345 * IPython/iplib.py (edit_syntax_error): added support for
1358 * IPython/iplib.py (edit_syntax_error): added support for
1346 automatically reopening the editor if the file had a syntax error
1359 automatically reopening the editor if the file had a syntax error
1347 in it. Thanks to scottt who provided the patch at:
1360 in it. Thanks to scottt who provided the patch at:
1348 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
1361 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
1349 version committed).
1362 version committed).
1350
1363
1351 * IPython/iplib.py (handle_normal): add suport for multi-line
1364 * IPython/iplib.py (handle_normal): add suport for multi-line
1352 input with emtpy lines. This fixes
1365 input with emtpy lines. This fixes
1353 http://www.scipy.net/roundup/ipython/issue43 and a similar
1366 http://www.scipy.net/roundup/ipython/issue43 and a similar
1354 discussion on the user list.
1367 discussion on the user list.
1355
1368
1356 WARNING: a behavior change is necessarily introduced to support
1369 WARNING: a behavior change is necessarily introduced to support
1357 blank lines: now a single blank line with whitespace does NOT
1370 blank lines: now a single blank line with whitespace does NOT
1358 break the input loop, which means that when autoindent is on, by
1371 break the input loop, which means that when autoindent is on, by
1359 default hitting return on the next (indented) line does NOT exit.
1372 default hitting return on the next (indented) line does NOT exit.
1360
1373
1361 Instead, to exit a multiline input you can either have:
1374 Instead, to exit a multiline input you can either have:
1362
1375
1363 - TWO whitespace lines (just hit return again), or
1376 - TWO whitespace lines (just hit return again), or
1364 - a single whitespace line of a different length than provided
1377 - a single whitespace line of a different length than provided
1365 by the autoindent (add or remove a space).
1378 by the autoindent (add or remove a space).
1366
1379
1367 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
1380 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
1368 module to better organize all readline-related functionality.
1381 module to better organize all readline-related functionality.
1369 I've deleted FlexCompleter and put all completion clases here.
1382 I've deleted FlexCompleter and put all completion clases here.
1370
1383
1371 * IPython/iplib.py (raw_input): improve indentation management.
1384 * IPython/iplib.py (raw_input): improve indentation management.
1372 It is now possible to paste indented code with autoindent on, and
1385 It is now possible to paste indented code with autoindent on, and
1373 the code is interpreted correctly (though it still looks bad on
1386 the code is interpreted correctly (though it still looks bad on
1374 screen, due to the line-oriented nature of ipython).
1387 screen, due to the line-oriented nature of ipython).
1375 (MagicCompleter.complete): change behavior so that a TAB key on an
1388 (MagicCompleter.complete): change behavior so that a TAB key on an
1376 otherwise empty line actually inserts a tab, instead of completing
1389 otherwise empty line actually inserts a tab, instead of completing
1377 on the entire global namespace. This makes it easier to use the
1390 on the entire global namespace. This makes it easier to use the
1378 TAB key for indentation. After a request by Hans Meine
1391 TAB key for indentation. After a request by Hans Meine
1379 <hans_meine-AT-gmx.net>
1392 <hans_meine-AT-gmx.net>
1380 (_prefilter): add support so that typing plain 'exit' or 'quit'
1393 (_prefilter): add support so that typing plain 'exit' or 'quit'
1381 does a sensible thing. Originally I tried to deviate as little as
1394 does a sensible thing. Originally I tried to deviate as little as
1382 possible from the default python behavior, but even that one may
1395 possible from the default python behavior, but even that one may
1383 change in this direction (thread on python-dev to that effect).
1396 change in this direction (thread on python-dev to that effect).
1384 Regardless, ipython should do the right thing even if CPython's
1397 Regardless, ipython should do the right thing even if CPython's
1385 '>>>' prompt doesn't.
1398 '>>>' prompt doesn't.
1386 (InteractiveShell): removed subclassing code.InteractiveConsole
1399 (InteractiveShell): removed subclassing code.InteractiveConsole
1387 class. By now we'd overridden just about all of its methods: I've
1400 class. By now we'd overridden just about all of its methods: I've
1388 copied the remaining two over, and now ipython is a standalone
1401 copied the remaining two over, and now ipython is a standalone
1389 class. This will provide a clearer picture for the chainsaw
1402 class. This will provide a clearer picture for the chainsaw
1390 branch refactoring.
1403 branch refactoring.
1391
1404
1392 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
1405 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
1393
1406
1394 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
1407 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
1395 failures for objects which break when dir() is called on them.
1408 failures for objects which break when dir() is called on them.
1396
1409
1397 * IPython/FlexCompleter.py (Completer.__init__): Added support for
1410 * IPython/FlexCompleter.py (Completer.__init__): Added support for
1398 distinct local and global namespaces in the completer API. This
1411 distinct local and global namespaces in the completer API. This
1399 change allows us to properly handle completion with distinct
1412 change allows us to properly handle completion with distinct
1400 scopes, including in embedded instances (this had never really
1413 scopes, including in embedded instances (this had never really
1401 worked correctly).
1414 worked correctly).
1402
1415
1403 Note: this introduces a change in the constructor for
1416 Note: this introduces a change in the constructor for
1404 MagicCompleter, as a new global_namespace parameter is now the
1417 MagicCompleter, as a new global_namespace parameter is now the
1405 second argument (the others were bumped one position).
1418 second argument (the others were bumped one position).
1406
1419
1407 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
1420 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
1408
1421
1409 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1422 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1410 embedded instances (which can be done now thanks to Vivian's
1423 embedded instances (which can be done now thanks to Vivian's
1411 frame-handling fixes for pdb).
1424 frame-handling fixes for pdb).
1412 (InteractiveShell.__init__): Fix namespace handling problem in
1425 (InteractiveShell.__init__): Fix namespace handling problem in
1413 embedded instances. We were overwriting __main__ unconditionally,
1426 embedded instances. We were overwriting __main__ unconditionally,
1414 and this should only be done for 'full' (non-embedded) IPython;
1427 and this should only be done for 'full' (non-embedded) IPython;
1415 embedded instances must respect the caller's __main__. Thanks to
1428 embedded instances must respect the caller's __main__. Thanks to
1416 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
1429 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
1417
1430
1418 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
1431 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
1419
1432
1420 * setup.py: added download_url to setup(). This registers the
1433 * setup.py: added download_url to setup(). This registers the
1421 download address at PyPI, which is not only useful to humans
1434 download address at PyPI, which is not only useful to humans
1422 browsing the site, but is also picked up by setuptools (the Eggs
1435 browsing the site, but is also picked up by setuptools (the Eggs
1423 machinery). Thanks to Ville and R. Kern for the info/discussion
1436 machinery). Thanks to Ville and R. Kern for the info/discussion
1424 on this.
1437 on this.
1425
1438
1426 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
1439 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
1427
1440
1428 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
1441 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
1429 This brings a lot of nice functionality to the pdb mode, which now
1442 This brings a lot of nice functionality to the pdb mode, which now
1430 has tab-completion, syntax highlighting, and better stack handling
1443 has tab-completion, syntax highlighting, and better stack handling
1431 than before. Many thanks to Vivian De Smedt
1444 than before. Many thanks to Vivian De Smedt
1432 <vivian-AT-vdesmedt.com> for the original patches.
1445 <vivian-AT-vdesmedt.com> for the original patches.
1433
1446
1434 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
1447 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
1435
1448
1436 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
1449 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
1437 sequence to consistently accept the banner argument. The
1450 sequence to consistently accept the banner argument. The
1438 inconsistency was tripping SAGE, thanks to Gary Zablackis
1451 inconsistency was tripping SAGE, thanks to Gary Zablackis
1439 <gzabl-AT-yahoo.com> for the report.
1452 <gzabl-AT-yahoo.com> for the report.
1440
1453
1441 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1454 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1442
1455
1443 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1456 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1444 Fix bug where a naked 'alias' call in the ipythonrc file would
1457 Fix bug where a naked 'alias' call in the ipythonrc file would
1445 cause a crash. Bug reported by Jorgen Stenarson.
1458 cause a crash. Bug reported by Jorgen Stenarson.
1446
1459
1447 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1460 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1448
1461
1449 * IPython/ipmaker.py (make_IPython): cleanups which should improve
1462 * IPython/ipmaker.py (make_IPython): cleanups which should improve
1450 startup time.
1463 startup time.
1451
1464
1452 * IPython/iplib.py (runcode): my globals 'fix' for embedded
1465 * IPython/iplib.py (runcode): my globals 'fix' for embedded
1453 instances had introduced a bug with globals in normal code. Now
1466 instances had introduced a bug with globals in normal code. Now
1454 it's working in all cases.
1467 it's working in all cases.
1455
1468
1456 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
1469 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
1457 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
1470 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
1458 has been introduced to set the default case sensitivity of the
1471 has been introduced to set the default case sensitivity of the
1459 searches. Users can still select either mode at runtime on a
1472 searches. Users can still select either mode at runtime on a
1460 per-search basis.
1473 per-search basis.
1461
1474
1462 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
1475 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
1463
1476
1464 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
1477 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
1465 attributes in wildcard searches for subclasses. Modified version
1478 attributes in wildcard searches for subclasses. Modified version
1466 of a patch by Jorgen.
1479 of a patch by Jorgen.
1467
1480
1468 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
1481 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
1469
1482
1470 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
1483 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
1471 embedded instances. I added a user_global_ns attribute to the
1484 embedded instances. I added a user_global_ns attribute to the
1472 InteractiveShell class to handle this.
1485 InteractiveShell class to handle this.
1473
1486
1474 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
1487 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
1475
1488
1476 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
1489 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
1477 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
1490 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
1478 (reported under win32, but may happen also in other platforms).
1491 (reported under win32, but may happen also in other platforms).
1479 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
1492 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
1480
1493
1481 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
1494 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
1482
1495
1483 * IPython/Magic.py (magic_psearch): new support for wildcard
1496 * IPython/Magic.py (magic_psearch): new support for wildcard
1484 patterns. Now, typing ?a*b will list all names which begin with a
1497 patterns. Now, typing ?a*b will list all names which begin with a
1485 and end in b, for example. The %psearch magic has full
1498 and end in b, for example. The %psearch magic has full
1486 docstrings. Many thanks to JΓΆrgen Stenarson
1499 docstrings. Many thanks to JΓΆrgen Stenarson
1487 <jorgen.stenarson-AT-bostream.nu>, author of the patches
1500 <jorgen.stenarson-AT-bostream.nu>, author of the patches
1488 implementing this functionality.
1501 implementing this functionality.
1489
1502
1490 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1503 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1491
1504
1492 * Manual: fixed long-standing annoyance of double-dashes (as in
1505 * Manual: fixed long-standing annoyance of double-dashes (as in
1493 --prefix=~, for example) being stripped in the HTML version. This
1506 --prefix=~, for example) being stripped in the HTML version. This
1494 is a latex2html bug, but a workaround was provided. Many thanks
1507 is a latex2html bug, but a workaround was provided. Many thanks
1495 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
1508 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
1496 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
1509 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
1497 rolling. This seemingly small issue had tripped a number of users
1510 rolling. This seemingly small issue had tripped a number of users
1498 when first installing, so I'm glad to see it gone.
1511 when first installing, so I'm glad to see it gone.
1499
1512
1500 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1513 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1501
1514
1502 * IPython/Extensions/numeric_formats.py: fix missing import,
1515 * IPython/Extensions/numeric_formats.py: fix missing import,
1503 reported by Stephen Walton.
1516 reported by Stephen Walton.
1504
1517
1505 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
1518 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
1506
1519
1507 * IPython/demo.py: finish demo module, fully documented now.
1520 * IPython/demo.py: finish demo module, fully documented now.
1508
1521
1509 * IPython/genutils.py (file_read): simple little utility to read a
1522 * IPython/genutils.py (file_read): simple little utility to read a
1510 file and ensure it's closed afterwards.
1523 file and ensure it's closed afterwards.
1511
1524
1512 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
1525 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
1513
1526
1514 * IPython/demo.py (Demo.__init__): added support for individually
1527 * IPython/demo.py (Demo.__init__): added support for individually
1515 tagging blocks for automatic execution.
1528 tagging blocks for automatic execution.
1516
1529
1517 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
1530 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
1518 syntax-highlighted python sources, requested by John.
1531 syntax-highlighted python sources, requested by John.
1519
1532
1520 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
1533 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
1521
1534
1522 * IPython/demo.py (Demo.again): fix bug where again() blocks after
1535 * IPython/demo.py (Demo.again): fix bug where again() blocks after
1523 finishing.
1536 finishing.
1524
1537
1525 * IPython/genutils.py (shlex_split): moved from Magic to here,
1538 * IPython/genutils.py (shlex_split): moved from Magic to here,
1526 where all 2.2 compatibility stuff lives. I needed it for demo.py.
1539 where all 2.2 compatibility stuff lives. I needed it for demo.py.
1527
1540
1528 * IPython/demo.py (Demo.__init__): added support for silent
1541 * IPython/demo.py (Demo.__init__): added support for silent
1529 blocks, improved marks as regexps, docstrings written.
1542 blocks, improved marks as regexps, docstrings written.
1530 (Demo.__init__): better docstring, added support for sys.argv.
1543 (Demo.__init__): better docstring, added support for sys.argv.
1531
1544
1532 * IPython/genutils.py (marquee): little utility used by the demo
1545 * IPython/genutils.py (marquee): little utility used by the demo
1533 code, handy in general.
1546 code, handy in general.
1534
1547
1535 * IPython/demo.py (Demo.__init__): new class for interactive
1548 * IPython/demo.py (Demo.__init__): new class for interactive
1536 demos. Not documented yet, I just wrote it in a hurry for
1549 demos. Not documented yet, I just wrote it in a hurry for
1537 scipy'05. Will docstring later.
1550 scipy'05. Will docstring later.
1538
1551
1539 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
1552 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
1540
1553
1541 * IPython/Shell.py (sigint_handler): Drastic simplification which
1554 * IPython/Shell.py (sigint_handler): Drastic simplification which
1542 also seems to make Ctrl-C work correctly across threads! This is
1555 also seems to make Ctrl-C work correctly across threads! This is
1543 so simple, that I can't beleive I'd missed it before. Needs more
1556 so simple, that I can't beleive I'd missed it before. Needs more
1544 testing, though.
1557 testing, though.
1545 (KBINT): Never mind, revert changes. I'm sure I'd tried something
1558 (KBINT): Never mind, revert changes. I'm sure I'd tried something
1546 like this before...
1559 like this before...
1547
1560
1548 * IPython/genutils.py (get_home_dir): add protection against
1561 * IPython/genutils.py (get_home_dir): add protection against
1549 non-dirs in win32 registry.
1562 non-dirs in win32 registry.
1550
1563
1551 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
1564 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
1552 bug where dict was mutated while iterating (pysh crash).
1565 bug where dict was mutated while iterating (pysh crash).
1553
1566
1554 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
1567 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
1555
1568
1556 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
1569 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
1557 spurious newlines added by this routine. After a report by
1570 spurious newlines added by this routine. After a report by
1558 F. Mantegazza.
1571 F. Mantegazza.
1559
1572
1560 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
1573 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
1561
1574
1562 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
1575 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
1563 calls. These were a leftover from the GTK 1.x days, and can cause
1576 calls. These were a leftover from the GTK 1.x days, and can cause
1564 problems in certain cases (after a report by John Hunter).
1577 problems in certain cases (after a report by John Hunter).
1565
1578
1566 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
1579 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
1567 os.getcwd() fails at init time. Thanks to patch from David Remahl
1580 os.getcwd() fails at init time. Thanks to patch from David Remahl
1568 <chmod007-AT-mac.com>.
1581 <chmod007-AT-mac.com>.
1569 (InteractiveShell.__init__): prevent certain special magics from
1582 (InteractiveShell.__init__): prevent certain special magics from
1570 being shadowed by aliases. Closes
1583 being shadowed by aliases. Closes
1571 http://www.scipy.net/roundup/ipython/issue41.
1584 http://www.scipy.net/roundup/ipython/issue41.
1572
1585
1573 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
1586 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
1574
1587
1575 * IPython/iplib.py (InteractiveShell.complete): Added new
1588 * IPython/iplib.py (InteractiveShell.complete): Added new
1576 top-level completion method to expose the completion mechanism
1589 top-level completion method to expose the completion mechanism
1577 beyond readline-based environments.
1590 beyond readline-based environments.
1578
1591
1579 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
1592 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
1580
1593
1581 * tools/ipsvnc (svnversion): fix svnversion capture.
1594 * tools/ipsvnc (svnversion): fix svnversion capture.
1582
1595
1583 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
1596 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
1584 attribute to self, which was missing. Before, it was set by a
1597 attribute to self, which was missing. Before, it was set by a
1585 routine which in certain cases wasn't being called, so the
1598 routine which in certain cases wasn't being called, so the
1586 instance could end up missing the attribute. This caused a crash.
1599 instance could end up missing the attribute. This caused a crash.
1587 Closes http://www.scipy.net/roundup/ipython/issue40.
1600 Closes http://www.scipy.net/roundup/ipython/issue40.
1588
1601
1589 2005-08-16 Fernando Perez <fperez@colorado.edu>
1602 2005-08-16 Fernando Perez <fperez@colorado.edu>
1590
1603
1591 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
1604 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
1592 contains non-string attribute. Closes
1605 contains non-string attribute. Closes
1593 http://www.scipy.net/roundup/ipython/issue38.
1606 http://www.scipy.net/roundup/ipython/issue38.
1594
1607
1595 2005-08-14 Fernando Perez <fperez@colorado.edu>
1608 2005-08-14 Fernando Perez <fperez@colorado.edu>
1596
1609
1597 * tools/ipsvnc: Minor improvements, to add changeset info.
1610 * tools/ipsvnc: Minor improvements, to add changeset info.
1598
1611
1599 2005-08-12 Fernando Perez <fperez@colorado.edu>
1612 2005-08-12 Fernando Perez <fperez@colorado.edu>
1600
1613
1601 * IPython/iplib.py (runsource): remove self.code_to_run_src
1614 * IPython/iplib.py (runsource): remove self.code_to_run_src
1602 attribute. I realized this is nothing more than
1615 attribute. I realized this is nothing more than
1603 '\n'.join(self.buffer), and having the same data in two different
1616 '\n'.join(self.buffer), and having the same data in two different
1604 places is just asking for synchronization bugs. This may impact
1617 places is just asking for synchronization bugs. This may impact
1605 people who have custom exception handlers, so I need to warn
1618 people who have custom exception handlers, so I need to warn
1606 ipython-dev about it (F. Mantegazza may use them).
1619 ipython-dev about it (F. Mantegazza may use them).
1607
1620
1608 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
1621 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
1609
1622
1610 * IPython/genutils.py: fix 2.2 compatibility (generators)
1623 * IPython/genutils.py: fix 2.2 compatibility (generators)
1611
1624
1612 2005-07-18 Fernando Perez <fperez@colorado.edu>
1625 2005-07-18 Fernando Perez <fperez@colorado.edu>
1613
1626
1614 * IPython/genutils.py (get_home_dir): fix to help users with
1627 * IPython/genutils.py (get_home_dir): fix to help users with
1615 invalid $HOME under win32.
1628 invalid $HOME under win32.
1616
1629
1617 2005-07-17 Fernando Perez <fperez@colorado.edu>
1630 2005-07-17 Fernando Perez <fperez@colorado.edu>
1618
1631
1619 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
1632 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
1620 some old hacks and clean up a bit other routines; code should be
1633 some old hacks and clean up a bit other routines; code should be
1621 simpler and a bit faster.
1634 simpler and a bit faster.
1622
1635
1623 * IPython/iplib.py (interact): removed some last-resort attempts
1636 * IPython/iplib.py (interact): removed some last-resort attempts
1624 to survive broken stdout/stderr. That code was only making it
1637 to survive broken stdout/stderr. That code was only making it
1625 harder to abstract out the i/o (necessary for gui integration),
1638 harder to abstract out the i/o (necessary for gui integration),
1626 and the crashes it could prevent were extremely rare in practice
1639 and the crashes it could prevent were extremely rare in practice
1627 (besides being fully user-induced in a pretty violent manner).
1640 (besides being fully user-induced in a pretty violent manner).
1628
1641
1629 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
1642 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
1630 Nothing major yet, but the code is simpler to read; this should
1643 Nothing major yet, but the code is simpler to read; this should
1631 make it easier to do more serious modifications in the future.
1644 make it easier to do more serious modifications in the future.
1632
1645
1633 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
1646 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
1634 which broke in .15 (thanks to a report by Ville).
1647 which broke in .15 (thanks to a report by Ville).
1635
1648
1636 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
1649 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
1637 be quite correct, I know next to nothing about unicode). This
1650 be quite correct, I know next to nothing about unicode). This
1638 will allow unicode strings to be used in prompts, amongst other
1651 will allow unicode strings to be used in prompts, amongst other
1639 cases. It also will prevent ipython from crashing when unicode
1652 cases. It also will prevent ipython from crashing when unicode
1640 shows up unexpectedly in many places. If ascii encoding fails, we
1653 shows up unexpectedly in many places. If ascii encoding fails, we
1641 assume utf_8. Currently the encoding is not a user-visible
1654 assume utf_8. Currently the encoding is not a user-visible
1642 setting, though it could be made so if there is demand for it.
1655 setting, though it could be made so if there is demand for it.
1643
1656
1644 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
1657 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
1645
1658
1646 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
1659 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
1647
1660
1648 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
1661 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
1649
1662
1650 * IPython/genutils.py: Add 2.2 compatibility here, so all other
1663 * IPython/genutils.py: Add 2.2 compatibility here, so all other
1651 code can work transparently for 2.2/2.3.
1664 code can work transparently for 2.2/2.3.
1652
1665
1653 2005-07-16 Fernando Perez <fperez@colorado.edu>
1666 2005-07-16 Fernando Perez <fperez@colorado.edu>
1654
1667
1655 * IPython/ultraTB.py (ExceptionColors): Make a global variable
1668 * IPython/ultraTB.py (ExceptionColors): Make a global variable
1656 out of the color scheme table used for coloring exception
1669 out of the color scheme table used for coloring exception
1657 tracebacks. This allows user code to add new schemes at runtime.
1670 tracebacks. This allows user code to add new schemes at runtime.
1658 This is a minimally modified version of the patch at
1671 This is a minimally modified version of the patch at
1659 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
1672 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
1660 for the contribution.
1673 for the contribution.
1661
1674
1662 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
1675 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
1663 slightly modified version of the patch in
1676 slightly modified version of the patch in
1664 http://www.scipy.net/roundup/ipython/issue34, which also allows me
1677 http://www.scipy.net/roundup/ipython/issue34, which also allows me
1665 to remove the previous try/except solution (which was costlier).
1678 to remove the previous try/except solution (which was costlier).
1666 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
1679 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
1667
1680
1668 2005-06-08 Fernando Perez <fperez@colorado.edu>
1681 2005-06-08 Fernando Perez <fperez@colorado.edu>
1669
1682
1670 * IPython/iplib.py (write/write_err): Add methods to abstract all
1683 * IPython/iplib.py (write/write_err): Add methods to abstract all
1671 I/O a bit more.
1684 I/O a bit more.
1672
1685
1673 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
1686 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
1674 warning, reported by Aric Hagberg, fix by JD Hunter.
1687 warning, reported by Aric Hagberg, fix by JD Hunter.
1675
1688
1676 2005-06-02 *** Released version 0.6.15
1689 2005-06-02 *** Released version 0.6.15
1677
1690
1678 2005-06-01 Fernando Perez <fperez@colorado.edu>
1691 2005-06-01 Fernando Perez <fperez@colorado.edu>
1679
1692
1680 * IPython/iplib.py (MagicCompleter.file_matches): Fix
1693 * IPython/iplib.py (MagicCompleter.file_matches): Fix
1681 tab-completion of filenames within open-quoted strings. Note that
1694 tab-completion of filenames within open-quoted strings. Note that
1682 this requires that in ~/.ipython/ipythonrc, users change the
1695 this requires that in ~/.ipython/ipythonrc, users change the
1683 readline delimiters configuration to read:
1696 readline delimiters configuration to read:
1684
1697
1685 readline_remove_delims -/~
1698 readline_remove_delims -/~
1686
1699
1687
1700
1688 2005-05-31 *** Released version 0.6.14
1701 2005-05-31 *** Released version 0.6.14
1689
1702
1690 2005-05-29 Fernando Perez <fperez@colorado.edu>
1703 2005-05-29 Fernando Perez <fperez@colorado.edu>
1691
1704
1692 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
1705 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
1693 with files not on the filesystem. Reported by Eliyahu Sandler
1706 with files not on the filesystem. Reported by Eliyahu Sandler
1694 <eli@gondolin.net>
1707 <eli@gondolin.net>
1695
1708
1696 2005-05-22 Fernando Perez <fperez@colorado.edu>
1709 2005-05-22 Fernando Perez <fperez@colorado.edu>
1697
1710
1698 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
1711 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
1699 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
1712 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
1700
1713
1701 2005-05-19 Fernando Perez <fperez@colorado.edu>
1714 2005-05-19 Fernando Perez <fperez@colorado.edu>
1702
1715
1703 * IPython/iplib.py (safe_execfile): close a file which could be
1716 * IPython/iplib.py (safe_execfile): close a file which could be
1704 left open (causing problems in win32, which locks open files).
1717 left open (causing problems in win32, which locks open files).
1705 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
1718 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
1706
1719
1707 2005-05-18 Fernando Perez <fperez@colorado.edu>
1720 2005-05-18 Fernando Perez <fperez@colorado.edu>
1708
1721
1709 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
1722 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
1710 keyword arguments correctly to safe_execfile().
1723 keyword arguments correctly to safe_execfile().
1711
1724
1712 2005-05-13 Fernando Perez <fperez@colorado.edu>
1725 2005-05-13 Fernando Perez <fperez@colorado.edu>
1713
1726
1714 * ipython.1: Added info about Qt to manpage, and threads warning
1727 * ipython.1: Added info about Qt to manpage, and threads warning
1715 to usage page (invoked with --help).
1728 to usage page (invoked with --help).
1716
1729
1717 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
1730 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
1718 new matcher (it goes at the end of the priority list) to do
1731 new matcher (it goes at the end of the priority list) to do
1719 tab-completion on named function arguments. Submitted by George
1732 tab-completion on named function arguments. Submitted by George
1720 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
1733 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
1721 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
1734 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
1722 for more details.
1735 for more details.
1723
1736
1724 * IPython/Magic.py (magic_run): Added new -e flag to ignore
1737 * IPython/Magic.py (magic_run): Added new -e flag to ignore
1725 SystemExit exceptions in the script being run. Thanks to a report
1738 SystemExit exceptions in the script being run. Thanks to a report
1726 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
1739 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
1727 producing very annoying behavior when running unit tests.
1740 producing very annoying behavior when running unit tests.
1728
1741
1729 2005-05-12 Fernando Perez <fperez@colorado.edu>
1742 2005-05-12 Fernando Perez <fperez@colorado.edu>
1730
1743
1731 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
1744 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
1732 which I'd broken (again) due to a changed regexp. In the process,
1745 which I'd broken (again) due to a changed regexp. In the process,
1733 added ';' as an escape to auto-quote the whole line without
1746 added ';' as an escape to auto-quote the whole line without
1734 splitting its arguments. Thanks to a report by Jerry McRae
1747 splitting its arguments. Thanks to a report by Jerry McRae
1735 <qrs0xyc02-AT-sneakemail.com>.
1748 <qrs0xyc02-AT-sneakemail.com>.
1736
1749
1737 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
1750 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
1738 possible crashes caused by a TokenError. Reported by Ed Schofield
1751 possible crashes caused by a TokenError. Reported by Ed Schofield
1739 <schofield-AT-ftw.at>.
1752 <schofield-AT-ftw.at>.
1740
1753
1741 2005-05-06 Fernando Perez <fperez@colorado.edu>
1754 2005-05-06 Fernando Perez <fperez@colorado.edu>
1742
1755
1743 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
1756 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
1744
1757
1745 2005-04-29 Fernando Perez <fperez@colorado.edu>
1758 2005-04-29 Fernando Perez <fperez@colorado.edu>
1746
1759
1747 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
1760 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
1748 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
1761 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
1749 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
1762 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
1750 which provides support for Qt interactive usage (similar to the
1763 which provides support for Qt interactive usage (similar to the
1751 existing one for WX and GTK). This had been often requested.
1764 existing one for WX and GTK). This had been often requested.
1752
1765
1753 2005-04-14 *** Released version 0.6.13
1766 2005-04-14 *** Released version 0.6.13
1754
1767
1755 2005-04-08 Fernando Perez <fperez@colorado.edu>
1768 2005-04-08 Fernando Perez <fperez@colorado.edu>
1756
1769
1757 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
1770 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
1758 from _ofind, which gets called on almost every input line. Now,
1771 from _ofind, which gets called on almost every input line. Now,
1759 we only try to get docstrings if they are actually going to be
1772 we only try to get docstrings if they are actually going to be
1760 used (the overhead of fetching unnecessary docstrings can be
1773 used (the overhead of fetching unnecessary docstrings can be
1761 noticeable for certain objects, such as Pyro proxies).
1774 noticeable for certain objects, such as Pyro proxies).
1762
1775
1763 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
1776 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
1764 for completers. For some reason I had been passing them the state
1777 for completers. For some reason I had been passing them the state
1765 variable, which completers never actually need, and was in
1778 variable, which completers never actually need, and was in
1766 conflict with the rlcompleter API. Custom completers ONLY need to
1779 conflict with the rlcompleter API. Custom completers ONLY need to
1767 take the text parameter.
1780 take the text parameter.
1768
1781
1769 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
1782 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
1770 work correctly in pysh. I've also moved all the logic which used
1783 work correctly in pysh. I've also moved all the logic which used
1771 to be in pysh.py here, which will prevent problems with future
1784 to be in pysh.py here, which will prevent problems with future
1772 upgrades. However, this time I must warn users to update their
1785 upgrades. However, this time I must warn users to update their
1773 pysh profile to include the line
1786 pysh profile to include the line
1774
1787
1775 import_all IPython.Extensions.InterpreterExec
1788 import_all IPython.Extensions.InterpreterExec
1776
1789
1777 because otherwise things won't work for them. They MUST also
1790 because otherwise things won't work for them. They MUST also
1778 delete pysh.py and the line
1791 delete pysh.py and the line
1779
1792
1780 execfile pysh.py
1793 execfile pysh.py
1781
1794
1782 from their ipythonrc-pysh.
1795 from their ipythonrc-pysh.
1783
1796
1784 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
1797 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
1785 robust in the face of objects whose dir() returns non-strings
1798 robust in the face of objects whose dir() returns non-strings
1786 (which it shouldn't, but some broken libs like ITK do). Thanks to
1799 (which it shouldn't, but some broken libs like ITK do). Thanks to
1787 a patch by John Hunter (implemented differently, though). Also
1800 a patch by John Hunter (implemented differently, though). Also
1788 minor improvements by using .extend instead of + on lists.
1801 minor improvements by using .extend instead of + on lists.
1789
1802
1790 * pysh.py:
1803 * pysh.py:
1791
1804
1792 2005-04-06 Fernando Perez <fperez@colorado.edu>
1805 2005-04-06 Fernando Perez <fperez@colorado.edu>
1793
1806
1794 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
1807 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
1795 by default, so that all users benefit from it. Those who don't
1808 by default, so that all users benefit from it. Those who don't
1796 want it can still turn it off.
1809 want it can still turn it off.
1797
1810
1798 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
1811 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
1799 config file, I'd forgotten about this, so users were getting it
1812 config file, I'd forgotten about this, so users were getting it
1800 off by default.
1813 off by default.
1801
1814
1802 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
1815 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
1803 consistency. Now magics can be called in multiline statements,
1816 consistency. Now magics can be called in multiline statements,
1804 and python variables can be expanded in magic calls via $var.
1817 and python variables can be expanded in magic calls via $var.
1805 This makes the magic system behave just like aliases or !system
1818 This makes the magic system behave just like aliases or !system
1806 calls.
1819 calls.
1807
1820
1808 2005-03-28 Fernando Perez <fperez@colorado.edu>
1821 2005-03-28 Fernando Perez <fperez@colorado.edu>
1809
1822
1810 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
1823 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
1811 expensive string additions for building command. Add support for
1824 expensive string additions for building command. Add support for
1812 trailing ';' when autocall is used.
1825 trailing ';' when autocall is used.
1813
1826
1814 2005-03-26 Fernando Perez <fperez@colorado.edu>
1827 2005-03-26 Fernando Perez <fperez@colorado.edu>
1815
1828
1816 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
1829 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
1817 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
1830 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
1818 ipython.el robust against prompts with any number of spaces
1831 ipython.el robust against prompts with any number of spaces
1819 (including 0) after the ':' character.
1832 (including 0) after the ':' character.
1820
1833
1821 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
1834 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
1822 continuation prompt, which misled users to think the line was
1835 continuation prompt, which misled users to think the line was
1823 already indented. Closes debian Bug#300847, reported to me by
1836 already indented. Closes debian Bug#300847, reported to me by
1824 Norbert Tretkowski <tretkowski-AT-inittab.de>.
1837 Norbert Tretkowski <tretkowski-AT-inittab.de>.
1825
1838
1826 2005-03-23 Fernando Perez <fperez@colorado.edu>
1839 2005-03-23 Fernando Perez <fperez@colorado.edu>
1827
1840
1828 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
1841 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
1829 properly aligned if they have embedded newlines.
1842 properly aligned if they have embedded newlines.
1830
1843
1831 * IPython/iplib.py (runlines): Add a public method to expose
1844 * IPython/iplib.py (runlines): Add a public method to expose
1832 IPython's code execution machinery, so that users can run strings
1845 IPython's code execution machinery, so that users can run strings
1833 as if they had been typed at the prompt interactively.
1846 as if they had been typed at the prompt interactively.
1834 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
1847 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
1835 methods which can call the system shell, but with python variable
1848 methods which can call the system shell, but with python variable
1836 expansion. The three such methods are: __IPYTHON__.system,
1849 expansion. The three such methods are: __IPYTHON__.system,
1837 .getoutput and .getoutputerror. These need to be documented in a
1850 .getoutput and .getoutputerror. These need to be documented in a
1838 'public API' section (to be written) of the manual.
1851 'public API' section (to be written) of the manual.
1839
1852
1840 2005-03-20 Fernando Perez <fperez@colorado.edu>
1853 2005-03-20 Fernando Perez <fperez@colorado.edu>
1841
1854
1842 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
1855 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
1843 for custom exception handling. This is quite powerful, and it
1856 for custom exception handling. This is quite powerful, and it
1844 allows for user-installable exception handlers which can trap
1857 allows for user-installable exception handlers which can trap
1845 custom exceptions at runtime and treat them separately from
1858 custom exceptions at runtime and treat them separately from
1846 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
1859 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
1847 Mantegazza <mantegazza-AT-ill.fr>.
1860 Mantegazza <mantegazza-AT-ill.fr>.
1848 (InteractiveShell.set_custom_completer): public API function to
1861 (InteractiveShell.set_custom_completer): public API function to
1849 add new completers at runtime.
1862 add new completers at runtime.
1850
1863
1851 2005-03-19 Fernando Perez <fperez@colorado.edu>
1864 2005-03-19 Fernando Perez <fperez@colorado.edu>
1852
1865
1853 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1866 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1854 allow objects which provide their docstrings via non-standard
1867 allow objects which provide their docstrings via non-standard
1855 mechanisms (like Pyro proxies) to still be inspected by ipython's
1868 mechanisms (like Pyro proxies) to still be inspected by ipython's
1856 ? system.
1869 ? system.
1857
1870
1858 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1871 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1859 automatic capture system. I tried quite hard to make it work
1872 automatic capture system. I tried quite hard to make it work
1860 reliably, and simply failed. I tried many combinations with the
1873 reliably, and simply failed. I tried many combinations with the
1861 subprocess module, but eventually nothing worked in all needed
1874 subprocess module, but eventually nothing worked in all needed
1862 cases (not blocking stdin for the child, duplicating stdout
1875 cases (not blocking stdin for the child, duplicating stdout
1863 without blocking, etc). The new %sc/%sx still do capture to these
1876 without blocking, etc). The new %sc/%sx still do capture to these
1864 magical list/string objects which make shell use much more
1877 magical list/string objects which make shell use much more
1865 conveninent, so not all is lost.
1878 conveninent, so not all is lost.
1866
1879
1867 XXX - FIX MANUAL for the change above!
1880 XXX - FIX MANUAL for the change above!
1868
1881
1869 (runsource): I copied code.py's runsource() into ipython to modify
1882 (runsource): I copied code.py's runsource() into ipython to modify
1870 it a bit. Now the code object and source to be executed are
1883 it a bit. Now the code object and source to be executed are
1871 stored in ipython. This makes this info accessible to third-party
1884 stored in ipython. This makes this info accessible to third-party
1872 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
1885 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
1873 Mantegazza <mantegazza-AT-ill.fr>.
1886 Mantegazza <mantegazza-AT-ill.fr>.
1874
1887
1875 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1888 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1876 history-search via readline (like C-p/C-n). I'd wanted this for a
1889 history-search via readline (like C-p/C-n). I'd wanted this for a
1877 long time, but only recently found out how to do it. For users
1890 long time, but only recently found out how to do it. For users
1878 who already have their ipythonrc files made and want this, just
1891 who already have their ipythonrc files made and want this, just
1879 add:
1892 add:
1880
1893
1881 readline_parse_and_bind "\e[A": history-search-backward
1894 readline_parse_and_bind "\e[A": history-search-backward
1882 readline_parse_and_bind "\e[B": history-search-forward
1895 readline_parse_and_bind "\e[B": history-search-forward
1883
1896
1884 2005-03-18 Fernando Perez <fperez@colorado.edu>
1897 2005-03-18 Fernando Perez <fperez@colorado.edu>
1885
1898
1886 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1899 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1887 LSString and SList classes which allow transparent conversions
1900 LSString and SList classes which allow transparent conversions
1888 between list mode and whitespace-separated string.
1901 between list mode and whitespace-separated string.
1889 (magic_r): Fix recursion problem in %r.
1902 (magic_r): Fix recursion problem in %r.
1890
1903
1891 * IPython/genutils.py (LSString): New class to be used for
1904 * IPython/genutils.py (LSString): New class to be used for
1892 automatic storage of the results of all alias/system calls in _o
1905 automatic storage of the results of all alias/system calls in _o
1893 and _e (stdout/err). These provide a .l/.list attribute which
1906 and _e (stdout/err). These provide a .l/.list attribute which
1894 does automatic splitting on newlines. This means that for most
1907 does automatic splitting on newlines. This means that for most
1895 uses, you'll never need to do capturing of output with %sc/%sx
1908 uses, you'll never need to do capturing of output with %sc/%sx
1896 anymore, since ipython keeps this always done for you. Note that
1909 anymore, since ipython keeps this always done for you. Note that
1897 only the LAST results are stored, the _o/e variables are
1910 only the LAST results are stored, the _o/e variables are
1898 overwritten on each call. If you need to save their contents
1911 overwritten on each call. If you need to save their contents
1899 further, simply bind them to any other name.
1912 further, simply bind them to any other name.
1900
1913
1901 2005-03-17 Fernando Perez <fperez@colorado.edu>
1914 2005-03-17 Fernando Perez <fperez@colorado.edu>
1902
1915
1903 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1916 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1904 prompt namespace handling.
1917 prompt namespace handling.
1905
1918
1906 2005-03-16 Fernando Perez <fperez@colorado.edu>
1919 2005-03-16 Fernando Perez <fperez@colorado.edu>
1907
1920
1908 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1921 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1909 classic prompts to be '>>> ' (final space was missing, and it
1922 classic prompts to be '>>> ' (final space was missing, and it
1910 trips the emacs python mode).
1923 trips the emacs python mode).
1911 (BasePrompt.__str__): Added safe support for dynamic prompt
1924 (BasePrompt.__str__): Added safe support for dynamic prompt
1912 strings. Now you can set your prompt string to be '$x', and the
1925 strings. Now you can set your prompt string to be '$x', and the
1913 value of x will be printed from your interactive namespace. The
1926 value of x will be printed from your interactive namespace. The
1914 interpolation syntax includes the full Itpl support, so
1927 interpolation syntax includes the full Itpl support, so
1915 ${foo()+x+bar()} is a valid prompt string now, and the function
1928 ${foo()+x+bar()} is a valid prompt string now, and the function
1916 calls will be made at runtime.
1929 calls will be made at runtime.
1917
1930
1918 2005-03-15 Fernando Perez <fperez@colorado.edu>
1931 2005-03-15 Fernando Perez <fperez@colorado.edu>
1919
1932
1920 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1933 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1921 avoid name clashes in pylab. %hist still works, it just forwards
1934 avoid name clashes in pylab. %hist still works, it just forwards
1922 the call to %history.
1935 the call to %history.
1923
1936
1924 2005-03-02 *** Released version 0.6.12
1937 2005-03-02 *** Released version 0.6.12
1925
1938
1926 2005-03-02 Fernando Perez <fperez@colorado.edu>
1939 2005-03-02 Fernando Perez <fperez@colorado.edu>
1927
1940
1928 * IPython/iplib.py (handle_magic): log magic calls properly as
1941 * IPython/iplib.py (handle_magic): log magic calls properly as
1929 ipmagic() function calls.
1942 ipmagic() function calls.
1930
1943
1931 * IPython/Magic.py (magic_time): Improved %time to support
1944 * IPython/Magic.py (magic_time): Improved %time to support
1932 statements and provide wall-clock as well as CPU time.
1945 statements and provide wall-clock as well as CPU time.
1933
1946
1934 2005-02-27 Fernando Perez <fperez@colorado.edu>
1947 2005-02-27 Fernando Perez <fperez@colorado.edu>
1935
1948
1936 * IPython/hooks.py: New hooks module, to expose user-modifiable
1949 * IPython/hooks.py: New hooks module, to expose user-modifiable
1937 IPython functionality in a clean manner. For now only the editor
1950 IPython functionality in a clean manner. For now only the editor
1938 hook is actually written, and other thigns which I intend to turn
1951 hook is actually written, and other thigns which I intend to turn
1939 into proper hooks aren't yet there. The display and prefilter
1952 into proper hooks aren't yet there. The display and prefilter
1940 stuff, for example, should be hooks. But at least now the
1953 stuff, for example, should be hooks. But at least now the
1941 framework is in place, and the rest can be moved here with more
1954 framework is in place, and the rest can be moved here with more
1942 time later. IPython had had a .hooks variable for a long time for
1955 time later. IPython had had a .hooks variable for a long time for
1943 this purpose, but I'd never actually used it for anything.
1956 this purpose, but I'd never actually used it for anything.
1944
1957
1945 2005-02-26 Fernando Perez <fperez@colorado.edu>
1958 2005-02-26 Fernando Perez <fperez@colorado.edu>
1946
1959
1947 * IPython/ipmaker.py (make_IPython): make the default ipython
1960 * IPython/ipmaker.py (make_IPython): make the default ipython
1948 directory be called _ipython under win32, to follow more the
1961 directory be called _ipython under win32, to follow more the
1949 naming peculiarities of that platform (where buggy software like
1962 naming peculiarities of that platform (where buggy software like
1950 Visual Sourcesafe breaks with .named directories). Reported by
1963 Visual Sourcesafe breaks with .named directories). Reported by
1951 Ville Vainio.
1964 Ville Vainio.
1952
1965
1953 2005-02-23 Fernando Perez <fperez@colorado.edu>
1966 2005-02-23 Fernando Perez <fperez@colorado.edu>
1954
1967
1955 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1968 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1956 auto_aliases for win32 which were causing problems. Users can
1969 auto_aliases for win32 which were causing problems. Users can
1957 define the ones they personally like.
1970 define the ones they personally like.
1958
1971
1959 2005-02-21 Fernando Perez <fperez@colorado.edu>
1972 2005-02-21 Fernando Perez <fperez@colorado.edu>
1960
1973
1961 * IPython/Magic.py (magic_time): new magic to time execution of
1974 * IPython/Magic.py (magic_time): new magic to time execution of
1962 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1975 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1963
1976
1964 2005-02-19 Fernando Perez <fperez@colorado.edu>
1977 2005-02-19 Fernando Perez <fperez@colorado.edu>
1965
1978
1966 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1979 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1967 into keys (for prompts, for example).
1980 into keys (for prompts, for example).
1968
1981
1969 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1982 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1970 prompts in case users want them. This introduces a small behavior
1983 prompts in case users want them. This introduces a small behavior
1971 change: ipython does not automatically add a space to all prompts
1984 change: ipython does not automatically add a space to all prompts
1972 anymore. To get the old prompts with a space, users should add it
1985 anymore. To get the old prompts with a space, users should add it
1973 manually to their ipythonrc file, so for example prompt_in1 should
1986 manually to their ipythonrc file, so for example prompt_in1 should
1974 now read 'In [\#]: ' instead of 'In [\#]:'.
1987 now read 'In [\#]: ' instead of 'In [\#]:'.
1975 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1988 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1976 file) to control left-padding of secondary prompts.
1989 file) to control left-padding of secondary prompts.
1977
1990
1978 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1991 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1979 the profiler can't be imported. Fix for Debian, which removed
1992 the profiler can't be imported. Fix for Debian, which removed
1980 profile.py because of License issues. I applied a slightly
1993 profile.py because of License issues. I applied a slightly
1981 modified version of the original Debian patch at
1994 modified version of the original Debian patch at
1982 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1995 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1983
1996
1984 2005-02-17 Fernando Perez <fperez@colorado.edu>
1997 2005-02-17 Fernando Perez <fperez@colorado.edu>
1985
1998
1986 * IPython/genutils.py (native_line_ends): Fix bug which would
1999 * IPython/genutils.py (native_line_ends): Fix bug which would
1987 cause improper line-ends under win32 b/c I was not opening files
2000 cause improper line-ends under win32 b/c I was not opening files
1988 in binary mode. Bug report and fix thanks to Ville.
2001 in binary mode. Bug report and fix thanks to Ville.
1989
2002
1990 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
2003 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1991 trying to catch spurious foo[1] autocalls. My fix actually broke
2004 trying to catch spurious foo[1] autocalls. My fix actually broke
1992 ',/' autoquote/call with explicit escape (bad regexp).
2005 ',/' autoquote/call with explicit escape (bad regexp).
1993
2006
1994 2005-02-15 *** Released version 0.6.11
2007 2005-02-15 *** Released version 0.6.11
1995
2008
1996 2005-02-14 Fernando Perez <fperez@colorado.edu>
2009 2005-02-14 Fernando Perez <fperez@colorado.edu>
1997
2010
1998 * IPython/background_jobs.py: New background job management
2011 * IPython/background_jobs.py: New background job management
1999 subsystem. This is implemented via a new set of classes, and
2012 subsystem. This is implemented via a new set of classes, and
2000 IPython now provides a builtin 'jobs' object for background job
2013 IPython now provides a builtin 'jobs' object for background job
2001 execution. A convenience %bg magic serves as a lightweight
2014 execution. A convenience %bg magic serves as a lightweight
2002 frontend for starting the more common type of calls. This was
2015 frontend for starting the more common type of calls. This was
2003 inspired by discussions with B. Granger and the BackgroundCommand
2016 inspired by discussions with B. Granger and the BackgroundCommand
2004 class described in the book Python Scripting for Computational
2017 class described in the book Python Scripting for Computational
2005 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
2018 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
2006 (although ultimately no code from this text was used, as IPython's
2019 (although ultimately no code from this text was used, as IPython's
2007 system is a separate implementation).
2020 system is a separate implementation).
2008
2021
2009 * IPython/iplib.py (MagicCompleter.python_matches): add new option
2022 * IPython/iplib.py (MagicCompleter.python_matches): add new option
2010 to control the completion of single/double underscore names
2023 to control the completion of single/double underscore names
2011 separately. As documented in the example ipytonrc file, the
2024 separately. As documented in the example ipytonrc file, the
2012 readline_omit__names variable can now be set to 2, to omit even
2025 readline_omit__names variable can now be set to 2, to omit even
2013 single underscore names. Thanks to a patch by Brian Wong
2026 single underscore names. Thanks to a patch by Brian Wong
2014 <BrianWong-AT-AirgoNetworks.Com>.
2027 <BrianWong-AT-AirgoNetworks.Com>.
2015 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
2028 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
2016 be autocalled as foo([1]) if foo were callable. A problem for
2029 be autocalled as foo([1]) if foo were callable. A problem for
2017 things which are both callable and implement __getitem__.
2030 things which are both callable and implement __getitem__.
2018 (init_readline): Fix autoindentation for win32. Thanks to a patch
2031 (init_readline): Fix autoindentation for win32. Thanks to a patch
2019 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
2032 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
2020
2033
2021 2005-02-12 Fernando Perez <fperez@colorado.edu>
2034 2005-02-12 Fernando Perez <fperez@colorado.edu>
2022
2035
2023 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
2036 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
2024 which I had written long ago to sort out user error messages which
2037 which I had written long ago to sort out user error messages which
2025 may occur during startup. This seemed like a good idea initially,
2038 may occur during startup. This seemed like a good idea initially,
2026 but it has proven a disaster in retrospect. I don't want to
2039 but it has proven a disaster in retrospect. I don't want to
2027 change much code for now, so my fix is to set the internal 'debug'
2040 change much code for now, so my fix is to set the internal 'debug'
2028 flag to true everywhere, whose only job was precisely to control
2041 flag to true everywhere, whose only job was precisely to control
2029 this subsystem. This closes issue 28 (as well as avoiding all
2042 this subsystem. This closes issue 28 (as well as avoiding all
2030 sorts of strange hangups which occur from time to time).
2043 sorts of strange hangups which occur from time to time).
2031
2044
2032 2005-02-07 Fernando Perez <fperez@colorado.edu>
2045 2005-02-07 Fernando Perez <fperez@colorado.edu>
2033
2046
2034 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
2047 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
2035 previous call produced a syntax error.
2048 previous call produced a syntax error.
2036
2049
2037 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
2050 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
2038 classes without constructor.
2051 classes without constructor.
2039
2052
2040 2005-02-06 Fernando Perez <fperez@colorado.edu>
2053 2005-02-06 Fernando Perez <fperez@colorado.edu>
2041
2054
2042 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
2055 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
2043 completions with the results of each matcher, so we return results
2056 completions with the results of each matcher, so we return results
2044 to the user from all namespaces. This breaks with ipython
2057 to the user from all namespaces. This breaks with ipython
2045 tradition, but I think it's a nicer behavior. Now you get all
2058 tradition, but I think it's a nicer behavior. Now you get all
2046 possible completions listed, from all possible namespaces (python,
2059 possible completions listed, from all possible namespaces (python,
2047 filesystem, magics...) After a request by John Hunter
2060 filesystem, magics...) After a request by John Hunter
2048 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2061 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2049
2062
2050 2005-02-05 Fernando Perez <fperez@colorado.edu>
2063 2005-02-05 Fernando Perez <fperez@colorado.edu>
2051
2064
2052 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
2065 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
2053 the call had quote characters in it (the quotes were stripped).
2066 the call had quote characters in it (the quotes were stripped).
2054
2067
2055 2005-01-31 Fernando Perez <fperez@colorado.edu>
2068 2005-01-31 Fernando Perez <fperez@colorado.edu>
2056
2069
2057 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
2070 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
2058 Itpl.itpl() to make the code more robust against psyco
2071 Itpl.itpl() to make the code more robust against psyco
2059 optimizations.
2072 optimizations.
2060
2073
2061 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
2074 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
2062 of causing an exception. Quicker, cleaner.
2075 of causing an exception. Quicker, cleaner.
2063
2076
2064 2005-01-28 Fernando Perez <fperez@colorado.edu>
2077 2005-01-28 Fernando Perez <fperez@colorado.edu>
2065
2078
2066 * scripts/ipython_win_post_install.py (install): hardcode
2079 * scripts/ipython_win_post_install.py (install): hardcode
2067 sys.prefix+'python.exe' as the executable path. It turns out that
2080 sys.prefix+'python.exe' as the executable path. It turns out that
2068 during the post-installation run, sys.executable resolves to the
2081 during the post-installation run, sys.executable resolves to the
2069 name of the binary installer! I should report this as a distutils
2082 name of the binary installer! I should report this as a distutils
2070 bug, I think. I updated the .10 release with this tiny fix, to
2083 bug, I think. I updated the .10 release with this tiny fix, to
2071 avoid annoying the lists further.
2084 avoid annoying the lists further.
2072
2085
2073 2005-01-27 *** Released version 0.6.10
2086 2005-01-27 *** Released version 0.6.10
2074
2087
2075 2005-01-27 Fernando Perez <fperez@colorado.edu>
2088 2005-01-27 Fernando Perez <fperez@colorado.edu>
2076
2089
2077 * IPython/numutils.py (norm): Added 'inf' as optional name for
2090 * IPython/numutils.py (norm): Added 'inf' as optional name for
2078 L-infinity norm, included references to mathworld.com for vector
2091 L-infinity norm, included references to mathworld.com for vector
2079 norm definitions.
2092 norm definitions.
2080 (amin/amax): added amin/amax for array min/max. Similar to what
2093 (amin/amax): added amin/amax for array min/max. Similar to what
2081 pylab ships with after the recent reorganization of names.
2094 pylab ships with after the recent reorganization of names.
2082 (spike/spike_odd): removed deprecated spike/spike_odd functions.
2095 (spike/spike_odd): removed deprecated spike/spike_odd functions.
2083
2096
2084 * ipython.el: committed Alex's recent fixes and improvements.
2097 * ipython.el: committed Alex's recent fixes and improvements.
2085 Tested with python-mode from CVS, and it looks excellent. Since
2098 Tested with python-mode from CVS, and it looks excellent. Since
2086 python-mode hasn't released anything in a while, I'm temporarily
2099 python-mode hasn't released anything in a while, I'm temporarily
2087 putting a copy of today's CVS (v 4.70) of python-mode in:
2100 putting a copy of today's CVS (v 4.70) of python-mode in:
2088 http://ipython.scipy.org/tmp/python-mode.el
2101 http://ipython.scipy.org/tmp/python-mode.el
2089
2102
2090 * scripts/ipython_win_post_install.py (install): Win32 fix to use
2103 * scripts/ipython_win_post_install.py (install): Win32 fix to use
2091 sys.executable for the executable name, instead of assuming it's
2104 sys.executable for the executable name, instead of assuming it's
2092 called 'python.exe' (the post-installer would have produced broken
2105 called 'python.exe' (the post-installer would have produced broken
2093 setups on systems with a differently named python binary).
2106 setups on systems with a differently named python binary).
2094
2107
2095 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
2108 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
2096 references to os.linesep, to make the code more
2109 references to os.linesep, to make the code more
2097 platform-independent. This is also part of the win32 coloring
2110 platform-independent. This is also part of the win32 coloring
2098 fixes.
2111 fixes.
2099
2112
2100 * IPython/genutils.py (page_dumb): Remove attempts to chop long
2113 * IPython/genutils.py (page_dumb): Remove attempts to chop long
2101 lines, which actually cause coloring bugs because the length of
2114 lines, which actually cause coloring bugs because the length of
2102 the line is very difficult to correctly compute with embedded
2115 the line is very difficult to correctly compute with embedded
2103 escapes. This was the source of all the coloring problems under
2116 escapes. This was the source of all the coloring problems under
2104 Win32. I think that _finally_, Win32 users have a properly
2117 Win32. I think that _finally_, Win32 users have a properly
2105 working ipython in all respects. This would never have happened
2118 working ipython in all respects. This would never have happened
2106 if not for Gary Bishop and Viktor Ransmayr's great help and work.
2119 if not for Gary Bishop and Viktor Ransmayr's great help and work.
2107
2120
2108 2005-01-26 *** Released version 0.6.9
2121 2005-01-26 *** Released version 0.6.9
2109
2122
2110 2005-01-25 Fernando Perez <fperez@colorado.edu>
2123 2005-01-25 Fernando Perez <fperez@colorado.edu>
2111
2124
2112 * setup.py: finally, we have a true Windows installer, thanks to
2125 * setup.py: finally, we have a true Windows installer, thanks to
2113 the excellent work of Viktor Ransmayr
2126 the excellent work of Viktor Ransmayr
2114 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
2127 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
2115 Windows users. The setup routine is quite a bit cleaner thanks to
2128 Windows users. The setup routine is quite a bit cleaner thanks to
2116 this, and the post-install script uses the proper functions to
2129 this, and the post-install script uses the proper functions to
2117 allow a clean de-installation using the standard Windows Control
2130 allow a clean de-installation using the standard Windows Control
2118 Panel.
2131 Panel.
2119
2132
2120 * IPython/genutils.py (get_home_dir): changed to use the $HOME
2133 * IPython/genutils.py (get_home_dir): changed to use the $HOME
2121 environment variable under all OSes (including win32) if
2134 environment variable under all OSes (including win32) if
2122 available. This will give consistency to win32 users who have set
2135 available. This will give consistency to win32 users who have set
2123 this variable for any reason. If os.environ['HOME'] fails, the
2136 this variable for any reason. If os.environ['HOME'] fails, the
2124 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
2137 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
2125
2138
2126 2005-01-24 Fernando Perez <fperez@colorado.edu>
2139 2005-01-24 Fernando Perez <fperez@colorado.edu>
2127
2140
2128 * IPython/numutils.py (empty_like): add empty_like(), similar to
2141 * IPython/numutils.py (empty_like): add empty_like(), similar to
2129 zeros_like() but taking advantage of the new empty() Numeric routine.
2142 zeros_like() but taking advantage of the new empty() Numeric routine.
2130
2143
2131 2005-01-23 *** Released version 0.6.8
2144 2005-01-23 *** Released version 0.6.8
2132
2145
2133 2005-01-22 Fernando Perez <fperez@colorado.edu>
2146 2005-01-22 Fernando Perez <fperez@colorado.edu>
2134
2147
2135 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
2148 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
2136 automatic show() calls. After discussing things with JDH, it
2149 automatic show() calls. After discussing things with JDH, it
2137 turns out there are too many corner cases where this can go wrong.
2150 turns out there are too many corner cases where this can go wrong.
2138 It's best not to try to be 'too smart', and simply have ipython
2151 It's best not to try to be 'too smart', and simply have ipython
2139 reproduce as much as possible the default behavior of a normal
2152 reproduce as much as possible the default behavior of a normal
2140 python shell.
2153 python shell.
2141
2154
2142 * IPython/iplib.py (InteractiveShell.__init__): Modified the
2155 * IPython/iplib.py (InteractiveShell.__init__): Modified the
2143 line-splitting regexp and _prefilter() to avoid calling getattr()
2156 line-splitting regexp and _prefilter() to avoid calling getattr()
2144 on assignments. This closes
2157 on assignments. This closes
2145 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
2158 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
2146 readline uses getattr(), so a simple <TAB> keypress is still
2159 readline uses getattr(), so a simple <TAB> keypress is still
2147 enough to trigger getattr() calls on an object.
2160 enough to trigger getattr() calls on an object.
2148
2161
2149 2005-01-21 Fernando Perez <fperez@colorado.edu>
2162 2005-01-21 Fernando Perez <fperez@colorado.edu>
2150
2163
2151 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
2164 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
2152 docstring under pylab so it doesn't mask the original.
2165 docstring under pylab so it doesn't mask the original.
2153
2166
2154 2005-01-21 *** Released version 0.6.7
2167 2005-01-21 *** Released version 0.6.7
2155
2168
2156 2005-01-21 Fernando Perez <fperez@colorado.edu>
2169 2005-01-21 Fernando Perez <fperez@colorado.edu>
2157
2170
2158 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
2171 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
2159 signal handling for win32 users in multithreaded mode.
2172 signal handling for win32 users in multithreaded mode.
2160
2173
2161 2005-01-17 Fernando Perez <fperez@colorado.edu>
2174 2005-01-17 Fernando Perez <fperez@colorado.edu>
2162
2175
2163 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
2176 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
2164 instances with no __init__. After a crash report by Norbert Nemec
2177 instances with no __init__. After a crash report by Norbert Nemec
2165 <Norbert-AT-nemec-online.de>.
2178 <Norbert-AT-nemec-online.de>.
2166
2179
2167 2005-01-14 Fernando Perez <fperez@colorado.edu>
2180 2005-01-14 Fernando Perez <fperez@colorado.edu>
2168
2181
2169 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
2182 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
2170 names for verbose exceptions, when multiple dotted names and the
2183 names for verbose exceptions, when multiple dotted names and the
2171 'parent' object were present on the same line.
2184 'parent' object were present on the same line.
2172
2185
2173 2005-01-11 Fernando Perez <fperez@colorado.edu>
2186 2005-01-11 Fernando Perez <fperez@colorado.edu>
2174
2187
2175 * IPython/genutils.py (flag_calls): new utility to trap and flag
2188 * IPython/genutils.py (flag_calls): new utility to trap and flag
2176 calls in functions. I need it to clean up matplotlib support.
2189 calls in functions. I need it to clean up matplotlib support.
2177 Also removed some deprecated code in genutils.
2190 Also removed some deprecated code in genutils.
2178
2191
2179 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
2192 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
2180 that matplotlib scripts called with %run, which don't call show()
2193 that matplotlib scripts called with %run, which don't call show()
2181 themselves, still have their plotting windows open.
2194 themselves, still have their plotting windows open.
2182
2195
2183 2005-01-05 Fernando Perez <fperez@colorado.edu>
2196 2005-01-05 Fernando Perez <fperez@colorado.edu>
2184
2197
2185 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
2198 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
2186 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
2199 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
2187
2200
2188 2004-12-19 Fernando Perez <fperez@colorado.edu>
2201 2004-12-19 Fernando Perez <fperez@colorado.edu>
2189
2202
2190 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
2203 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
2191 parent_runcode, which was an eyesore. The same result can be
2204 parent_runcode, which was an eyesore. The same result can be
2192 obtained with Python's regular superclass mechanisms.
2205 obtained with Python's regular superclass mechanisms.
2193
2206
2194 2004-12-17 Fernando Perez <fperez@colorado.edu>
2207 2004-12-17 Fernando Perez <fperez@colorado.edu>
2195
2208
2196 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
2209 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
2197 reported by Prabhu.
2210 reported by Prabhu.
2198 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
2211 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
2199 sys.stderr) instead of explicitly calling sys.stderr. This helps
2212 sys.stderr) instead of explicitly calling sys.stderr. This helps
2200 maintain our I/O abstractions clean, for future GUI embeddings.
2213 maintain our I/O abstractions clean, for future GUI embeddings.
2201
2214
2202 * IPython/genutils.py (info): added new utility for sys.stderr
2215 * IPython/genutils.py (info): added new utility for sys.stderr
2203 unified info message handling (thin wrapper around warn()).
2216 unified info message handling (thin wrapper around warn()).
2204
2217
2205 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
2218 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
2206 composite (dotted) names on verbose exceptions.
2219 composite (dotted) names on verbose exceptions.
2207 (VerboseTB.nullrepr): harden against another kind of errors which
2220 (VerboseTB.nullrepr): harden against another kind of errors which
2208 Python's inspect module can trigger, and which were crashing
2221 Python's inspect module can trigger, and which were crashing
2209 IPython. Thanks to a report by Marco Lombardi
2222 IPython. Thanks to a report by Marco Lombardi
2210 <mlombard-AT-ma010192.hq.eso.org>.
2223 <mlombard-AT-ma010192.hq.eso.org>.
2211
2224
2212 2004-12-13 *** Released version 0.6.6
2225 2004-12-13 *** Released version 0.6.6
2213
2226
2214 2004-12-12 Fernando Perez <fperez@colorado.edu>
2227 2004-12-12 Fernando Perez <fperez@colorado.edu>
2215
2228
2216 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
2229 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
2217 generated by pygtk upon initialization if it was built without
2230 generated by pygtk upon initialization if it was built without
2218 threads (for matplotlib users). After a crash reported by
2231 threads (for matplotlib users). After a crash reported by
2219 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
2232 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
2220
2233
2221 * IPython/ipmaker.py (make_IPython): fix small bug in the
2234 * IPython/ipmaker.py (make_IPython): fix small bug in the
2222 import_some parameter for multiple imports.
2235 import_some parameter for multiple imports.
2223
2236
2224 * IPython/iplib.py (ipmagic): simplified the interface of
2237 * IPython/iplib.py (ipmagic): simplified the interface of
2225 ipmagic() to take a single string argument, just as it would be
2238 ipmagic() to take a single string argument, just as it would be
2226 typed at the IPython cmd line.
2239 typed at the IPython cmd line.
2227 (ipalias): Added new ipalias() with an interface identical to
2240 (ipalias): Added new ipalias() with an interface identical to
2228 ipmagic(). This completes exposing a pure python interface to the
2241 ipmagic(). This completes exposing a pure python interface to the
2229 alias and magic system, which can be used in loops or more complex
2242 alias and magic system, which can be used in loops or more complex
2230 code where IPython's automatic line mangling is not active.
2243 code where IPython's automatic line mangling is not active.
2231
2244
2232 * IPython/genutils.py (timing): changed interface of timing to
2245 * IPython/genutils.py (timing): changed interface of timing to
2233 simply run code once, which is the most common case. timings()
2246 simply run code once, which is the most common case. timings()
2234 remains unchanged, for the cases where you want multiple runs.
2247 remains unchanged, for the cases where you want multiple runs.
2235
2248
2236 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
2249 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
2237 bug where Python2.2 crashes with exec'ing code which does not end
2250 bug where Python2.2 crashes with exec'ing code which does not end
2238 in a single newline. Python 2.3 is OK, so I hadn't noticed this
2251 in a single newline. Python 2.3 is OK, so I hadn't noticed this
2239 before.
2252 before.
2240
2253
2241 2004-12-10 Fernando Perez <fperez@colorado.edu>
2254 2004-12-10 Fernando Perez <fperez@colorado.edu>
2242
2255
2243 * IPython/Magic.py (Magic.magic_prun): changed name of option from
2256 * IPython/Magic.py (Magic.magic_prun): changed name of option from
2244 -t to -T, to accomodate the new -t flag in %run (the %run and
2257 -t to -T, to accomodate the new -t flag in %run (the %run and
2245 %prun options are kind of intermixed, and it's not easy to change
2258 %prun options are kind of intermixed, and it's not easy to change
2246 this with the limitations of python's getopt).
2259 this with the limitations of python's getopt).
2247
2260
2248 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
2261 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
2249 the execution of scripts. It's not as fine-tuned as timeit.py,
2262 the execution of scripts. It's not as fine-tuned as timeit.py,
2250 but it works from inside ipython (and under 2.2, which lacks
2263 but it works from inside ipython (and under 2.2, which lacks
2251 timeit.py). Optionally a number of runs > 1 can be given for
2264 timeit.py). Optionally a number of runs > 1 can be given for
2252 timing very short-running code.
2265 timing very short-running code.
2253
2266
2254 * IPython/genutils.py (uniq_stable): new routine which returns a
2267 * IPython/genutils.py (uniq_stable): new routine which returns a
2255 list of unique elements in any iterable, but in stable order of
2268 list of unique elements in any iterable, but in stable order of
2256 appearance. I needed this for the ultraTB fixes, and it's a handy
2269 appearance. I needed this for the ultraTB fixes, and it's a handy
2257 utility.
2270 utility.
2258
2271
2259 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
2272 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
2260 dotted names in Verbose exceptions. This had been broken since
2273 dotted names in Verbose exceptions. This had been broken since
2261 the very start, now x.y will properly be printed in a Verbose
2274 the very start, now x.y will properly be printed in a Verbose
2262 traceback, instead of x being shown and y appearing always as an
2275 traceback, instead of x being shown and y appearing always as an
2263 'undefined global'. Getting this to work was a bit tricky,
2276 'undefined global'. Getting this to work was a bit tricky,
2264 because by default python tokenizers are stateless. Saved by
2277 because by default python tokenizers are stateless. Saved by
2265 python's ability to easily add a bit of state to an arbitrary
2278 python's ability to easily add a bit of state to an arbitrary
2266 function (without needing to build a full-blown callable object).
2279 function (without needing to build a full-blown callable object).
2267
2280
2268 Also big cleanup of this code, which had horrendous runtime
2281 Also big cleanup of this code, which had horrendous runtime
2269 lookups of zillions of attributes for colorization. Moved all
2282 lookups of zillions of attributes for colorization. Moved all
2270 this code into a few templates, which make it cleaner and quicker.
2283 this code into a few templates, which make it cleaner and quicker.
2271
2284
2272 Printout quality was also improved for Verbose exceptions: one
2285 Printout quality was also improved for Verbose exceptions: one
2273 variable per line, and memory addresses are printed (this can be
2286 variable per line, and memory addresses are printed (this can be
2274 quite handy in nasty debugging situations, which is what Verbose
2287 quite handy in nasty debugging situations, which is what Verbose
2275 is for).
2288 is for).
2276
2289
2277 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
2290 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
2278 the command line as scripts to be loaded by embedded instances.
2291 the command line as scripts to be loaded by embedded instances.
2279 Doing so has the potential for an infinite recursion if there are
2292 Doing so has the potential for an infinite recursion if there are
2280 exceptions thrown in the process. This fixes a strange crash
2293 exceptions thrown in the process. This fixes a strange crash
2281 reported by Philippe MULLER <muller-AT-irit.fr>.
2294 reported by Philippe MULLER <muller-AT-irit.fr>.
2282
2295
2283 2004-12-09 Fernando Perez <fperez@colorado.edu>
2296 2004-12-09 Fernando Perez <fperez@colorado.edu>
2284
2297
2285 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
2298 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
2286 to reflect new names in matplotlib, which now expose the
2299 to reflect new names in matplotlib, which now expose the
2287 matlab-compatible interface via a pylab module instead of the
2300 matlab-compatible interface via a pylab module instead of the
2288 'matlab' name. The new code is backwards compatible, so users of
2301 'matlab' name. The new code is backwards compatible, so users of
2289 all matplotlib versions are OK. Patch by J. Hunter.
2302 all matplotlib versions are OK. Patch by J. Hunter.
2290
2303
2291 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
2304 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
2292 of __init__ docstrings for instances (class docstrings are already
2305 of __init__ docstrings for instances (class docstrings are already
2293 automatically printed). Instances with customized docstrings
2306 automatically printed). Instances with customized docstrings
2294 (indep. of the class) are also recognized and all 3 separate
2307 (indep. of the class) are also recognized and all 3 separate
2295 docstrings are printed (instance, class, constructor). After some
2308 docstrings are printed (instance, class, constructor). After some
2296 comments/suggestions by J. Hunter.
2309 comments/suggestions by J. Hunter.
2297
2310
2298 2004-12-05 Fernando Perez <fperez@colorado.edu>
2311 2004-12-05 Fernando Perez <fperez@colorado.edu>
2299
2312
2300 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
2313 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
2301 warnings when tab-completion fails and triggers an exception.
2314 warnings when tab-completion fails and triggers an exception.
2302
2315
2303 2004-12-03 Fernando Perez <fperez@colorado.edu>
2316 2004-12-03 Fernando Perez <fperez@colorado.edu>
2304
2317
2305 * IPython/Magic.py (magic_prun): Fix bug where an exception would
2318 * IPython/Magic.py (magic_prun): Fix bug where an exception would
2306 be triggered when using 'run -p'. An incorrect option flag was
2319 be triggered when using 'run -p'. An incorrect option flag was
2307 being set ('d' instead of 'D').
2320 being set ('d' instead of 'D').
2308 (manpage): fix missing escaped \- sign.
2321 (manpage): fix missing escaped \- sign.
2309
2322
2310 2004-11-30 *** Released version 0.6.5
2323 2004-11-30 *** Released version 0.6.5
2311
2324
2312 2004-11-30 Fernando Perez <fperez@colorado.edu>
2325 2004-11-30 Fernando Perez <fperez@colorado.edu>
2313
2326
2314 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
2327 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
2315 setting with -d option.
2328 setting with -d option.
2316
2329
2317 * setup.py (docfiles): Fix problem where the doc glob I was using
2330 * setup.py (docfiles): Fix problem where the doc glob I was using
2318 was COMPLETELY BROKEN. It was giving the right files by pure
2331 was COMPLETELY BROKEN. It was giving the right files by pure
2319 accident, but failed once I tried to include ipython.el. Note:
2332 accident, but failed once I tried to include ipython.el. Note:
2320 glob() does NOT allow you to do exclusion on multiple endings!
2333 glob() does NOT allow you to do exclusion on multiple endings!
2321
2334
2322 2004-11-29 Fernando Perez <fperez@colorado.edu>
2335 2004-11-29 Fernando Perez <fperez@colorado.edu>
2323
2336
2324 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
2337 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
2325 the manpage as the source. Better formatting & consistency.
2338 the manpage as the source. Better formatting & consistency.
2326
2339
2327 * IPython/Magic.py (magic_run): Added new -d option, to run
2340 * IPython/Magic.py (magic_run): Added new -d option, to run
2328 scripts under the control of the python pdb debugger. Note that
2341 scripts under the control of the python pdb debugger. Note that
2329 this required changing the %prun option -d to -D, to avoid a clash
2342 this required changing the %prun option -d to -D, to avoid a clash
2330 (since %run must pass options to %prun, and getopt is too dumb to
2343 (since %run must pass options to %prun, and getopt is too dumb to
2331 handle options with string values with embedded spaces). Thanks
2344 handle options with string values with embedded spaces). Thanks
2332 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
2345 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
2333 (magic_who_ls): added type matching to %who and %whos, so that one
2346 (magic_who_ls): added type matching to %who and %whos, so that one
2334 can filter their output to only include variables of certain
2347 can filter their output to only include variables of certain
2335 types. Another suggestion by Matthew.
2348 types. Another suggestion by Matthew.
2336 (magic_whos): Added memory summaries in kb and Mb for arrays.
2349 (magic_whos): Added memory summaries in kb and Mb for arrays.
2337 (magic_who): Improve formatting (break lines every 9 vars).
2350 (magic_who): Improve formatting (break lines every 9 vars).
2338
2351
2339 2004-11-28 Fernando Perez <fperez@colorado.edu>
2352 2004-11-28 Fernando Perez <fperez@colorado.edu>
2340
2353
2341 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
2354 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
2342 cache when empty lines were present.
2355 cache when empty lines were present.
2343
2356
2344 2004-11-24 Fernando Perez <fperez@colorado.edu>
2357 2004-11-24 Fernando Perez <fperez@colorado.edu>
2345
2358
2346 * IPython/usage.py (__doc__): document the re-activated threading
2359 * IPython/usage.py (__doc__): document the re-activated threading
2347 options for WX and GTK.
2360 options for WX and GTK.
2348
2361
2349 2004-11-23 Fernando Perez <fperez@colorado.edu>
2362 2004-11-23 Fernando Perez <fperez@colorado.edu>
2350
2363
2351 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
2364 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
2352 the -wthread and -gthread options, along with a new -tk one to try
2365 the -wthread and -gthread options, along with a new -tk one to try
2353 and coordinate Tk threading with wx/gtk. The tk support is very
2366 and coordinate Tk threading with wx/gtk. The tk support is very
2354 platform dependent, since it seems to require Tcl and Tk to be
2367 platform dependent, since it seems to require Tcl and Tk to be
2355 built with threads (Fedora1/2 appears NOT to have it, but in
2368 built with threads (Fedora1/2 appears NOT to have it, but in
2356 Prabhu's Debian boxes it works OK). But even with some Tk
2369 Prabhu's Debian boxes it works OK). But even with some Tk
2357 limitations, this is a great improvement.
2370 limitations, this is a great improvement.
2358
2371
2359 * IPython/Prompts.py (prompt_specials_color): Added \t for time
2372 * IPython/Prompts.py (prompt_specials_color): Added \t for time
2360 info in user prompts. Patch by Prabhu.
2373 info in user prompts. Patch by Prabhu.
2361
2374
2362 2004-11-18 Fernando Perez <fperez@colorado.edu>
2375 2004-11-18 Fernando Perez <fperez@colorado.edu>
2363
2376
2364 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
2377 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
2365 EOFErrors and bail, to avoid infinite loops if a non-terminating
2378 EOFErrors and bail, to avoid infinite loops if a non-terminating
2366 file is fed into ipython. Patch submitted in issue 19 by user,
2379 file is fed into ipython. Patch submitted in issue 19 by user,
2367 many thanks.
2380 many thanks.
2368
2381
2369 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
2382 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
2370 autoquote/parens in continuation prompts, which can cause lots of
2383 autoquote/parens in continuation prompts, which can cause lots of
2371 problems. Closes roundup issue 20.
2384 problems. Closes roundup issue 20.
2372
2385
2373 2004-11-17 Fernando Perez <fperez@colorado.edu>
2386 2004-11-17 Fernando Perez <fperez@colorado.edu>
2374
2387
2375 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
2388 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
2376 reported as debian bug #280505. I'm not sure my local changelog
2389 reported as debian bug #280505. I'm not sure my local changelog
2377 entry has the proper debian format (Jack?).
2390 entry has the proper debian format (Jack?).
2378
2391
2379 2004-11-08 *** Released version 0.6.4
2392 2004-11-08 *** Released version 0.6.4
2380
2393
2381 2004-11-08 Fernando Perez <fperez@colorado.edu>
2394 2004-11-08 Fernando Perez <fperez@colorado.edu>
2382
2395
2383 * IPython/iplib.py (init_readline): Fix exit message for Windows
2396 * IPython/iplib.py (init_readline): Fix exit message for Windows
2384 when readline is active. Thanks to a report by Eric Jones
2397 when readline is active. Thanks to a report by Eric Jones
2385 <eric-AT-enthought.com>.
2398 <eric-AT-enthought.com>.
2386
2399
2387 2004-11-07 Fernando Perez <fperez@colorado.edu>
2400 2004-11-07 Fernando Perez <fperez@colorado.edu>
2388
2401
2389 * IPython/genutils.py (page): Add a trap for OSError exceptions,
2402 * IPython/genutils.py (page): Add a trap for OSError exceptions,
2390 sometimes seen by win2k/cygwin users.
2403 sometimes seen by win2k/cygwin users.
2391
2404
2392 2004-11-06 Fernando Perez <fperez@colorado.edu>
2405 2004-11-06 Fernando Perez <fperez@colorado.edu>
2393
2406
2394 * IPython/iplib.py (interact): Change the handling of %Exit from
2407 * IPython/iplib.py (interact): Change the handling of %Exit from
2395 trying to propagate a SystemExit to an internal ipython flag.
2408 trying to propagate a SystemExit to an internal ipython flag.
2396 This is less elegant than using Python's exception mechanism, but
2409 This is less elegant than using Python's exception mechanism, but
2397 I can't get that to work reliably with threads, so under -pylab
2410 I can't get that to work reliably with threads, so under -pylab
2398 %Exit was hanging IPython. Cross-thread exception handling is
2411 %Exit was hanging IPython. Cross-thread exception handling is
2399 really a bitch. Thaks to a bug report by Stephen Walton
2412 really a bitch. Thaks to a bug report by Stephen Walton
2400 <stephen.walton-AT-csun.edu>.
2413 <stephen.walton-AT-csun.edu>.
2401
2414
2402 2004-11-04 Fernando Perez <fperez@colorado.edu>
2415 2004-11-04 Fernando Perez <fperez@colorado.edu>
2403
2416
2404 * IPython/iplib.py (raw_input_original): store a pointer to the
2417 * IPython/iplib.py (raw_input_original): store a pointer to the
2405 true raw_input to harden against code which can modify it
2418 true raw_input to harden against code which can modify it
2406 (wx.py.PyShell does this and would otherwise crash ipython).
2419 (wx.py.PyShell does this and would otherwise crash ipython).
2407 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
2420 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
2408
2421
2409 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
2422 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
2410 Ctrl-C problem, which does not mess up the input line.
2423 Ctrl-C problem, which does not mess up the input line.
2411
2424
2412 2004-11-03 Fernando Perez <fperez@colorado.edu>
2425 2004-11-03 Fernando Perez <fperez@colorado.edu>
2413
2426
2414 * IPython/Release.py: Changed licensing to BSD, in all files.
2427 * IPython/Release.py: Changed licensing to BSD, in all files.
2415 (name): lowercase name for tarball/RPM release.
2428 (name): lowercase name for tarball/RPM release.
2416
2429
2417 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
2430 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
2418 use throughout ipython.
2431 use throughout ipython.
2419
2432
2420 * IPython/Magic.py (Magic._ofind): Switch to using the new
2433 * IPython/Magic.py (Magic._ofind): Switch to using the new
2421 OInspect.getdoc() function.
2434 OInspect.getdoc() function.
2422
2435
2423 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
2436 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
2424 of the line currently being canceled via Ctrl-C. It's extremely
2437 of the line currently being canceled via Ctrl-C. It's extremely
2425 ugly, but I don't know how to do it better (the problem is one of
2438 ugly, but I don't know how to do it better (the problem is one of
2426 handling cross-thread exceptions).
2439 handling cross-thread exceptions).
2427
2440
2428 2004-10-28 Fernando Perez <fperez@colorado.edu>
2441 2004-10-28 Fernando Perez <fperez@colorado.edu>
2429
2442
2430 * IPython/Shell.py (signal_handler): add signal handlers to trap
2443 * IPython/Shell.py (signal_handler): add signal handlers to trap
2431 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
2444 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
2432 report by Francesc Alted.
2445 report by Francesc Alted.
2433
2446
2434 2004-10-21 Fernando Perez <fperez@colorado.edu>
2447 2004-10-21 Fernando Perez <fperez@colorado.edu>
2435
2448
2436 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
2449 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
2437 to % for pysh syntax extensions.
2450 to % for pysh syntax extensions.
2438
2451
2439 2004-10-09 Fernando Perez <fperez@colorado.edu>
2452 2004-10-09 Fernando Perez <fperez@colorado.edu>
2440
2453
2441 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
2454 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
2442 arrays to print a more useful summary, without calling str(arr).
2455 arrays to print a more useful summary, without calling str(arr).
2443 This avoids the problem of extremely lengthy computations which
2456 This avoids the problem of extremely lengthy computations which
2444 occur if arr is large, and appear to the user as a system lockup
2457 occur if arr is large, and appear to the user as a system lockup
2445 with 100% cpu activity. After a suggestion by Kristian Sandberg
2458 with 100% cpu activity. After a suggestion by Kristian Sandberg
2446 <Kristian.Sandberg@colorado.edu>.
2459 <Kristian.Sandberg@colorado.edu>.
2447 (Magic.__init__): fix bug in global magic escapes not being
2460 (Magic.__init__): fix bug in global magic escapes not being
2448 correctly set.
2461 correctly set.
2449
2462
2450 2004-10-08 Fernando Perez <fperez@colorado.edu>
2463 2004-10-08 Fernando Perez <fperez@colorado.edu>
2451
2464
2452 * IPython/Magic.py (__license__): change to absolute imports of
2465 * IPython/Magic.py (__license__): change to absolute imports of
2453 ipython's own internal packages, to start adapting to the absolute
2466 ipython's own internal packages, to start adapting to the absolute
2454 import requirement of PEP-328.
2467 import requirement of PEP-328.
2455
2468
2456 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
2469 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
2457 files, and standardize author/license marks through the Release
2470 files, and standardize author/license marks through the Release
2458 module instead of having per/file stuff (except for files with
2471 module instead of having per/file stuff (except for files with
2459 particular licenses, like the MIT/PSF-licensed codes).
2472 particular licenses, like the MIT/PSF-licensed codes).
2460
2473
2461 * IPython/Debugger.py: remove dead code for python 2.1
2474 * IPython/Debugger.py: remove dead code for python 2.1
2462
2475
2463 2004-10-04 Fernando Perez <fperez@colorado.edu>
2476 2004-10-04 Fernando Perez <fperez@colorado.edu>
2464
2477
2465 * IPython/iplib.py (ipmagic): New function for accessing magics
2478 * IPython/iplib.py (ipmagic): New function for accessing magics
2466 via a normal python function call.
2479 via a normal python function call.
2467
2480
2468 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
2481 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
2469 from '@' to '%', to accomodate the new @decorator syntax of python
2482 from '@' to '%', to accomodate the new @decorator syntax of python
2470 2.4.
2483 2.4.
2471
2484
2472 2004-09-29 Fernando Perez <fperez@colorado.edu>
2485 2004-09-29 Fernando Perez <fperez@colorado.edu>
2473
2486
2474 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
2487 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
2475 matplotlib.use to prevent running scripts which try to switch
2488 matplotlib.use to prevent running scripts which try to switch
2476 interactive backends from within ipython. This will just crash
2489 interactive backends from within ipython. This will just crash
2477 the python interpreter, so we can't allow it (but a detailed error
2490 the python interpreter, so we can't allow it (but a detailed error
2478 is given to the user).
2491 is given to the user).
2479
2492
2480 2004-09-28 Fernando Perez <fperez@colorado.edu>
2493 2004-09-28 Fernando Perez <fperez@colorado.edu>
2481
2494
2482 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
2495 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
2483 matplotlib-related fixes so that using @run with non-matplotlib
2496 matplotlib-related fixes so that using @run with non-matplotlib
2484 scripts doesn't pop up spurious plot windows. This requires
2497 scripts doesn't pop up spurious plot windows. This requires
2485 matplotlib >= 0.63, where I had to make some changes as well.
2498 matplotlib >= 0.63, where I had to make some changes as well.
2486
2499
2487 * IPython/ipmaker.py (make_IPython): update version requirement to
2500 * IPython/ipmaker.py (make_IPython): update version requirement to
2488 python 2.2.
2501 python 2.2.
2489
2502
2490 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
2503 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
2491 banner arg for embedded customization.
2504 banner arg for embedded customization.
2492
2505
2493 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
2506 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
2494 explicit uses of __IP as the IPython's instance name. Now things
2507 explicit uses of __IP as the IPython's instance name. Now things
2495 are properly handled via the shell.name value. The actual code
2508 are properly handled via the shell.name value. The actual code
2496 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
2509 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
2497 is much better than before. I'll clean things completely when the
2510 is much better than before. I'll clean things completely when the
2498 magic stuff gets a real overhaul.
2511 magic stuff gets a real overhaul.
2499
2512
2500 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
2513 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
2501 minor changes to debian dir.
2514 minor changes to debian dir.
2502
2515
2503 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
2516 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
2504 pointer to the shell itself in the interactive namespace even when
2517 pointer to the shell itself in the interactive namespace even when
2505 a user-supplied dict is provided. This is needed for embedding
2518 a user-supplied dict is provided. This is needed for embedding
2506 purposes (found by tests with Michel Sanner).
2519 purposes (found by tests with Michel Sanner).
2507
2520
2508 2004-09-27 Fernando Perez <fperez@colorado.edu>
2521 2004-09-27 Fernando Perez <fperez@colorado.edu>
2509
2522
2510 * IPython/UserConfig/ipythonrc: remove []{} from
2523 * IPython/UserConfig/ipythonrc: remove []{} from
2511 readline_remove_delims, so that things like [modname.<TAB> do
2524 readline_remove_delims, so that things like [modname.<TAB> do
2512 proper completion. This disables [].TAB, but that's a less common
2525 proper completion. This disables [].TAB, but that's a less common
2513 case than module names in list comprehensions, for example.
2526 case than module names in list comprehensions, for example.
2514 Thanks to a report by Andrea Riciputi.
2527 Thanks to a report by Andrea Riciputi.
2515
2528
2516 2004-09-09 Fernando Perez <fperez@colorado.edu>
2529 2004-09-09 Fernando Perez <fperez@colorado.edu>
2517
2530
2518 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
2531 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
2519 blocking problems in win32 and osx. Fix by John.
2532 blocking problems in win32 and osx. Fix by John.
2520
2533
2521 2004-09-08 Fernando Perez <fperez@colorado.edu>
2534 2004-09-08 Fernando Perez <fperez@colorado.edu>
2522
2535
2523 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
2536 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
2524 for Win32 and OSX. Fix by John Hunter.
2537 for Win32 and OSX. Fix by John Hunter.
2525
2538
2526 2004-08-30 *** Released version 0.6.3
2539 2004-08-30 *** Released version 0.6.3
2527
2540
2528 2004-08-30 Fernando Perez <fperez@colorado.edu>
2541 2004-08-30 Fernando Perez <fperez@colorado.edu>
2529
2542
2530 * setup.py (isfile): Add manpages to list of dependent files to be
2543 * setup.py (isfile): Add manpages to list of dependent files to be
2531 updated.
2544 updated.
2532
2545
2533 2004-08-27 Fernando Perez <fperez@colorado.edu>
2546 2004-08-27 Fernando Perez <fperez@colorado.edu>
2534
2547
2535 * IPython/Shell.py (start): I've disabled -wthread and -gthread
2548 * IPython/Shell.py (start): I've disabled -wthread and -gthread
2536 for now. They don't really work with standalone WX/GTK code
2549 for now. They don't really work with standalone WX/GTK code
2537 (though matplotlib IS working fine with both of those backends).
2550 (though matplotlib IS working fine with both of those backends).
2538 This will neeed much more testing. I disabled most things with
2551 This will neeed much more testing. I disabled most things with
2539 comments, so turning it back on later should be pretty easy.
2552 comments, so turning it back on later should be pretty easy.
2540
2553
2541 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
2554 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
2542 autocalling of expressions like r'foo', by modifying the line
2555 autocalling of expressions like r'foo', by modifying the line
2543 split regexp. Closes
2556 split regexp. Closes
2544 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
2557 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
2545 Riley <ipythonbugs-AT-sabi.net>.
2558 Riley <ipythonbugs-AT-sabi.net>.
2546 (InteractiveShell.mainloop): honor --nobanner with banner
2559 (InteractiveShell.mainloop): honor --nobanner with banner
2547 extensions.
2560 extensions.
2548
2561
2549 * IPython/Shell.py: Significant refactoring of all classes, so
2562 * IPython/Shell.py: Significant refactoring of all classes, so
2550 that we can really support ALL matplotlib backends and threading
2563 that we can really support ALL matplotlib backends and threading
2551 models (John spotted a bug with Tk which required this). Now we
2564 models (John spotted a bug with Tk which required this). Now we
2552 should support single-threaded, WX-threads and GTK-threads, both
2565 should support single-threaded, WX-threads and GTK-threads, both
2553 for generic code and for matplotlib.
2566 for generic code and for matplotlib.
2554
2567
2555 * IPython/ipmaker.py (__call__): Changed -mpthread option to
2568 * IPython/ipmaker.py (__call__): Changed -mpthread option to
2556 -pylab, to simplify things for users. Will also remove the pylab
2569 -pylab, to simplify things for users. Will also remove the pylab
2557 profile, since now all of matplotlib configuration is directly
2570 profile, since now all of matplotlib configuration is directly
2558 handled here. This also reduces startup time.
2571 handled here. This also reduces startup time.
2559
2572
2560 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
2573 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
2561 shell wasn't being correctly called. Also in IPShellWX.
2574 shell wasn't being correctly called. Also in IPShellWX.
2562
2575
2563 * IPython/iplib.py (InteractiveShell.__init__): Added option to
2576 * IPython/iplib.py (InteractiveShell.__init__): Added option to
2564 fine-tune banner.
2577 fine-tune banner.
2565
2578
2566 * IPython/numutils.py (spike): Deprecate these spike functions,
2579 * IPython/numutils.py (spike): Deprecate these spike functions,
2567 delete (long deprecated) gnuplot_exec handler.
2580 delete (long deprecated) gnuplot_exec handler.
2568
2581
2569 2004-08-26 Fernando Perez <fperez@colorado.edu>
2582 2004-08-26 Fernando Perez <fperez@colorado.edu>
2570
2583
2571 * ipython.1: Update for threading options, plus some others which
2584 * ipython.1: Update for threading options, plus some others which
2572 were missing.
2585 were missing.
2573
2586
2574 * IPython/ipmaker.py (__call__): Added -wthread option for
2587 * IPython/ipmaker.py (__call__): Added -wthread option for
2575 wxpython thread handling. Make sure threading options are only
2588 wxpython thread handling. Make sure threading options are only
2576 valid at the command line.
2589 valid at the command line.
2577
2590
2578 * scripts/ipython: moved shell selection into a factory function
2591 * scripts/ipython: moved shell selection into a factory function
2579 in Shell.py, to keep the starter script to a minimum.
2592 in Shell.py, to keep the starter script to a minimum.
2580
2593
2581 2004-08-25 Fernando Perez <fperez@colorado.edu>
2594 2004-08-25 Fernando Perez <fperez@colorado.edu>
2582
2595
2583 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
2596 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
2584 John. Along with some recent changes he made to matplotlib, the
2597 John. Along with some recent changes he made to matplotlib, the
2585 next versions of both systems should work very well together.
2598 next versions of both systems should work very well together.
2586
2599
2587 2004-08-24 Fernando Perez <fperez@colorado.edu>
2600 2004-08-24 Fernando Perez <fperez@colorado.edu>
2588
2601
2589 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
2602 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
2590 tried to switch the profiling to using hotshot, but I'm getting
2603 tried to switch the profiling to using hotshot, but I'm getting
2591 strange errors from prof.runctx() there. I may be misreading the
2604 strange errors from prof.runctx() there. I may be misreading the
2592 docs, but it looks weird. For now the profiling code will
2605 docs, but it looks weird. For now the profiling code will
2593 continue to use the standard profiler.
2606 continue to use the standard profiler.
2594
2607
2595 2004-08-23 Fernando Perez <fperez@colorado.edu>
2608 2004-08-23 Fernando Perez <fperez@colorado.edu>
2596
2609
2597 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
2610 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
2598 threaded shell, by John Hunter. It's not quite ready yet, but
2611 threaded shell, by John Hunter. It's not quite ready yet, but
2599 close.
2612 close.
2600
2613
2601 2004-08-22 Fernando Perez <fperez@colorado.edu>
2614 2004-08-22 Fernando Perez <fperez@colorado.edu>
2602
2615
2603 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
2616 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
2604 in Magic and ultraTB.
2617 in Magic and ultraTB.
2605
2618
2606 * ipython.1: document threading options in manpage.
2619 * ipython.1: document threading options in manpage.
2607
2620
2608 * scripts/ipython: Changed name of -thread option to -gthread,
2621 * scripts/ipython: Changed name of -thread option to -gthread,
2609 since this is GTK specific. I want to leave the door open for a
2622 since this is GTK specific. I want to leave the door open for a
2610 -wthread option for WX, which will most likely be necessary. This
2623 -wthread option for WX, which will most likely be necessary. This
2611 change affects usage and ipmaker as well.
2624 change affects usage and ipmaker as well.
2612
2625
2613 * IPython/Shell.py (matplotlib_shell): Add a factory function to
2626 * IPython/Shell.py (matplotlib_shell): Add a factory function to
2614 handle the matplotlib shell issues. Code by John Hunter
2627 handle the matplotlib shell issues. Code by John Hunter
2615 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2628 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2616 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
2629 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
2617 broken (and disabled for end users) for now, but it puts the
2630 broken (and disabled for end users) for now, but it puts the
2618 infrastructure in place.
2631 infrastructure in place.
2619
2632
2620 2004-08-21 Fernando Perez <fperez@colorado.edu>
2633 2004-08-21 Fernando Perez <fperez@colorado.edu>
2621
2634
2622 * ipythonrc-pylab: Add matplotlib support.
2635 * ipythonrc-pylab: Add matplotlib support.
2623
2636
2624 * matplotlib_config.py: new files for matplotlib support, part of
2637 * matplotlib_config.py: new files for matplotlib support, part of
2625 the pylab profile.
2638 the pylab profile.
2626
2639
2627 * IPython/usage.py (__doc__): documented the threading options.
2640 * IPython/usage.py (__doc__): documented the threading options.
2628
2641
2629 2004-08-20 Fernando Perez <fperez@colorado.edu>
2642 2004-08-20 Fernando Perez <fperez@colorado.edu>
2630
2643
2631 * ipython: Modified the main calling routine to handle the -thread
2644 * ipython: Modified the main calling routine to handle the -thread
2632 and -mpthread options. This needs to be done as a top-level hack,
2645 and -mpthread options. This needs to be done as a top-level hack,
2633 because it determines which class to instantiate for IPython
2646 because it determines which class to instantiate for IPython
2634 itself.
2647 itself.
2635
2648
2636 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
2649 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
2637 classes to support multithreaded GTK operation without blocking,
2650 classes to support multithreaded GTK operation without blocking,
2638 and matplotlib with all backends. This is a lot of still very
2651 and matplotlib with all backends. This is a lot of still very
2639 experimental code, and threads are tricky. So it may still have a
2652 experimental code, and threads are tricky. So it may still have a
2640 few rough edges... This code owes a lot to
2653 few rough edges... This code owes a lot to
2641 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
2654 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
2642 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
2655 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
2643 to John Hunter for all the matplotlib work.
2656 to John Hunter for all the matplotlib work.
2644
2657
2645 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
2658 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
2646 options for gtk thread and matplotlib support.
2659 options for gtk thread and matplotlib support.
2647
2660
2648 2004-08-16 Fernando Perez <fperez@colorado.edu>
2661 2004-08-16 Fernando Perez <fperez@colorado.edu>
2649
2662
2650 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
2663 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
2651 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
2664 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
2652 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
2665 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
2653
2666
2654 2004-08-11 Fernando Perez <fperez@colorado.edu>
2667 2004-08-11 Fernando Perez <fperez@colorado.edu>
2655
2668
2656 * setup.py (isfile): Fix build so documentation gets updated for
2669 * setup.py (isfile): Fix build so documentation gets updated for
2657 rpms (it was only done for .tgz builds).
2670 rpms (it was only done for .tgz builds).
2658
2671
2659 2004-08-10 Fernando Perez <fperez@colorado.edu>
2672 2004-08-10 Fernando Perez <fperez@colorado.edu>
2660
2673
2661 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
2674 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
2662
2675
2663 * iplib.py : Silence syntax error exceptions in tab-completion.
2676 * iplib.py : Silence syntax error exceptions in tab-completion.
2664
2677
2665 2004-08-05 Fernando Perez <fperez@colorado.edu>
2678 2004-08-05 Fernando Perez <fperez@colorado.edu>
2666
2679
2667 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
2680 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
2668 'color off' mark for continuation prompts. This was causing long
2681 'color off' mark for continuation prompts. This was causing long
2669 continuation lines to mis-wrap.
2682 continuation lines to mis-wrap.
2670
2683
2671 2004-08-01 Fernando Perez <fperez@colorado.edu>
2684 2004-08-01 Fernando Perez <fperez@colorado.edu>
2672
2685
2673 * IPython/ipmaker.py (make_IPython): Allow the shell class used
2686 * IPython/ipmaker.py (make_IPython): Allow the shell class used
2674 for building ipython to be a parameter. All this is necessary
2687 for building ipython to be a parameter. All this is necessary
2675 right now to have a multithreaded version, but this insane
2688 right now to have a multithreaded version, but this insane
2676 non-design will be cleaned up soon. For now, it's a hack that
2689 non-design will be cleaned up soon. For now, it's a hack that
2677 works.
2690 works.
2678
2691
2679 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
2692 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
2680 args in various places. No bugs so far, but it's a dangerous
2693 args in various places. No bugs so far, but it's a dangerous
2681 practice.
2694 practice.
2682
2695
2683 2004-07-31 Fernando Perez <fperez@colorado.edu>
2696 2004-07-31 Fernando Perez <fperez@colorado.edu>
2684
2697
2685 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
2698 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
2686 fix completion of files with dots in their names under most
2699 fix completion of files with dots in their names under most
2687 profiles (pysh was OK because the completion order is different).
2700 profiles (pysh was OK because the completion order is different).
2688
2701
2689 2004-07-27 Fernando Perez <fperez@colorado.edu>
2702 2004-07-27 Fernando Perez <fperez@colorado.edu>
2690
2703
2691 * IPython/iplib.py (InteractiveShell.__init__): build dict of
2704 * IPython/iplib.py (InteractiveShell.__init__): build dict of
2692 keywords manually, b/c the one in keyword.py was removed in python
2705 keywords manually, b/c the one in keyword.py was removed in python
2693 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
2706 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
2694 This is NOT a bug under python 2.3 and earlier.
2707 This is NOT a bug under python 2.3 and earlier.
2695
2708
2696 2004-07-26 Fernando Perez <fperez@colorado.edu>
2709 2004-07-26 Fernando Perez <fperez@colorado.edu>
2697
2710
2698 * IPython/ultraTB.py (VerboseTB.text): Add another
2711 * IPython/ultraTB.py (VerboseTB.text): Add another
2699 linecache.checkcache() call to try to prevent inspect.py from
2712 linecache.checkcache() call to try to prevent inspect.py from
2700 crashing under python 2.3. I think this fixes
2713 crashing under python 2.3. I think this fixes
2701 http://www.scipy.net/roundup/ipython/issue17.
2714 http://www.scipy.net/roundup/ipython/issue17.
2702
2715
2703 2004-07-26 *** Released version 0.6.2
2716 2004-07-26 *** Released version 0.6.2
2704
2717
2705 2004-07-26 Fernando Perez <fperez@colorado.edu>
2718 2004-07-26 Fernando Perez <fperez@colorado.edu>
2706
2719
2707 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
2720 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
2708 fail for any number.
2721 fail for any number.
2709 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
2722 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
2710 empty bookmarks.
2723 empty bookmarks.
2711
2724
2712 2004-07-26 *** Released version 0.6.1
2725 2004-07-26 *** Released version 0.6.1
2713
2726
2714 2004-07-26 Fernando Perez <fperez@colorado.edu>
2727 2004-07-26 Fernando Perez <fperez@colorado.edu>
2715
2728
2716 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
2729 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
2717
2730
2718 * IPython/iplib.py (protect_filename): Applied Ville's patch for
2731 * IPython/iplib.py (protect_filename): Applied Ville's patch for
2719 escaping '()[]{}' in filenames.
2732 escaping '()[]{}' in filenames.
2720
2733
2721 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
2734 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
2722 Python 2.2 users who lack a proper shlex.split.
2735 Python 2.2 users who lack a proper shlex.split.
2723
2736
2724 2004-07-19 Fernando Perez <fperez@colorado.edu>
2737 2004-07-19 Fernando Perez <fperez@colorado.edu>
2725
2738
2726 * IPython/iplib.py (InteractiveShell.init_readline): Add support
2739 * IPython/iplib.py (InteractiveShell.init_readline): Add support
2727 for reading readline's init file. I follow the normal chain:
2740 for reading readline's init file. I follow the normal chain:
2728 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
2741 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
2729 report by Mike Heeter. This closes
2742 report by Mike Heeter. This closes
2730 http://www.scipy.net/roundup/ipython/issue16.
2743 http://www.scipy.net/roundup/ipython/issue16.
2731
2744
2732 2004-07-18 Fernando Perez <fperez@colorado.edu>
2745 2004-07-18 Fernando Perez <fperez@colorado.edu>
2733
2746
2734 * IPython/iplib.py (__init__): Add better handling of '\' under
2747 * IPython/iplib.py (__init__): Add better handling of '\' under
2735 Win32 for filenames. After a patch by Ville.
2748 Win32 for filenames. After a patch by Ville.
2736
2749
2737 2004-07-17 Fernando Perez <fperez@colorado.edu>
2750 2004-07-17 Fernando Perez <fperez@colorado.edu>
2738
2751
2739 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2752 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2740 autocalling would be triggered for 'foo is bar' if foo is
2753 autocalling would be triggered for 'foo is bar' if foo is
2741 callable. I also cleaned up the autocall detection code to use a
2754 callable. I also cleaned up the autocall detection code to use a
2742 regexp, which is faster. Bug reported by Alexander Schmolck.
2755 regexp, which is faster. Bug reported by Alexander Schmolck.
2743
2756
2744 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
2757 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
2745 '?' in them would confuse the help system. Reported by Alex
2758 '?' in them would confuse the help system. Reported by Alex
2746 Schmolck.
2759 Schmolck.
2747
2760
2748 2004-07-16 Fernando Perez <fperez@colorado.edu>
2761 2004-07-16 Fernando Perez <fperez@colorado.edu>
2749
2762
2750 * IPython/GnuplotInteractive.py (__all__): added plot2.
2763 * IPython/GnuplotInteractive.py (__all__): added plot2.
2751
2764
2752 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
2765 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
2753 plotting dictionaries, lists or tuples of 1d arrays.
2766 plotting dictionaries, lists or tuples of 1d arrays.
2754
2767
2755 * IPython/Magic.py (Magic.magic_hist): small clenaups and
2768 * IPython/Magic.py (Magic.magic_hist): small clenaups and
2756 optimizations.
2769 optimizations.
2757
2770
2758 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
2771 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
2759 the information which was there from Janko's original IPP code:
2772 the information which was there from Janko's original IPP code:
2760
2773
2761 03.05.99 20:53 porto.ifm.uni-kiel.de
2774 03.05.99 20:53 porto.ifm.uni-kiel.de
2762 --Started changelog.
2775 --Started changelog.
2763 --make clear do what it say it does
2776 --make clear do what it say it does
2764 --added pretty output of lines from inputcache
2777 --added pretty output of lines from inputcache
2765 --Made Logger a mixin class, simplifies handling of switches
2778 --Made Logger a mixin class, simplifies handling of switches
2766 --Added own completer class. .string<TAB> expands to last history
2779 --Added own completer class. .string<TAB> expands to last history
2767 line which starts with string. The new expansion is also present
2780 line which starts with string. The new expansion is also present
2768 with Ctrl-r from the readline library. But this shows, who this
2781 with Ctrl-r from the readline library. But this shows, who this
2769 can be done for other cases.
2782 can be done for other cases.
2770 --Added convention that all shell functions should accept a
2783 --Added convention that all shell functions should accept a
2771 parameter_string This opens the door for different behaviour for
2784 parameter_string This opens the door for different behaviour for
2772 each function. @cd is a good example of this.
2785 each function. @cd is a good example of this.
2773
2786
2774 04.05.99 12:12 porto.ifm.uni-kiel.de
2787 04.05.99 12:12 porto.ifm.uni-kiel.de
2775 --added logfile rotation
2788 --added logfile rotation
2776 --added new mainloop method which freezes first the namespace
2789 --added new mainloop method which freezes first the namespace
2777
2790
2778 07.05.99 21:24 porto.ifm.uni-kiel.de
2791 07.05.99 21:24 porto.ifm.uni-kiel.de
2779 --added the docreader classes. Now there is a help system.
2792 --added the docreader classes. Now there is a help system.
2780 -This is only a first try. Currently it's not easy to put new
2793 -This is only a first try. Currently it's not easy to put new
2781 stuff in the indices. But this is the way to go. Info would be
2794 stuff in the indices. But this is the way to go. Info would be
2782 better, but HTML is every where and not everybody has an info
2795 better, but HTML is every where and not everybody has an info
2783 system installed and it's not so easy to change html-docs to info.
2796 system installed and it's not so easy to change html-docs to info.
2784 --added global logfile option
2797 --added global logfile option
2785 --there is now a hook for object inspection method pinfo needs to
2798 --there is now a hook for object inspection method pinfo needs to
2786 be provided for this. Can be reached by two '??'.
2799 be provided for this. Can be reached by two '??'.
2787
2800
2788 08.05.99 20:51 porto.ifm.uni-kiel.de
2801 08.05.99 20:51 porto.ifm.uni-kiel.de
2789 --added a README
2802 --added a README
2790 --bug in rc file. Something has changed so functions in the rc
2803 --bug in rc file. Something has changed so functions in the rc
2791 file need to reference the shell and not self. Not clear if it's a
2804 file need to reference the shell and not self. Not clear if it's a
2792 bug or feature.
2805 bug or feature.
2793 --changed rc file for new behavior
2806 --changed rc file for new behavior
2794
2807
2795 2004-07-15 Fernando Perez <fperez@colorado.edu>
2808 2004-07-15 Fernando Perez <fperez@colorado.edu>
2796
2809
2797 * IPython/Logger.py (Logger.log): fixed recent bug where the input
2810 * IPython/Logger.py (Logger.log): fixed recent bug where the input
2798 cache was falling out of sync in bizarre manners when multi-line
2811 cache was falling out of sync in bizarre manners when multi-line
2799 input was present. Minor optimizations and cleanup.
2812 input was present. Minor optimizations and cleanup.
2800
2813
2801 (Logger): Remove old Changelog info for cleanup. This is the
2814 (Logger): Remove old Changelog info for cleanup. This is the
2802 information which was there from Janko's original code:
2815 information which was there from Janko's original code:
2803
2816
2804 Changes to Logger: - made the default log filename a parameter
2817 Changes to Logger: - made the default log filename a parameter
2805
2818
2806 - put a check for lines beginning with !@? in log(). Needed
2819 - put a check for lines beginning with !@? in log(). Needed
2807 (even if the handlers properly log their lines) for mid-session
2820 (even if the handlers properly log their lines) for mid-session
2808 logging activation to work properly. Without this, lines logged
2821 logging activation to work properly. Without this, lines logged
2809 in mid session, which get read from the cache, would end up
2822 in mid session, which get read from the cache, would end up
2810 'bare' (with !@? in the open) in the log. Now they are caught
2823 'bare' (with !@? in the open) in the log. Now they are caught
2811 and prepended with a #.
2824 and prepended with a #.
2812
2825
2813 * IPython/iplib.py (InteractiveShell.init_readline): added check
2826 * IPython/iplib.py (InteractiveShell.init_readline): added check
2814 in case MagicCompleter fails to be defined, so we don't crash.
2827 in case MagicCompleter fails to be defined, so we don't crash.
2815
2828
2816 2004-07-13 Fernando Perez <fperez@colorado.edu>
2829 2004-07-13 Fernando Perez <fperez@colorado.edu>
2817
2830
2818 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
2831 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
2819 of EPS if the requested filename ends in '.eps'.
2832 of EPS if the requested filename ends in '.eps'.
2820
2833
2821 2004-07-04 Fernando Perez <fperez@colorado.edu>
2834 2004-07-04 Fernando Perez <fperez@colorado.edu>
2822
2835
2823 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
2836 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
2824 escaping of quotes when calling the shell.
2837 escaping of quotes when calling the shell.
2825
2838
2826 2004-07-02 Fernando Perez <fperez@colorado.edu>
2839 2004-07-02 Fernando Perez <fperez@colorado.edu>
2827
2840
2828 * IPython/Prompts.py (CachedOutput.update): Fix problem with
2841 * IPython/Prompts.py (CachedOutput.update): Fix problem with
2829 gettext not working because we were clobbering '_'. Fixes
2842 gettext not working because we were clobbering '_'. Fixes
2830 http://www.scipy.net/roundup/ipython/issue6.
2843 http://www.scipy.net/roundup/ipython/issue6.
2831
2844
2832 2004-07-01 Fernando Perez <fperez@colorado.edu>
2845 2004-07-01 Fernando Perez <fperez@colorado.edu>
2833
2846
2834 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
2847 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
2835 into @cd. Patch by Ville.
2848 into @cd. Patch by Ville.
2836
2849
2837 * IPython/iplib.py (InteractiveShell.post_config_initialization):
2850 * IPython/iplib.py (InteractiveShell.post_config_initialization):
2838 new function to store things after ipmaker runs. Patch by Ville.
2851 new function to store things after ipmaker runs. Patch by Ville.
2839 Eventually this will go away once ipmaker is removed and the class
2852 Eventually this will go away once ipmaker is removed and the class
2840 gets cleaned up, but for now it's ok. Key functionality here is
2853 gets cleaned up, but for now it's ok. Key functionality here is
2841 the addition of the persistent storage mechanism, a dict for
2854 the addition of the persistent storage mechanism, a dict for
2842 keeping data across sessions (for now just bookmarks, but more can
2855 keeping data across sessions (for now just bookmarks, but more can
2843 be implemented later).
2856 be implemented later).
2844
2857
2845 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2858 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2846 persistent across sections. Patch by Ville, I modified it
2859 persistent across sections. Patch by Ville, I modified it
2847 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2860 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2848 added a '-l' option to list all bookmarks.
2861 added a '-l' option to list all bookmarks.
2849
2862
2850 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2863 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2851 center for cleanup. Registered with atexit.register(). I moved
2864 center for cleanup. Registered with atexit.register(). I moved
2852 here the old exit_cleanup(). After a patch by Ville.
2865 here the old exit_cleanup(). After a patch by Ville.
2853
2866
2854 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2867 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2855 characters in the hacked shlex_split for python 2.2.
2868 characters in the hacked shlex_split for python 2.2.
2856
2869
2857 * IPython/iplib.py (file_matches): more fixes to filenames with
2870 * IPython/iplib.py (file_matches): more fixes to filenames with
2858 whitespace in them. It's not perfect, but limitations in python's
2871 whitespace in them. It's not perfect, but limitations in python's
2859 readline make it impossible to go further.
2872 readline make it impossible to go further.
2860
2873
2861 2004-06-29 Fernando Perez <fperez@colorado.edu>
2874 2004-06-29 Fernando Perez <fperez@colorado.edu>
2862
2875
2863 * IPython/iplib.py (file_matches): escape whitespace correctly in
2876 * IPython/iplib.py (file_matches): escape whitespace correctly in
2864 filename completions. Bug reported by Ville.
2877 filename completions. Bug reported by Ville.
2865
2878
2866 2004-06-28 Fernando Perez <fperez@colorado.edu>
2879 2004-06-28 Fernando Perez <fperez@colorado.edu>
2867
2880
2868 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2881 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2869 the history file will be called 'history-PROFNAME' (or just
2882 the history file will be called 'history-PROFNAME' (or just
2870 'history' if no profile is loaded). I was getting annoyed at
2883 'history' if no profile is loaded). I was getting annoyed at
2871 getting my Numerical work history clobbered by pysh sessions.
2884 getting my Numerical work history clobbered by pysh sessions.
2872
2885
2873 * IPython/iplib.py (InteractiveShell.__init__): Internal
2886 * IPython/iplib.py (InteractiveShell.__init__): Internal
2874 getoutputerror() function so that we can honor the system_verbose
2887 getoutputerror() function so that we can honor the system_verbose
2875 flag for _all_ system calls. I also added escaping of #
2888 flag for _all_ system calls. I also added escaping of #
2876 characters here to avoid confusing Itpl.
2889 characters here to avoid confusing Itpl.
2877
2890
2878 * IPython/Magic.py (shlex_split): removed call to shell in
2891 * IPython/Magic.py (shlex_split): removed call to shell in
2879 parse_options and replaced it with shlex.split(). The annoying
2892 parse_options and replaced it with shlex.split(). The annoying
2880 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2893 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2881 to backport it from 2.3, with several frail hacks (the shlex
2894 to backport it from 2.3, with several frail hacks (the shlex
2882 module is rather limited in 2.2). Thanks to a suggestion by Ville
2895 module is rather limited in 2.2). Thanks to a suggestion by Ville
2883 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2896 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2884 problem.
2897 problem.
2885
2898
2886 (Magic.magic_system_verbose): new toggle to print the actual
2899 (Magic.magic_system_verbose): new toggle to print the actual
2887 system calls made by ipython. Mainly for debugging purposes.
2900 system calls made by ipython. Mainly for debugging purposes.
2888
2901
2889 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2902 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2890 doesn't support persistence. Reported (and fix suggested) by
2903 doesn't support persistence. Reported (and fix suggested) by
2891 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2904 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2892
2905
2893 2004-06-26 Fernando Perez <fperez@colorado.edu>
2906 2004-06-26 Fernando Perez <fperez@colorado.edu>
2894
2907
2895 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2908 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2896 continue prompts.
2909 continue prompts.
2897
2910
2898 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2911 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2899 function (basically a big docstring) and a few more things here to
2912 function (basically a big docstring) and a few more things here to
2900 speedup startup. pysh.py is now very lightweight. We want because
2913 speedup startup. pysh.py is now very lightweight. We want because
2901 it gets execfile'd, while InterpreterExec gets imported, so
2914 it gets execfile'd, while InterpreterExec gets imported, so
2902 byte-compilation saves time.
2915 byte-compilation saves time.
2903
2916
2904 2004-06-25 Fernando Perez <fperez@colorado.edu>
2917 2004-06-25 Fernando Perez <fperez@colorado.edu>
2905
2918
2906 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2919 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2907 -NUM', which was recently broken.
2920 -NUM', which was recently broken.
2908
2921
2909 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2922 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2910 in multi-line input (but not !!, which doesn't make sense there).
2923 in multi-line input (but not !!, which doesn't make sense there).
2911
2924
2912 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2925 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2913 It's just too useful, and people can turn it off in the less
2926 It's just too useful, and people can turn it off in the less
2914 common cases where it's a problem.
2927 common cases where it's a problem.
2915
2928
2916 2004-06-24 Fernando Perez <fperez@colorado.edu>
2929 2004-06-24 Fernando Perez <fperez@colorado.edu>
2917
2930
2918 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2931 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2919 special syntaxes (like alias calling) is now allied in multi-line
2932 special syntaxes (like alias calling) is now allied in multi-line
2920 input. This is still _very_ experimental, but it's necessary for
2933 input. This is still _very_ experimental, but it's necessary for
2921 efficient shell usage combining python looping syntax with system
2934 efficient shell usage combining python looping syntax with system
2922 calls. For now it's restricted to aliases, I don't think it
2935 calls. For now it's restricted to aliases, I don't think it
2923 really even makes sense to have this for magics.
2936 really even makes sense to have this for magics.
2924
2937
2925 2004-06-23 Fernando Perez <fperez@colorado.edu>
2938 2004-06-23 Fernando Perez <fperez@colorado.edu>
2926
2939
2927 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2940 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2928 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2941 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2929
2942
2930 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2943 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2931 extensions under Windows (after code sent by Gary Bishop). The
2944 extensions under Windows (after code sent by Gary Bishop). The
2932 extensions considered 'executable' are stored in IPython's rc
2945 extensions considered 'executable' are stored in IPython's rc
2933 structure as win_exec_ext.
2946 structure as win_exec_ext.
2934
2947
2935 * IPython/genutils.py (shell): new function, like system() but
2948 * IPython/genutils.py (shell): new function, like system() but
2936 without return value. Very useful for interactive shell work.
2949 without return value. Very useful for interactive shell work.
2937
2950
2938 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2951 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2939 delete aliases.
2952 delete aliases.
2940
2953
2941 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2954 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2942 sure that the alias table doesn't contain python keywords.
2955 sure that the alias table doesn't contain python keywords.
2943
2956
2944 2004-06-21 Fernando Perez <fperez@colorado.edu>
2957 2004-06-21 Fernando Perez <fperez@colorado.edu>
2945
2958
2946 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2959 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2947 non-existent items are found in $PATH. Reported by Thorsten.
2960 non-existent items are found in $PATH. Reported by Thorsten.
2948
2961
2949 2004-06-20 Fernando Perez <fperez@colorado.edu>
2962 2004-06-20 Fernando Perez <fperez@colorado.edu>
2950
2963
2951 * IPython/iplib.py (complete): modified the completer so that the
2964 * IPython/iplib.py (complete): modified the completer so that the
2952 order of priorities can be easily changed at runtime.
2965 order of priorities can be easily changed at runtime.
2953
2966
2954 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2967 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2955 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2968 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2956
2969
2957 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2970 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2958 expand Python variables prepended with $ in all system calls. The
2971 expand Python variables prepended with $ in all system calls. The
2959 same was done to InteractiveShell.handle_shell_escape. Now all
2972 same was done to InteractiveShell.handle_shell_escape. Now all
2960 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2973 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2961 expansion of python variables and expressions according to the
2974 expansion of python variables and expressions according to the
2962 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2975 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2963
2976
2964 Though PEP-215 has been rejected, a similar (but simpler) one
2977 Though PEP-215 has been rejected, a similar (but simpler) one
2965 seems like it will go into Python 2.4, PEP-292 -
2978 seems like it will go into Python 2.4, PEP-292 -
2966 http://www.python.org/peps/pep-0292.html.
2979 http://www.python.org/peps/pep-0292.html.
2967
2980
2968 I'll keep the full syntax of PEP-215, since IPython has since the
2981 I'll keep the full syntax of PEP-215, since IPython has since the
2969 start used Ka-Ping Yee's reference implementation discussed there
2982 start used Ka-Ping Yee's reference implementation discussed there
2970 (Itpl), and I actually like the powerful semantics it offers.
2983 (Itpl), and I actually like the powerful semantics it offers.
2971
2984
2972 In order to access normal shell variables, the $ has to be escaped
2985 In order to access normal shell variables, the $ has to be escaped
2973 via an extra $. For example:
2986 via an extra $. For example:
2974
2987
2975 In [7]: PATH='a python variable'
2988 In [7]: PATH='a python variable'
2976
2989
2977 In [8]: !echo $PATH
2990 In [8]: !echo $PATH
2978 a python variable
2991 a python variable
2979
2992
2980 In [9]: !echo $$PATH
2993 In [9]: !echo $$PATH
2981 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2994 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2982
2995
2983 (Magic.parse_options): escape $ so the shell doesn't evaluate
2996 (Magic.parse_options): escape $ so the shell doesn't evaluate
2984 things prematurely.
2997 things prematurely.
2985
2998
2986 * IPython/iplib.py (InteractiveShell.call_alias): added the
2999 * IPython/iplib.py (InteractiveShell.call_alias): added the
2987 ability for aliases to expand python variables via $.
3000 ability for aliases to expand python variables via $.
2988
3001
2989 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
3002 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2990 system, now there's a @rehash/@rehashx pair of magics. These work
3003 system, now there's a @rehash/@rehashx pair of magics. These work
2991 like the csh rehash command, and can be invoked at any time. They
3004 like the csh rehash command, and can be invoked at any time. They
2992 build a table of aliases to everything in the user's $PATH
3005 build a table of aliases to everything in the user's $PATH
2993 (@rehash uses everything, @rehashx is slower but only adds
3006 (@rehash uses everything, @rehashx is slower but only adds
2994 executable files). With this, the pysh.py-based shell profile can
3007 executable files). With this, the pysh.py-based shell profile can
2995 now simply call rehash upon startup, and full access to all
3008 now simply call rehash upon startup, and full access to all
2996 programs in the user's path is obtained.
3009 programs in the user's path is obtained.
2997
3010
2998 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
3011 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2999 functionality is now fully in place. I removed the old dynamic
3012 functionality is now fully in place. I removed the old dynamic
3000 code generation based approach, in favor of a much lighter one
3013 code generation based approach, in favor of a much lighter one
3001 based on a simple dict. The advantage is that this allows me to
3014 based on a simple dict. The advantage is that this allows me to
3002 now have thousands of aliases with negligible cost (unthinkable
3015 now have thousands of aliases with negligible cost (unthinkable
3003 with the old system).
3016 with the old system).
3004
3017
3005 2004-06-19 Fernando Perez <fperez@colorado.edu>
3018 2004-06-19 Fernando Perez <fperez@colorado.edu>
3006
3019
3007 * IPython/iplib.py (__init__): extended MagicCompleter class to
3020 * IPython/iplib.py (__init__): extended MagicCompleter class to
3008 also complete (last in priority) on user aliases.
3021 also complete (last in priority) on user aliases.
3009
3022
3010 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
3023 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
3011 call to eval.
3024 call to eval.
3012 (ItplNS.__init__): Added a new class which functions like Itpl,
3025 (ItplNS.__init__): Added a new class which functions like Itpl,
3013 but allows configuring the namespace for the evaluation to occur
3026 but allows configuring the namespace for the evaluation to occur
3014 in.
3027 in.
3015
3028
3016 2004-06-18 Fernando Perez <fperez@colorado.edu>
3029 2004-06-18 Fernando Perez <fperez@colorado.edu>
3017
3030
3018 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
3031 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
3019 better message when 'exit' or 'quit' are typed (a common newbie
3032 better message when 'exit' or 'quit' are typed (a common newbie
3020 confusion).
3033 confusion).
3021
3034
3022 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
3035 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
3023 check for Windows users.
3036 check for Windows users.
3024
3037
3025 * IPython/iplib.py (InteractiveShell.user_setup): removed
3038 * IPython/iplib.py (InteractiveShell.user_setup): removed
3026 disabling of colors for Windows. I'll test at runtime and issue a
3039 disabling of colors for Windows. I'll test at runtime and issue a
3027 warning if Gary's readline isn't found, as to nudge users to
3040 warning if Gary's readline isn't found, as to nudge users to
3028 download it.
3041 download it.
3029
3042
3030 2004-06-16 Fernando Perez <fperez@colorado.edu>
3043 2004-06-16 Fernando Perez <fperez@colorado.edu>
3031
3044
3032 * IPython/genutils.py (Stream.__init__): changed to print errors
3045 * IPython/genutils.py (Stream.__init__): changed to print errors
3033 to sys.stderr. I had a circular dependency here. Now it's
3046 to sys.stderr. I had a circular dependency here. Now it's
3034 possible to run ipython as IDLE's shell (consider this pre-alpha,
3047 possible to run ipython as IDLE's shell (consider this pre-alpha,
3035 since true stdout things end up in the starting terminal instead
3048 since true stdout things end up in the starting terminal instead
3036 of IDLE's out).
3049 of IDLE's out).
3037
3050
3038 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
3051 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
3039 users who haven't # updated their prompt_in2 definitions. Remove
3052 users who haven't # updated their prompt_in2 definitions. Remove
3040 eventually.
3053 eventually.
3041 (multiple_replace): added credit to original ASPN recipe.
3054 (multiple_replace): added credit to original ASPN recipe.
3042
3055
3043 2004-06-15 Fernando Perez <fperez@colorado.edu>
3056 2004-06-15 Fernando Perez <fperez@colorado.edu>
3044
3057
3045 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
3058 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
3046 list of auto-defined aliases.
3059 list of auto-defined aliases.
3047
3060
3048 2004-06-13 Fernando Perez <fperez@colorado.edu>
3061 2004-06-13 Fernando Perez <fperez@colorado.edu>
3049
3062
3050 * setup.py (scriptfiles): Don't trigger win_post_install unless an
3063 * setup.py (scriptfiles): Don't trigger win_post_install unless an
3051 install was really requested (so setup.py can be used for other
3064 install was really requested (so setup.py can be used for other
3052 things under Windows).
3065 things under Windows).
3053
3066
3054 2004-06-10 Fernando Perez <fperez@colorado.edu>
3067 2004-06-10 Fernando Perez <fperez@colorado.edu>
3055
3068
3056 * IPython/Logger.py (Logger.create_log): Manually remove any old
3069 * IPython/Logger.py (Logger.create_log): Manually remove any old
3057 backup, since os.remove may fail under Windows. Fixes bug
3070 backup, since os.remove may fail under Windows. Fixes bug
3058 reported by Thorsten.
3071 reported by Thorsten.
3059
3072
3060 2004-06-09 Fernando Perez <fperez@colorado.edu>
3073 2004-06-09 Fernando Perez <fperez@colorado.edu>
3061
3074
3062 * examples/example-embed.py: fixed all references to %n (replaced
3075 * examples/example-embed.py: fixed all references to %n (replaced
3063 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
3076 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
3064 for all examples and the manual as well.
3077 for all examples and the manual as well.
3065
3078
3066 2004-06-08 Fernando Perez <fperez@colorado.edu>
3079 2004-06-08 Fernando Perez <fperez@colorado.edu>
3067
3080
3068 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
3081 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
3069 alignment and color management. All 3 prompt subsystems now
3082 alignment and color management. All 3 prompt subsystems now
3070 inherit from BasePrompt.
3083 inherit from BasePrompt.
3071
3084
3072 * tools/release: updates for windows installer build and tag rpms
3085 * tools/release: updates for windows installer build and tag rpms
3073 with python version (since paths are fixed).
3086 with python version (since paths are fixed).
3074
3087
3075 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
3088 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
3076 which will become eventually obsolete. Also fixed the default
3089 which will become eventually obsolete. Also fixed the default
3077 prompt_in2 to use \D, so at least new users start with the correct
3090 prompt_in2 to use \D, so at least new users start with the correct
3078 defaults.
3091 defaults.
3079 WARNING: Users with existing ipythonrc files will need to apply
3092 WARNING: Users with existing ipythonrc files will need to apply
3080 this fix manually!
3093 this fix manually!
3081
3094
3082 * setup.py: make windows installer (.exe). This is finally the
3095 * setup.py: make windows installer (.exe). This is finally the
3083 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
3096 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
3084 which I hadn't included because it required Python 2.3 (or recent
3097 which I hadn't included because it required Python 2.3 (or recent
3085 distutils).
3098 distutils).
3086
3099
3087 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
3100 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
3088 usage of new '\D' escape.
3101 usage of new '\D' escape.
3089
3102
3090 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
3103 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
3091 lacks os.getuid())
3104 lacks os.getuid())
3092 (CachedOutput.set_colors): Added the ability to turn coloring
3105 (CachedOutput.set_colors): Added the ability to turn coloring
3093 on/off with @colors even for manually defined prompt colors. It
3106 on/off with @colors even for manually defined prompt colors. It
3094 uses a nasty global, but it works safely and via the generic color
3107 uses a nasty global, but it works safely and via the generic color
3095 handling mechanism.
3108 handling mechanism.
3096 (Prompt2.__init__): Introduced new escape '\D' for continuation
3109 (Prompt2.__init__): Introduced new escape '\D' for continuation
3097 prompts. It represents the counter ('\#') as dots.
3110 prompts. It represents the counter ('\#') as dots.
3098 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
3111 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
3099 need to update their ipythonrc files and replace '%n' with '\D' in
3112 need to update their ipythonrc files and replace '%n' with '\D' in
3100 their prompt_in2 settings everywhere. Sorry, but there's
3113 their prompt_in2 settings everywhere. Sorry, but there's
3101 otherwise no clean way to get all prompts to properly align. The
3114 otherwise no clean way to get all prompts to properly align. The
3102 ipythonrc shipped with IPython has been updated.
3115 ipythonrc shipped with IPython has been updated.
3103
3116
3104 2004-06-07 Fernando Perez <fperez@colorado.edu>
3117 2004-06-07 Fernando Perez <fperez@colorado.edu>
3105
3118
3106 * setup.py (isfile): Pass local_icons option to latex2html, so the
3119 * setup.py (isfile): Pass local_icons option to latex2html, so the
3107 resulting HTML file is self-contained. Thanks to
3120 resulting HTML file is self-contained. Thanks to
3108 dryice-AT-liu.com.cn for the tip.
3121 dryice-AT-liu.com.cn for the tip.
3109
3122
3110 * pysh.py: I created a new profile 'shell', which implements a
3123 * pysh.py: I created a new profile 'shell', which implements a
3111 _rudimentary_ IPython-based shell. This is in NO WAY a realy
3124 _rudimentary_ IPython-based shell. This is in NO WAY a realy
3112 system shell, nor will it become one anytime soon. It's mainly
3125 system shell, nor will it become one anytime soon. It's mainly
3113 meant to illustrate the use of the new flexible bash-like prompts.
3126 meant to illustrate the use of the new flexible bash-like prompts.
3114 I guess it could be used by hardy souls for true shell management,
3127 I guess it could be used by hardy souls for true shell management,
3115 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
3128 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
3116 profile. This uses the InterpreterExec extension provided by
3129 profile. This uses the InterpreterExec extension provided by
3117 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
3130 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
3118
3131
3119 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
3132 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
3120 auto-align itself with the length of the previous input prompt
3133 auto-align itself with the length of the previous input prompt
3121 (taking into account the invisible color escapes).
3134 (taking into account the invisible color escapes).
3122 (CachedOutput.__init__): Large restructuring of this class. Now
3135 (CachedOutput.__init__): Large restructuring of this class. Now
3123 all three prompts (primary1, primary2, output) are proper objects,
3136 all three prompts (primary1, primary2, output) are proper objects,
3124 managed by the 'parent' CachedOutput class. The code is still a
3137 managed by the 'parent' CachedOutput class. The code is still a
3125 bit hackish (all prompts share state via a pointer to the cache),
3138 bit hackish (all prompts share state via a pointer to the cache),
3126 but it's overall far cleaner than before.
3139 but it's overall far cleaner than before.
3127
3140
3128 * IPython/genutils.py (getoutputerror): modified to add verbose,
3141 * IPython/genutils.py (getoutputerror): modified to add verbose,
3129 debug and header options. This makes the interface of all getout*
3142 debug and header options. This makes the interface of all getout*
3130 functions uniform.
3143 functions uniform.
3131 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
3144 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
3132
3145
3133 * IPython/Magic.py (Magic.default_option): added a function to
3146 * IPython/Magic.py (Magic.default_option): added a function to
3134 allow registering default options for any magic command. This
3147 allow registering default options for any magic command. This
3135 makes it easy to have profiles which customize the magics globally
3148 makes it easy to have profiles which customize the magics globally
3136 for a certain use. The values set through this function are
3149 for a certain use. The values set through this function are
3137 picked up by the parse_options() method, which all magics should
3150 picked up by the parse_options() method, which all magics should
3138 use to parse their options.
3151 use to parse their options.
3139
3152
3140 * IPython/genutils.py (warn): modified the warnings framework to
3153 * IPython/genutils.py (warn): modified the warnings framework to
3141 use the Term I/O class. I'm trying to slowly unify all of
3154 use the Term I/O class. I'm trying to slowly unify all of
3142 IPython's I/O operations to pass through Term.
3155 IPython's I/O operations to pass through Term.
3143
3156
3144 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
3157 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
3145 the secondary prompt to correctly match the length of the primary
3158 the secondary prompt to correctly match the length of the primary
3146 one for any prompt. Now multi-line code will properly line up
3159 one for any prompt. Now multi-line code will properly line up
3147 even for path dependent prompts, such as the new ones available
3160 even for path dependent prompts, such as the new ones available
3148 via the prompt_specials.
3161 via the prompt_specials.
3149
3162
3150 2004-06-06 Fernando Perez <fperez@colorado.edu>
3163 2004-06-06 Fernando Perez <fperez@colorado.edu>
3151
3164
3152 * IPython/Prompts.py (prompt_specials): Added the ability to have
3165 * IPython/Prompts.py (prompt_specials): Added the ability to have
3153 bash-like special sequences in the prompts, which get
3166 bash-like special sequences in the prompts, which get
3154 automatically expanded. Things like hostname, current working
3167 automatically expanded. Things like hostname, current working
3155 directory and username are implemented already, but it's easy to
3168 directory and username are implemented already, but it's easy to
3156 add more in the future. Thanks to a patch by W.J. van der Laan
3169 add more in the future. Thanks to a patch by W.J. van der Laan
3157 <gnufnork-AT-hetdigitalegat.nl>
3170 <gnufnork-AT-hetdigitalegat.nl>
3158 (prompt_specials): Added color support for prompt strings, so
3171 (prompt_specials): Added color support for prompt strings, so
3159 users can define arbitrary color setups for their prompts.
3172 users can define arbitrary color setups for their prompts.
3160
3173
3161 2004-06-05 Fernando Perez <fperez@colorado.edu>
3174 2004-06-05 Fernando Perez <fperez@colorado.edu>
3162
3175
3163 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
3176 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
3164 code to load Gary Bishop's readline and configure it
3177 code to load Gary Bishop's readline and configure it
3165 automatically. Thanks to Gary for help on this.
3178 automatically. Thanks to Gary for help on this.
3166
3179
3167 2004-06-01 Fernando Perez <fperez@colorado.edu>
3180 2004-06-01 Fernando Perez <fperez@colorado.edu>
3168
3181
3169 * IPython/Logger.py (Logger.create_log): fix bug for logging
3182 * IPython/Logger.py (Logger.create_log): fix bug for logging
3170 with no filename (previous fix was incomplete).
3183 with no filename (previous fix was incomplete).
3171
3184
3172 2004-05-25 Fernando Perez <fperez@colorado.edu>
3185 2004-05-25 Fernando Perez <fperez@colorado.edu>
3173
3186
3174 * IPython/Magic.py (Magic.parse_options): fix bug where naked
3187 * IPython/Magic.py (Magic.parse_options): fix bug where naked
3175 parens would get passed to the shell.
3188 parens would get passed to the shell.
3176
3189
3177 2004-05-20 Fernando Perez <fperez@colorado.edu>
3190 2004-05-20 Fernando Perez <fperez@colorado.edu>
3178
3191
3179 * IPython/Magic.py (Magic.magic_prun): changed default profile
3192 * IPython/Magic.py (Magic.magic_prun): changed default profile
3180 sort order to 'time' (the more common profiling need).
3193 sort order to 'time' (the more common profiling need).
3181
3194
3182 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
3195 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
3183 so that source code shown is guaranteed in sync with the file on
3196 so that source code shown is guaranteed in sync with the file on
3184 disk (also changed in psource). Similar fix to the one for
3197 disk (also changed in psource). Similar fix to the one for
3185 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
3198 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
3186 <yann.ledu-AT-noos.fr>.
3199 <yann.ledu-AT-noos.fr>.
3187
3200
3188 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
3201 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
3189 with a single option would not be correctly parsed. Closes
3202 with a single option would not be correctly parsed. Closes
3190 http://www.scipy.net/roundup/ipython/issue14. This bug had been
3203 http://www.scipy.net/roundup/ipython/issue14. This bug had been
3191 introduced in 0.6.0 (on 2004-05-06).
3204 introduced in 0.6.0 (on 2004-05-06).
3192
3205
3193 2004-05-13 *** Released version 0.6.0
3206 2004-05-13 *** Released version 0.6.0
3194
3207
3195 2004-05-13 Fernando Perez <fperez@colorado.edu>
3208 2004-05-13 Fernando Perez <fperez@colorado.edu>
3196
3209
3197 * debian/: Added debian/ directory to CVS, so that debian support
3210 * debian/: Added debian/ directory to CVS, so that debian support
3198 is publicly accessible. The debian package is maintained by Jack
3211 is publicly accessible. The debian package is maintained by Jack
3199 Moffit <jack-AT-xiph.org>.
3212 Moffit <jack-AT-xiph.org>.
3200
3213
3201 * Documentation: included the notes about an ipython-based system
3214 * Documentation: included the notes about an ipython-based system
3202 shell (the hypothetical 'pysh') into the new_design.pdf document,
3215 shell (the hypothetical 'pysh') into the new_design.pdf document,
3203 so that these ideas get distributed to users along with the
3216 so that these ideas get distributed to users along with the
3204 official documentation.
3217 official documentation.
3205
3218
3206 2004-05-10 Fernando Perez <fperez@colorado.edu>
3219 2004-05-10 Fernando Perez <fperez@colorado.edu>
3207
3220
3208 * IPython/Logger.py (Logger.create_log): fix recently introduced
3221 * IPython/Logger.py (Logger.create_log): fix recently introduced
3209 bug (misindented line) where logstart would fail when not given an
3222 bug (misindented line) where logstart would fail when not given an
3210 explicit filename.
3223 explicit filename.
3211
3224
3212 2004-05-09 Fernando Perez <fperez@colorado.edu>
3225 2004-05-09 Fernando Perez <fperez@colorado.edu>
3213
3226
3214 * IPython/Magic.py (Magic.parse_options): skip system call when
3227 * IPython/Magic.py (Magic.parse_options): skip system call when
3215 there are no options to look for. Faster, cleaner for the common
3228 there are no options to look for. Faster, cleaner for the common
3216 case.
3229 case.
3217
3230
3218 * Documentation: many updates to the manual: describing Windows
3231 * Documentation: many updates to the manual: describing Windows
3219 support better, Gnuplot updates, credits, misc small stuff. Also
3232 support better, Gnuplot updates, credits, misc small stuff. Also
3220 updated the new_design doc a bit.
3233 updated the new_design doc a bit.
3221
3234
3222 2004-05-06 *** Released version 0.6.0.rc1
3235 2004-05-06 *** Released version 0.6.0.rc1
3223
3236
3224 2004-05-06 Fernando Perez <fperez@colorado.edu>
3237 2004-05-06 Fernando Perez <fperez@colorado.edu>
3225
3238
3226 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
3239 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
3227 operations to use the vastly more efficient list/''.join() method.
3240 operations to use the vastly more efficient list/''.join() method.
3228 (FormattedTB.text): Fix
3241 (FormattedTB.text): Fix
3229 http://www.scipy.net/roundup/ipython/issue12 - exception source
3242 http://www.scipy.net/roundup/ipython/issue12 - exception source
3230 extract not updated after reload. Thanks to Mike Salib
3243 extract not updated after reload. Thanks to Mike Salib
3231 <msalib-AT-mit.edu> for pinning the source of the problem.
3244 <msalib-AT-mit.edu> for pinning the source of the problem.
3232 Fortunately, the solution works inside ipython and doesn't require
3245 Fortunately, the solution works inside ipython and doesn't require
3233 any changes to python proper.
3246 any changes to python proper.
3234
3247
3235 * IPython/Magic.py (Magic.parse_options): Improved to process the
3248 * IPython/Magic.py (Magic.parse_options): Improved to process the
3236 argument list as a true shell would (by actually using the
3249 argument list as a true shell would (by actually using the
3237 underlying system shell). This way, all @magics automatically get
3250 underlying system shell). This way, all @magics automatically get
3238 shell expansion for variables. Thanks to a comment by Alex
3251 shell expansion for variables. Thanks to a comment by Alex
3239 Schmolck.
3252 Schmolck.
3240
3253
3241 2004-04-04 Fernando Perez <fperez@colorado.edu>
3254 2004-04-04 Fernando Perez <fperez@colorado.edu>
3242
3255
3243 * IPython/iplib.py (InteractiveShell.interact): Added a special
3256 * IPython/iplib.py (InteractiveShell.interact): Added a special
3244 trap for a debugger quit exception, which is basically impossible
3257 trap for a debugger quit exception, which is basically impossible
3245 to handle by normal mechanisms, given what pdb does to the stack.
3258 to handle by normal mechanisms, given what pdb does to the stack.
3246 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
3259 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
3247
3260
3248 2004-04-03 Fernando Perez <fperez@colorado.edu>
3261 2004-04-03 Fernando Perez <fperez@colorado.edu>
3249
3262
3250 * IPython/genutils.py (Term): Standardized the names of the Term
3263 * IPython/genutils.py (Term): Standardized the names of the Term
3251 class streams to cin/cout/cerr, following C++ naming conventions
3264 class streams to cin/cout/cerr, following C++ naming conventions
3252 (I can't use in/out/err because 'in' is not a valid attribute
3265 (I can't use in/out/err because 'in' is not a valid attribute
3253 name).
3266 name).
3254
3267
3255 * IPython/iplib.py (InteractiveShell.interact): don't increment
3268 * IPython/iplib.py (InteractiveShell.interact): don't increment
3256 the prompt if there's no user input. By Daniel 'Dang' Griffith
3269 the prompt if there's no user input. By Daniel 'Dang' Griffith
3257 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
3270 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
3258 Francois Pinard.
3271 Francois Pinard.
3259
3272
3260 2004-04-02 Fernando Perez <fperez@colorado.edu>
3273 2004-04-02 Fernando Perez <fperez@colorado.edu>
3261
3274
3262 * IPython/genutils.py (Stream.__init__): Modified to survive at
3275 * IPython/genutils.py (Stream.__init__): Modified to survive at
3263 least importing in contexts where stdin/out/err aren't true file
3276 least importing in contexts where stdin/out/err aren't true file
3264 objects, such as PyCrust (they lack fileno() and mode). However,
3277 objects, such as PyCrust (they lack fileno() and mode). However,
3265 the recovery facilities which rely on these things existing will
3278 the recovery facilities which rely on these things existing will
3266 not work.
3279 not work.
3267
3280
3268 2004-04-01 Fernando Perez <fperez@colorado.edu>
3281 2004-04-01 Fernando Perez <fperez@colorado.edu>
3269
3282
3270 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
3283 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
3271 use the new getoutputerror() function, so it properly
3284 use the new getoutputerror() function, so it properly
3272 distinguishes stdout/err.
3285 distinguishes stdout/err.
3273
3286
3274 * IPython/genutils.py (getoutputerror): added a function to
3287 * IPython/genutils.py (getoutputerror): added a function to
3275 capture separately the standard output and error of a command.
3288 capture separately the standard output and error of a command.
3276 After a comment from dang on the mailing lists. This code is
3289 After a comment from dang on the mailing lists. This code is
3277 basically a modified version of commands.getstatusoutput(), from
3290 basically a modified version of commands.getstatusoutput(), from
3278 the standard library.
3291 the standard library.
3279
3292
3280 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
3293 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
3281 '!!' as a special syntax (shorthand) to access @sx.
3294 '!!' as a special syntax (shorthand) to access @sx.
3282
3295
3283 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
3296 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
3284 command and return its output as a list split on '\n'.
3297 command and return its output as a list split on '\n'.
3285
3298
3286 2004-03-31 Fernando Perez <fperez@colorado.edu>
3299 2004-03-31 Fernando Perez <fperez@colorado.edu>
3287
3300
3288 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
3301 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
3289 method to dictionaries used as FakeModule instances if they lack
3302 method to dictionaries used as FakeModule instances if they lack
3290 it. At least pydoc in python2.3 breaks for runtime-defined
3303 it. At least pydoc in python2.3 breaks for runtime-defined
3291 functions without this hack. At some point I need to _really_
3304 functions without this hack. At some point I need to _really_
3292 understand what FakeModule is doing, because it's a gross hack.
3305 understand what FakeModule is doing, because it's a gross hack.
3293 But it solves Arnd's problem for now...
3306 But it solves Arnd's problem for now...
3294
3307
3295 2004-02-27 Fernando Perez <fperez@colorado.edu>
3308 2004-02-27 Fernando Perez <fperez@colorado.edu>
3296
3309
3297 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
3310 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
3298 mode would behave erratically. Also increased the number of
3311 mode would behave erratically. Also increased the number of
3299 possible logs in rotate mod to 999. Thanks to Rod Holland
3312 possible logs in rotate mod to 999. Thanks to Rod Holland
3300 <rhh@StructureLABS.com> for the report and fixes.
3313 <rhh@StructureLABS.com> for the report and fixes.
3301
3314
3302 2004-02-26 Fernando Perez <fperez@colorado.edu>
3315 2004-02-26 Fernando Perez <fperez@colorado.edu>
3303
3316
3304 * IPython/genutils.py (page): Check that the curses module really
3317 * IPython/genutils.py (page): Check that the curses module really
3305 has the initscr attribute before trying to use it. For some
3318 has the initscr attribute before trying to use it. For some
3306 reason, the Solaris curses module is missing this. I think this
3319 reason, the Solaris curses module is missing this. I think this
3307 should be considered a Solaris python bug, but I'm not sure.
3320 should be considered a Solaris python bug, but I'm not sure.
3308
3321
3309 2004-01-17 Fernando Perez <fperez@colorado.edu>
3322 2004-01-17 Fernando Perez <fperez@colorado.edu>
3310
3323
3311 * IPython/genutils.py (Stream.__init__): Changes to try to make
3324 * IPython/genutils.py (Stream.__init__): Changes to try to make
3312 ipython robust against stdin/out/err being closed by the user.
3325 ipython robust against stdin/out/err being closed by the user.
3313 This is 'user error' (and blocks a normal python session, at least
3326 This is 'user error' (and blocks a normal python session, at least
3314 the stdout case). However, Ipython should be able to survive such
3327 the stdout case). However, Ipython should be able to survive such
3315 instances of abuse as gracefully as possible. To simplify the
3328 instances of abuse as gracefully as possible. To simplify the
3316 coding and maintain compatibility with Gary Bishop's Term
3329 coding and maintain compatibility with Gary Bishop's Term
3317 contributions, I've made use of classmethods for this. I think
3330 contributions, I've made use of classmethods for this. I think
3318 this introduces a dependency on python 2.2.
3331 this introduces a dependency on python 2.2.
3319
3332
3320 2004-01-13 Fernando Perez <fperez@colorado.edu>
3333 2004-01-13 Fernando Perez <fperez@colorado.edu>
3321
3334
3322 * IPython/numutils.py (exp_safe): simplified the code a bit and
3335 * IPython/numutils.py (exp_safe): simplified the code a bit and
3323 removed the need for importing the kinds module altogether.
3336 removed the need for importing the kinds module altogether.
3324
3337
3325 2004-01-06 Fernando Perez <fperez@colorado.edu>
3338 2004-01-06 Fernando Perez <fperez@colorado.edu>
3326
3339
3327 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
3340 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
3328 a magic function instead, after some community feedback. No
3341 a magic function instead, after some community feedback. No
3329 special syntax will exist for it, but its name is deliberately
3342 special syntax will exist for it, but its name is deliberately
3330 very short.
3343 very short.
3331
3344
3332 2003-12-20 Fernando Perez <fperez@colorado.edu>
3345 2003-12-20 Fernando Perez <fperez@colorado.edu>
3333
3346
3334 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
3347 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
3335 new functionality, to automagically assign the result of a shell
3348 new functionality, to automagically assign the result of a shell
3336 command to a variable. I'll solicit some community feedback on
3349 command to a variable. I'll solicit some community feedback on
3337 this before making it permanent.
3350 this before making it permanent.
3338
3351
3339 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
3352 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
3340 requested about callables for which inspect couldn't obtain a
3353 requested about callables for which inspect couldn't obtain a
3341 proper argspec. Thanks to a crash report sent by Etienne
3354 proper argspec. Thanks to a crash report sent by Etienne
3342 Posthumus <etienne-AT-apple01.cs.vu.nl>.
3355 Posthumus <etienne-AT-apple01.cs.vu.nl>.
3343
3356
3344 2003-12-09 Fernando Perez <fperez@colorado.edu>
3357 2003-12-09 Fernando Perez <fperez@colorado.edu>
3345
3358
3346 * IPython/genutils.py (page): patch for the pager to work across
3359 * IPython/genutils.py (page): patch for the pager to work across
3347 various versions of Windows. By Gary Bishop.
3360 various versions of Windows. By Gary Bishop.
3348
3361
3349 2003-12-04 Fernando Perez <fperez@colorado.edu>
3362 2003-12-04 Fernando Perez <fperez@colorado.edu>
3350
3363
3351 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
3364 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
3352 Gnuplot.py version 1.7, whose internal names changed quite a bit.
3365 Gnuplot.py version 1.7, whose internal names changed quite a bit.
3353 While I tested this and it looks ok, there may still be corner
3366 While I tested this and it looks ok, there may still be corner
3354 cases I've missed.
3367 cases I've missed.
3355
3368
3356 2003-12-01 Fernando Perez <fperez@colorado.edu>
3369 2003-12-01 Fernando Perez <fperez@colorado.edu>
3357
3370
3358 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
3371 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
3359 where a line like 'p,q=1,2' would fail because the automagic
3372 where a line like 'p,q=1,2' would fail because the automagic
3360 system would be triggered for @p.
3373 system would be triggered for @p.
3361
3374
3362 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
3375 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
3363 cleanups, code unmodified.
3376 cleanups, code unmodified.
3364
3377
3365 * IPython/genutils.py (Term): added a class for IPython to handle
3378 * IPython/genutils.py (Term): added a class for IPython to handle
3366 output. In most cases it will just be a proxy for stdout/err, but
3379 output. In most cases it will just be a proxy for stdout/err, but
3367 having this allows modifications to be made for some platforms,
3380 having this allows modifications to be made for some platforms,
3368 such as handling color escapes under Windows. All of this code
3381 such as handling color escapes under Windows. All of this code
3369 was contributed by Gary Bishop, with minor modifications by me.
3382 was contributed by Gary Bishop, with minor modifications by me.
3370 The actual changes affect many files.
3383 The actual changes affect many files.
3371
3384
3372 2003-11-30 Fernando Perez <fperez@colorado.edu>
3385 2003-11-30 Fernando Perez <fperez@colorado.edu>
3373
3386
3374 * IPython/iplib.py (file_matches): new completion code, courtesy
3387 * IPython/iplib.py (file_matches): new completion code, courtesy
3375 of Jeff Collins. This enables filename completion again under
3388 of Jeff Collins. This enables filename completion again under
3376 python 2.3, which disabled it at the C level.
3389 python 2.3, which disabled it at the C level.
3377
3390
3378 2003-11-11 Fernando Perez <fperez@colorado.edu>
3391 2003-11-11 Fernando Perez <fperez@colorado.edu>
3379
3392
3380 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
3393 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
3381 for Numeric.array(map(...)), but often convenient.
3394 for Numeric.array(map(...)), but often convenient.
3382
3395
3383 2003-11-05 Fernando Perez <fperez@colorado.edu>
3396 2003-11-05 Fernando Perez <fperez@colorado.edu>
3384
3397
3385 * IPython/numutils.py (frange): Changed a call from int() to
3398 * IPython/numutils.py (frange): Changed a call from int() to
3386 int(round()) to prevent a problem reported with arange() in the
3399 int(round()) to prevent a problem reported with arange() in the
3387 numpy list.
3400 numpy list.
3388
3401
3389 2003-10-06 Fernando Perez <fperez@colorado.edu>
3402 2003-10-06 Fernando Perez <fperez@colorado.edu>
3390
3403
3391 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
3404 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
3392 prevent crashes if sys lacks an argv attribute (it happens with
3405 prevent crashes if sys lacks an argv attribute (it happens with
3393 embedded interpreters which build a bare-bones sys module).
3406 embedded interpreters which build a bare-bones sys module).
3394 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
3407 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
3395
3408
3396 2003-09-24 Fernando Perez <fperez@colorado.edu>
3409 2003-09-24 Fernando Perez <fperez@colorado.edu>
3397
3410
3398 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
3411 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
3399 to protect against poorly written user objects where __getattr__
3412 to protect against poorly written user objects where __getattr__
3400 raises exceptions other than AttributeError. Thanks to a bug
3413 raises exceptions other than AttributeError. Thanks to a bug
3401 report by Oliver Sander <osander-AT-gmx.de>.
3414 report by Oliver Sander <osander-AT-gmx.de>.
3402
3415
3403 * IPython/FakeModule.py (FakeModule.__repr__): this method was
3416 * IPython/FakeModule.py (FakeModule.__repr__): this method was
3404 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
3417 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
3405
3418
3406 2003-09-09 Fernando Perez <fperez@colorado.edu>
3419 2003-09-09 Fernando Perez <fperez@colorado.edu>
3407
3420
3408 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
3421 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
3409 unpacking a list whith a callable as first element would
3422 unpacking a list whith a callable as first element would
3410 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
3423 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
3411 Collins.
3424 Collins.
3412
3425
3413 2003-08-25 *** Released version 0.5.0
3426 2003-08-25 *** Released version 0.5.0
3414
3427
3415 2003-08-22 Fernando Perez <fperez@colorado.edu>
3428 2003-08-22 Fernando Perez <fperez@colorado.edu>
3416
3429
3417 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
3430 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
3418 improperly defined user exceptions. Thanks to feedback from Mark
3431 improperly defined user exceptions. Thanks to feedback from Mark
3419 Russell <mrussell-AT-verio.net>.
3432 Russell <mrussell-AT-verio.net>.
3420
3433
3421 2003-08-20 Fernando Perez <fperez@colorado.edu>
3434 2003-08-20 Fernando Perez <fperez@colorado.edu>
3422
3435
3423 * IPython/OInspect.py (Inspector.pinfo): changed String Form
3436 * IPython/OInspect.py (Inspector.pinfo): changed String Form
3424 printing so that it would print multi-line string forms starting
3437 printing so that it would print multi-line string forms starting
3425 with a new line. This way the formatting is better respected for
3438 with a new line. This way the formatting is better respected for
3426 objects which work hard to make nice string forms.
3439 objects which work hard to make nice string forms.
3427
3440
3428 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
3441 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
3429 autocall would overtake data access for objects with both
3442 autocall would overtake data access for objects with both
3430 __getitem__ and __call__.
3443 __getitem__ and __call__.
3431
3444
3432 2003-08-19 *** Released version 0.5.0-rc1
3445 2003-08-19 *** Released version 0.5.0-rc1
3433
3446
3434 2003-08-19 Fernando Perez <fperez@colorado.edu>
3447 2003-08-19 Fernando Perez <fperez@colorado.edu>
3435
3448
3436 * IPython/deep_reload.py (load_tail): single tiny change here
3449 * IPython/deep_reload.py (load_tail): single tiny change here
3437 seems to fix the long-standing bug of dreload() failing to work
3450 seems to fix the long-standing bug of dreload() failing to work
3438 for dotted names. But this module is pretty tricky, so I may have
3451 for dotted names. But this module is pretty tricky, so I may have
3439 missed some subtlety. Needs more testing!.
3452 missed some subtlety. Needs more testing!.
3440
3453
3441 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
3454 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
3442 exceptions which have badly implemented __str__ methods.
3455 exceptions which have badly implemented __str__ methods.
3443 (VerboseTB.text): harden against inspect.getinnerframes crashing,
3456 (VerboseTB.text): harden against inspect.getinnerframes crashing,
3444 which I've been getting reports about from Python 2.3 users. I
3457 which I've been getting reports about from Python 2.3 users. I
3445 wish I had a simple test case to reproduce the problem, so I could
3458 wish I had a simple test case to reproduce the problem, so I could
3446 either write a cleaner workaround or file a bug report if
3459 either write a cleaner workaround or file a bug report if
3447 necessary.
3460 necessary.
3448
3461
3449 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
3462 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
3450 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
3463 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
3451 a bug report by Tjabo Kloppenburg.
3464 a bug report by Tjabo Kloppenburg.
3452
3465
3453 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
3466 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
3454 crashes. Wrapped the pdb call in a blanket try/except, since pdb
3467 crashes. Wrapped the pdb call in a blanket try/except, since pdb
3455 seems rather unstable. Thanks to a bug report by Tjabo
3468 seems rather unstable. Thanks to a bug report by Tjabo
3456 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
3469 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
3457
3470
3458 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
3471 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
3459 this out soon because of the critical fixes in the inner loop for
3472 this out soon because of the critical fixes in the inner loop for
3460 generators.
3473 generators.
3461
3474
3462 * IPython/Magic.py (Magic.getargspec): removed. This (and
3475 * IPython/Magic.py (Magic.getargspec): removed. This (and
3463 _get_def) have been obsoleted by OInspect for a long time, I
3476 _get_def) have been obsoleted by OInspect for a long time, I
3464 hadn't noticed that they were dead code.
3477 hadn't noticed that they were dead code.
3465 (Magic._ofind): restored _ofind functionality for a few literals
3478 (Magic._ofind): restored _ofind functionality for a few literals
3466 (those in ["''",'""','[]','{}','()']). But it won't work anymore
3479 (those in ["''",'""','[]','{}','()']). But it won't work anymore
3467 for things like "hello".capitalize?, since that would require a
3480 for things like "hello".capitalize?, since that would require a
3468 potentially dangerous eval() again.
3481 potentially dangerous eval() again.
3469
3482
3470 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
3483 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
3471 logic a bit more to clean up the escapes handling and minimize the
3484 logic a bit more to clean up the escapes handling and minimize the
3472 use of _ofind to only necessary cases. The interactive 'feel' of
3485 use of _ofind to only necessary cases. The interactive 'feel' of
3473 IPython should have improved quite a bit with the changes in
3486 IPython should have improved quite a bit with the changes in
3474 _prefilter and _ofind (besides being far safer than before).
3487 _prefilter and _ofind (besides being far safer than before).
3475
3488
3476 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
3489 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
3477 obscure, never reported). Edit would fail to find the object to
3490 obscure, never reported). Edit would fail to find the object to
3478 edit under some circumstances.
3491 edit under some circumstances.
3479 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
3492 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
3480 which were causing double-calling of generators. Those eval calls
3493 which were causing double-calling of generators. Those eval calls
3481 were _very_ dangerous, since code with side effects could be
3494 were _very_ dangerous, since code with side effects could be
3482 triggered. As they say, 'eval is evil'... These were the
3495 triggered. As they say, 'eval is evil'... These were the
3483 nastiest evals in IPython. Besides, _ofind is now far simpler,
3496 nastiest evals in IPython. Besides, _ofind is now far simpler,
3484 and it should also be quite a bit faster. Its use of inspect is
3497 and it should also be quite a bit faster. Its use of inspect is
3485 also safer, so perhaps some of the inspect-related crashes I've
3498 also safer, so perhaps some of the inspect-related crashes I've
3486 seen lately with Python 2.3 might be taken care of. That will
3499 seen lately with Python 2.3 might be taken care of. That will
3487 need more testing.
3500 need more testing.
3488
3501
3489 2003-08-17 Fernando Perez <fperez@colorado.edu>
3502 2003-08-17 Fernando Perez <fperez@colorado.edu>
3490
3503
3491 * IPython/iplib.py (InteractiveShell._prefilter): significant
3504 * IPython/iplib.py (InteractiveShell._prefilter): significant
3492 simplifications to the logic for handling user escapes. Faster
3505 simplifications to the logic for handling user escapes. Faster
3493 and simpler code.
3506 and simpler code.
3494
3507
3495 2003-08-14 Fernando Perez <fperez@colorado.edu>
3508 2003-08-14 Fernando Perez <fperez@colorado.edu>
3496
3509
3497 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
3510 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
3498 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
3511 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
3499 but it should be quite a bit faster. And the recursive version
3512 but it should be quite a bit faster. And the recursive version
3500 generated O(log N) intermediate storage for all rank>1 arrays,
3513 generated O(log N) intermediate storage for all rank>1 arrays,
3501 even if they were contiguous.
3514 even if they were contiguous.
3502 (l1norm): Added this function.
3515 (l1norm): Added this function.
3503 (norm): Added this function for arbitrary norms (including
3516 (norm): Added this function for arbitrary norms (including
3504 l-infinity). l1 and l2 are still special cases for convenience
3517 l-infinity). l1 and l2 are still special cases for convenience
3505 and speed.
3518 and speed.
3506
3519
3507 2003-08-03 Fernando Perez <fperez@colorado.edu>
3520 2003-08-03 Fernando Perez <fperez@colorado.edu>
3508
3521
3509 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
3522 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
3510 exceptions, which now raise PendingDeprecationWarnings in Python
3523 exceptions, which now raise PendingDeprecationWarnings in Python
3511 2.3. There were some in Magic and some in Gnuplot2.
3524 2.3. There were some in Magic and some in Gnuplot2.
3512
3525
3513 2003-06-30 Fernando Perez <fperez@colorado.edu>
3526 2003-06-30 Fernando Perez <fperez@colorado.edu>
3514
3527
3515 * IPython/genutils.py (page): modified to call curses only for
3528 * IPython/genutils.py (page): modified to call curses only for
3516 terminals where TERM=='xterm'. After problems under many other
3529 terminals where TERM=='xterm'. After problems under many other
3517 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
3530 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
3518
3531
3519 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
3532 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
3520 would be triggered when readline was absent. This was just an old
3533 would be triggered when readline was absent. This was just an old
3521 debugging statement I'd forgotten to take out.
3534 debugging statement I'd forgotten to take out.
3522
3535
3523 2003-06-20 Fernando Perez <fperez@colorado.edu>
3536 2003-06-20 Fernando Perez <fperez@colorado.edu>
3524
3537
3525 * IPython/genutils.py (clock): modified to return only user time
3538 * IPython/genutils.py (clock): modified to return only user time
3526 (not counting system time), after a discussion on scipy. While
3539 (not counting system time), after a discussion on scipy. While
3527 system time may be a useful quantity occasionally, it may much
3540 system time may be a useful quantity occasionally, it may much
3528 more easily be skewed by occasional swapping or other similar
3541 more easily be skewed by occasional swapping or other similar
3529 activity.
3542 activity.
3530
3543
3531 2003-06-05 Fernando Perez <fperez@colorado.edu>
3544 2003-06-05 Fernando Perez <fperez@colorado.edu>
3532
3545
3533 * IPython/numutils.py (identity): new function, for building
3546 * IPython/numutils.py (identity): new function, for building
3534 arbitrary rank Kronecker deltas (mostly backwards compatible with
3547 arbitrary rank Kronecker deltas (mostly backwards compatible with
3535 Numeric.identity)
3548 Numeric.identity)
3536
3549
3537 2003-06-03 Fernando Perez <fperez@colorado.edu>
3550 2003-06-03 Fernando Perez <fperez@colorado.edu>
3538
3551
3539 * IPython/iplib.py (InteractiveShell.handle_magic): protect
3552 * IPython/iplib.py (InteractiveShell.handle_magic): protect
3540 arguments passed to magics with spaces, to allow trailing '\' to
3553 arguments passed to magics with spaces, to allow trailing '\' to
3541 work normally (mainly for Windows users).
3554 work normally (mainly for Windows users).
3542
3555
3543 2003-05-29 Fernando Perez <fperez@colorado.edu>
3556 2003-05-29 Fernando Perez <fperez@colorado.edu>
3544
3557
3545 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
3558 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
3546 instead of pydoc.help. This fixes a bizarre behavior where
3559 instead of pydoc.help. This fixes a bizarre behavior where
3547 printing '%s' % locals() would trigger the help system. Now
3560 printing '%s' % locals() would trigger the help system. Now
3548 ipython behaves like normal python does.
3561 ipython behaves like normal python does.
3549
3562
3550 Note that if one does 'from pydoc import help', the bizarre
3563 Note that if one does 'from pydoc import help', the bizarre
3551 behavior returns, but this will also happen in normal python, so
3564 behavior returns, but this will also happen in normal python, so
3552 it's not an ipython bug anymore (it has to do with how pydoc.help
3565 it's not an ipython bug anymore (it has to do with how pydoc.help
3553 is implemented).
3566 is implemented).
3554
3567
3555 2003-05-22 Fernando Perez <fperez@colorado.edu>
3568 2003-05-22 Fernando Perez <fperez@colorado.edu>
3556
3569
3557 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
3570 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
3558 return [] instead of None when nothing matches, also match to end
3571 return [] instead of None when nothing matches, also match to end
3559 of line. Patch by Gary Bishop.
3572 of line. Patch by Gary Bishop.
3560
3573
3561 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
3574 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
3562 protection as before, for files passed on the command line. This
3575 protection as before, for files passed on the command line. This
3563 prevents the CrashHandler from kicking in if user files call into
3576 prevents the CrashHandler from kicking in if user files call into
3564 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
3577 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
3565 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
3578 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
3566
3579
3567 2003-05-20 *** Released version 0.4.0
3580 2003-05-20 *** Released version 0.4.0
3568
3581
3569 2003-05-20 Fernando Perez <fperez@colorado.edu>
3582 2003-05-20 Fernando Perez <fperez@colorado.edu>
3570
3583
3571 * setup.py: added support for manpages. It's a bit hackish b/c of
3584 * setup.py: added support for manpages. It's a bit hackish b/c of
3572 a bug in the way the bdist_rpm distutils target handles gzipped
3585 a bug in the way the bdist_rpm distutils target handles gzipped
3573 manpages, but it works. After a patch by Jack.
3586 manpages, but it works. After a patch by Jack.
3574
3587
3575 2003-05-19 Fernando Perez <fperez@colorado.edu>
3588 2003-05-19 Fernando Perez <fperez@colorado.edu>
3576
3589
3577 * IPython/numutils.py: added a mockup of the kinds module, since
3590 * IPython/numutils.py: added a mockup of the kinds module, since
3578 it was recently removed from Numeric. This way, numutils will
3591 it was recently removed from Numeric. This way, numutils will
3579 work for all users even if they are missing kinds.
3592 work for all users even if they are missing kinds.
3580
3593
3581 * IPython/Magic.py (Magic._ofind): Harden against an inspect
3594 * IPython/Magic.py (Magic._ofind): Harden against an inspect
3582 failure, which can occur with SWIG-wrapped extensions. After a
3595 failure, which can occur with SWIG-wrapped extensions. After a
3583 crash report from Prabhu.
3596 crash report from Prabhu.
3584
3597
3585 2003-05-16 Fernando Perez <fperez@colorado.edu>
3598 2003-05-16 Fernando Perez <fperez@colorado.edu>
3586
3599
3587 * IPython/iplib.py (InteractiveShell.excepthook): New method to
3600 * IPython/iplib.py (InteractiveShell.excepthook): New method to
3588 protect ipython from user code which may call directly
3601 protect ipython from user code which may call directly
3589 sys.excepthook (this looks like an ipython crash to the user, even
3602 sys.excepthook (this looks like an ipython crash to the user, even
3590 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3603 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3591 This is especially important to help users of WxWindows, but may
3604 This is especially important to help users of WxWindows, but may
3592 also be useful in other cases.
3605 also be useful in other cases.
3593
3606
3594 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
3607 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
3595 an optional tb_offset to be specified, and to preserve exception
3608 an optional tb_offset to be specified, and to preserve exception
3596 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3609 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3597
3610
3598 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
3611 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
3599
3612
3600 2003-05-15 Fernando Perez <fperez@colorado.edu>
3613 2003-05-15 Fernando Perez <fperez@colorado.edu>
3601
3614
3602 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
3615 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
3603 installing for a new user under Windows.
3616 installing for a new user under Windows.
3604
3617
3605 2003-05-12 Fernando Perez <fperez@colorado.edu>
3618 2003-05-12 Fernando Perez <fperez@colorado.edu>
3606
3619
3607 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
3620 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
3608 handler for Emacs comint-based lines. Currently it doesn't do
3621 handler for Emacs comint-based lines. Currently it doesn't do
3609 much (but importantly, it doesn't update the history cache). In
3622 much (but importantly, it doesn't update the history cache). In
3610 the future it may be expanded if Alex needs more functionality
3623 the future it may be expanded if Alex needs more functionality
3611 there.
3624 there.
3612
3625
3613 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
3626 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
3614 info to crash reports.
3627 info to crash reports.
3615
3628
3616 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
3629 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
3617 just like Python's -c. Also fixed crash with invalid -color
3630 just like Python's -c. Also fixed crash with invalid -color
3618 option value at startup. Thanks to Will French
3631 option value at startup. Thanks to Will French
3619 <wfrench-AT-bestweb.net> for the bug report.
3632 <wfrench-AT-bestweb.net> for the bug report.
3620
3633
3621 2003-05-09 Fernando Perez <fperez@colorado.edu>
3634 2003-05-09 Fernando Perez <fperez@colorado.edu>
3622
3635
3623 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
3636 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
3624 to EvalDict (it's a mapping, after all) and simplified its code
3637 to EvalDict (it's a mapping, after all) and simplified its code
3625 quite a bit, after a nice discussion on c.l.py where Gustavo
3638 quite a bit, after a nice discussion on c.l.py where Gustavo
3626 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
3639 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
3627
3640
3628 2003-04-30 Fernando Perez <fperez@colorado.edu>
3641 2003-04-30 Fernando Perez <fperez@colorado.edu>
3629
3642
3630 * IPython/genutils.py (timings_out): modified it to reduce its
3643 * IPython/genutils.py (timings_out): modified it to reduce its
3631 overhead in the common reps==1 case.
3644 overhead in the common reps==1 case.
3632
3645
3633 2003-04-29 Fernando Perez <fperez@colorado.edu>
3646 2003-04-29 Fernando Perez <fperez@colorado.edu>
3634
3647
3635 * IPython/genutils.py (timings_out): Modified to use the resource
3648 * IPython/genutils.py (timings_out): Modified to use the resource
3636 module, which avoids the wraparound problems of time.clock().
3649 module, which avoids the wraparound problems of time.clock().
3637
3650
3638 2003-04-17 *** Released version 0.2.15pre4
3651 2003-04-17 *** Released version 0.2.15pre4
3639
3652
3640 2003-04-17 Fernando Perez <fperez@colorado.edu>
3653 2003-04-17 Fernando Perez <fperez@colorado.edu>
3641
3654
3642 * setup.py (scriptfiles): Split windows-specific stuff over to a
3655 * setup.py (scriptfiles): Split windows-specific stuff over to a
3643 separate file, in an attempt to have a Windows GUI installer.
3656 separate file, in an attempt to have a Windows GUI installer.
3644 That didn't work, but part of the groundwork is done.
3657 That didn't work, but part of the groundwork is done.
3645
3658
3646 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
3659 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
3647 indent/unindent with 4 spaces. Particularly useful in combination
3660 indent/unindent with 4 spaces. Particularly useful in combination
3648 with the new auto-indent option.
3661 with the new auto-indent option.
3649
3662
3650 2003-04-16 Fernando Perez <fperez@colorado.edu>
3663 2003-04-16 Fernando Perez <fperez@colorado.edu>
3651
3664
3652 * IPython/Magic.py: various replacements of self.rc for
3665 * IPython/Magic.py: various replacements of self.rc for
3653 self.shell.rc. A lot more remains to be done to fully disentangle
3666 self.shell.rc. A lot more remains to be done to fully disentangle
3654 this class from the main Shell class.
3667 this class from the main Shell class.
3655
3668
3656 * IPython/GnuplotRuntime.py: added checks for mouse support so
3669 * IPython/GnuplotRuntime.py: added checks for mouse support so
3657 that we don't try to enable it if the current gnuplot doesn't
3670 that we don't try to enable it if the current gnuplot doesn't
3658 really support it. Also added checks so that we don't try to
3671 really support it. Also added checks so that we don't try to
3659 enable persist under Windows (where Gnuplot doesn't recognize the
3672 enable persist under Windows (where Gnuplot doesn't recognize the
3660 option).
3673 option).
3661
3674
3662 * IPython/iplib.py (InteractiveShell.interact): Added optional
3675 * IPython/iplib.py (InteractiveShell.interact): Added optional
3663 auto-indenting code, after a patch by King C. Shu
3676 auto-indenting code, after a patch by King C. Shu
3664 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
3677 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
3665 get along well with pasting indented code. If I ever figure out
3678 get along well with pasting indented code. If I ever figure out
3666 how to make that part go well, it will become on by default.
3679 how to make that part go well, it will become on by default.
3667
3680
3668 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
3681 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
3669 crash ipython if there was an unmatched '%' in the user's prompt
3682 crash ipython if there was an unmatched '%' in the user's prompt
3670 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3683 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3671
3684
3672 * IPython/iplib.py (InteractiveShell.interact): removed the
3685 * IPython/iplib.py (InteractiveShell.interact): removed the
3673 ability to ask the user whether he wants to crash or not at the
3686 ability to ask the user whether he wants to crash or not at the
3674 'last line' exception handler. Calling functions at that point
3687 'last line' exception handler. Calling functions at that point
3675 changes the stack, and the error reports would have incorrect
3688 changes the stack, and the error reports would have incorrect
3676 tracebacks.
3689 tracebacks.
3677
3690
3678 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
3691 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
3679 pass through a peger a pretty-printed form of any object. After a
3692 pass through a peger a pretty-printed form of any object. After a
3680 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
3693 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
3681
3694
3682 2003-04-14 Fernando Perez <fperez@colorado.edu>
3695 2003-04-14 Fernando Perez <fperez@colorado.edu>
3683
3696
3684 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
3697 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
3685 all files in ~ would be modified at first install (instead of
3698 all files in ~ would be modified at first install (instead of
3686 ~/.ipython). This could be potentially disastrous, as the
3699 ~/.ipython). This could be potentially disastrous, as the
3687 modification (make line-endings native) could damage binary files.
3700 modification (make line-endings native) could damage binary files.
3688
3701
3689 2003-04-10 Fernando Perez <fperez@colorado.edu>
3702 2003-04-10 Fernando Perez <fperez@colorado.edu>
3690
3703
3691 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
3704 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
3692 handle only lines which are invalid python. This now means that
3705 handle only lines which are invalid python. This now means that
3693 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
3706 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
3694 for the bug report.
3707 for the bug report.
3695
3708
3696 2003-04-01 Fernando Perez <fperez@colorado.edu>
3709 2003-04-01 Fernando Perez <fperez@colorado.edu>
3697
3710
3698 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
3711 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
3699 where failing to set sys.last_traceback would crash pdb.pm().
3712 where failing to set sys.last_traceback would crash pdb.pm().
3700 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
3713 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
3701 report.
3714 report.
3702
3715
3703 2003-03-25 Fernando Perez <fperez@colorado.edu>
3716 2003-03-25 Fernando Perez <fperez@colorado.edu>
3704
3717
3705 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
3718 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
3706 before printing it (it had a lot of spurious blank lines at the
3719 before printing it (it had a lot of spurious blank lines at the
3707 end).
3720 end).
3708
3721
3709 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
3722 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
3710 output would be sent 21 times! Obviously people don't use this
3723 output would be sent 21 times! Obviously people don't use this
3711 too often, or I would have heard about it.
3724 too often, or I would have heard about it.
3712
3725
3713 2003-03-24 Fernando Perez <fperez@colorado.edu>
3726 2003-03-24 Fernando Perez <fperez@colorado.edu>
3714
3727
3715 * setup.py (scriptfiles): renamed the data_files parameter from
3728 * setup.py (scriptfiles): renamed the data_files parameter from
3716 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
3729 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
3717 for the patch.
3730 for the patch.
3718
3731
3719 2003-03-20 Fernando Perez <fperez@colorado.edu>
3732 2003-03-20 Fernando Perez <fperez@colorado.edu>
3720
3733
3721 * IPython/genutils.py (error): added error() and fatal()
3734 * IPython/genutils.py (error): added error() and fatal()
3722 functions.
3735 functions.
3723
3736
3724 2003-03-18 *** Released version 0.2.15pre3
3737 2003-03-18 *** Released version 0.2.15pre3
3725
3738
3726 2003-03-18 Fernando Perez <fperez@colorado.edu>
3739 2003-03-18 Fernando Perez <fperez@colorado.edu>
3727
3740
3728 * setupext/install_data_ext.py
3741 * setupext/install_data_ext.py
3729 (install_data_ext.initialize_options): Class contributed by Jack
3742 (install_data_ext.initialize_options): Class contributed by Jack
3730 Moffit for fixing the old distutils hack. He is sending this to
3743 Moffit for fixing the old distutils hack. He is sending this to
3731 the distutils folks so in the future we may not need it as a
3744 the distutils folks so in the future we may not need it as a
3732 private fix.
3745 private fix.
3733
3746
3734 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
3747 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
3735 changes for Debian packaging. See his patch for full details.
3748 changes for Debian packaging. See his patch for full details.
3736 The old distutils hack of making the ipythonrc* files carry a
3749 The old distutils hack of making the ipythonrc* files carry a
3737 bogus .py extension is gone, at last. Examples were moved to a
3750 bogus .py extension is gone, at last. Examples were moved to a
3738 separate subdir under doc/, and the separate executable scripts
3751 separate subdir under doc/, and the separate executable scripts
3739 now live in their own directory. Overall a great cleanup. The
3752 now live in their own directory. Overall a great cleanup. The
3740 manual was updated to use the new files, and setup.py has been
3753 manual was updated to use the new files, and setup.py has been
3741 fixed for this setup.
3754 fixed for this setup.
3742
3755
3743 * IPython/PyColorize.py (Parser.usage): made non-executable and
3756 * IPython/PyColorize.py (Parser.usage): made non-executable and
3744 created a pycolor wrapper around it to be included as a script.
3757 created a pycolor wrapper around it to be included as a script.
3745
3758
3746 2003-03-12 *** Released version 0.2.15pre2
3759 2003-03-12 *** Released version 0.2.15pre2
3747
3760
3748 2003-03-12 Fernando Perez <fperez@colorado.edu>
3761 2003-03-12 Fernando Perez <fperez@colorado.edu>
3749
3762
3750 * IPython/ColorANSI.py (make_color_table): Finally fixed the
3763 * IPython/ColorANSI.py (make_color_table): Finally fixed the
3751 long-standing problem with garbage characters in some terminals.
3764 long-standing problem with garbage characters in some terminals.
3752 The issue was really that the \001 and \002 escapes must _only_ be
3765 The issue was really that the \001 and \002 escapes must _only_ be
3753 passed to input prompts (which call readline), but _never_ to
3766 passed to input prompts (which call readline), but _never_ to
3754 normal text to be printed on screen. I changed ColorANSI to have
3767 normal text to be printed on screen. I changed ColorANSI to have
3755 two classes: TermColors and InputTermColors, each with the
3768 two classes: TermColors and InputTermColors, each with the
3756 appropriate escapes for input prompts or normal text. The code in
3769 appropriate escapes for input prompts or normal text. The code in
3757 Prompts.py got slightly more complicated, but this very old and
3770 Prompts.py got slightly more complicated, but this very old and
3758 annoying bug is finally fixed.
3771 annoying bug is finally fixed.
3759
3772
3760 All the credit for nailing down the real origin of this problem
3773 All the credit for nailing down the real origin of this problem
3761 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
3774 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
3762 *Many* thanks to him for spending quite a bit of effort on this.
3775 *Many* thanks to him for spending quite a bit of effort on this.
3763
3776
3764 2003-03-05 *** Released version 0.2.15pre1
3777 2003-03-05 *** Released version 0.2.15pre1
3765
3778
3766 2003-03-03 Fernando Perez <fperez@colorado.edu>
3779 2003-03-03 Fernando Perez <fperez@colorado.edu>
3767
3780
3768 * IPython/FakeModule.py: Moved the former _FakeModule to a
3781 * IPython/FakeModule.py: Moved the former _FakeModule to a
3769 separate file, because it's also needed by Magic (to fix a similar
3782 separate file, because it's also needed by Magic (to fix a similar
3770 pickle-related issue in @run).
3783 pickle-related issue in @run).
3771
3784
3772 2003-03-02 Fernando Perez <fperez@colorado.edu>
3785 2003-03-02 Fernando Perez <fperez@colorado.edu>
3773
3786
3774 * IPython/Magic.py (Magic.magic_autocall): new magic to control
3787 * IPython/Magic.py (Magic.magic_autocall): new magic to control
3775 the autocall option at runtime.
3788 the autocall option at runtime.
3776 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
3789 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
3777 across Magic.py to start separating Magic from InteractiveShell.
3790 across Magic.py to start separating Magic from InteractiveShell.
3778 (Magic._ofind): Fixed to return proper namespace for dotted
3791 (Magic._ofind): Fixed to return proper namespace for dotted
3779 names. Before, a dotted name would always return 'not currently
3792 names. Before, a dotted name would always return 'not currently
3780 defined', because it would find the 'parent'. s.x would be found,
3793 defined', because it would find the 'parent'. s.x would be found,
3781 but since 'x' isn't defined by itself, it would get confused.
3794 but since 'x' isn't defined by itself, it would get confused.
3782 (Magic.magic_run): Fixed pickling problems reported by Ralf
3795 (Magic.magic_run): Fixed pickling problems reported by Ralf
3783 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
3796 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
3784 that I'd used when Mike Heeter reported similar issues at the
3797 that I'd used when Mike Heeter reported similar issues at the
3785 top-level, but now for @run. It boils down to injecting the
3798 top-level, but now for @run. It boils down to injecting the
3786 namespace where code is being executed with something that looks
3799 namespace where code is being executed with something that looks
3787 enough like a module to fool pickle.dump(). Since a pickle stores
3800 enough like a module to fool pickle.dump(). Since a pickle stores
3788 a named reference to the importing module, we need this for
3801 a named reference to the importing module, we need this for
3789 pickles to save something sensible.
3802 pickles to save something sensible.
3790
3803
3791 * IPython/ipmaker.py (make_IPython): added an autocall option.
3804 * IPython/ipmaker.py (make_IPython): added an autocall option.
3792
3805
3793 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
3806 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
3794 the auto-eval code. Now autocalling is an option, and the code is
3807 the auto-eval code. Now autocalling is an option, and the code is
3795 also vastly safer. There is no more eval() involved at all.
3808 also vastly safer. There is no more eval() involved at all.
3796
3809
3797 2003-03-01 Fernando Perez <fperez@colorado.edu>
3810 2003-03-01 Fernando Perez <fperez@colorado.edu>
3798
3811
3799 * IPython/Magic.py (Magic._ofind): Changed interface to return a
3812 * IPython/Magic.py (Magic._ofind): Changed interface to return a
3800 dict with named keys instead of a tuple.
3813 dict with named keys instead of a tuple.
3801
3814
3802 * IPython: Started using CVS for IPython as of 0.2.15pre1.
3815 * IPython: Started using CVS for IPython as of 0.2.15pre1.
3803
3816
3804 * setup.py (make_shortcut): Fixed message about directories
3817 * setup.py (make_shortcut): Fixed message about directories
3805 created during Windows installation (the directories were ok, just
3818 created during Windows installation (the directories were ok, just
3806 the printed message was misleading). Thanks to Chris Liechti
3819 the printed message was misleading). Thanks to Chris Liechti
3807 <cliechti-AT-gmx.net> for the heads up.
3820 <cliechti-AT-gmx.net> for the heads up.
3808
3821
3809 2003-02-21 Fernando Perez <fperez@colorado.edu>
3822 2003-02-21 Fernando Perez <fperez@colorado.edu>
3810
3823
3811 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
3824 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
3812 of ValueError exception when checking for auto-execution. This
3825 of ValueError exception when checking for auto-execution. This
3813 one is raised by things like Numeric arrays arr.flat when the
3826 one is raised by things like Numeric arrays arr.flat when the
3814 array is non-contiguous.
3827 array is non-contiguous.
3815
3828
3816 2003-01-31 Fernando Perez <fperez@colorado.edu>
3829 2003-01-31 Fernando Perez <fperez@colorado.edu>
3817
3830
3818 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
3831 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
3819 not return any value at all (even though the command would get
3832 not return any value at all (even though the command would get
3820 executed).
3833 executed).
3821 (xsys): Flush stdout right after printing the command to ensure
3834 (xsys): Flush stdout right after printing the command to ensure
3822 proper ordering of commands and command output in the total
3835 proper ordering of commands and command output in the total
3823 output.
3836 output.
3824 (SystemExec/xsys/bq): Switched the names of xsys/bq and
3837 (SystemExec/xsys/bq): Switched the names of xsys/bq and
3825 system/getoutput as defaults. The old ones are kept for
3838 system/getoutput as defaults. The old ones are kept for
3826 compatibility reasons, so no code which uses this library needs
3839 compatibility reasons, so no code which uses this library needs
3827 changing.
3840 changing.
3828
3841
3829 2003-01-27 *** Released version 0.2.14
3842 2003-01-27 *** Released version 0.2.14
3830
3843
3831 2003-01-25 Fernando Perez <fperez@colorado.edu>
3844 2003-01-25 Fernando Perez <fperez@colorado.edu>
3832
3845
3833 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
3846 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
3834 functions defined in previous edit sessions could not be re-edited
3847 functions defined in previous edit sessions could not be re-edited
3835 (because the temp files were immediately removed). Now temp files
3848 (because the temp files were immediately removed). Now temp files
3836 are removed only at IPython's exit.
3849 are removed only at IPython's exit.
3837 (Magic.magic_run): Improved @run to perform shell-like expansions
3850 (Magic.magic_run): Improved @run to perform shell-like expansions
3838 on its arguments (~users and $VARS). With this, @run becomes more
3851 on its arguments (~users and $VARS). With this, @run becomes more
3839 like a normal command-line.
3852 like a normal command-line.
3840
3853
3841 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
3854 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
3842 bugs related to embedding and cleaned up that code. A fairly
3855 bugs related to embedding and cleaned up that code. A fairly
3843 important one was the impossibility to access the global namespace
3856 important one was the impossibility to access the global namespace
3844 through the embedded IPython (only local variables were visible).
3857 through the embedded IPython (only local variables were visible).
3845
3858
3846 2003-01-14 Fernando Perez <fperez@colorado.edu>
3859 2003-01-14 Fernando Perez <fperez@colorado.edu>
3847
3860
3848 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3861 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3849 auto-calling to be a bit more conservative. Now it doesn't get
3862 auto-calling to be a bit more conservative. Now it doesn't get
3850 triggered if any of '!=()<>' are in the rest of the input line, to
3863 triggered if any of '!=()<>' are in the rest of the input line, to
3851 allow comparing callables. Thanks to Alex for the heads up.
3864 allow comparing callables. Thanks to Alex for the heads up.
3852
3865
3853 2003-01-07 Fernando Perez <fperez@colorado.edu>
3866 2003-01-07 Fernando Perez <fperez@colorado.edu>
3854
3867
3855 * IPython/genutils.py (page): fixed estimation of the number of
3868 * IPython/genutils.py (page): fixed estimation of the number of
3856 lines in a string to be paged to simply count newlines. This
3869 lines in a string to be paged to simply count newlines. This
3857 prevents over-guessing due to embedded escape sequences. A better
3870 prevents over-guessing due to embedded escape sequences. A better
3858 long-term solution would involve stripping out the control chars
3871 long-term solution would involve stripping out the control chars
3859 for the count, but it's potentially so expensive I just don't
3872 for the count, but it's potentially so expensive I just don't
3860 think it's worth doing.
3873 think it's worth doing.
3861
3874
3862 2002-12-19 *** Released version 0.2.14pre50
3875 2002-12-19 *** Released version 0.2.14pre50
3863
3876
3864 2002-12-19 Fernando Perez <fperez@colorado.edu>
3877 2002-12-19 Fernando Perez <fperez@colorado.edu>
3865
3878
3866 * tools/release (version): Changed release scripts to inform
3879 * tools/release (version): Changed release scripts to inform
3867 Andrea and build a NEWS file with a list of recent changes.
3880 Andrea and build a NEWS file with a list of recent changes.
3868
3881
3869 * IPython/ColorANSI.py (__all__): changed terminal detection
3882 * IPython/ColorANSI.py (__all__): changed terminal detection
3870 code. Seems to work better for xterms without breaking
3883 code. Seems to work better for xterms without breaking
3871 konsole. Will need more testing to determine if WinXP and Mac OSX
3884 konsole. Will need more testing to determine if WinXP and Mac OSX
3872 also work ok.
3885 also work ok.
3873
3886
3874 2002-12-18 *** Released version 0.2.14pre49
3887 2002-12-18 *** Released version 0.2.14pre49
3875
3888
3876 2002-12-18 Fernando Perez <fperez@colorado.edu>
3889 2002-12-18 Fernando Perez <fperez@colorado.edu>
3877
3890
3878 * Docs: added new info about Mac OSX, from Andrea.
3891 * Docs: added new info about Mac OSX, from Andrea.
3879
3892
3880 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3893 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3881 allow direct plotting of python strings whose format is the same
3894 allow direct plotting of python strings whose format is the same
3882 of gnuplot data files.
3895 of gnuplot data files.
3883
3896
3884 2002-12-16 Fernando Perez <fperez@colorado.edu>
3897 2002-12-16 Fernando Perez <fperez@colorado.edu>
3885
3898
3886 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3899 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3887 value of exit question to be acknowledged.
3900 value of exit question to be acknowledged.
3888
3901
3889 2002-12-03 Fernando Perez <fperez@colorado.edu>
3902 2002-12-03 Fernando Perez <fperez@colorado.edu>
3890
3903
3891 * IPython/ipmaker.py: removed generators, which had been added
3904 * IPython/ipmaker.py: removed generators, which had been added
3892 by mistake in an earlier debugging run. This was causing trouble
3905 by mistake in an earlier debugging run. This was causing trouble
3893 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3906 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3894 for pointing this out.
3907 for pointing this out.
3895
3908
3896 2002-11-17 Fernando Perez <fperez@colorado.edu>
3909 2002-11-17 Fernando Perez <fperez@colorado.edu>
3897
3910
3898 * Manual: updated the Gnuplot section.
3911 * Manual: updated the Gnuplot section.
3899
3912
3900 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3913 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3901 a much better split of what goes in Runtime and what goes in
3914 a much better split of what goes in Runtime and what goes in
3902 Interactive.
3915 Interactive.
3903
3916
3904 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3917 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3905 being imported from iplib.
3918 being imported from iplib.
3906
3919
3907 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3920 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3908 for command-passing. Now the global Gnuplot instance is called
3921 for command-passing. Now the global Gnuplot instance is called
3909 'gp' instead of 'g', which was really a far too fragile and
3922 'gp' instead of 'g', which was really a far too fragile and
3910 common name.
3923 common name.
3911
3924
3912 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3925 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3913 bounding boxes generated by Gnuplot for square plots.
3926 bounding boxes generated by Gnuplot for square plots.
3914
3927
3915 * IPython/genutils.py (popkey): new function added. I should
3928 * IPython/genutils.py (popkey): new function added. I should
3916 suggest this on c.l.py as a dict method, it seems useful.
3929 suggest this on c.l.py as a dict method, it seems useful.
3917
3930
3918 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3931 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3919 to transparently handle PostScript generation. MUCH better than
3932 to transparently handle PostScript generation. MUCH better than
3920 the previous plot_eps/replot_eps (which I removed now). The code
3933 the previous plot_eps/replot_eps (which I removed now). The code
3921 is also fairly clean and well documented now (including
3934 is also fairly clean and well documented now (including
3922 docstrings).
3935 docstrings).
3923
3936
3924 2002-11-13 Fernando Perez <fperez@colorado.edu>
3937 2002-11-13 Fernando Perez <fperez@colorado.edu>
3925
3938
3926 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3939 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3927 (inconsistent with options).
3940 (inconsistent with options).
3928
3941
3929 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3942 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3930 manually disabled, I don't know why. Fixed it.
3943 manually disabled, I don't know why. Fixed it.
3931 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3944 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3932 eps output.
3945 eps output.
3933
3946
3934 2002-11-12 Fernando Perez <fperez@colorado.edu>
3947 2002-11-12 Fernando Perez <fperez@colorado.edu>
3935
3948
3936 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3949 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3937 don't propagate up to caller. Fixes crash reported by François
3950 don't propagate up to caller. Fixes crash reported by François
3938 Pinard.
3951 Pinard.
3939
3952
3940 2002-11-09 Fernando Perez <fperez@colorado.edu>
3953 2002-11-09 Fernando Perez <fperez@colorado.edu>
3941
3954
3942 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3955 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3943 history file for new users.
3956 history file for new users.
3944 (make_IPython): fixed bug where initial install would leave the
3957 (make_IPython): fixed bug where initial install would leave the
3945 user running in the .ipython dir.
3958 user running in the .ipython dir.
3946 (make_IPython): fixed bug where config dir .ipython would be
3959 (make_IPython): fixed bug where config dir .ipython would be
3947 created regardless of the given -ipythondir option. Thanks to Cory
3960 created regardless of the given -ipythondir option. Thanks to Cory
3948 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3961 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3949
3962
3950 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3963 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3951 type confirmations. Will need to use it in all of IPython's code
3964 type confirmations. Will need to use it in all of IPython's code
3952 consistently.
3965 consistently.
3953
3966
3954 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3967 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3955 context to print 31 lines instead of the default 5. This will make
3968 context to print 31 lines instead of the default 5. This will make
3956 the crash reports extremely detailed in case the problem is in
3969 the crash reports extremely detailed in case the problem is in
3957 libraries I don't have access to.
3970 libraries I don't have access to.
3958
3971
3959 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3972 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3960 line of defense' code to still crash, but giving users fair
3973 line of defense' code to still crash, but giving users fair
3961 warning. I don't want internal errors to go unreported: if there's
3974 warning. I don't want internal errors to go unreported: if there's
3962 an internal problem, IPython should crash and generate a full
3975 an internal problem, IPython should crash and generate a full
3963 report.
3976 report.
3964
3977
3965 2002-11-08 Fernando Perez <fperez@colorado.edu>
3978 2002-11-08 Fernando Perez <fperez@colorado.edu>
3966
3979
3967 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3980 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3968 otherwise uncaught exceptions which can appear if people set
3981 otherwise uncaught exceptions which can appear if people set
3969 sys.stdout to something badly broken. Thanks to a crash report
3982 sys.stdout to something badly broken. Thanks to a crash report
3970 from henni-AT-mail.brainbot.com.
3983 from henni-AT-mail.brainbot.com.
3971
3984
3972 2002-11-04 Fernando Perez <fperez@colorado.edu>
3985 2002-11-04 Fernando Perez <fperez@colorado.edu>
3973
3986
3974 * IPython/iplib.py (InteractiveShell.interact): added
3987 * IPython/iplib.py (InteractiveShell.interact): added
3975 __IPYTHON__active to the builtins. It's a flag which goes on when
3988 __IPYTHON__active to the builtins. It's a flag which goes on when
3976 the interaction starts and goes off again when it stops. This
3989 the interaction starts and goes off again when it stops. This
3977 allows embedding code to detect being inside IPython. Before this
3990 allows embedding code to detect being inside IPython. Before this
3978 was done via __IPYTHON__, but that only shows that an IPython
3991 was done via __IPYTHON__, but that only shows that an IPython
3979 instance has been created.
3992 instance has been created.
3980
3993
3981 * IPython/Magic.py (Magic.magic_env): I realized that in a
3994 * IPython/Magic.py (Magic.magic_env): I realized that in a
3982 UserDict, instance.data holds the data as a normal dict. So I
3995 UserDict, instance.data holds the data as a normal dict. So I
3983 modified @env to return os.environ.data instead of rebuilding a
3996 modified @env to return os.environ.data instead of rebuilding a
3984 dict by hand.
3997 dict by hand.
3985
3998
3986 2002-11-02 Fernando Perez <fperez@colorado.edu>
3999 2002-11-02 Fernando Perez <fperez@colorado.edu>
3987
4000
3988 * IPython/genutils.py (warn): changed so that level 1 prints no
4001 * IPython/genutils.py (warn): changed so that level 1 prints no
3989 header. Level 2 is now the default (with 'WARNING' header, as
4002 header. Level 2 is now the default (with 'WARNING' header, as
3990 before). I think I tracked all places where changes were needed in
4003 before). I think I tracked all places where changes were needed in
3991 IPython, but outside code using the old level numbering may have
4004 IPython, but outside code using the old level numbering may have
3992 broken.
4005 broken.
3993
4006
3994 * IPython/iplib.py (InteractiveShell.runcode): added this to
4007 * IPython/iplib.py (InteractiveShell.runcode): added this to
3995 handle the tracebacks in SystemExit traps correctly. The previous
4008 handle the tracebacks in SystemExit traps correctly. The previous
3996 code (through interact) was printing more of the stack than
4009 code (through interact) was printing more of the stack than
3997 necessary, showing IPython internal code to the user.
4010 necessary, showing IPython internal code to the user.
3998
4011
3999 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
4012 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
4000 default. Now that the default at the confirmation prompt is yes,
4013 default. Now that the default at the confirmation prompt is yes,
4001 it's not so intrusive. François' argument that ipython sessions
4014 it's not so intrusive. François' argument that ipython sessions
4002 tend to be complex enough not to lose them from an accidental C-d,
4015 tend to be complex enough not to lose them from an accidental C-d,
4003 is a valid one.
4016 is a valid one.
4004
4017
4005 * IPython/iplib.py (InteractiveShell.interact): added a
4018 * IPython/iplib.py (InteractiveShell.interact): added a
4006 showtraceback() call to the SystemExit trap, and modified the exit
4019 showtraceback() call to the SystemExit trap, and modified the exit
4007 confirmation to have yes as the default.
4020 confirmation to have yes as the default.
4008
4021
4009 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
4022 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
4010 this file. It's been gone from the code for a long time, this was
4023 this file. It's been gone from the code for a long time, this was
4011 simply leftover junk.
4024 simply leftover junk.
4012
4025
4013 2002-11-01 Fernando Perez <fperez@colorado.edu>
4026 2002-11-01 Fernando Perez <fperez@colorado.edu>
4014
4027
4015 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
4028 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
4016 added. If set, IPython now traps EOF and asks for
4029 added. If set, IPython now traps EOF and asks for
4017 confirmation. After a request by François Pinard.
4030 confirmation. After a request by François Pinard.
4018
4031
4019 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
4032 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
4020 of @abort, and with a new (better) mechanism for handling the
4033 of @abort, and with a new (better) mechanism for handling the
4021 exceptions.
4034 exceptions.
4022
4035
4023 2002-10-27 Fernando Perez <fperez@colorado.edu>
4036 2002-10-27 Fernando Perez <fperez@colorado.edu>
4024
4037
4025 * IPython/usage.py (__doc__): updated the --help information and
4038 * IPython/usage.py (__doc__): updated the --help information and
4026 the ipythonrc file to indicate that -log generates
4039 the ipythonrc file to indicate that -log generates
4027 ./ipython.log. Also fixed the corresponding info in @logstart.
4040 ./ipython.log. Also fixed the corresponding info in @logstart.
4028 This and several other fixes in the manuals thanks to reports by
4041 This and several other fixes in the manuals thanks to reports by
4029 François Pinard <pinard-AT-iro.umontreal.ca>.
4042 François Pinard <pinard-AT-iro.umontreal.ca>.
4030
4043
4031 * IPython/Logger.py (Logger.switch_log): Fixed error message to
4044 * IPython/Logger.py (Logger.switch_log): Fixed error message to
4032 refer to @logstart (instead of @log, which doesn't exist).
4045 refer to @logstart (instead of @log, which doesn't exist).
4033
4046
4034 * IPython/iplib.py (InteractiveShell._prefilter): fixed
4047 * IPython/iplib.py (InteractiveShell._prefilter): fixed
4035 AttributeError crash. Thanks to Christopher Armstrong
4048 AttributeError crash. Thanks to Christopher Armstrong
4036 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
4049 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
4037 introduced recently (in 0.2.14pre37) with the fix to the eval
4050 introduced recently (in 0.2.14pre37) with the fix to the eval
4038 problem mentioned below.
4051 problem mentioned below.
4039
4052
4040 2002-10-17 Fernando Perez <fperez@colorado.edu>
4053 2002-10-17 Fernando Perez <fperez@colorado.edu>
4041
4054
4042 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
4055 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
4043 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
4056 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
4044
4057
4045 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
4058 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
4046 this function to fix a problem reported by Alex Schmolck. He saw
4059 this function to fix a problem reported by Alex Schmolck. He saw
4047 it with list comprehensions and generators, which were getting
4060 it with list comprehensions and generators, which were getting
4048 called twice. The real problem was an 'eval' call in testing for
4061 called twice. The real problem was an 'eval' call in testing for
4049 automagic which was evaluating the input line silently.
4062 automagic which was evaluating the input line silently.
4050
4063
4051 This is a potentially very nasty bug, if the input has side
4064 This is a potentially very nasty bug, if the input has side
4052 effects which must not be repeated. The code is much cleaner now,
4065 effects which must not be repeated. The code is much cleaner now,
4053 without any blanket 'except' left and with a regexp test for
4066 without any blanket 'except' left and with a regexp test for
4054 actual function names.
4067 actual function names.
4055
4068
4056 But an eval remains, which I'm not fully comfortable with. I just
4069 But an eval remains, which I'm not fully comfortable with. I just
4057 don't know how to find out if an expression could be a callable in
4070 don't know how to find out if an expression could be a callable in
4058 the user's namespace without doing an eval on the string. However
4071 the user's namespace without doing an eval on the string. However
4059 that string is now much more strictly checked so that no code
4072 that string is now much more strictly checked so that no code
4060 slips by, so the eval should only happen for things that can
4073 slips by, so the eval should only happen for things that can
4061 really be only function/method names.
4074 really be only function/method names.
4062
4075
4063 2002-10-15 Fernando Perez <fperez@colorado.edu>
4076 2002-10-15 Fernando Perez <fperez@colorado.edu>
4064
4077
4065 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
4078 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
4066 OSX information to main manual, removed README_Mac_OSX file from
4079 OSX information to main manual, removed README_Mac_OSX file from
4067 distribution. Also updated credits for recent additions.
4080 distribution. Also updated credits for recent additions.
4068
4081
4069 2002-10-10 Fernando Perez <fperez@colorado.edu>
4082 2002-10-10 Fernando Perez <fperez@colorado.edu>
4070
4083
4071 * README_Mac_OSX: Added a README for Mac OSX users for fixing
4084 * README_Mac_OSX: Added a README for Mac OSX users for fixing
4072 terminal-related issues. Many thanks to Andrea Riciputi
4085 terminal-related issues. Many thanks to Andrea Riciputi
4073 <andrea.riciputi-AT-libero.it> for writing it.
4086 <andrea.riciputi-AT-libero.it> for writing it.
4074
4087
4075 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
4088 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
4076 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
4089 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
4077
4090
4078 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
4091 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
4079 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
4092 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
4080 <syver-en-AT-online.no> who both submitted patches for this problem.
4093 <syver-en-AT-online.no> who both submitted patches for this problem.
4081
4094
4082 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
4095 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
4083 global embedding to make sure that things don't overwrite user
4096 global embedding to make sure that things don't overwrite user
4084 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
4097 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
4085
4098
4086 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
4099 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
4087 compatibility. Thanks to Hayden Callow
4100 compatibility. Thanks to Hayden Callow
4088 <h.callow-AT-elec.canterbury.ac.nz>
4101 <h.callow-AT-elec.canterbury.ac.nz>
4089
4102
4090 2002-10-04 Fernando Perez <fperez@colorado.edu>
4103 2002-10-04 Fernando Perez <fperez@colorado.edu>
4091
4104
4092 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
4105 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
4093 Gnuplot.File objects.
4106 Gnuplot.File objects.
4094
4107
4095 2002-07-23 Fernando Perez <fperez@colorado.edu>
4108 2002-07-23 Fernando Perez <fperez@colorado.edu>
4096
4109
4097 * IPython/genutils.py (timing): Added timings() and timing() for
4110 * IPython/genutils.py (timing): Added timings() and timing() for
4098 quick access to the most commonly needed data, the execution
4111 quick access to the most commonly needed data, the execution
4099 times. Old timing() renamed to timings_out().
4112 times. Old timing() renamed to timings_out().
4100
4113
4101 2002-07-18 Fernando Perez <fperez@colorado.edu>
4114 2002-07-18 Fernando Perez <fperez@colorado.edu>
4102
4115
4103 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
4116 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
4104 bug with nested instances disrupting the parent's tab completion.
4117 bug with nested instances disrupting the parent's tab completion.
4105
4118
4106 * IPython/iplib.py (all_completions): Added Alex Schmolck's
4119 * IPython/iplib.py (all_completions): Added Alex Schmolck's
4107 all_completions code to begin the emacs integration.
4120 all_completions code to begin the emacs integration.
4108
4121
4109 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
4122 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
4110 argument to allow titling individual arrays when plotting.
4123 argument to allow titling individual arrays when plotting.
4111
4124
4112 2002-07-15 Fernando Perez <fperez@colorado.edu>
4125 2002-07-15 Fernando Perez <fperez@colorado.edu>
4113
4126
4114 * setup.py (make_shortcut): changed to retrieve the value of
4127 * setup.py (make_shortcut): changed to retrieve the value of
4115 'Program Files' directory from the registry (this value changes in
4128 'Program Files' directory from the registry (this value changes in
4116 non-english versions of Windows). Thanks to Thomas Fanslau
4129 non-english versions of Windows). Thanks to Thomas Fanslau
4117 <tfanslau-AT-gmx.de> for the report.
4130 <tfanslau-AT-gmx.de> for the report.
4118
4131
4119 2002-07-10 Fernando Perez <fperez@colorado.edu>
4132 2002-07-10 Fernando Perez <fperez@colorado.edu>
4120
4133
4121 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
4134 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
4122 a bug in pdb, which crashes if a line with only whitespace is
4135 a bug in pdb, which crashes if a line with only whitespace is
4123 entered. Bug report submitted to sourceforge.
4136 entered. Bug report submitted to sourceforge.
4124
4137
4125 2002-07-09 Fernando Perez <fperez@colorado.edu>
4138 2002-07-09 Fernando Perez <fperez@colorado.edu>
4126
4139
4127 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
4140 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
4128 reporting exceptions (it's a bug in inspect.py, I just set a
4141 reporting exceptions (it's a bug in inspect.py, I just set a
4129 workaround).
4142 workaround).
4130
4143
4131 2002-07-08 Fernando Perez <fperez@colorado.edu>
4144 2002-07-08 Fernando Perez <fperez@colorado.edu>
4132
4145
4133 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
4146 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
4134 __IPYTHON__ in __builtins__ to show up in user_ns.
4147 __IPYTHON__ in __builtins__ to show up in user_ns.
4135
4148
4136 2002-07-03 Fernando Perez <fperez@colorado.edu>
4149 2002-07-03 Fernando Perez <fperez@colorado.edu>
4137
4150
4138 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
4151 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
4139 name from @gp_set_instance to @gp_set_default.
4152 name from @gp_set_instance to @gp_set_default.
4140
4153
4141 * IPython/ipmaker.py (make_IPython): default editor value set to
4154 * IPython/ipmaker.py (make_IPython): default editor value set to
4142 '0' (a string), to match the rc file. Otherwise will crash when
4155 '0' (a string), to match the rc file. Otherwise will crash when
4143 .strip() is called on it.
4156 .strip() is called on it.
4144
4157
4145
4158
4146 2002-06-28 Fernando Perez <fperez@colorado.edu>
4159 2002-06-28 Fernando Perez <fperez@colorado.edu>
4147
4160
4148 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
4161 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
4149 of files in current directory when a file is executed via
4162 of files in current directory when a file is executed via
4150 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
4163 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
4151
4164
4152 * setup.py (manfiles): fix for rpm builds, submitted by RA
4165 * setup.py (manfiles): fix for rpm builds, submitted by RA
4153 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
4166 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
4154
4167
4155 * IPython/ipmaker.py (make_IPython): fixed lookup of default
4168 * IPython/ipmaker.py (make_IPython): fixed lookup of default
4156 editor when set to '0'. Problem was, '0' evaluates to True (it's a
4169 editor when set to '0'. Problem was, '0' evaluates to True (it's a
4157 string!). A. Schmolck caught this one.
4170 string!). A. Schmolck caught this one.
4158
4171
4159 2002-06-27 Fernando Perez <fperez@colorado.edu>
4172 2002-06-27 Fernando Perez <fperez@colorado.edu>
4160
4173
4161 * IPython/ipmaker.py (make_IPython): fixed bug when running user
4174 * IPython/ipmaker.py (make_IPython): fixed bug when running user
4162 defined files at the cmd line. __name__ wasn't being set to
4175 defined files at the cmd line. __name__ wasn't being set to
4163 __main__.
4176 __main__.
4164
4177
4165 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
4178 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
4166 regular lists and tuples besides Numeric arrays.
4179 regular lists and tuples besides Numeric arrays.
4167
4180
4168 * IPython/Prompts.py (CachedOutput.__call__): Added output
4181 * IPython/Prompts.py (CachedOutput.__call__): Added output
4169 supression for input ending with ';'. Similar to Mathematica and
4182 supression for input ending with ';'. Similar to Mathematica and
4170 Matlab. The _* vars and Out[] list are still updated, just like
4183 Matlab. The _* vars and Out[] list are still updated, just like
4171 Mathematica behaves.
4184 Mathematica behaves.
4172
4185
4173 2002-06-25 Fernando Perez <fperez@colorado.edu>
4186 2002-06-25 Fernando Perez <fperez@colorado.edu>
4174
4187
4175 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
4188 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
4176 .ini extensions for profiels under Windows.
4189 .ini extensions for profiels under Windows.
4177
4190
4178 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
4191 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
4179 string form. Fix contributed by Alexander Schmolck
4192 string form. Fix contributed by Alexander Schmolck
4180 <a.schmolck-AT-gmx.net>
4193 <a.schmolck-AT-gmx.net>
4181
4194
4182 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
4195 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
4183 pre-configured Gnuplot instance.
4196 pre-configured Gnuplot instance.
4184
4197
4185 2002-06-21 Fernando Perez <fperez@colorado.edu>
4198 2002-06-21 Fernando Perez <fperez@colorado.edu>
4186
4199
4187 * IPython/numutils.py (exp_safe): new function, works around the
4200 * IPython/numutils.py (exp_safe): new function, works around the
4188 underflow problems in Numeric.
4201 underflow problems in Numeric.
4189 (log2): New fn. Safe log in base 2: returns exact integer answer
4202 (log2): New fn. Safe log in base 2: returns exact integer answer
4190 for exact integer powers of 2.
4203 for exact integer powers of 2.
4191
4204
4192 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
4205 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
4193 properly.
4206 properly.
4194
4207
4195 2002-06-20 Fernando Perez <fperez@colorado.edu>
4208 2002-06-20 Fernando Perez <fperez@colorado.edu>
4196
4209
4197 * IPython/genutils.py (timing): new function like
4210 * IPython/genutils.py (timing): new function like
4198 Mathematica's. Similar to time_test, but returns more info.
4211 Mathematica's. Similar to time_test, but returns more info.
4199
4212
4200 2002-06-18 Fernando Perez <fperez@colorado.edu>
4213 2002-06-18 Fernando Perez <fperez@colorado.edu>
4201
4214
4202 * IPython/Magic.py (Magic.magic_save): modified @save and @r
4215 * IPython/Magic.py (Magic.magic_save): modified @save and @r
4203 according to Mike Heeter's suggestions.
4216 according to Mike Heeter's suggestions.
4204
4217
4205 2002-06-16 Fernando Perez <fperez@colorado.edu>
4218 2002-06-16 Fernando Perez <fperez@colorado.edu>
4206
4219
4207 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
4220 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
4208 system. GnuplotMagic is gone as a user-directory option. New files
4221 system. GnuplotMagic is gone as a user-directory option. New files
4209 make it easier to use all the gnuplot stuff both from external
4222 make it easier to use all the gnuplot stuff both from external
4210 programs as well as from IPython. Had to rewrite part of
4223 programs as well as from IPython. Had to rewrite part of
4211 hardcopy() b/c of a strange bug: often the ps files simply don't
4224 hardcopy() b/c of a strange bug: often the ps files simply don't
4212 get created, and require a repeat of the command (often several
4225 get created, and require a repeat of the command (often several
4213 times).
4226 times).
4214
4227
4215 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
4228 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
4216 resolve output channel at call time, so that if sys.stderr has
4229 resolve output channel at call time, so that if sys.stderr has
4217 been redirected by user this gets honored.
4230 been redirected by user this gets honored.
4218
4231
4219 2002-06-13 Fernando Perez <fperez@colorado.edu>
4232 2002-06-13 Fernando Perez <fperez@colorado.edu>
4220
4233
4221 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
4234 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
4222 IPShell. Kept a copy with the old names to avoid breaking people's
4235 IPShell. Kept a copy with the old names to avoid breaking people's
4223 embedded code.
4236 embedded code.
4224
4237
4225 * IPython/ipython: simplified it to the bare minimum after
4238 * IPython/ipython: simplified it to the bare minimum after
4226 Holger's suggestions. Added info about how to use it in
4239 Holger's suggestions. Added info about how to use it in
4227 PYTHONSTARTUP.
4240 PYTHONSTARTUP.
4228
4241
4229 * IPython/Shell.py (IPythonShell): changed the options passing
4242 * IPython/Shell.py (IPythonShell): changed the options passing
4230 from a string with funky %s replacements to a straight list. Maybe
4243 from a string with funky %s replacements to a straight list. Maybe
4231 a bit more typing, but it follows sys.argv conventions, so there's
4244 a bit more typing, but it follows sys.argv conventions, so there's
4232 less special-casing to remember.
4245 less special-casing to remember.
4233
4246
4234 2002-06-12 Fernando Perez <fperez@colorado.edu>
4247 2002-06-12 Fernando Perez <fperez@colorado.edu>
4235
4248
4236 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
4249 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
4237 command. Thanks to a suggestion by Mike Heeter.
4250 command. Thanks to a suggestion by Mike Heeter.
4238 (Magic.magic_pfile): added behavior to look at filenames if given
4251 (Magic.magic_pfile): added behavior to look at filenames if given
4239 arg is not a defined object.
4252 arg is not a defined object.
4240 (Magic.magic_save): New @save function to save code snippets. Also
4253 (Magic.magic_save): New @save function to save code snippets. Also
4241 a Mike Heeter idea.
4254 a Mike Heeter idea.
4242
4255
4243 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
4256 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
4244 plot() and replot(). Much more convenient now, especially for
4257 plot() and replot(). Much more convenient now, especially for
4245 interactive use.
4258 interactive use.
4246
4259
4247 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
4260 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
4248 filenames.
4261 filenames.
4249
4262
4250 2002-06-02 Fernando Perez <fperez@colorado.edu>
4263 2002-06-02 Fernando Perez <fperez@colorado.edu>
4251
4264
4252 * IPython/Struct.py (Struct.__init__): modified to admit
4265 * IPython/Struct.py (Struct.__init__): modified to admit
4253 initialization via another struct.
4266 initialization via another struct.
4254
4267
4255 * IPython/genutils.py (SystemExec.__init__): New stateful
4268 * IPython/genutils.py (SystemExec.__init__): New stateful
4256 interface to xsys and bq. Useful for writing system scripts.
4269 interface to xsys and bq. Useful for writing system scripts.
4257
4270
4258 2002-05-30 Fernando Perez <fperez@colorado.edu>
4271 2002-05-30 Fernando Perez <fperez@colorado.edu>
4259
4272
4260 * MANIFEST.in: Changed docfile selection to exclude all the lyx
4273 * MANIFEST.in: Changed docfile selection to exclude all the lyx
4261 documents. This will make the user download smaller (it's getting
4274 documents. This will make the user download smaller (it's getting
4262 too big).
4275 too big).
4263
4276
4264 2002-05-29 Fernando Perez <fperez@colorado.edu>
4277 2002-05-29 Fernando Perez <fperez@colorado.edu>
4265
4278
4266 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
4279 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
4267 fix problems with shelve and pickle. Seems to work, but I don't
4280 fix problems with shelve and pickle. Seems to work, but I don't
4268 know if corner cases break it. Thanks to Mike Heeter
4281 know if corner cases break it. Thanks to Mike Heeter
4269 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
4282 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
4270
4283
4271 2002-05-24 Fernando Perez <fperez@colorado.edu>
4284 2002-05-24 Fernando Perez <fperez@colorado.edu>
4272
4285
4273 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
4286 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
4274 macros having broken.
4287 macros having broken.
4275
4288
4276 2002-05-21 Fernando Perez <fperez@colorado.edu>
4289 2002-05-21 Fernando Perez <fperez@colorado.edu>
4277
4290
4278 * IPython/Magic.py (Magic.magic_logstart): fixed recently
4291 * IPython/Magic.py (Magic.magic_logstart): fixed recently
4279 introduced logging bug: all history before logging started was
4292 introduced logging bug: all history before logging started was
4280 being written one character per line! This came from the redesign
4293 being written one character per line! This came from the redesign
4281 of the input history as a special list which slices to strings,
4294 of the input history as a special list which slices to strings,
4282 not to lists.
4295 not to lists.
4283
4296
4284 2002-05-20 Fernando Perez <fperez@colorado.edu>
4297 2002-05-20 Fernando Perez <fperez@colorado.edu>
4285
4298
4286 * IPython/Prompts.py (CachedOutput.__init__): made the color table
4299 * IPython/Prompts.py (CachedOutput.__init__): made the color table
4287 be an attribute of all classes in this module. The design of these
4300 be an attribute of all classes in this module. The design of these
4288 classes needs some serious overhauling.
4301 classes needs some serious overhauling.
4289
4302
4290 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
4303 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
4291 which was ignoring '_' in option names.
4304 which was ignoring '_' in option names.
4292
4305
4293 * IPython/ultraTB.py (FormattedTB.__init__): Changed
4306 * IPython/ultraTB.py (FormattedTB.__init__): Changed
4294 'Verbose_novars' to 'Context' and made it the new default. It's a
4307 'Verbose_novars' to 'Context' and made it the new default. It's a
4295 bit more readable and also safer than verbose.
4308 bit more readable and also safer than verbose.
4296
4309
4297 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
4310 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
4298 triple-quoted strings.
4311 triple-quoted strings.
4299
4312
4300 * IPython/OInspect.py (__all__): new module exposing the object
4313 * IPython/OInspect.py (__all__): new module exposing the object
4301 introspection facilities. Now the corresponding magics are dummy
4314 introspection facilities. Now the corresponding magics are dummy
4302 wrappers around this. Having this module will make it much easier
4315 wrappers around this. Having this module will make it much easier
4303 to put these functions into our modified pdb.
4316 to put these functions into our modified pdb.
4304 This new object inspector system uses the new colorizing module,
4317 This new object inspector system uses the new colorizing module,
4305 so source code and other things are nicely syntax highlighted.
4318 so source code and other things are nicely syntax highlighted.
4306
4319
4307 2002-05-18 Fernando Perez <fperez@colorado.edu>
4320 2002-05-18 Fernando Perez <fperez@colorado.edu>
4308
4321
4309 * IPython/ColorANSI.py: Split the coloring tools into a separate
4322 * IPython/ColorANSI.py: Split the coloring tools into a separate
4310 module so I can use them in other code easier (they were part of
4323 module so I can use them in other code easier (they were part of
4311 ultraTB).
4324 ultraTB).
4312
4325
4313 2002-05-17 Fernando Perez <fperez@colorado.edu>
4326 2002-05-17 Fernando Perez <fperez@colorado.edu>
4314
4327
4315 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4328 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4316 fixed it to set the global 'g' also to the called instance, as
4329 fixed it to set the global 'g' also to the called instance, as
4317 long as 'g' was still a gnuplot instance (so it doesn't overwrite
4330 long as 'g' was still a gnuplot instance (so it doesn't overwrite
4318 user's 'g' variables).
4331 user's 'g' variables).
4319
4332
4320 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
4333 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
4321 global variables (aliases to _ih,_oh) so that users which expect
4334 global variables (aliases to _ih,_oh) so that users which expect
4322 In[5] or Out[7] to work aren't unpleasantly surprised.
4335 In[5] or Out[7] to work aren't unpleasantly surprised.
4323 (InputList.__getslice__): new class to allow executing slices of
4336 (InputList.__getslice__): new class to allow executing slices of
4324 input history directly. Very simple class, complements the use of
4337 input history directly. Very simple class, complements the use of
4325 macros.
4338 macros.
4326
4339
4327 2002-05-16 Fernando Perez <fperez@colorado.edu>
4340 2002-05-16 Fernando Perez <fperez@colorado.edu>
4328
4341
4329 * setup.py (docdirbase): make doc directory be just doc/IPython
4342 * setup.py (docdirbase): make doc directory be just doc/IPython
4330 without version numbers, it will reduce clutter for users.
4343 without version numbers, it will reduce clutter for users.
4331
4344
4332 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
4345 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
4333 execfile call to prevent possible memory leak. See for details:
4346 execfile call to prevent possible memory leak. See for details:
4334 http://mail.python.org/pipermail/python-list/2002-February/088476.html
4347 http://mail.python.org/pipermail/python-list/2002-February/088476.html
4335
4348
4336 2002-05-15 Fernando Perez <fperez@colorado.edu>
4349 2002-05-15 Fernando Perez <fperez@colorado.edu>
4337
4350
4338 * IPython/Magic.py (Magic.magic_psource): made the object
4351 * IPython/Magic.py (Magic.magic_psource): made the object
4339 introspection names be more standard: pdoc, pdef, pfile and
4352 introspection names be more standard: pdoc, pdef, pfile and
4340 psource. They all print/page their output, and it makes
4353 psource. They all print/page their output, and it makes
4341 remembering them easier. Kept old names for compatibility as
4354 remembering them easier. Kept old names for compatibility as
4342 aliases.
4355 aliases.
4343
4356
4344 2002-05-14 Fernando Perez <fperez@colorado.edu>
4357 2002-05-14 Fernando Perez <fperez@colorado.edu>
4345
4358
4346 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
4359 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
4347 what the mouse problem was. The trick is to use gnuplot with temp
4360 what the mouse problem was. The trick is to use gnuplot with temp
4348 files and NOT with pipes (for data communication), because having
4361 files and NOT with pipes (for data communication), because having
4349 both pipes and the mouse on is bad news.
4362 both pipes and the mouse on is bad news.
4350
4363
4351 2002-05-13 Fernando Perez <fperez@colorado.edu>
4364 2002-05-13 Fernando Perez <fperez@colorado.edu>
4352
4365
4353 * IPython/Magic.py (Magic._ofind): fixed namespace order search
4366 * IPython/Magic.py (Magic._ofind): fixed namespace order search
4354 bug. Information would be reported about builtins even when
4367 bug. Information would be reported about builtins even when
4355 user-defined functions overrode them.
4368 user-defined functions overrode them.
4356
4369
4357 2002-05-11 Fernando Perez <fperez@colorado.edu>
4370 2002-05-11 Fernando Perez <fperez@colorado.edu>
4358
4371
4359 * IPython/__init__.py (__all__): removed FlexCompleter from
4372 * IPython/__init__.py (__all__): removed FlexCompleter from
4360 __all__ so that things don't fail in platforms without readline.
4373 __all__ so that things don't fail in platforms without readline.
4361
4374
4362 2002-05-10 Fernando Perez <fperez@colorado.edu>
4375 2002-05-10 Fernando Perez <fperez@colorado.edu>
4363
4376
4364 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
4377 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
4365 it requires Numeric, effectively making Numeric a dependency for
4378 it requires Numeric, effectively making Numeric a dependency for
4366 IPython.
4379 IPython.
4367
4380
4368 * Released 0.2.13
4381 * Released 0.2.13
4369
4382
4370 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
4383 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
4371 profiler interface. Now all the major options from the profiler
4384 profiler interface. Now all the major options from the profiler
4372 module are directly supported in IPython, both for single
4385 module are directly supported in IPython, both for single
4373 expressions (@prun) and for full programs (@run -p).
4386 expressions (@prun) and for full programs (@run -p).
4374
4387
4375 2002-05-09 Fernando Perez <fperez@colorado.edu>
4388 2002-05-09 Fernando Perez <fperez@colorado.edu>
4376
4389
4377 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
4390 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
4378 magic properly formatted for screen.
4391 magic properly formatted for screen.
4379
4392
4380 * setup.py (make_shortcut): Changed things to put pdf version in
4393 * setup.py (make_shortcut): Changed things to put pdf version in
4381 doc/ instead of doc/manual (had to change lyxport a bit).
4394 doc/ instead of doc/manual (had to change lyxport a bit).
4382
4395
4383 * IPython/Magic.py (Profile.string_stats): made profile runs go
4396 * IPython/Magic.py (Profile.string_stats): made profile runs go
4384 through pager (they are long and a pager allows searching, saving,
4397 through pager (they are long and a pager allows searching, saving,
4385 etc.)
4398 etc.)
4386
4399
4387 2002-05-08 Fernando Perez <fperez@colorado.edu>
4400 2002-05-08 Fernando Perez <fperez@colorado.edu>
4388
4401
4389 * Released 0.2.12
4402 * Released 0.2.12
4390
4403
4391 2002-05-06 Fernando Perez <fperez@colorado.edu>
4404 2002-05-06 Fernando Perez <fperez@colorado.edu>
4392
4405
4393 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
4406 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
4394 introduced); 'hist n1 n2' was broken.
4407 introduced); 'hist n1 n2' was broken.
4395 (Magic.magic_pdb): added optional on/off arguments to @pdb
4408 (Magic.magic_pdb): added optional on/off arguments to @pdb
4396 (Magic.magic_run): added option -i to @run, which executes code in
4409 (Magic.magic_run): added option -i to @run, which executes code in
4397 the IPython namespace instead of a clean one. Also added @irun as
4410 the IPython namespace instead of a clean one. Also added @irun as
4398 an alias to @run -i.
4411 an alias to @run -i.
4399
4412
4400 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4413 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4401 fixed (it didn't really do anything, the namespaces were wrong).
4414 fixed (it didn't really do anything, the namespaces were wrong).
4402
4415
4403 * IPython/Debugger.py (__init__): Added workaround for python 2.1
4416 * IPython/Debugger.py (__init__): Added workaround for python 2.1
4404
4417
4405 * IPython/__init__.py (__all__): Fixed package namespace, now
4418 * IPython/__init__.py (__all__): Fixed package namespace, now
4406 'import IPython' does give access to IPython.<all> as
4419 'import IPython' does give access to IPython.<all> as
4407 expected. Also renamed __release__ to Release.
4420 expected. Also renamed __release__ to Release.
4408
4421
4409 * IPython/Debugger.py (__license__): created new Pdb class which
4422 * IPython/Debugger.py (__license__): created new Pdb class which
4410 functions like a drop-in for the normal pdb.Pdb but does NOT
4423 functions like a drop-in for the normal pdb.Pdb but does NOT
4411 import readline by default. This way it doesn't muck up IPython's
4424 import readline by default. This way it doesn't muck up IPython's
4412 readline handling, and now tab-completion finally works in the
4425 readline handling, and now tab-completion finally works in the
4413 debugger -- sort of. It completes things globally visible, but the
4426 debugger -- sort of. It completes things globally visible, but the
4414 completer doesn't track the stack as pdb walks it. That's a bit
4427 completer doesn't track the stack as pdb walks it. That's a bit
4415 tricky, and I'll have to implement it later.
4428 tricky, and I'll have to implement it later.
4416
4429
4417 2002-05-05 Fernando Perez <fperez@colorado.edu>
4430 2002-05-05 Fernando Perez <fperez@colorado.edu>
4418
4431
4419 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
4432 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
4420 magic docstrings when printed via ? (explicit \'s were being
4433 magic docstrings when printed via ? (explicit \'s were being
4421 printed).
4434 printed).
4422
4435
4423 * IPython/ipmaker.py (make_IPython): fixed namespace
4436 * IPython/ipmaker.py (make_IPython): fixed namespace
4424 identification bug. Now variables loaded via logs or command-line
4437 identification bug. Now variables loaded via logs or command-line
4425 files are recognized in the interactive namespace by @who.
4438 files are recognized in the interactive namespace by @who.
4426
4439
4427 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
4440 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
4428 log replay system stemming from the string form of Structs.
4441 log replay system stemming from the string form of Structs.
4429
4442
4430 * IPython/Magic.py (Macro.__init__): improved macros to properly
4443 * IPython/Magic.py (Macro.__init__): improved macros to properly
4431 handle magic commands in them.
4444 handle magic commands in them.
4432 (Magic.magic_logstart): usernames are now expanded so 'logstart
4445 (Magic.magic_logstart): usernames are now expanded so 'logstart
4433 ~/mylog' now works.
4446 ~/mylog' now works.
4434
4447
4435 * IPython/iplib.py (complete): fixed bug where paths starting with
4448 * IPython/iplib.py (complete): fixed bug where paths starting with
4436 '/' would be completed as magic names.
4449 '/' would be completed as magic names.
4437
4450
4438 2002-05-04 Fernando Perez <fperez@colorado.edu>
4451 2002-05-04 Fernando Perez <fperez@colorado.edu>
4439
4452
4440 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
4453 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
4441 allow running full programs under the profiler's control.
4454 allow running full programs under the profiler's control.
4442
4455
4443 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
4456 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
4444 mode to report exceptions verbosely but without formatting
4457 mode to report exceptions verbosely but without formatting
4445 variables. This addresses the issue of ipython 'freezing' (it's
4458 variables. This addresses the issue of ipython 'freezing' (it's
4446 not frozen, but caught in an expensive formatting loop) when huge
4459 not frozen, but caught in an expensive formatting loop) when huge
4447 variables are in the context of an exception.
4460 variables are in the context of an exception.
4448 (VerboseTB.text): Added '--->' markers at line where exception was
4461 (VerboseTB.text): Added '--->' markers at line where exception was
4449 triggered. Much clearer to read, especially in NoColor modes.
4462 triggered. Much clearer to read, especially in NoColor modes.
4450
4463
4451 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
4464 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
4452 implemented in reverse when changing to the new parse_options().
4465 implemented in reverse when changing to the new parse_options().
4453
4466
4454 2002-05-03 Fernando Perez <fperez@colorado.edu>
4467 2002-05-03 Fernando Perez <fperez@colorado.edu>
4455
4468
4456 * IPython/Magic.py (Magic.parse_options): new function so that
4469 * IPython/Magic.py (Magic.parse_options): new function so that
4457 magics can parse options easier.
4470 magics can parse options easier.
4458 (Magic.magic_prun): new function similar to profile.run(),
4471 (Magic.magic_prun): new function similar to profile.run(),
4459 suggested by Chris Hart.
4472 suggested by Chris Hart.
4460 (Magic.magic_cd): fixed behavior so that it only changes if
4473 (Magic.magic_cd): fixed behavior so that it only changes if
4461 directory actually is in history.
4474 directory actually is in history.
4462
4475
4463 * IPython/usage.py (__doc__): added information about potential
4476 * IPython/usage.py (__doc__): added information about potential
4464 slowness of Verbose exception mode when there are huge data
4477 slowness of Verbose exception mode when there are huge data
4465 structures to be formatted (thanks to Archie Paulson).
4478 structures to be formatted (thanks to Archie Paulson).
4466
4479
4467 * IPython/ipmaker.py (make_IPython): Changed default logging
4480 * IPython/ipmaker.py (make_IPython): Changed default logging
4468 (when simply called with -log) to use curr_dir/ipython.log in
4481 (when simply called with -log) to use curr_dir/ipython.log in
4469 rotate mode. Fixed crash which was occuring with -log before
4482 rotate mode. Fixed crash which was occuring with -log before
4470 (thanks to Jim Boyle).
4483 (thanks to Jim Boyle).
4471
4484
4472 2002-05-01 Fernando Perez <fperez@colorado.edu>
4485 2002-05-01 Fernando Perez <fperez@colorado.edu>
4473
4486
4474 * Released 0.2.11 for these fixes (mainly the ultraTB one which
4487 * Released 0.2.11 for these fixes (mainly the ultraTB one which
4475 was nasty -- though somewhat of a corner case).
4488 was nasty -- though somewhat of a corner case).
4476
4489
4477 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
4490 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
4478 text (was a bug).
4491 text (was a bug).
4479
4492
4480 2002-04-30 Fernando Perez <fperez@colorado.edu>
4493 2002-04-30 Fernando Perez <fperez@colorado.edu>
4481
4494
4482 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
4495 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
4483 a print after ^D or ^C from the user so that the In[] prompt
4496 a print after ^D or ^C from the user so that the In[] prompt
4484 doesn't over-run the gnuplot one.
4497 doesn't over-run the gnuplot one.
4485
4498
4486 2002-04-29 Fernando Perez <fperez@colorado.edu>
4499 2002-04-29 Fernando Perez <fperez@colorado.edu>
4487
4500
4488 * Released 0.2.10
4501 * Released 0.2.10
4489
4502
4490 * IPython/__release__.py (version): get date dynamically.
4503 * IPython/__release__.py (version): get date dynamically.
4491
4504
4492 * Misc. documentation updates thanks to Arnd's comments. Also ran
4505 * Misc. documentation updates thanks to Arnd's comments. Also ran
4493 a full spellcheck on the manual (hadn't been done in a while).
4506 a full spellcheck on the manual (hadn't been done in a while).
4494
4507
4495 2002-04-27 Fernando Perez <fperez@colorado.edu>
4508 2002-04-27 Fernando Perez <fperez@colorado.edu>
4496
4509
4497 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
4510 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
4498 starting a log in mid-session would reset the input history list.
4511 starting a log in mid-session would reset the input history list.
4499
4512
4500 2002-04-26 Fernando Perez <fperez@colorado.edu>
4513 2002-04-26 Fernando Perez <fperez@colorado.edu>
4501
4514
4502 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
4515 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
4503 all files were being included in an update. Now anything in
4516 all files were being included in an update. Now anything in
4504 UserConfig that matches [A-Za-z]*.py will go (this excludes
4517 UserConfig that matches [A-Za-z]*.py will go (this excludes
4505 __init__.py)
4518 __init__.py)
4506
4519
4507 2002-04-25 Fernando Perez <fperez@colorado.edu>
4520 2002-04-25 Fernando Perez <fperez@colorado.edu>
4508
4521
4509 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
4522 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
4510 to __builtins__ so that any form of embedded or imported code can
4523 to __builtins__ so that any form of embedded or imported code can
4511 test for being inside IPython.
4524 test for being inside IPython.
4512
4525
4513 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
4526 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
4514 changed to GnuplotMagic because it's now an importable module,
4527 changed to GnuplotMagic because it's now an importable module,
4515 this makes the name follow that of the standard Gnuplot module.
4528 this makes the name follow that of the standard Gnuplot module.
4516 GnuplotMagic can now be loaded at any time in mid-session.
4529 GnuplotMagic can now be loaded at any time in mid-session.
4517
4530
4518 2002-04-24 Fernando Perez <fperez@colorado.edu>
4531 2002-04-24 Fernando Perez <fperez@colorado.edu>
4519
4532
4520 * IPython/numutils.py: removed SIUnits. It doesn't properly set
4533 * IPython/numutils.py: removed SIUnits. It doesn't properly set
4521 the globals (IPython has its own namespace) and the
4534 the globals (IPython has its own namespace) and the
4522 PhysicalQuantity stuff is much better anyway.
4535 PhysicalQuantity stuff is much better anyway.
4523
4536
4524 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
4537 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
4525 embedding example to standard user directory for
4538 embedding example to standard user directory for
4526 distribution. Also put it in the manual.
4539 distribution. Also put it in the manual.
4527
4540
4528 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
4541 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
4529 instance as first argument (so it doesn't rely on some obscure
4542 instance as first argument (so it doesn't rely on some obscure
4530 hidden global).
4543 hidden global).
4531
4544
4532 * IPython/UserConfig/ipythonrc.py: put () back in accepted
4545 * IPython/UserConfig/ipythonrc.py: put () back in accepted
4533 delimiters. While it prevents ().TAB from working, it allows
4546 delimiters. While it prevents ().TAB from working, it allows
4534 completions in open (... expressions. This is by far a more common
4547 completions in open (... expressions. This is by far a more common
4535 case.
4548 case.
4536
4549
4537 2002-04-23 Fernando Perez <fperez@colorado.edu>
4550 2002-04-23 Fernando Perez <fperez@colorado.edu>
4538
4551
4539 * IPython/Extensions/InterpreterPasteInput.py: new
4552 * IPython/Extensions/InterpreterPasteInput.py: new
4540 syntax-processing module for pasting lines with >>> or ... at the
4553 syntax-processing module for pasting lines with >>> or ... at the
4541 start.
4554 start.
4542
4555
4543 * IPython/Extensions/PhysicalQ_Interactive.py
4556 * IPython/Extensions/PhysicalQ_Interactive.py
4544 (PhysicalQuantityInteractive.__int__): fixed to work with either
4557 (PhysicalQuantityInteractive.__int__): fixed to work with either
4545 Numeric or math.
4558 Numeric or math.
4546
4559
4547 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
4560 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
4548 provided profiles. Now we have:
4561 provided profiles. Now we have:
4549 -math -> math module as * and cmath with its own namespace.
4562 -math -> math module as * and cmath with its own namespace.
4550 -numeric -> Numeric as *, plus gnuplot & grace
4563 -numeric -> Numeric as *, plus gnuplot & grace
4551 -physics -> same as before
4564 -physics -> same as before
4552
4565
4553 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
4566 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
4554 user-defined magics wouldn't be found by @magic if they were
4567 user-defined magics wouldn't be found by @magic if they were
4555 defined as class methods. Also cleaned up the namespace search
4568 defined as class methods. Also cleaned up the namespace search
4556 logic and the string building (to use %s instead of many repeated
4569 logic and the string building (to use %s instead of many repeated
4557 string adds).
4570 string adds).
4558
4571
4559 * IPython/UserConfig/example-magic.py (magic_foo): updated example
4572 * IPython/UserConfig/example-magic.py (magic_foo): updated example
4560 of user-defined magics to operate with class methods (cleaner, in
4573 of user-defined magics to operate with class methods (cleaner, in
4561 line with the gnuplot code).
4574 line with the gnuplot code).
4562
4575
4563 2002-04-22 Fernando Perez <fperez@colorado.edu>
4576 2002-04-22 Fernando Perez <fperez@colorado.edu>
4564
4577
4565 * setup.py: updated dependency list so that manual is updated when
4578 * setup.py: updated dependency list so that manual is updated when
4566 all included files change.
4579 all included files change.
4567
4580
4568 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
4581 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
4569 the delimiter removal option (the fix is ugly right now).
4582 the delimiter removal option (the fix is ugly right now).
4570
4583
4571 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
4584 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
4572 all of the math profile (quicker loading, no conflict between
4585 all of the math profile (quicker loading, no conflict between
4573 g-9.8 and g-gnuplot).
4586 g-9.8 and g-gnuplot).
4574
4587
4575 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
4588 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
4576 name of post-mortem files to IPython_crash_report.txt.
4589 name of post-mortem files to IPython_crash_report.txt.
4577
4590
4578 * Cleanup/update of the docs. Added all the new readline info and
4591 * Cleanup/update of the docs. Added all the new readline info and
4579 formatted all lists as 'real lists'.
4592 formatted all lists as 'real lists'.
4580
4593
4581 * IPython/ipmaker.py (make_IPython): removed now-obsolete
4594 * IPython/ipmaker.py (make_IPython): removed now-obsolete
4582 tab-completion options, since the full readline parse_and_bind is
4595 tab-completion options, since the full readline parse_and_bind is
4583 now accessible.
4596 now accessible.
4584
4597
4585 * IPython/iplib.py (InteractiveShell.init_readline): Changed
4598 * IPython/iplib.py (InteractiveShell.init_readline): Changed
4586 handling of readline options. Now users can specify any string to
4599 handling of readline options. Now users can specify any string to
4587 be passed to parse_and_bind(), as well as the delimiters to be
4600 be passed to parse_and_bind(), as well as the delimiters to be
4588 removed.
4601 removed.
4589 (InteractiveShell.__init__): Added __name__ to the global
4602 (InteractiveShell.__init__): Added __name__ to the global
4590 namespace so that things like Itpl which rely on its existence
4603 namespace so that things like Itpl which rely on its existence
4591 don't crash.
4604 don't crash.
4592 (InteractiveShell._prefilter): Defined the default with a _ so
4605 (InteractiveShell._prefilter): Defined the default with a _ so
4593 that prefilter() is easier to override, while the default one
4606 that prefilter() is easier to override, while the default one
4594 remains available.
4607 remains available.
4595
4608
4596 2002-04-18 Fernando Perez <fperez@colorado.edu>
4609 2002-04-18 Fernando Perez <fperez@colorado.edu>
4597
4610
4598 * Added information about pdb in the docs.
4611 * Added information about pdb in the docs.
4599
4612
4600 2002-04-17 Fernando Perez <fperez@colorado.edu>
4613 2002-04-17 Fernando Perez <fperez@colorado.edu>
4601
4614
4602 * IPython/ipmaker.py (make_IPython): added rc_override option to
4615 * IPython/ipmaker.py (make_IPython): added rc_override option to
4603 allow passing config options at creation time which may override
4616 allow passing config options at creation time which may override
4604 anything set in the config files or command line. This is
4617 anything set in the config files or command line. This is
4605 particularly useful for configuring embedded instances.
4618 particularly useful for configuring embedded instances.
4606
4619
4607 2002-04-15 Fernando Perez <fperez@colorado.edu>
4620 2002-04-15 Fernando Perez <fperez@colorado.edu>
4608
4621
4609 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
4622 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
4610 crash embedded instances because of the input cache falling out of
4623 crash embedded instances because of the input cache falling out of
4611 sync with the output counter.
4624 sync with the output counter.
4612
4625
4613 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
4626 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
4614 mode which calls pdb after an uncaught exception in IPython itself.
4627 mode which calls pdb after an uncaught exception in IPython itself.
4615
4628
4616 2002-04-14 Fernando Perez <fperez@colorado.edu>
4629 2002-04-14 Fernando Perez <fperez@colorado.edu>
4617
4630
4618 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
4631 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
4619 readline, fix it back after each call.
4632 readline, fix it back after each call.
4620
4633
4621 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
4634 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
4622 method to force all access via __call__(), which guarantees that
4635 method to force all access via __call__(), which guarantees that
4623 traceback references are properly deleted.
4636 traceback references are properly deleted.
4624
4637
4625 * IPython/Prompts.py (CachedOutput._display): minor fixes to
4638 * IPython/Prompts.py (CachedOutput._display): minor fixes to
4626 improve printing when pprint is in use.
4639 improve printing when pprint is in use.
4627
4640
4628 2002-04-13 Fernando Perez <fperez@colorado.edu>
4641 2002-04-13 Fernando Perez <fperez@colorado.edu>
4629
4642
4630 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
4643 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
4631 exceptions aren't caught anymore. If the user triggers one, he
4644 exceptions aren't caught anymore. If the user triggers one, he
4632 should know why he's doing it and it should go all the way up,
4645 should know why he's doing it and it should go all the way up,
4633 just like any other exception. So now @abort will fully kill the
4646 just like any other exception. So now @abort will fully kill the
4634 embedded interpreter and the embedding code (unless that happens
4647 embedded interpreter and the embedding code (unless that happens
4635 to catch SystemExit).
4648 to catch SystemExit).
4636
4649
4637 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
4650 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
4638 and a debugger() method to invoke the interactive pdb debugger
4651 and a debugger() method to invoke the interactive pdb debugger
4639 after printing exception information. Also added the corresponding
4652 after printing exception information. Also added the corresponding
4640 -pdb option and @pdb magic to control this feature, and updated
4653 -pdb option and @pdb magic to control this feature, and updated
4641 the docs. After a suggestion from Christopher Hart
4654 the docs. After a suggestion from Christopher Hart
4642 (hart-AT-caltech.edu).
4655 (hart-AT-caltech.edu).
4643
4656
4644 2002-04-12 Fernando Perez <fperez@colorado.edu>
4657 2002-04-12 Fernando Perez <fperez@colorado.edu>
4645
4658
4646 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
4659 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
4647 the exception handlers defined by the user (not the CrashHandler)
4660 the exception handlers defined by the user (not the CrashHandler)
4648 so that user exceptions don't trigger an ipython bug report.
4661 so that user exceptions don't trigger an ipython bug report.
4649
4662
4650 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
4663 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
4651 configurable (it should have always been so).
4664 configurable (it should have always been so).
4652
4665
4653 2002-03-26 Fernando Perez <fperez@colorado.edu>
4666 2002-03-26 Fernando Perez <fperez@colorado.edu>
4654
4667
4655 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
4668 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
4656 and there to fix embedding namespace issues. This should all be
4669 and there to fix embedding namespace issues. This should all be
4657 done in a more elegant way.
4670 done in a more elegant way.
4658
4671
4659 2002-03-25 Fernando Perez <fperez@colorado.edu>
4672 2002-03-25 Fernando Perez <fperez@colorado.edu>
4660
4673
4661 * IPython/genutils.py (get_home_dir): Try to make it work under
4674 * IPython/genutils.py (get_home_dir): Try to make it work under
4662 win9x also.
4675 win9x also.
4663
4676
4664 2002-03-20 Fernando Perez <fperez@colorado.edu>
4677 2002-03-20 Fernando Perez <fperez@colorado.edu>
4665
4678
4666 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
4679 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
4667 sys.displayhook untouched upon __init__.
4680 sys.displayhook untouched upon __init__.
4668
4681
4669 2002-03-19 Fernando Perez <fperez@colorado.edu>
4682 2002-03-19 Fernando Perez <fperez@colorado.edu>
4670
4683
4671 * Released 0.2.9 (for embedding bug, basically).
4684 * Released 0.2.9 (for embedding bug, basically).
4672
4685
4673 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
4686 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
4674 exceptions so that enclosing shell's state can be restored.
4687 exceptions so that enclosing shell's state can be restored.
4675
4688
4676 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
4689 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
4677 naming conventions in the .ipython/ dir.
4690 naming conventions in the .ipython/ dir.
4678
4691
4679 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
4692 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
4680 from delimiters list so filenames with - in them get expanded.
4693 from delimiters list so filenames with - in them get expanded.
4681
4694
4682 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
4695 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
4683 sys.displayhook not being properly restored after an embedded call.
4696 sys.displayhook not being properly restored after an embedded call.
4684
4697
4685 2002-03-18 Fernando Perez <fperez@colorado.edu>
4698 2002-03-18 Fernando Perez <fperez@colorado.edu>
4686
4699
4687 * Released 0.2.8
4700 * Released 0.2.8
4688
4701
4689 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
4702 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
4690 some files weren't being included in a -upgrade.
4703 some files weren't being included in a -upgrade.
4691 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
4704 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
4692 on' so that the first tab completes.
4705 on' so that the first tab completes.
4693 (InteractiveShell.handle_magic): fixed bug with spaces around
4706 (InteractiveShell.handle_magic): fixed bug with spaces around
4694 quotes breaking many magic commands.
4707 quotes breaking many magic commands.
4695
4708
4696 * setup.py: added note about ignoring the syntax error messages at
4709 * setup.py: added note about ignoring the syntax error messages at
4697 installation.
4710 installation.
4698
4711
4699 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
4712 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
4700 streamlining the gnuplot interface, now there's only one magic @gp.
4713 streamlining the gnuplot interface, now there's only one magic @gp.
4701
4714
4702 2002-03-17 Fernando Perez <fperez@colorado.edu>
4715 2002-03-17 Fernando Perez <fperez@colorado.edu>
4703
4716
4704 * IPython/UserConfig/magic_gnuplot.py: new name for the
4717 * IPython/UserConfig/magic_gnuplot.py: new name for the
4705 example-magic_pm.py file. Much enhanced system, now with a shell
4718 example-magic_pm.py file. Much enhanced system, now with a shell
4706 for communicating directly with gnuplot, one command at a time.
4719 for communicating directly with gnuplot, one command at a time.
4707
4720
4708 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
4721 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
4709 setting __name__=='__main__'.
4722 setting __name__=='__main__'.
4710
4723
4711 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
4724 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
4712 mini-shell for accessing gnuplot from inside ipython. Should
4725 mini-shell for accessing gnuplot from inside ipython. Should
4713 extend it later for grace access too. Inspired by Arnd's
4726 extend it later for grace access too. Inspired by Arnd's
4714 suggestion.
4727 suggestion.
4715
4728
4716 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
4729 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
4717 calling magic functions with () in their arguments. Thanks to Arnd
4730 calling magic functions with () in their arguments. Thanks to Arnd
4718 Baecker for pointing this to me.
4731 Baecker for pointing this to me.
4719
4732
4720 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
4733 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
4721 infinitely for integer or complex arrays (only worked with floats).
4734 infinitely for integer or complex arrays (only worked with floats).
4722
4735
4723 2002-03-16 Fernando Perez <fperez@colorado.edu>
4736 2002-03-16 Fernando Perez <fperez@colorado.edu>
4724
4737
4725 * setup.py: Merged setup and setup_windows into a single script
4738 * setup.py: Merged setup and setup_windows into a single script
4726 which properly handles things for windows users.
4739 which properly handles things for windows users.
4727
4740
4728 2002-03-15 Fernando Perez <fperez@colorado.edu>
4741 2002-03-15 Fernando Perez <fperez@colorado.edu>
4729
4742
4730 * Big change to the manual: now the magics are all automatically
4743 * Big change to the manual: now the magics are all automatically
4731 documented. This information is generated from their docstrings
4744 documented. This information is generated from their docstrings
4732 and put in a latex file included by the manual lyx file. This way
4745 and put in a latex file included by the manual lyx file. This way
4733 we get always up to date information for the magics. The manual
4746 we get always up to date information for the magics. The manual
4734 now also has proper version information, also auto-synced.
4747 now also has proper version information, also auto-synced.
4735
4748
4736 For this to work, an undocumented --magic_docstrings option was added.
4749 For this to work, an undocumented --magic_docstrings option was added.
4737
4750
4738 2002-03-13 Fernando Perez <fperez@colorado.edu>
4751 2002-03-13 Fernando Perez <fperez@colorado.edu>
4739
4752
4740 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
4753 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
4741 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
4754 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
4742
4755
4743 2002-03-12 Fernando Perez <fperez@colorado.edu>
4756 2002-03-12 Fernando Perez <fperez@colorado.edu>
4744
4757
4745 * IPython/ultraTB.py (TermColors): changed color escapes again to
4758 * IPython/ultraTB.py (TermColors): changed color escapes again to
4746 fix the (old, reintroduced) line-wrapping bug. Basically, if
4759 fix the (old, reintroduced) line-wrapping bug. Basically, if
4747 \001..\002 aren't given in the color escapes, lines get wrapped
4760 \001..\002 aren't given in the color escapes, lines get wrapped
4748 weirdly. But giving those screws up old xterms and emacs terms. So
4761 weirdly. But giving those screws up old xterms and emacs terms. So
4749 I added some logic for emacs terms to be ok, but I can't identify old
4762 I added some logic for emacs terms to be ok, but I can't identify old
4750 xterms separately ($TERM=='xterm' for many terminals, like konsole).
4763 xterms separately ($TERM=='xterm' for many terminals, like konsole).
4751
4764
4752 2002-03-10 Fernando Perez <fperez@colorado.edu>
4765 2002-03-10 Fernando Perez <fperez@colorado.edu>
4753
4766
4754 * IPython/usage.py (__doc__): Various documentation cleanups and
4767 * IPython/usage.py (__doc__): Various documentation cleanups and
4755 updates, both in usage docstrings and in the manual.
4768 updates, both in usage docstrings and in the manual.
4756
4769
4757 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
4770 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
4758 handling of caching. Set minimum acceptabe value for having a
4771 handling of caching. Set minimum acceptabe value for having a
4759 cache at 20 values.
4772 cache at 20 values.
4760
4773
4761 * IPython/iplib.py (InteractiveShell.user_setup): moved the
4774 * IPython/iplib.py (InteractiveShell.user_setup): moved the
4762 install_first_time function to a method, renamed it and added an
4775 install_first_time function to a method, renamed it and added an
4763 'upgrade' mode. Now people can update their config directory with
4776 'upgrade' mode. Now people can update their config directory with
4764 a simple command line switch (-upgrade, also new).
4777 a simple command line switch (-upgrade, also new).
4765
4778
4766 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
4779 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
4767 @file (convenient for automagic users under Python >= 2.2).
4780 @file (convenient for automagic users under Python >= 2.2).
4768 Removed @files (it seemed more like a plural than an abbrev. of
4781 Removed @files (it seemed more like a plural than an abbrev. of
4769 'file show').
4782 'file show').
4770
4783
4771 * IPython/iplib.py (install_first_time): Fixed crash if there were
4784 * IPython/iplib.py (install_first_time): Fixed crash if there were
4772 backup files ('~') in .ipython/ install directory.
4785 backup files ('~') in .ipython/ install directory.
4773
4786
4774 * IPython/ipmaker.py (make_IPython): fixes for new prompt
4787 * IPython/ipmaker.py (make_IPython): fixes for new prompt
4775 system. Things look fine, but these changes are fairly
4788 system. Things look fine, but these changes are fairly
4776 intrusive. Test them for a few days.
4789 intrusive. Test them for a few days.
4777
4790
4778 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
4791 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
4779 the prompts system. Now all in/out prompt strings are user
4792 the prompts system. Now all in/out prompt strings are user
4780 controllable. This is particularly useful for embedding, as one
4793 controllable. This is particularly useful for embedding, as one
4781 can tag embedded instances with particular prompts.
4794 can tag embedded instances with particular prompts.
4782
4795
4783 Also removed global use of sys.ps1/2, which now allows nested
4796 Also removed global use of sys.ps1/2, which now allows nested
4784 embeddings without any problems. Added command-line options for
4797 embeddings without any problems. Added command-line options for
4785 the prompt strings.
4798 the prompt strings.
4786
4799
4787 2002-03-08 Fernando Perez <fperez@colorado.edu>
4800 2002-03-08 Fernando Perez <fperez@colorado.edu>
4788
4801
4789 * IPython/UserConfig/example-embed-short.py (ipshell): added
4802 * IPython/UserConfig/example-embed-short.py (ipshell): added
4790 example file with the bare minimum code for embedding.
4803 example file with the bare minimum code for embedding.
4791
4804
4792 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
4805 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
4793 functionality for the embeddable shell to be activated/deactivated
4806 functionality for the embeddable shell to be activated/deactivated
4794 either globally or at each call.
4807 either globally or at each call.
4795
4808
4796 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
4809 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
4797 rewriting the prompt with '--->' for auto-inputs with proper
4810 rewriting the prompt with '--->' for auto-inputs with proper
4798 coloring. Now the previous UGLY hack in handle_auto() is gone, and
4811 coloring. Now the previous UGLY hack in handle_auto() is gone, and
4799 this is handled by the prompts class itself, as it should.
4812 this is handled by the prompts class itself, as it should.
4800
4813
4801 2002-03-05 Fernando Perez <fperez@colorado.edu>
4814 2002-03-05 Fernando Perez <fperez@colorado.edu>
4802
4815
4803 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
4816 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
4804 @logstart to avoid name clashes with the math log function.
4817 @logstart to avoid name clashes with the math log function.
4805
4818
4806 * Big updates to X/Emacs section of the manual.
4819 * Big updates to X/Emacs section of the manual.
4807
4820
4808 * Removed ipython_emacs. Milan explained to me how to pass
4821 * Removed ipython_emacs. Milan explained to me how to pass
4809 arguments to ipython through Emacs. Some day I'm going to end up
4822 arguments to ipython through Emacs. Some day I'm going to end up
4810 learning some lisp...
4823 learning some lisp...
4811
4824
4812 2002-03-04 Fernando Perez <fperez@colorado.edu>
4825 2002-03-04 Fernando Perez <fperez@colorado.edu>
4813
4826
4814 * IPython/ipython_emacs: Created script to be used as the
4827 * IPython/ipython_emacs: Created script to be used as the
4815 py-python-command Emacs variable so we can pass IPython
4828 py-python-command Emacs variable so we can pass IPython
4816 parameters. I can't figure out how to tell Emacs directly to pass
4829 parameters. I can't figure out how to tell Emacs directly to pass
4817 parameters to IPython, so a dummy shell script will do it.
4830 parameters to IPython, so a dummy shell script will do it.
4818
4831
4819 Other enhancements made for things to work better under Emacs'
4832 Other enhancements made for things to work better under Emacs'
4820 various types of terminals. Many thanks to Milan Zamazal
4833 various types of terminals. Many thanks to Milan Zamazal
4821 <pdm-AT-zamazal.org> for all the suggestions and pointers.
4834 <pdm-AT-zamazal.org> for all the suggestions and pointers.
4822
4835
4823 2002-03-01 Fernando Perez <fperez@colorado.edu>
4836 2002-03-01 Fernando Perez <fperez@colorado.edu>
4824
4837
4825 * IPython/ipmaker.py (make_IPython): added a --readline! option so
4838 * IPython/ipmaker.py (make_IPython): added a --readline! option so
4826 that loading of readline is now optional. This gives better
4839 that loading of readline is now optional. This gives better
4827 control to emacs users.
4840 control to emacs users.
4828
4841
4829 * IPython/ultraTB.py (__date__): Modified color escape sequences
4842 * IPython/ultraTB.py (__date__): Modified color escape sequences
4830 and now things work fine under xterm and in Emacs' term buffers
4843 and now things work fine under xterm and in Emacs' term buffers
4831 (though not shell ones). Well, in emacs you get colors, but all
4844 (though not shell ones). Well, in emacs you get colors, but all
4832 seem to be 'light' colors (no difference between dark and light
4845 seem to be 'light' colors (no difference between dark and light
4833 ones). But the garbage chars are gone, and also in xterms. It
4846 ones). But the garbage chars are gone, and also in xterms. It
4834 seems that now I'm using 'cleaner' ansi sequences.
4847 seems that now I'm using 'cleaner' ansi sequences.
4835
4848
4836 2002-02-21 Fernando Perez <fperez@colorado.edu>
4849 2002-02-21 Fernando Perez <fperez@colorado.edu>
4837
4850
4838 * Released 0.2.7 (mainly to publish the scoping fix).
4851 * Released 0.2.7 (mainly to publish the scoping fix).
4839
4852
4840 * IPython/Logger.py (Logger.logstate): added. A corresponding
4853 * IPython/Logger.py (Logger.logstate): added. A corresponding
4841 @logstate magic was created.
4854 @logstate magic was created.
4842
4855
4843 * IPython/Magic.py: fixed nested scoping problem under Python
4856 * IPython/Magic.py: fixed nested scoping problem under Python
4844 2.1.x (automagic wasn't working).
4857 2.1.x (automagic wasn't working).
4845
4858
4846 2002-02-20 Fernando Perez <fperez@colorado.edu>
4859 2002-02-20 Fernando Perez <fperez@colorado.edu>
4847
4860
4848 * Released 0.2.6.
4861 * Released 0.2.6.
4849
4862
4850 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4863 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4851 option so that logs can come out without any headers at all.
4864 option so that logs can come out without any headers at all.
4852
4865
4853 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4866 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4854 SciPy.
4867 SciPy.
4855
4868
4856 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4869 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4857 that embedded IPython calls don't require vars() to be explicitly
4870 that embedded IPython calls don't require vars() to be explicitly
4858 passed. Now they are extracted from the caller's frame (code
4871 passed. Now they are extracted from the caller's frame (code
4859 snatched from Eric Jones' weave). Added better documentation to
4872 snatched from Eric Jones' weave). Added better documentation to
4860 the section on embedding and the example file.
4873 the section on embedding and the example file.
4861
4874
4862 * IPython/genutils.py (page): Changed so that under emacs, it just
4875 * IPython/genutils.py (page): Changed so that under emacs, it just
4863 prints the string. You can then page up and down in the emacs
4876 prints the string. You can then page up and down in the emacs
4864 buffer itself. This is how the builtin help() works.
4877 buffer itself. This is how the builtin help() works.
4865
4878
4866 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4879 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4867 macro scoping: macros need to be executed in the user's namespace
4880 macro scoping: macros need to be executed in the user's namespace
4868 to work as if they had been typed by the user.
4881 to work as if they had been typed by the user.
4869
4882
4870 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4883 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4871 execute automatically (no need to type 'exec...'). They then
4884 execute automatically (no need to type 'exec...'). They then
4872 behave like 'true macros'. The printing system was also modified
4885 behave like 'true macros'. The printing system was also modified
4873 for this to work.
4886 for this to work.
4874
4887
4875 2002-02-19 Fernando Perez <fperez@colorado.edu>
4888 2002-02-19 Fernando Perez <fperez@colorado.edu>
4876
4889
4877 * IPython/genutils.py (page_file): new function for paging files
4890 * IPython/genutils.py (page_file): new function for paging files
4878 in an OS-independent way. Also necessary for file viewing to work
4891 in an OS-independent way. Also necessary for file viewing to work
4879 well inside Emacs buffers.
4892 well inside Emacs buffers.
4880 (page): Added checks for being in an emacs buffer.
4893 (page): Added checks for being in an emacs buffer.
4881 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4894 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4882 same bug in iplib.
4895 same bug in iplib.
4883
4896
4884 2002-02-18 Fernando Perez <fperez@colorado.edu>
4897 2002-02-18 Fernando Perez <fperez@colorado.edu>
4885
4898
4886 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4899 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4887 of readline so that IPython can work inside an Emacs buffer.
4900 of readline so that IPython can work inside an Emacs buffer.
4888
4901
4889 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4902 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4890 method signatures (they weren't really bugs, but it looks cleaner
4903 method signatures (they weren't really bugs, but it looks cleaner
4891 and keeps PyChecker happy).
4904 and keeps PyChecker happy).
4892
4905
4893 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4906 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4894 for implementing various user-defined hooks. Currently only
4907 for implementing various user-defined hooks. Currently only
4895 display is done.
4908 display is done.
4896
4909
4897 * IPython/Prompts.py (CachedOutput._display): changed display
4910 * IPython/Prompts.py (CachedOutput._display): changed display
4898 functions so that they can be dynamically changed by users easily.
4911 functions so that they can be dynamically changed by users easily.
4899
4912
4900 * IPython/Extensions/numeric_formats.py (num_display): added an
4913 * IPython/Extensions/numeric_formats.py (num_display): added an
4901 extension for printing NumPy arrays in flexible manners. It
4914 extension for printing NumPy arrays in flexible manners. It
4902 doesn't do anything yet, but all the structure is in
4915 doesn't do anything yet, but all the structure is in
4903 place. Ultimately the plan is to implement output format control
4916 place. Ultimately the plan is to implement output format control
4904 like in Octave.
4917 like in Octave.
4905
4918
4906 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4919 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4907 methods are found at run-time by all the automatic machinery.
4920 methods are found at run-time by all the automatic machinery.
4908
4921
4909 2002-02-17 Fernando Perez <fperez@colorado.edu>
4922 2002-02-17 Fernando Perez <fperez@colorado.edu>
4910
4923
4911 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4924 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4912 whole file a little.
4925 whole file a little.
4913
4926
4914 * ToDo: closed this document. Now there's a new_design.lyx
4927 * ToDo: closed this document. Now there's a new_design.lyx
4915 document for all new ideas. Added making a pdf of it for the
4928 document for all new ideas. Added making a pdf of it for the
4916 end-user distro.
4929 end-user distro.
4917
4930
4918 * IPython/Logger.py (Logger.switch_log): Created this to replace
4931 * IPython/Logger.py (Logger.switch_log): Created this to replace
4919 logon() and logoff(). It also fixes a nasty crash reported by
4932 logon() and logoff(). It also fixes a nasty crash reported by
4920 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4933 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4921
4934
4922 * IPython/iplib.py (complete): got auto-completion to work with
4935 * IPython/iplib.py (complete): got auto-completion to work with
4923 automagic (I had wanted this for a long time).
4936 automagic (I had wanted this for a long time).
4924
4937
4925 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4938 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4926 to @file, since file() is now a builtin and clashes with automagic
4939 to @file, since file() is now a builtin and clashes with automagic
4927 for @file.
4940 for @file.
4928
4941
4929 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4942 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4930 of this was previously in iplib, which had grown to more than 2000
4943 of this was previously in iplib, which had grown to more than 2000
4931 lines, way too long. No new functionality, but it makes managing
4944 lines, way too long. No new functionality, but it makes managing
4932 the code a bit easier.
4945 the code a bit easier.
4933
4946
4934 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4947 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4935 information to crash reports.
4948 information to crash reports.
4936
4949
4937 2002-02-12 Fernando Perez <fperez@colorado.edu>
4950 2002-02-12 Fernando Perez <fperez@colorado.edu>
4938
4951
4939 * Released 0.2.5.
4952 * Released 0.2.5.
4940
4953
4941 2002-02-11 Fernando Perez <fperez@colorado.edu>
4954 2002-02-11 Fernando Perez <fperez@colorado.edu>
4942
4955
4943 * Wrote a relatively complete Windows installer. It puts
4956 * Wrote a relatively complete Windows installer. It puts
4944 everything in place, creates Start Menu entries and fixes the
4957 everything in place, creates Start Menu entries and fixes the
4945 color issues. Nothing fancy, but it works.
4958 color issues. Nothing fancy, but it works.
4946
4959
4947 2002-02-10 Fernando Perez <fperez@colorado.edu>
4960 2002-02-10 Fernando Perez <fperez@colorado.edu>
4948
4961
4949 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4962 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4950 os.path.expanduser() call so that we can type @run ~/myfile.py and
4963 os.path.expanduser() call so that we can type @run ~/myfile.py and
4951 have thigs work as expected.
4964 have thigs work as expected.
4952
4965
4953 * IPython/genutils.py (page): fixed exception handling so things
4966 * IPython/genutils.py (page): fixed exception handling so things
4954 work both in Unix and Windows correctly. Quitting a pager triggers
4967 work both in Unix and Windows correctly. Quitting a pager triggers
4955 an IOError/broken pipe in Unix, and in windows not finding a pager
4968 an IOError/broken pipe in Unix, and in windows not finding a pager
4956 is also an IOError, so I had to actually look at the return value
4969 is also an IOError, so I had to actually look at the return value
4957 of the exception, not just the exception itself. Should be ok now.
4970 of the exception, not just the exception itself. Should be ok now.
4958
4971
4959 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4972 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4960 modified to allow case-insensitive color scheme changes.
4973 modified to allow case-insensitive color scheme changes.
4961
4974
4962 2002-02-09 Fernando Perez <fperez@colorado.edu>
4975 2002-02-09 Fernando Perez <fperez@colorado.edu>
4963
4976
4964 * IPython/genutils.py (native_line_ends): new function to leave
4977 * IPython/genutils.py (native_line_ends): new function to leave
4965 user config files with os-native line-endings.
4978 user config files with os-native line-endings.
4966
4979
4967 * README and manual updates.
4980 * README and manual updates.
4968
4981
4969 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4982 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4970 instead of StringType to catch Unicode strings.
4983 instead of StringType to catch Unicode strings.
4971
4984
4972 * IPython/genutils.py (filefind): fixed bug for paths with
4985 * IPython/genutils.py (filefind): fixed bug for paths with
4973 embedded spaces (very common in Windows).
4986 embedded spaces (very common in Windows).
4974
4987
4975 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4988 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4976 files under Windows, so that they get automatically associated
4989 files under Windows, so that they get automatically associated
4977 with a text editor. Windows makes it a pain to handle
4990 with a text editor. Windows makes it a pain to handle
4978 extension-less files.
4991 extension-less files.
4979
4992
4980 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4993 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4981 warning about readline only occur for Posix. In Windows there's no
4994 warning about readline only occur for Posix. In Windows there's no
4982 way to get readline, so why bother with the warning.
4995 way to get readline, so why bother with the warning.
4983
4996
4984 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4997 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4985 for __str__ instead of dir(self), since dir() changed in 2.2.
4998 for __str__ instead of dir(self), since dir() changed in 2.2.
4986
4999
4987 * Ported to Windows! Tested on XP, I suspect it should work fine
5000 * Ported to Windows! Tested on XP, I suspect it should work fine
4988 on NT/2000, but I don't think it will work on 98 et al. That
5001 on NT/2000, but I don't think it will work on 98 et al. That
4989 series of Windows is such a piece of junk anyway that I won't try
5002 series of Windows is such a piece of junk anyway that I won't try
4990 porting it there. The XP port was straightforward, showed a few
5003 porting it there. The XP port was straightforward, showed a few
4991 bugs here and there (fixed all), in particular some string
5004 bugs here and there (fixed all), in particular some string
4992 handling stuff which required considering Unicode strings (which
5005 handling stuff which required considering Unicode strings (which
4993 Windows uses). This is good, but hasn't been too tested :) No
5006 Windows uses). This is good, but hasn't been too tested :) No
4994 fancy installer yet, I'll put a note in the manual so people at
5007 fancy installer yet, I'll put a note in the manual so people at
4995 least make manually a shortcut.
5008 least make manually a shortcut.
4996
5009
4997 * IPython/iplib.py (Magic.magic_colors): Unified the color options
5010 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4998 into a single one, "colors". This now controls both prompt and
5011 into a single one, "colors". This now controls both prompt and
4999 exception color schemes, and can be changed both at startup
5012 exception color schemes, and can be changed both at startup
5000 (either via command-line switches or via ipythonrc files) and at
5013 (either via command-line switches or via ipythonrc files) and at
5001 runtime, with @colors.
5014 runtime, with @colors.
5002 (Magic.magic_run): renamed @prun to @run and removed the old
5015 (Magic.magic_run): renamed @prun to @run and removed the old
5003 @run. The two were too similar to warrant keeping both.
5016 @run. The two were too similar to warrant keeping both.
5004
5017
5005 2002-02-03 Fernando Perez <fperez@colorado.edu>
5018 2002-02-03 Fernando Perez <fperez@colorado.edu>
5006
5019
5007 * IPython/iplib.py (install_first_time): Added comment on how to
5020 * IPython/iplib.py (install_first_time): Added comment on how to
5008 configure the color options for first-time users. Put a <return>
5021 configure the color options for first-time users. Put a <return>
5009 request at the end so that small-terminal users get a chance to
5022 request at the end so that small-terminal users get a chance to
5010 read the startup info.
5023 read the startup info.
5011
5024
5012 2002-01-23 Fernando Perez <fperez@colorado.edu>
5025 2002-01-23 Fernando Perez <fperez@colorado.edu>
5013
5026
5014 * IPython/iplib.py (CachedOutput.update): Changed output memory
5027 * IPython/iplib.py (CachedOutput.update): Changed output memory
5015 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
5028 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
5016 input history we still use _i. Did this b/c these variable are
5029 input history we still use _i. Did this b/c these variable are
5017 very commonly used in interactive work, so the less we need to
5030 very commonly used in interactive work, so the less we need to
5018 type the better off we are.
5031 type the better off we are.
5019 (Magic.magic_prun): updated @prun to better handle the namespaces
5032 (Magic.magic_prun): updated @prun to better handle the namespaces
5020 the file will run in, including a fix for __name__ not being set
5033 the file will run in, including a fix for __name__ not being set
5021 before.
5034 before.
5022
5035
5023 2002-01-20 Fernando Perez <fperez@colorado.edu>
5036 2002-01-20 Fernando Perez <fperez@colorado.edu>
5024
5037
5025 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
5038 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
5026 extra garbage for Python 2.2. Need to look more carefully into
5039 extra garbage for Python 2.2. Need to look more carefully into
5027 this later.
5040 this later.
5028
5041
5029 2002-01-19 Fernando Perez <fperez@colorado.edu>
5042 2002-01-19 Fernando Perez <fperez@colorado.edu>
5030
5043
5031 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
5044 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
5032 display SyntaxError exceptions properly formatted when they occur
5045 display SyntaxError exceptions properly formatted when they occur
5033 (they can be triggered by imported code).
5046 (they can be triggered by imported code).
5034
5047
5035 2002-01-18 Fernando Perez <fperez@colorado.edu>
5048 2002-01-18 Fernando Perez <fperez@colorado.edu>
5036
5049
5037 * IPython/iplib.py (InteractiveShell.safe_execfile): now
5050 * IPython/iplib.py (InteractiveShell.safe_execfile): now
5038 SyntaxError exceptions are reported nicely formatted, instead of
5051 SyntaxError exceptions are reported nicely formatted, instead of
5039 spitting out only offset information as before.
5052 spitting out only offset information as before.
5040 (Magic.magic_prun): Added the @prun function for executing
5053 (Magic.magic_prun): Added the @prun function for executing
5041 programs with command line args inside IPython.
5054 programs with command line args inside IPython.
5042
5055
5043 2002-01-16 Fernando Perez <fperez@colorado.edu>
5056 2002-01-16 Fernando Perez <fperez@colorado.edu>
5044
5057
5045 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
5058 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
5046 to *not* include the last item given in a range. This brings their
5059 to *not* include the last item given in a range. This brings their
5047 behavior in line with Python's slicing:
5060 behavior in line with Python's slicing:
5048 a[n1:n2] -> a[n1]...a[n2-1]
5061 a[n1:n2] -> a[n1]...a[n2-1]
5049 It may be a bit less convenient, but I prefer to stick to Python's
5062 It may be a bit less convenient, but I prefer to stick to Python's
5050 conventions *everywhere*, so users never have to wonder.
5063 conventions *everywhere*, so users never have to wonder.
5051 (Magic.magic_macro): Added @macro function to ease the creation of
5064 (Magic.magic_macro): Added @macro function to ease the creation of
5052 macros.
5065 macros.
5053
5066
5054 2002-01-05 Fernando Perez <fperez@colorado.edu>
5067 2002-01-05 Fernando Perez <fperez@colorado.edu>
5055
5068
5056 * Released 0.2.4.
5069 * Released 0.2.4.
5057
5070
5058 * IPython/iplib.py (Magic.magic_pdef):
5071 * IPython/iplib.py (Magic.magic_pdef):
5059 (InteractiveShell.safe_execfile): report magic lines and error
5072 (InteractiveShell.safe_execfile): report magic lines and error
5060 lines without line numbers so one can easily copy/paste them for
5073 lines without line numbers so one can easily copy/paste them for
5061 re-execution.
5074 re-execution.
5062
5075
5063 * Updated manual with recent changes.
5076 * Updated manual with recent changes.
5064
5077
5065 * IPython/iplib.py (Magic.magic_oinfo): added constructor
5078 * IPython/iplib.py (Magic.magic_oinfo): added constructor
5066 docstring printing when class? is called. Very handy for knowing
5079 docstring printing when class? is called. Very handy for knowing
5067 how to create class instances (as long as __init__ is well
5080 how to create class instances (as long as __init__ is well
5068 documented, of course :)
5081 documented, of course :)
5069 (Magic.magic_doc): print both class and constructor docstrings.
5082 (Magic.magic_doc): print both class and constructor docstrings.
5070 (Magic.magic_pdef): give constructor info if passed a class and
5083 (Magic.magic_pdef): give constructor info if passed a class and
5071 __call__ info for callable object instances.
5084 __call__ info for callable object instances.
5072
5085
5073 2002-01-04 Fernando Perez <fperez@colorado.edu>
5086 2002-01-04 Fernando Perez <fperez@colorado.edu>
5074
5087
5075 * Made deep_reload() off by default. It doesn't always work
5088 * Made deep_reload() off by default. It doesn't always work
5076 exactly as intended, so it's probably safer to have it off. It's
5089 exactly as intended, so it's probably safer to have it off. It's
5077 still available as dreload() anyway, so nothing is lost.
5090 still available as dreload() anyway, so nothing is lost.
5078
5091
5079 2002-01-02 Fernando Perez <fperez@colorado.edu>
5092 2002-01-02 Fernando Perez <fperez@colorado.edu>
5080
5093
5081 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
5094 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
5082 so I wanted an updated release).
5095 so I wanted an updated release).
5083
5096
5084 2001-12-27 Fernando Perez <fperez@colorado.edu>
5097 2001-12-27 Fernando Perez <fperez@colorado.edu>
5085
5098
5086 * IPython/iplib.py (InteractiveShell.interact): Added the original
5099 * IPython/iplib.py (InteractiveShell.interact): Added the original
5087 code from 'code.py' for this module in order to change the
5100 code from 'code.py' for this module in order to change the
5088 handling of a KeyboardInterrupt. This was necessary b/c otherwise
5101 handling of a KeyboardInterrupt. This was necessary b/c otherwise
5089 the history cache would break when the user hit Ctrl-C, and
5102 the history cache would break when the user hit Ctrl-C, and
5090 interact() offers no way to add any hooks to it.
5103 interact() offers no way to add any hooks to it.
5091
5104
5092 2001-12-23 Fernando Perez <fperez@colorado.edu>
5105 2001-12-23 Fernando Perez <fperez@colorado.edu>
5093
5106
5094 * setup.py: added check for 'MANIFEST' before trying to remove
5107 * setup.py: added check for 'MANIFEST' before trying to remove
5095 it. Thanks to Sean Reifschneider.
5108 it. Thanks to Sean Reifschneider.
5096
5109
5097 2001-12-22 Fernando Perez <fperez@colorado.edu>
5110 2001-12-22 Fernando Perez <fperez@colorado.edu>
5098
5111
5099 * Released 0.2.2.
5112 * Released 0.2.2.
5100
5113
5101 * Finished (reasonably) writing the manual. Later will add the
5114 * Finished (reasonably) writing the manual. Later will add the
5102 python-standard navigation stylesheets, but for the time being
5115 python-standard navigation stylesheets, but for the time being
5103 it's fairly complete. Distribution will include html and pdf
5116 it's fairly complete. Distribution will include html and pdf
5104 versions.
5117 versions.
5105
5118
5106 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
5119 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
5107 (MayaVi author).
5120 (MayaVi author).
5108
5121
5109 2001-12-21 Fernando Perez <fperez@colorado.edu>
5122 2001-12-21 Fernando Perez <fperez@colorado.edu>
5110
5123
5111 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
5124 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
5112 good public release, I think (with the manual and the distutils
5125 good public release, I think (with the manual and the distutils
5113 installer). The manual can use some work, but that can go
5126 installer). The manual can use some work, but that can go
5114 slowly. Otherwise I think it's quite nice for end users. Next
5127 slowly. Otherwise I think it's quite nice for end users. Next
5115 summer, rewrite the guts of it...
5128 summer, rewrite the guts of it...
5116
5129
5117 * Changed format of ipythonrc files to use whitespace as the
5130 * Changed format of ipythonrc files to use whitespace as the
5118 separator instead of an explicit '='. Cleaner.
5131 separator instead of an explicit '='. Cleaner.
5119
5132
5120 2001-12-20 Fernando Perez <fperez@colorado.edu>
5133 2001-12-20 Fernando Perez <fperez@colorado.edu>
5121
5134
5122 * Started a manual in LyX. For now it's just a quick merge of the
5135 * Started a manual in LyX. For now it's just a quick merge of the
5123 various internal docstrings and READMEs. Later it may grow into a
5136 various internal docstrings and READMEs. Later it may grow into a
5124 nice, full-blown manual.
5137 nice, full-blown manual.
5125
5138
5126 * Set up a distutils based installer. Installation should now be
5139 * Set up a distutils based installer. Installation should now be
5127 trivially simple for end-users.
5140 trivially simple for end-users.
5128
5141
5129 2001-12-11 Fernando Perez <fperez@colorado.edu>
5142 2001-12-11 Fernando Perez <fperez@colorado.edu>
5130
5143
5131 * Released 0.2.0. First public release, announced it at
5144 * Released 0.2.0. First public release, announced it at
5132 comp.lang.python. From now on, just bugfixes...
5145 comp.lang.python. From now on, just bugfixes...
5133
5146
5134 * Went through all the files, set copyright/license notices and
5147 * Went through all the files, set copyright/license notices and
5135 cleaned up things. Ready for release.
5148 cleaned up things. Ready for release.
5136
5149
5137 2001-12-10 Fernando Perez <fperez@colorado.edu>
5150 2001-12-10 Fernando Perez <fperez@colorado.edu>
5138
5151
5139 * Changed the first-time installer not to use tarfiles. It's more
5152 * Changed the first-time installer not to use tarfiles. It's more
5140 robust now and less unix-dependent. Also makes it easier for
5153 robust now and less unix-dependent. Also makes it easier for
5141 people to later upgrade versions.
5154 people to later upgrade versions.
5142
5155
5143 * Changed @exit to @abort to reflect the fact that it's pretty
5156 * Changed @exit to @abort to reflect the fact that it's pretty
5144 brutal (a sys.exit()). The difference between @abort and Ctrl-D
5157 brutal (a sys.exit()). The difference between @abort and Ctrl-D
5145 becomes significant only when IPyhton is embedded: in that case,
5158 becomes significant only when IPyhton is embedded: in that case,
5146 C-D closes IPython only, but @abort kills the enclosing program
5159 C-D closes IPython only, but @abort kills the enclosing program
5147 too (unless it had called IPython inside a try catching
5160 too (unless it had called IPython inside a try catching
5148 SystemExit).
5161 SystemExit).
5149
5162
5150 * Created Shell module which exposes the actuall IPython Shell
5163 * Created Shell module which exposes the actuall IPython Shell
5151 classes, currently the normal and the embeddable one. This at
5164 classes, currently the normal and the embeddable one. This at
5152 least offers a stable interface we won't need to change when
5165 least offers a stable interface we won't need to change when
5153 (later) the internals are rewritten. That rewrite will be confined
5166 (later) the internals are rewritten. That rewrite will be confined
5154 to iplib and ipmaker, but the Shell interface should remain as is.
5167 to iplib and ipmaker, but the Shell interface should remain as is.
5155
5168
5156 * Added embed module which offers an embeddable IPShell object,
5169 * Added embed module which offers an embeddable IPShell object,
5157 useful to fire up IPython *inside* a running program. Great for
5170 useful to fire up IPython *inside* a running program. Great for
5158 debugging or dynamical data analysis.
5171 debugging or dynamical data analysis.
5159
5172
5160 2001-12-08 Fernando Perez <fperez@colorado.edu>
5173 2001-12-08 Fernando Perez <fperez@colorado.edu>
5161
5174
5162 * Fixed small bug preventing seeing info from methods of defined
5175 * Fixed small bug preventing seeing info from methods of defined
5163 objects (incorrect namespace in _ofind()).
5176 objects (incorrect namespace in _ofind()).
5164
5177
5165 * Documentation cleanup. Moved the main usage docstrings to a
5178 * Documentation cleanup. Moved the main usage docstrings to a
5166 separate file, usage.py (cleaner to maintain, and hopefully in the
5179 separate file, usage.py (cleaner to maintain, and hopefully in the
5167 future some perlpod-like way of producing interactive, man and
5180 future some perlpod-like way of producing interactive, man and
5168 html docs out of it will be found).
5181 html docs out of it will be found).
5169
5182
5170 * Added @profile to see your profile at any time.
5183 * Added @profile to see your profile at any time.
5171
5184
5172 * Added @p as an alias for 'print'. It's especially convenient if
5185 * Added @p as an alias for 'print'. It's especially convenient if
5173 using automagic ('p x' prints x).
5186 using automagic ('p x' prints x).
5174
5187
5175 * Small cleanups and fixes after a pychecker run.
5188 * Small cleanups and fixes after a pychecker run.
5176
5189
5177 * Changed the @cd command to handle @cd - and @cd -<n> for
5190 * Changed the @cd command to handle @cd - and @cd -<n> for
5178 visiting any directory in _dh.
5191 visiting any directory in _dh.
5179
5192
5180 * Introduced _dh, a history of visited directories. @dhist prints
5193 * Introduced _dh, a history of visited directories. @dhist prints
5181 it out with numbers.
5194 it out with numbers.
5182
5195
5183 2001-12-07 Fernando Perez <fperez@colorado.edu>
5196 2001-12-07 Fernando Perez <fperez@colorado.edu>
5184
5197
5185 * Released 0.1.22
5198 * Released 0.1.22
5186
5199
5187 * Made initialization a bit more robust against invalid color
5200 * Made initialization a bit more robust against invalid color
5188 options in user input (exit, not traceback-crash).
5201 options in user input (exit, not traceback-crash).
5189
5202
5190 * Changed the bug crash reporter to write the report only in the
5203 * Changed the bug crash reporter to write the report only in the
5191 user's .ipython directory. That way IPython won't litter people's
5204 user's .ipython directory. That way IPython won't litter people's
5192 hard disks with crash files all over the place. Also print on
5205 hard disks with crash files all over the place. Also print on
5193 screen the necessary mail command.
5206 screen the necessary mail command.
5194
5207
5195 * With the new ultraTB, implemented LightBG color scheme for light
5208 * With the new ultraTB, implemented LightBG color scheme for light
5196 background terminals. A lot of people like white backgrounds, so I
5209 background terminals. A lot of people like white backgrounds, so I
5197 guess we should at least give them something readable.
5210 guess we should at least give them something readable.
5198
5211
5199 2001-12-06 Fernando Perez <fperez@colorado.edu>
5212 2001-12-06 Fernando Perez <fperez@colorado.edu>
5200
5213
5201 * Modified the structure of ultraTB. Now there's a proper class
5214 * Modified the structure of ultraTB. Now there's a proper class
5202 for tables of color schemes which allow adding schemes easily and
5215 for tables of color schemes which allow adding schemes easily and
5203 switching the active scheme without creating a new instance every
5216 switching the active scheme without creating a new instance every
5204 time (which was ridiculous). The syntax for creating new schemes
5217 time (which was ridiculous). The syntax for creating new schemes
5205 is also cleaner. I think ultraTB is finally done, with a clean
5218 is also cleaner. I think ultraTB is finally done, with a clean
5206 class structure. Names are also much cleaner (now there's proper
5219 class structure. Names are also much cleaner (now there's proper
5207 color tables, no need for every variable to also have 'color' in
5220 color tables, no need for every variable to also have 'color' in
5208 its name).
5221 its name).
5209
5222
5210 * Broke down genutils into separate files. Now genutils only
5223 * Broke down genutils into separate files. Now genutils only
5211 contains utility functions, and classes have been moved to their
5224 contains utility functions, and classes have been moved to their
5212 own files (they had enough independent functionality to warrant
5225 own files (they had enough independent functionality to warrant
5213 it): ConfigLoader, OutputTrap, Struct.
5226 it): ConfigLoader, OutputTrap, Struct.
5214
5227
5215 2001-12-05 Fernando Perez <fperez@colorado.edu>
5228 2001-12-05 Fernando Perez <fperez@colorado.edu>
5216
5229
5217 * IPython turns 21! Released version 0.1.21, as a candidate for
5230 * IPython turns 21! Released version 0.1.21, as a candidate for
5218 public consumption. If all goes well, release in a few days.
5231 public consumption. If all goes well, release in a few days.
5219
5232
5220 * Fixed path bug (files in Extensions/ directory wouldn't be found
5233 * Fixed path bug (files in Extensions/ directory wouldn't be found
5221 unless IPython/ was explicitly in sys.path).
5234 unless IPython/ was explicitly in sys.path).
5222
5235
5223 * Extended the FlexCompleter class as MagicCompleter to allow
5236 * Extended the FlexCompleter class as MagicCompleter to allow
5224 completion of @-starting lines.
5237 completion of @-starting lines.
5225
5238
5226 * Created __release__.py file as a central repository for release
5239 * Created __release__.py file as a central repository for release
5227 info that other files can read from.
5240 info that other files can read from.
5228
5241
5229 * Fixed small bug in logging: when logging was turned on in
5242 * Fixed small bug in logging: when logging was turned on in
5230 mid-session, old lines with special meanings (!@?) were being
5243 mid-session, old lines with special meanings (!@?) were being
5231 logged without the prepended comment, which is necessary since
5244 logged without the prepended comment, which is necessary since
5232 they are not truly valid python syntax. This should make session
5245 they are not truly valid python syntax. This should make session
5233 restores produce less errors.
5246 restores produce less errors.
5234
5247
5235 * The namespace cleanup forced me to make a FlexCompleter class
5248 * The namespace cleanup forced me to make a FlexCompleter class
5236 which is nothing but a ripoff of rlcompleter, but with selectable
5249 which is nothing but a ripoff of rlcompleter, but with selectable
5237 namespace (rlcompleter only works in __main__.__dict__). I'll try
5250 namespace (rlcompleter only works in __main__.__dict__). I'll try
5238 to submit a note to the authors to see if this change can be
5251 to submit a note to the authors to see if this change can be
5239 incorporated in future rlcompleter releases (Dec.6: done)
5252 incorporated in future rlcompleter releases (Dec.6: done)
5240
5253
5241 * More fixes to namespace handling. It was a mess! Now all
5254 * More fixes to namespace handling. It was a mess! Now all
5242 explicit references to __main__.__dict__ are gone (except when
5255 explicit references to __main__.__dict__ are gone (except when
5243 really needed) and everything is handled through the namespace
5256 really needed) and everything is handled through the namespace
5244 dicts in the IPython instance. We seem to be getting somewhere
5257 dicts in the IPython instance. We seem to be getting somewhere
5245 with this, finally...
5258 with this, finally...
5246
5259
5247 * Small documentation updates.
5260 * Small documentation updates.
5248
5261
5249 * Created the Extensions directory under IPython (with an
5262 * Created the Extensions directory under IPython (with an
5250 __init__.py). Put the PhysicalQ stuff there. This directory should
5263 __init__.py). Put the PhysicalQ stuff there. This directory should
5251 be used for all special-purpose extensions.
5264 be used for all special-purpose extensions.
5252
5265
5253 * File renaming:
5266 * File renaming:
5254 ipythonlib --> ipmaker
5267 ipythonlib --> ipmaker
5255 ipplib --> iplib
5268 ipplib --> iplib
5256 This makes a bit more sense in terms of what these files actually do.
5269 This makes a bit more sense in terms of what these files actually do.
5257
5270
5258 * Moved all the classes and functions in ipythonlib to ipplib, so
5271 * Moved all the classes and functions in ipythonlib to ipplib, so
5259 now ipythonlib only has make_IPython(). This will ease up its
5272 now ipythonlib only has make_IPython(). This will ease up its
5260 splitting in smaller functional chunks later.
5273 splitting in smaller functional chunks later.
5261
5274
5262 * Cleaned up (done, I think) output of @whos. Better column
5275 * Cleaned up (done, I think) output of @whos. Better column
5263 formatting, and now shows str(var) for as much as it can, which is
5276 formatting, and now shows str(var) for as much as it can, which is
5264 typically what one gets with a 'print var'.
5277 typically what one gets with a 'print var'.
5265
5278
5266 2001-12-04 Fernando Perez <fperez@colorado.edu>
5279 2001-12-04 Fernando Perez <fperez@colorado.edu>
5267
5280
5268 * Fixed namespace problems. Now builtin/IPyhton/user names get
5281 * Fixed namespace problems. Now builtin/IPyhton/user names get
5269 properly reported in their namespace. Internal namespace handling
5282 properly reported in their namespace. Internal namespace handling
5270 is finally getting decent (not perfect yet, but much better than
5283 is finally getting decent (not perfect yet, but much better than
5271 the ad-hoc mess we had).
5284 the ad-hoc mess we had).
5272
5285
5273 * Removed -exit option. If people just want to run a python
5286 * Removed -exit option. If people just want to run a python
5274 script, that's what the normal interpreter is for. Less
5287 script, that's what the normal interpreter is for. Less
5275 unnecessary options, less chances for bugs.
5288 unnecessary options, less chances for bugs.
5276
5289
5277 * Added a crash handler which generates a complete post-mortem if
5290 * Added a crash handler which generates a complete post-mortem if
5278 IPython crashes. This will help a lot in tracking bugs down the
5291 IPython crashes. This will help a lot in tracking bugs down the
5279 road.
5292 road.
5280
5293
5281 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
5294 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
5282 which were boud to functions being reassigned would bypass the
5295 which were boud to functions being reassigned would bypass the
5283 logger, breaking the sync of _il with the prompt counter. This
5296 logger, breaking the sync of _il with the prompt counter. This
5284 would then crash IPython later when a new line was logged.
5297 would then crash IPython later when a new line was logged.
5285
5298
5286 2001-12-02 Fernando Perez <fperez@colorado.edu>
5299 2001-12-02 Fernando Perez <fperez@colorado.edu>
5287
5300
5288 * Made IPython a package. This means people don't have to clutter
5301 * Made IPython a package. This means people don't have to clutter
5289 their sys.path with yet another directory. Changed the INSTALL
5302 their sys.path with yet another directory. Changed the INSTALL
5290 file accordingly.
5303 file accordingly.
5291
5304
5292 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
5305 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
5293 sorts its output (so @who shows it sorted) and @whos formats the
5306 sorts its output (so @who shows it sorted) and @whos formats the
5294 table according to the width of the first column. Nicer, easier to
5307 table according to the width of the first column. Nicer, easier to
5295 read. Todo: write a generic table_format() which takes a list of
5308 read. Todo: write a generic table_format() which takes a list of
5296 lists and prints it nicely formatted, with optional row/column
5309 lists and prints it nicely formatted, with optional row/column
5297 separators and proper padding and justification.
5310 separators and proper padding and justification.
5298
5311
5299 * Released 0.1.20
5312 * Released 0.1.20
5300
5313
5301 * Fixed bug in @log which would reverse the inputcache list (a
5314 * Fixed bug in @log which would reverse the inputcache list (a
5302 copy operation was missing).
5315 copy operation was missing).
5303
5316
5304 * Code cleanup. @config was changed to use page(). Better, since
5317 * Code cleanup. @config was changed to use page(). Better, since
5305 its output is always quite long.
5318 its output is always quite long.
5306
5319
5307 * Itpl is back as a dependency. I was having too many problems
5320 * Itpl is back as a dependency. I was having too many problems
5308 getting the parametric aliases to work reliably, and it's just
5321 getting the parametric aliases to work reliably, and it's just
5309 easier to code weird string operations with it than playing %()s
5322 easier to code weird string operations with it than playing %()s
5310 games. It's only ~6k, so I don't think it's too big a deal.
5323 games. It's only ~6k, so I don't think it's too big a deal.
5311
5324
5312 * Found (and fixed) a very nasty bug with history. !lines weren't
5325 * Found (and fixed) a very nasty bug with history. !lines weren't
5313 getting cached, and the out of sync caches would crash
5326 getting cached, and the out of sync caches would crash
5314 IPython. Fixed it by reorganizing the prefilter/handlers/logger
5327 IPython. Fixed it by reorganizing the prefilter/handlers/logger
5315 division of labor a bit better. Bug fixed, cleaner structure.
5328 division of labor a bit better. Bug fixed, cleaner structure.
5316
5329
5317 2001-12-01 Fernando Perez <fperez@colorado.edu>
5330 2001-12-01 Fernando Perez <fperez@colorado.edu>
5318
5331
5319 * Released 0.1.19
5332 * Released 0.1.19
5320
5333
5321 * Added option -n to @hist to prevent line number printing. Much
5334 * Added option -n to @hist to prevent line number printing. Much
5322 easier to copy/paste code this way.
5335 easier to copy/paste code this way.
5323
5336
5324 * Created global _il to hold the input list. Allows easy
5337 * Created global _il to hold the input list. Allows easy
5325 re-execution of blocks of code by slicing it (inspired by Janko's
5338 re-execution of blocks of code by slicing it (inspired by Janko's
5326 comment on 'macros').
5339 comment on 'macros').
5327
5340
5328 * Small fixes and doc updates.
5341 * Small fixes and doc updates.
5329
5342
5330 * Rewrote @history function (was @h). Renamed it to @hist, @h is
5343 * Rewrote @history function (was @h). Renamed it to @hist, @h is
5331 much too fragile with automagic. Handles properly multi-line
5344 much too fragile with automagic. Handles properly multi-line
5332 statements and takes parameters.
5345 statements and takes parameters.
5333
5346
5334 2001-11-30 Fernando Perez <fperez@colorado.edu>
5347 2001-11-30 Fernando Perez <fperez@colorado.edu>
5335
5348
5336 * Version 0.1.18 released.
5349 * Version 0.1.18 released.
5337
5350
5338 * Fixed nasty namespace bug in initial module imports.
5351 * Fixed nasty namespace bug in initial module imports.
5339
5352
5340 * Added copyright/license notes to all code files (except
5353 * Added copyright/license notes to all code files (except
5341 DPyGetOpt). For the time being, LGPL. That could change.
5354 DPyGetOpt). For the time being, LGPL. That could change.
5342
5355
5343 * Rewrote a much nicer README, updated INSTALL, cleaned up
5356 * Rewrote a much nicer README, updated INSTALL, cleaned up
5344 ipythonrc-* samples.
5357 ipythonrc-* samples.
5345
5358
5346 * Overall code/documentation cleanup. Basically ready for
5359 * Overall code/documentation cleanup. Basically ready for
5347 release. Only remaining thing: licence decision (LGPL?).
5360 release. Only remaining thing: licence decision (LGPL?).
5348
5361
5349 * Converted load_config to a class, ConfigLoader. Now recursion
5362 * Converted load_config to a class, ConfigLoader. Now recursion
5350 control is better organized. Doesn't include the same file twice.
5363 control is better organized. Doesn't include the same file twice.
5351
5364
5352 2001-11-29 Fernando Perez <fperez@colorado.edu>
5365 2001-11-29 Fernando Perez <fperez@colorado.edu>
5353
5366
5354 * Got input history working. Changed output history variables from
5367 * Got input history working. Changed output history variables from
5355 _p to _o so that _i is for input and _o for output. Just cleaner
5368 _p to _o so that _i is for input and _o for output. Just cleaner
5356 convention.
5369 convention.
5357
5370
5358 * Implemented parametric aliases. This pretty much allows the
5371 * Implemented parametric aliases. This pretty much allows the
5359 alias system to offer full-blown shell convenience, I think.
5372 alias system to offer full-blown shell convenience, I think.
5360
5373
5361 * Version 0.1.17 released, 0.1.18 opened.
5374 * Version 0.1.17 released, 0.1.18 opened.
5362
5375
5363 * dot_ipython/ipythonrc (alias): added documentation.
5376 * dot_ipython/ipythonrc (alias): added documentation.
5364 (xcolor): Fixed small bug (xcolors -> xcolor)
5377 (xcolor): Fixed small bug (xcolors -> xcolor)
5365
5378
5366 * Changed the alias system. Now alias is a magic command to define
5379 * Changed the alias system. Now alias is a magic command to define
5367 aliases just like the shell. Rationale: the builtin magics should
5380 aliases just like the shell. Rationale: the builtin magics should
5368 be there for things deeply connected to IPython's
5381 be there for things deeply connected to IPython's
5369 architecture. And this is a much lighter system for what I think
5382 architecture. And this is a much lighter system for what I think
5370 is the really important feature: allowing users to define quickly
5383 is the really important feature: allowing users to define quickly
5371 magics that will do shell things for them, so they can customize
5384 magics that will do shell things for them, so they can customize
5372 IPython easily to match their work habits. If someone is really
5385 IPython easily to match their work habits. If someone is really
5373 desperate to have another name for a builtin alias, they can
5386 desperate to have another name for a builtin alias, they can
5374 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
5387 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
5375 works.
5388 works.
5376
5389
5377 2001-11-28 Fernando Perez <fperez@colorado.edu>
5390 2001-11-28 Fernando Perez <fperez@colorado.edu>
5378
5391
5379 * Changed @file so that it opens the source file at the proper
5392 * Changed @file so that it opens the source file at the proper
5380 line. Since it uses less, if your EDITOR environment is
5393 line. Since it uses less, if your EDITOR environment is
5381 configured, typing v will immediately open your editor of choice
5394 configured, typing v will immediately open your editor of choice
5382 right at the line where the object is defined. Not as quick as
5395 right at the line where the object is defined. Not as quick as
5383 having a direct @edit command, but for all intents and purposes it
5396 having a direct @edit command, but for all intents and purposes it
5384 works. And I don't have to worry about writing @edit to deal with
5397 works. And I don't have to worry about writing @edit to deal with
5385 all the editors, less does that.
5398 all the editors, less does that.
5386
5399
5387 * Version 0.1.16 released, 0.1.17 opened.
5400 * Version 0.1.16 released, 0.1.17 opened.
5388
5401
5389 * Fixed some nasty bugs in the page/page_dumb combo that could
5402 * Fixed some nasty bugs in the page/page_dumb combo that could
5390 crash IPython.
5403 crash IPython.
5391
5404
5392 2001-11-27 Fernando Perez <fperez@colorado.edu>
5405 2001-11-27 Fernando Perez <fperez@colorado.edu>
5393
5406
5394 * Version 0.1.15 released, 0.1.16 opened.
5407 * Version 0.1.15 released, 0.1.16 opened.
5395
5408
5396 * Finally got ? and ?? to work for undefined things: now it's
5409 * Finally got ? and ?? to work for undefined things: now it's
5397 possible to type {}.get? and get information about the get method
5410 possible to type {}.get? and get information about the get method
5398 of dicts, or os.path? even if only os is defined (so technically
5411 of dicts, or os.path? even if only os is defined (so technically
5399 os.path isn't). Works at any level. For example, after import os,
5412 os.path isn't). Works at any level. For example, after import os,
5400 os?, os.path?, os.path.abspath? all work. This is great, took some
5413 os?, os.path?, os.path.abspath? all work. This is great, took some
5401 work in _ofind.
5414 work in _ofind.
5402
5415
5403 * Fixed more bugs with logging. The sanest way to do it was to add
5416 * Fixed more bugs with logging. The sanest way to do it was to add
5404 to @log a 'mode' parameter. Killed two in one shot (this mode
5417 to @log a 'mode' parameter. Killed two in one shot (this mode
5405 option was a request of Janko's). I think it's finally clean
5418 option was a request of Janko's). I think it's finally clean
5406 (famous last words).
5419 (famous last words).
5407
5420
5408 * Added a page_dumb() pager which does a decent job of paging on
5421 * Added a page_dumb() pager which does a decent job of paging on
5409 screen, if better things (like less) aren't available. One less
5422 screen, if better things (like less) aren't available. One less
5410 unix dependency (someday maybe somebody will port this to
5423 unix dependency (someday maybe somebody will port this to
5411 windows).
5424 windows).
5412
5425
5413 * Fixed problem in magic_log: would lock of logging out if log
5426 * Fixed problem in magic_log: would lock of logging out if log
5414 creation failed (because it would still think it had succeeded).
5427 creation failed (because it would still think it had succeeded).
5415
5428
5416 * Improved the page() function using curses to auto-detect screen
5429 * Improved the page() function using curses to auto-detect screen
5417 size. Now it can make a much better decision on whether to print
5430 size. Now it can make a much better decision on whether to print
5418 or page a string. Option screen_length was modified: a value 0
5431 or page a string. Option screen_length was modified: a value 0
5419 means auto-detect, and that's the default now.
5432 means auto-detect, and that's the default now.
5420
5433
5421 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
5434 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
5422 go out. I'll test it for a few days, then talk to Janko about
5435 go out. I'll test it for a few days, then talk to Janko about
5423 licences and announce it.
5436 licences and announce it.
5424
5437
5425 * Fixed the length of the auto-generated ---> prompt which appears
5438 * Fixed the length of the auto-generated ---> prompt which appears
5426 for auto-parens and auto-quotes. Getting this right isn't trivial,
5439 for auto-parens and auto-quotes. Getting this right isn't trivial,
5427 with all the color escapes, different prompt types and optional
5440 with all the color escapes, different prompt types and optional
5428 separators. But it seems to be working in all the combinations.
5441 separators. But it seems to be working in all the combinations.
5429
5442
5430 2001-11-26 Fernando Perez <fperez@colorado.edu>
5443 2001-11-26 Fernando Perez <fperez@colorado.edu>
5431
5444
5432 * Wrote a regexp filter to get option types from the option names
5445 * Wrote a regexp filter to get option types from the option names
5433 string. This eliminates the need to manually keep two duplicate
5446 string. This eliminates the need to manually keep two duplicate
5434 lists.
5447 lists.
5435
5448
5436 * Removed the unneeded check_option_names. Now options are handled
5449 * Removed the unneeded check_option_names. Now options are handled
5437 in a much saner manner and it's easy to visually check that things
5450 in a much saner manner and it's easy to visually check that things
5438 are ok.
5451 are ok.
5439
5452
5440 * Updated version numbers on all files I modified to carry a
5453 * Updated version numbers on all files I modified to carry a
5441 notice so Janko and Nathan have clear version markers.
5454 notice so Janko and Nathan have clear version markers.
5442
5455
5443 * Updated docstring for ultraTB with my changes. I should send
5456 * Updated docstring for ultraTB with my changes. I should send
5444 this to Nathan.
5457 this to Nathan.
5445
5458
5446 * Lots of small fixes. Ran everything through pychecker again.
5459 * Lots of small fixes. Ran everything through pychecker again.
5447
5460
5448 * Made loading of deep_reload an cmd line option. If it's not too
5461 * Made loading of deep_reload an cmd line option. If it's not too
5449 kosher, now people can just disable it. With -nodeep_reload it's
5462 kosher, now people can just disable it. With -nodeep_reload it's
5450 still available as dreload(), it just won't overwrite reload().
5463 still available as dreload(), it just won't overwrite reload().
5451
5464
5452 * Moved many options to the no| form (-opt and -noopt
5465 * Moved many options to the no| form (-opt and -noopt
5453 accepted). Cleaner.
5466 accepted). Cleaner.
5454
5467
5455 * Changed magic_log so that if called with no parameters, it uses
5468 * Changed magic_log so that if called with no parameters, it uses
5456 'rotate' mode. That way auto-generated logs aren't automatically
5469 'rotate' mode. That way auto-generated logs aren't automatically
5457 over-written. For normal logs, now a backup is made if it exists
5470 over-written. For normal logs, now a backup is made if it exists
5458 (only 1 level of backups). A new 'backup' mode was added to the
5471 (only 1 level of backups). A new 'backup' mode was added to the
5459 Logger class to support this. This was a request by Janko.
5472 Logger class to support this. This was a request by Janko.
5460
5473
5461 * Added @logoff/@logon to stop/restart an active log.
5474 * Added @logoff/@logon to stop/restart an active log.
5462
5475
5463 * Fixed a lot of bugs in log saving/replay. It was pretty
5476 * Fixed a lot of bugs in log saving/replay. It was pretty
5464 broken. Now special lines (!@,/) appear properly in the command
5477 broken. Now special lines (!@,/) appear properly in the command
5465 history after a log replay.
5478 history after a log replay.
5466
5479
5467 * Tried and failed to implement full session saving via pickle. My
5480 * Tried and failed to implement full session saving via pickle. My
5468 idea was to pickle __main__.__dict__, but modules can't be
5481 idea was to pickle __main__.__dict__, but modules can't be
5469 pickled. This would be a better alternative to replaying logs, but
5482 pickled. This would be a better alternative to replaying logs, but
5470 seems quite tricky to get to work. Changed -session to be called
5483 seems quite tricky to get to work. Changed -session to be called
5471 -logplay, which more accurately reflects what it does. And if we
5484 -logplay, which more accurately reflects what it does. And if we
5472 ever get real session saving working, -session is now available.
5485 ever get real session saving working, -session is now available.
5473
5486
5474 * Implemented color schemes for prompts also. As for tracebacks,
5487 * Implemented color schemes for prompts also. As for tracebacks,
5475 currently only NoColor and Linux are supported. But now the
5488 currently only NoColor and Linux are supported. But now the
5476 infrastructure is in place, based on a generic ColorScheme
5489 infrastructure is in place, based on a generic ColorScheme
5477 class. So writing and activating new schemes both for the prompts
5490 class. So writing and activating new schemes both for the prompts
5478 and the tracebacks should be straightforward.
5491 and the tracebacks should be straightforward.
5479
5492
5480 * Version 0.1.13 released, 0.1.14 opened.
5493 * Version 0.1.13 released, 0.1.14 opened.
5481
5494
5482 * Changed handling of options for output cache. Now counter is
5495 * Changed handling of options for output cache. Now counter is
5483 hardwired starting at 1 and one specifies the maximum number of
5496 hardwired starting at 1 and one specifies the maximum number of
5484 entries *in the outcache* (not the max prompt counter). This is
5497 entries *in the outcache* (not the max prompt counter). This is
5485 much better, since many statements won't increase the cache
5498 much better, since many statements won't increase the cache
5486 count. It also eliminated some confusing options, now there's only
5499 count. It also eliminated some confusing options, now there's only
5487 one: cache_size.
5500 one: cache_size.
5488
5501
5489 * Added 'alias' magic function and magic_alias option in the
5502 * Added 'alias' magic function and magic_alias option in the
5490 ipythonrc file. Now the user can easily define whatever names he
5503 ipythonrc file. Now the user can easily define whatever names he
5491 wants for the magic functions without having to play weird
5504 wants for the magic functions without having to play weird
5492 namespace games. This gives IPython a real shell-like feel.
5505 namespace games. This gives IPython a real shell-like feel.
5493
5506
5494 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
5507 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
5495 @ or not).
5508 @ or not).
5496
5509
5497 This was one of the last remaining 'visible' bugs (that I know
5510 This was one of the last remaining 'visible' bugs (that I know
5498 of). I think if I can clean up the session loading so it works
5511 of). I think if I can clean up the session loading so it works
5499 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
5512 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
5500 about licensing).
5513 about licensing).
5501
5514
5502 2001-11-25 Fernando Perez <fperez@colorado.edu>
5515 2001-11-25 Fernando Perez <fperez@colorado.edu>
5503
5516
5504 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
5517 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
5505 there's a cleaner distinction between what ? and ?? show.
5518 there's a cleaner distinction between what ? and ?? show.
5506
5519
5507 * Added screen_length option. Now the user can define his own
5520 * Added screen_length option. Now the user can define his own
5508 screen size for page() operations.
5521 screen size for page() operations.
5509
5522
5510 * Implemented magic shell-like functions with automatic code
5523 * Implemented magic shell-like functions with automatic code
5511 generation. Now adding another function is just a matter of adding
5524 generation. Now adding another function is just a matter of adding
5512 an entry to a dict, and the function is dynamically generated at
5525 an entry to a dict, and the function is dynamically generated at
5513 run-time. Python has some really cool features!
5526 run-time. Python has some really cool features!
5514
5527
5515 * Renamed many options to cleanup conventions a little. Now all
5528 * Renamed many options to cleanup conventions a little. Now all
5516 are lowercase, and only underscores where needed. Also in the code
5529 are lowercase, and only underscores where needed. Also in the code
5517 option name tables are clearer.
5530 option name tables are clearer.
5518
5531
5519 * Changed prompts a little. Now input is 'In [n]:' instead of
5532 * Changed prompts a little. Now input is 'In [n]:' instead of
5520 'In[n]:='. This allows it the numbers to be aligned with the
5533 'In[n]:='. This allows it the numbers to be aligned with the
5521 Out[n] numbers, and removes usage of ':=' which doesn't exist in
5534 Out[n] numbers, and removes usage of ':=' which doesn't exist in
5522 Python (it was a Mathematica thing). The '...' continuation prompt
5535 Python (it was a Mathematica thing). The '...' continuation prompt
5523 was also changed a little to align better.
5536 was also changed a little to align better.
5524
5537
5525 * Fixed bug when flushing output cache. Not all _p<n> variables
5538 * Fixed bug when flushing output cache. Not all _p<n> variables
5526 exist, so their deletion needs to be wrapped in a try:
5539 exist, so their deletion needs to be wrapped in a try:
5527
5540
5528 * Figured out how to properly use inspect.formatargspec() (it
5541 * Figured out how to properly use inspect.formatargspec() (it
5529 requires the args preceded by *). So I removed all the code from
5542 requires the args preceded by *). So I removed all the code from
5530 _get_pdef in Magic, which was just replicating that.
5543 _get_pdef in Magic, which was just replicating that.
5531
5544
5532 * Added test to prefilter to allow redefining magic function names
5545 * Added test to prefilter to allow redefining magic function names
5533 as variables. This is ok, since the @ form is always available,
5546 as variables. This is ok, since the @ form is always available,
5534 but whe should allow the user to define a variable called 'ls' if
5547 but whe should allow the user to define a variable called 'ls' if
5535 he needs it.
5548 he needs it.
5536
5549
5537 * Moved the ToDo information from README into a separate ToDo.
5550 * Moved the ToDo information from README into a separate ToDo.
5538
5551
5539 * General code cleanup and small bugfixes. I think it's close to a
5552 * General code cleanup and small bugfixes. I think it's close to a
5540 state where it can be released, obviously with a big 'beta'
5553 state where it can be released, obviously with a big 'beta'
5541 warning on it.
5554 warning on it.
5542
5555
5543 * Got the magic function split to work. Now all magics are defined
5556 * Got the magic function split to work. Now all magics are defined
5544 in a separate class. It just organizes things a bit, and now
5557 in a separate class. It just organizes things a bit, and now
5545 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
5558 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
5546 was too long).
5559 was too long).
5547
5560
5548 * Changed @clear to @reset to avoid potential confusions with
5561 * Changed @clear to @reset to avoid potential confusions with
5549 the shell command clear. Also renamed @cl to @clear, which does
5562 the shell command clear. Also renamed @cl to @clear, which does
5550 exactly what people expect it to from their shell experience.
5563 exactly what people expect it to from their shell experience.
5551
5564
5552 Added a check to the @reset command (since it's so
5565 Added a check to the @reset command (since it's so
5553 destructive, it's probably a good idea to ask for confirmation).
5566 destructive, it's probably a good idea to ask for confirmation).
5554 But now reset only works for full namespace resetting. Since the
5567 But now reset only works for full namespace resetting. Since the
5555 del keyword is already there for deleting a few specific
5568 del keyword is already there for deleting a few specific
5556 variables, I don't see the point of having a redundant magic
5569 variables, I don't see the point of having a redundant magic
5557 function for the same task.
5570 function for the same task.
5558
5571
5559 2001-11-24 Fernando Perez <fperez@colorado.edu>
5572 2001-11-24 Fernando Perez <fperez@colorado.edu>
5560
5573
5561 * Updated the builtin docs (esp. the ? ones).
5574 * Updated the builtin docs (esp. the ? ones).
5562
5575
5563 * Ran all the code through pychecker. Not terribly impressed with
5576 * Ran all the code through pychecker. Not terribly impressed with
5564 it: lots of spurious warnings and didn't really find anything of
5577 it: lots of spurious warnings and didn't really find anything of
5565 substance (just a few modules being imported and not used).
5578 substance (just a few modules being imported and not used).
5566
5579
5567 * Implemented the new ultraTB functionality into IPython. New
5580 * Implemented the new ultraTB functionality into IPython. New
5568 option: xcolors. This chooses color scheme. xmode now only selects
5581 option: xcolors. This chooses color scheme. xmode now only selects
5569 between Plain and Verbose. Better orthogonality.
5582 between Plain and Verbose. Better orthogonality.
5570
5583
5571 * Large rewrite of ultraTB. Much cleaner now, with a separation of
5584 * Large rewrite of ultraTB. Much cleaner now, with a separation of
5572 mode and color scheme for the exception handlers. Now it's
5585 mode and color scheme for the exception handlers. Now it's
5573 possible to have the verbose traceback with no coloring.
5586 possible to have the verbose traceback with no coloring.
5574
5587
5575 2001-11-23 Fernando Perez <fperez@colorado.edu>
5588 2001-11-23 Fernando Perez <fperez@colorado.edu>
5576
5589
5577 * Version 0.1.12 released, 0.1.13 opened.
5590 * Version 0.1.12 released, 0.1.13 opened.
5578
5591
5579 * Removed option to set auto-quote and auto-paren escapes by
5592 * Removed option to set auto-quote and auto-paren escapes by
5580 user. The chances of breaking valid syntax are just too high. If
5593 user. The chances of breaking valid syntax are just too high. If
5581 someone *really* wants, they can always dig into the code.
5594 someone *really* wants, they can always dig into the code.
5582
5595
5583 * Made prompt separators configurable.
5596 * Made prompt separators configurable.
5584
5597
5585 2001-11-22 Fernando Perez <fperez@colorado.edu>
5598 2001-11-22 Fernando Perez <fperez@colorado.edu>
5586
5599
5587 * Small bugfixes in many places.
5600 * Small bugfixes in many places.
5588
5601
5589 * Removed the MyCompleter class from ipplib. It seemed redundant
5602 * Removed the MyCompleter class from ipplib. It seemed redundant
5590 with the C-p,C-n history search functionality. Less code to
5603 with the C-p,C-n history search functionality. Less code to
5591 maintain.
5604 maintain.
5592
5605
5593 * Moved all the original ipython.py code into ipythonlib.py. Right
5606 * Moved all the original ipython.py code into ipythonlib.py. Right
5594 now it's just one big dump into a function called make_IPython, so
5607 now it's just one big dump into a function called make_IPython, so
5595 no real modularity has been gained. But at least it makes the
5608 no real modularity has been gained. But at least it makes the
5596 wrapper script tiny, and since ipythonlib is a module, it gets
5609 wrapper script tiny, and since ipythonlib is a module, it gets
5597 compiled and startup is much faster.
5610 compiled and startup is much faster.
5598
5611
5599 This is a reasobably 'deep' change, so we should test it for a
5612 This is a reasobably 'deep' change, so we should test it for a
5600 while without messing too much more with the code.
5613 while without messing too much more with the code.
5601
5614
5602 2001-11-21 Fernando Perez <fperez@colorado.edu>
5615 2001-11-21 Fernando Perez <fperez@colorado.edu>
5603
5616
5604 * Version 0.1.11 released, 0.1.12 opened for further work.
5617 * Version 0.1.11 released, 0.1.12 opened for further work.
5605
5618
5606 * Removed dependency on Itpl. It was only needed in one place. It
5619 * Removed dependency on Itpl. It was only needed in one place. It
5607 would be nice if this became part of python, though. It makes life
5620 would be nice if this became part of python, though. It makes life
5608 *a lot* easier in some cases.
5621 *a lot* easier in some cases.
5609
5622
5610 * Simplified the prefilter code a bit. Now all handlers are
5623 * Simplified the prefilter code a bit. Now all handlers are
5611 expected to explicitly return a value (at least a blank string).
5624 expected to explicitly return a value (at least a blank string).
5612
5625
5613 * Heavy edits in ipplib. Removed the help system altogether. Now
5626 * Heavy edits in ipplib. Removed the help system altogether. Now
5614 obj?/?? is used for inspecting objects, a magic @doc prints
5627 obj?/?? is used for inspecting objects, a magic @doc prints
5615 docstrings, and full-blown Python help is accessed via the 'help'
5628 docstrings, and full-blown Python help is accessed via the 'help'
5616 keyword. This cleans up a lot of code (less to maintain) and does
5629 keyword. This cleans up a lot of code (less to maintain) and does
5617 the job. Since 'help' is now a standard Python component, might as
5630 the job. Since 'help' is now a standard Python component, might as
5618 well use it and remove duplicate functionality.
5631 well use it and remove duplicate functionality.
5619
5632
5620 Also removed the option to use ipplib as a standalone program. By
5633 Also removed the option to use ipplib as a standalone program. By
5621 now it's too dependent on other parts of IPython to function alone.
5634 now it's too dependent on other parts of IPython to function alone.
5622
5635
5623 * Fixed bug in genutils.pager. It would crash if the pager was
5636 * Fixed bug in genutils.pager. It would crash if the pager was
5624 exited immediately after opening (broken pipe).
5637 exited immediately after opening (broken pipe).
5625
5638
5626 * Trimmed down the VerboseTB reporting a little. The header is
5639 * Trimmed down the VerboseTB reporting a little. The header is
5627 much shorter now and the repeated exception arguments at the end
5640 much shorter now and the repeated exception arguments at the end
5628 have been removed. For interactive use the old header seemed a bit
5641 have been removed. For interactive use the old header seemed a bit
5629 excessive.
5642 excessive.
5630
5643
5631 * Fixed small bug in output of @whos for variables with multi-word
5644 * Fixed small bug in output of @whos for variables with multi-word
5632 types (only first word was displayed).
5645 types (only first word was displayed).
5633
5646
5634 2001-11-17 Fernando Perez <fperez@colorado.edu>
5647 2001-11-17 Fernando Perez <fperez@colorado.edu>
5635
5648
5636 * Version 0.1.10 released, 0.1.11 opened for further work.
5649 * Version 0.1.10 released, 0.1.11 opened for further work.
5637
5650
5638 * Modified dirs and friends. dirs now *returns* the stack (not
5651 * Modified dirs and friends. dirs now *returns* the stack (not
5639 prints), so one can manipulate it as a variable. Convenient to
5652 prints), so one can manipulate it as a variable. Convenient to
5640 travel along many directories.
5653 travel along many directories.
5641
5654
5642 * Fixed bug in magic_pdef: would only work with functions with
5655 * Fixed bug in magic_pdef: would only work with functions with
5643 arguments with default values.
5656 arguments with default values.
5644
5657
5645 2001-11-14 Fernando Perez <fperez@colorado.edu>
5658 2001-11-14 Fernando Perez <fperez@colorado.edu>
5646
5659
5647 * Added the PhysicsInput stuff to dot_ipython so it ships as an
5660 * Added the PhysicsInput stuff to dot_ipython so it ships as an
5648 example with IPython. Various other minor fixes and cleanups.
5661 example with IPython. Various other minor fixes and cleanups.
5649
5662
5650 * Version 0.1.9 released, 0.1.10 opened for further work.
5663 * Version 0.1.9 released, 0.1.10 opened for further work.
5651
5664
5652 * Added sys.path to the list of directories searched in the
5665 * Added sys.path to the list of directories searched in the
5653 execfile= option. It used to be the current directory and the
5666 execfile= option. It used to be the current directory and the
5654 user's IPYTHONDIR only.
5667 user's IPYTHONDIR only.
5655
5668
5656 2001-11-13 Fernando Perez <fperez@colorado.edu>
5669 2001-11-13 Fernando Perez <fperez@colorado.edu>
5657
5670
5658 * Reinstated the raw_input/prefilter separation that Janko had
5671 * Reinstated the raw_input/prefilter separation that Janko had
5659 initially. This gives a more convenient setup for extending the
5672 initially. This gives a more convenient setup for extending the
5660 pre-processor from the outside: raw_input always gets a string,
5673 pre-processor from the outside: raw_input always gets a string,
5661 and prefilter has to process it. We can then redefine prefilter
5674 and prefilter has to process it. We can then redefine prefilter
5662 from the outside and implement extensions for special
5675 from the outside and implement extensions for special
5663 purposes.
5676 purposes.
5664
5677
5665 Today I got one for inputting PhysicalQuantity objects
5678 Today I got one for inputting PhysicalQuantity objects
5666 (from Scientific) without needing any function calls at
5679 (from Scientific) without needing any function calls at
5667 all. Extremely convenient, and it's all done as a user-level
5680 all. Extremely convenient, and it's all done as a user-level
5668 extension (no IPython code was touched). Now instead of:
5681 extension (no IPython code was touched). Now instead of:
5669 a = PhysicalQuantity(4.2,'m/s**2')
5682 a = PhysicalQuantity(4.2,'m/s**2')
5670 one can simply say
5683 one can simply say
5671 a = 4.2 m/s**2
5684 a = 4.2 m/s**2
5672 or even
5685 or even
5673 a = 4.2 m/s^2
5686 a = 4.2 m/s^2
5674
5687
5675 I use this, but it's also a proof of concept: IPython really is
5688 I use this, but it's also a proof of concept: IPython really is
5676 fully user-extensible, even at the level of the parsing of the
5689 fully user-extensible, even at the level of the parsing of the
5677 command line. It's not trivial, but it's perfectly doable.
5690 command line. It's not trivial, but it's perfectly doable.
5678
5691
5679 * Added 'add_flip' method to inclusion conflict resolver. Fixes
5692 * Added 'add_flip' method to inclusion conflict resolver. Fixes
5680 the problem of modules being loaded in the inverse order in which
5693 the problem of modules being loaded in the inverse order in which
5681 they were defined in
5694 they were defined in
5682
5695
5683 * Version 0.1.8 released, 0.1.9 opened for further work.
5696 * Version 0.1.8 released, 0.1.9 opened for further work.
5684
5697
5685 * Added magics pdef, source and file. They respectively show the
5698 * Added magics pdef, source and file. They respectively show the
5686 definition line ('prototype' in C), source code and full python
5699 definition line ('prototype' in C), source code and full python
5687 file for any callable object. The object inspector oinfo uses
5700 file for any callable object. The object inspector oinfo uses
5688 these to show the same information.
5701 these to show the same information.
5689
5702
5690 * Version 0.1.7 released, 0.1.8 opened for further work.
5703 * Version 0.1.7 released, 0.1.8 opened for further work.
5691
5704
5692 * Separated all the magic functions into a class called Magic. The
5705 * Separated all the magic functions into a class called Magic. The
5693 InteractiveShell class was becoming too big for Xemacs to handle
5706 InteractiveShell class was becoming too big for Xemacs to handle
5694 (de-indenting a line would lock it up for 10 seconds while it
5707 (de-indenting a line would lock it up for 10 seconds while it
5695 backtracked on the whole class!)
5708 backtracked on the whole class!)
5696
5709
5697 FIXME: didn't work. It can be done, but right now namespaces are
5710 FIXME: didn't work. It can be done, but right now namespaces are
5698 all messed up. Do it later (reverted it for now, so at least
5711 all messed up. Do it later (reverted it for now, so at least
5699 everything works as before).
5712 everything works as before).
5700
5713
5701 * Got the object introspection system (magic_oinfo) working! I
5714 * Got the object introspection system (magic_oinfo) working! I
5702 think this is pretty much ready for release to Janko, so he can
5715 think this is pretty much ready for release to Janko, so he can
5703 test it for a while and then announce it. Pretty much 100% of what
5716 test it for a while and then announce it. Pretty much 100% of what
5704 I wanted for the 'phase 1' release is ready. Happy, tired.
5717 I wanted for the 'phase 1' release is ready. Happy, tired.
5705
5718
5706 2001-11-12 Fernando Perez <fperez@colorado.edu>
5719 2001-11-12 Fernando Perez <fperez@colorado.edu>
5707
5720
5708 * Version 0.1.6 released, 0.1.7 opened for further work.
5721 * Version 0.1.6 released, 0.1.7 opened for further work.
5709
5722
5710 * Fixed bug in printing: it used to test for truth before
5723 * Fixed bug in printing: it used to test for truth before
5711 printing, so 0 wouldn't print. Now checks for None.
5724 printing, so 0 wouldn't print. Now checks for None.
5712
5725
5713 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
5726 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
5714 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
5727 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
5715 reaches by hand into the outputcache. Think of a better way to do
5728 reaches by hand into the outputcache. Think of a better way to do
5716 this later.
5729 this later.
5717
5730
5718 * Various small fixes thanks to Nathan's comments.
5731 * Various small fixes thanks to Nathan's comments.
5719
5732
5720 * Changed magic_pprint to magic_Pprint. This way it doesn't
5733 * Changed magic_pprint to magic_Pprint. This way it doesn't
5721 collide with pprint() and the name is consistent with the command
5734 collide with pprint() and the name is consistent with the command
5722 line option.
5735 line option.
5723
5736
5724 * Changed prompt counter behavior to be fully like
5737 * Changed prompt counter behavior to be fully like
5725 Mathematica's. That is, even input that doesn't return a result
5738 Mathematica's. That is, even input that doesn't return a result
5726 raises the prompt counter. The old behavior was kind of confusing
5739 raises the prompt counter. The old behavior was kind of confusing
5727 (getting the same prompt number several times if the operation
5740 (getting the same prompt number several times if the operation
5728 didn't return a result).
5741 didn't return a result).
5729
5742
5730 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
5743 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
5731
5744
5732 * Fixed -Classic mode (wasn't working anymore).
5745 * Fixed -Classic mode (wasn't working anymore).
5733
5746
5734 * Added colored prompts using Nathan's new code. Colors are
5747 * Added colored prompts using Nathan's new code. Colors are
5735 currently hardwired, they can be user-configurable. For
5748 currently hardwired, they can be user-configurable. For
5736 developers, they can be chosen in file ipythonlib.py, at the
5749 developers, they can be chosen in file ipythonlib.py, at the
5737 beginning of the CachedOutput class def.
5750 beginning of the CachedOutput class def.
5738
5751
5739 2001-11-11 Fernando Perez <fperez@colorado.edu>
5752 2001-11-11 Fernando Perez <fperez@colorado.edu>
5740
5753
5741 * Version 0.1.5 released, 0.1.6 opened for further work.
5754 * Version 0.1.5 released, 0.1.6 opened for further work.
5742
5755
5743 * Changed magic_env to *return* the environment as a dict (not to
5756 * Changed magic_env to *return* the environment as a dict (not to
5744 print it). This way it prints, but it can also be processed.
5757 print it). This way it prints, but it can also be processed.
5745
5758
5746 * Added Verbose exception reporting to interactive
5759 * Added Verbose exception reporting to interactive
5747 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
5760 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
5748 traceback. Had to make some changes to the ultraTB file. This is
5761 traceback. Had to make some changes to the ultraTB file. This is
5749 probably the last 'big' thing in my mental todo list. This ties
5762 probably the last 'big' thing in my mental todo list. This ties
5750 in with the next entry:
5763 in with the next entry:
5751
5764
5752 * Changed -Xi and -Xf to a single -xmode option. Now all the user
5765 * Changed -Xi and -Xf to a single -xmode option. Now all the user
5753 has to specify is Plain, Color or Verbose for all exception
5766 has to specify is Plain, Color or Verbose for all exception
5754 handling.
5767 handling.
5755
5768
5756 * Removed ShellServices option. All this can really be done via
5769 * Removed ShellServices option. All this can really be done via
5757 the magic system. It's easier to extend, cleaner and has automatic
5770 the magic system. It's easier to extend, cleaner and has automatic
5758 namespace protection and documentation.
5771 namespace protection and documentation.
5759
5772
5760 2001-11-09 Fernando Perez <fperez@colorado.edu>
5773 2001-11-09 Fernando Perez <fperez@colorado.edu>
5761
5774
5762 * Fixed bug in output cache flushing (missing parameter to
5775 * Fixed bug in output cache flushing (missing parameter to
5763 __init__). Other small bugs fixed (found using pychecker).
5776 __init__). Other small bugs fixed (found using pychecker).
5764
5777
5765 * Version 0.1.4 opened for bugfixing.
5778 * Version 0.1.4 opened for bugfixing.
5766
5779
5767 2001-11-07 Fernando Perez <fperez@colorado.edu>
5780 2001-11-07 Fernando Perez <fperez@colorado.edu>
5768
5781
5769 * Version 0.1.3 released, mainly because of the raw_input bug.
5782 * Version 0.1.3 released, mainly because of the raw_input bug.
5770
5783
5771 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
5784 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
5772 and when testing for whether things were callable, a call could
5785 and when testing for whether things were callable, a call could
5773 actually be made to certain functions. They would get called again
5786 actually be made to certain functions. They would get called again
5774 once 'really' executed, with a resulting double call. A disaster
5787 once 'really' executed, with a resulting double call. A disaster
5775 in many cases (list.reverse() would never work!).
5788 in many cases (list.reverse() would never work!).
5776
5789
5777 * Removed prefilter() function, moved its code to raw_input (which
5790 * Removed prefilter() function, moved its code to raw_input (which
5778 after all was just a near-empty caller for prefilter). This saves
5791 after all was just a near-empty caller for prefilter). This saves
5779 a function call on every prompt, and simplifies the class a tiny bit.
5792 a function call on every prompt, and simplifies the class a tiny bit.
5780
5793
5781 * Fix _ip to __ip name in magic example file.
5794 * Fix _ip to __ip name in magic example file.
5782
5795
5783 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
5796 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
5784 work with non-gnu versions of tar.
5797 work with non-gnu versions of tar.
5785
5798
5786 2001-11-06 Fernando Perez <fperez@colorado.edu>
5799 2001-11-06 Fernando Perez <fperez@colorado.edu>
5787
5800
5788 * Version 0.1.2. Just to keep track of the recent changes.
5801 * Version 0.1.2. Just to keep track of the recent changes.
5789
5802
5790 * Fixed nasty bug in output prompt routine. It used to check 'if
5803 * Fixed nasty bug in output prompt routine. It used to check 'if
5791 arg != None...'. Problem is, this fails if arg implements a
5804 arg != None...'. Problem is, this fails if arg implements a
5792 special comparison (__cmp__) which disallows comparing to
5805 special comparison (__cmp__) which disallows comparing to
5793 None. Found it when trying to use the PhysicalQuantity module from
5806 None. Found it when trying to use the PhysicalQuantity module from
5794 ScientificPython.
5807 ScientificPython.
5795
5808
5796 2001-11-05 Fernando Perez <fperez@colorado.edu>
5809 2001-11-05 Fernando Perez <fperez@colorado.edu>
5797
5810
5798 * Also added dirs. Now the pushd/popd/dirs family functions
5811 * Also added dirs. Now the pushd/popd/dirs family functions
5799 basically like the shell, with the added convenience of going home
5812 basically like the shell, with the added convenience of going home
5800 when called with no args.
5813 when called with no args.
5801
5814
5802 * pushd/popd slightly modified to mimic shell behavior more
5815 * pushd/popd slightly modified to mimic shell behavior more
5803 closely.
5816 closely.
5804
5817
5805 * Added env,pushd,popd from ShellServices as magic functions. I
5818 * Added env,pushd,popd from ShellServices as magic functions. I
5806 think the cleanest will be to port all desired functions from
5819 think the cleanest will be to port all desired functions from
5807 ShellServices as magics and remove ShellServices altogether. This
5820 ShellServices as magics and remove ShellServices altogether. This
5808 will provide a single, clean way of adding functionality
5821 will provide a single, clean way of adding functionality
5809 (shell-type or otherwise) to IP.
5822 (shell-type or otherwise) to IP.
5810
5823
5811 2001-11-04 Fernando Perez <fperez@colorado.edu>
5824 2001-11-04 Fernando Perez <fperez@colorado.edu>
5812
5825
5813 * Added .ipython/ directory to sys.path. This way users can keep
5826 * Added .ipython/ directory to sys.path. This way users can keep
5814 customizations there and access them via import.
5827 customizations there and access them via import.
5815
5828
5816 2001-11-03 Fernando Perez <fperez@colorado.edu>
5829 2001-11-03 Fernando Perez <fperez@colorado.edu>
5817
5830
5818 * Opened version 0.1.1 for new changes.
5831 * Opened version 0.1.1 for new changes.
5819
5832
5820 * Changed version number to 0.1.0: first 'public' release, sent to
5833 * Changed version number to 0.1.0: first 'public' release, sent to
5821 Nathan and Janko.
5834 Nathan and Janko.
5822
5835
5823 * Lots of small fixes and tweaks.
5836 * Lots of small fixes and tweaks.
5824
5837
5825 * Minor changes to whos format. Now strings are shown, snipped if
5838 * Minor changes to whos format. Now strings are shown, snipped if
5826 too long.
5839 too long.
5827
5840
5828 * Changed ShellServices to work on __main__ so they show up in @who
5841 * Changed ShellServices to work on __main__ so they show up in @who
5829
5842
5830 * Help also works with ? at the end of a line:
5843 * Help also works with ? at the end of a line:
5831 ?sin and sin?
5844 ?sin and sin?
5832 both produce the same effect. This is nice, as often I use the
5845 both produce the same effect. This is nice, as often I use the
5833 tab-complete to find the name of a method, but I used to then have
5846 tab-complete to find the name of a method, but I used to then have
5834 to go to the beginning of the line to put a ? if I wanted more
5847 to go to the beginning of the line to put a ? if I wanted more
5835 info. Now I can just add the ? and hit return. Convenient.
5848 info. Now I can just add the ? and hit return. Convenient.
5836
5849
5837 2001-11-02 Fernando Perez <fperez@colorado.edu>
5850 2001-11-02 Fernando Perez <fperez@colorado.edu>
5838
5851
5839 * Python version check (>=2.1) added.
5852 * Python version check (>=2.1) added.
5840
5853
5841 * Added LazyPython documentation. At this point the docs are quite
5854 * Added LazyPython documentation. At this point the docs are quite
5842 a mess. A cleanup is in order.
5855 a mess. A cleanup is in order.
5843
5856
5844 * Auto-installer created. For some bizarre reason, the zipfiles
5857 * Auto-installer created. For some bizarre reason, the zipfiles
5845 module isn't working on my system. So I made a tar version
5858 module isn't working on my system. So I made a tar version
5846 (hopefully the command line options in various systems won't kill
5859 (hopefully the command line options in various systems won't kill
5847 me).
5860 me).
5848
5861
5849 * Fixes to Struct in genutils. Now all dictionary-like methods are
5862 * Fixes to Struct in genutils. Now all dictionary-like methods are
5850 protected (reasonably).
5863 protected (reasonably).
5851
5864
5852 * Added pager function to genutils and changed ? to print usage
5865 * Added pager function to genutils and changed ? to print usage
5853 note through it (it was too long).
5866 note through it (it was too long).
5854
5867
5855 * Added the LazyPython functionality. Works great! I changed the
5868 * Added the LazyPython functionality. Works great! I changed the
5856 auto-quote escape to ';', it's on home row and next to '. But
5869 auto-quote escape to ';', it's on home row and next to '. But
5857 both auto-quote and auto-paren (still /) escapes are command-line
5870 both auto-quote and auto-paren (still /) escapes are command-line
5858 parameters.
5871 parameters.
5859
5872
5860
5873
5861 2001-11-01 Fernando Perez <fperez@colorado.edu>
5874 2001-11-01 Fernando Perez <fperez@colorado.edu>
5862
5875
5863 * Version changed to 0.0.7. Fairly large change: configuration now
5876 * Version changed to 0.0.7. Fairly large change: configuration now
5864 is all stored in a directory, by default .ipython. There, all
5877 is all stored in a directory, by default .ipython. There, all
5865 config files have normal looking names (not .names)
5878 config files have normal looking names (not .names)
5866
5879
5867 * Version 0.0.6 Released first to Lucas and Archie as a test
5880 * Version 0.0.6 Released first to Lucas and Archie as a test
5868 run. Since it's the first 'semi-public' release, change version to
5881 run. Since it's the first 'semi-public' release, change version to
5869 > 0.0.6 for any changes now.
5882 > 0.0.6 for any changes now.
5870
5883
5871 * Stuff I had put in the ipplib.py changelog:
5884 * Stuff I had put in the ipplib.py changelog:
5872
5885
5873 Changes to InteractiveShell:
5886 Changes to InteractiveShell:
5874
5887
5875 - Made the usage message a parameter.
5888 - Made the usage message a parameter.
5876
5889
5877 - Require the name of the shell variable to be given. It's a bit
5890 - Require the name of the shell variable to be given. It's a bit
5878 of a hack, but allows the name 'shell' not to be hardwired in the
5891 of a hack, but allows the name 'shell' not to be hardwired in the
5879 magic (@) handler, which is problematic b/c it requires
5892 magic (@) handler, which is problematic b/c it requires
5880 polluting the global namespace with 'shell'. This in turn is
5893 polluting the global namespace with 'shell'. This in turn is
5881 fragile: if a user redefines a variable called shell, things
5894 fragile: if a user redefines a variable called shell, things
5882 break.
5895 break.
5883
5896
5884 - magic @: all functions available through @ need to be defined
5897 - magic @: all functions available through @ need to be defined
5885 as magic_<name>, even though they can be called simply as
5898 as magic_<name>, even though they can be called simply as
5886 @<name>. This allows the special command @magic to gather
5899 @<name>. This allows the special command @magic to gather
5887 information automatically about all existing magic functions,
5900 information automatically about all existing magic functions,
5888 even if they are run-time user extensions, by parsing the shell
5901 even if they are run-time user extensions, by parsing the shell
5889 instance __dict__ looking for special magic_ names.
5902 instance __dict__ looking for special magic_ names.
5890
5903
5891 - mainloop: added *two* local namespace parameters. This allows
5904 - mainloop: added *two* local namespace parameters. This allows
5892 the class to differentiate between parameters which were there
5905 the class to differentiate between parameters which were there
5893 before and after command line initialization was processed. This
5906 before and after command line initialization was processed. This
5894 way, later @who can show things loaded at startup by the
5907 way, later @who can show things loaded at startup by the
5895 user. This trick was necessary to make session saving/reloading
5908 user. This trick was necessary to make session saving/reloading
5896 really work: ideally after saving/exiting/reloading a session,
5909 really work: ideally after saving/exiting/reloading a session,
5897 *everything* should look the same, including the output of @who. I
5910 *everything* should look the same, including the output of @who. I
5898 was only able to make this work with this double namespace
5911 was only able to make this work with this double namespace
5899 trick.
5912 trick.
5900
5913
5901 - added a header to the logfile which allows (almost) full
5914 - added a header to the logfile which allows (almost) full
5902 session restoring.
5915 session restoring.
5903
5916
5904 - prepend lines beginning with @ or !, with a and log
5917 - prepend lines beginning with @ or !, with a and log
5905 them. Why? !lines: may be useful to know what you did @lines:
5918 them. Why? !lines: may be useful to know what you did @lines:
5906 they may affect session state. So when restoring a session, at
5919 they may affect session state. So when restoring a session, at
5907 least inform the user of their presence. I couldn't quite get
5920 least inform the user of their presence. I couldn't quite get
5908 them to properly re-execute, but at least the user is warned.
5921 them to properly re-execute, but at least the user is warned.
5909
5922
5910 * Started ChangeLog.
5923 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now