##// END OF EJS Templates
- add support for PyCrust-style _getAttributeNames magic method. Closes #50....
fperez -
Show More
@@ -1,48 +1,51 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Class which mimics a module.
3 Class which mimics a module.
4
4
5 Needed to allow pickle to correctly resolve namespaces during IPython
5 Needed to allow pickle to correctly resolve namespaces during IPython
6 sessions.
6 sessions.
7
7
8 $Id: FakeModule.py 410 2004-11-04 07:58:17Z fperez $"""
8 $Id: FakeModule.py 1322 2006-05-24 07:51:39Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 class FakeModule:
17 class FakeModule:
18 """Simple class with attribute access to fake a module.
18 """Simple class with attribute access to fake a module.
19
19
20 This is not meant to replace a module, but to allow inserting a fake
20 This is not meant to replace a module, but to allow inserting a fake
21 module in sys.modules so that systems which rely on run-time module
21 module in sys.modules so that systems which rely on run-time module
22 importing (like shelve and pickle) work correctly in interactive IPython
22 importing (like shelve and pickle) work correctly in interactive IPython
23 sessions.
23 sessions.
24
24
25 Do NOT use this code for anything other than this IPython private hack."""
25 Do NOT use this code for anything other than this IPython private hack."""
26
26
27 def __init__(self,adict):
27 def __init__(self,adict):
28
28
29 # It seems pydoc (and perhaps others) needs any module instance to
29 # It seems pydoc (and perhaps others) needs any module instance to
30 # implement a __nonzero__ method, so we add it if missing:
30 # implement a __nonzero__ method, so we add it if missing:
31 if '__nonzero__' not in adict:
31 if '__nonzero__' not in adict:
32 def __nonzero__():
32 def __nonzero__():
33 return 1
33 return 1
34 adict['__nonzero__'] = __nonzero__
34 adict['__nonzero__'] = __nonzero__
35
35
36 self.__dict__ = adict
36 self.__dict__ = adict
37
37
38 # modules should have a __file__ attribute
39 adict['__file__'] = __file__
40
38 def __getattr__(self,key):
41 def __getattr__(self,key):
39 try:
42 try:
40 return self.__dict__[key]
43 return self.__dict__[key]
41 except KeyError, e:
44 except KeyError, e:
42 raise AttributeError("FakeModule object has no attribute %s" % e)
45 raise AttributeError("FakeModule object has no attribute %s" % e)
43
46
44 def __str__(self):
47 def __str__(self):
45 return "<IPython.FakeModule instance>"
48 return "<IPython.FakeModule instance>"
46
49
47 def __repr__(self):
50 def __repr__(self):
48 return str(self)
51 return str(self)
@@ -1,2953 +1,2958 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 1314 2006-05-19 18:24:14Z fperez $"""
4 $Id: Magic.py 1322 2006-05-24 07:51:39Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import shlex
29 import shlex
30 import sys
30 import sys
31 import re
31 import re
32 import tempfile
32 import tempfile
33 import time
33 import time
34 import cPickle as pickle
34 import cPickle as pickle
35 import textwrap
35 import textwrap
36 from cStringIO import StringIO
36 from cStringIO import StringIO
37 from getopt import getopt,GetoptError
37 from getopt import getopt,GetoptError
38 from pprint import pprint, pformat
38 from pprint import pprint, pformat
39
39
40 # profile isn't bundled by default in Debian for license reasons
40 # profile isn't bundled by default in Debian for license reasons
41 try:
41 try:
42 import profile,pstats
42 import profile,pstats
43 except ImportError:
43 except ImportError:
44 profile = pstats = None
44 profile = pstats = None
45
45
46 # Homebrewed
46 # Homebrewed
47 import IPython
47 import IPython
48 from IPython import Debugger, OInspect, wildcard
48 from IPython import Debugger, OInspect, wildcard
49 from IPython.FakeModule import FakeModule
49 from IPython.FakeModule import FakeModule
50 from IPython.Itpl import Itpl, itpl, printpl,itplns
50 from IPython.Itpl import Itpl, itpl, printpl,itplns
51 from IPython.PyColorize import Parser
51 from IPython.PyColorize import Parser
52 from IPython.ipstruct import Struct
52 from IPython.ipstruct import Struct
53 from IPython.macro import Macro
53 from IPython.macro import Macro
54 from IPython.genutils import *
54 from IPython.genutils import *
55 from IPython import platutils
55 from IPython import platutils
56
56
57 #***************************************************************************
57 #***************************************************************************
58 # Utility functions
58 # Utility functions
59 def on_off(tag):
59 def on_off(tag):
60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
61 return ['OFF','ON'][tag]
61 return ['OFF','ON'][tag]
62
62
63 class Bunch: pass
63 class Bunch: pass
64
64
65 #***************************************************************************
65 #***************************************************************************
66 # Main class implementing Magic functionality
66 # Main class implementing Magic functionality
67 class Magic:
67 class Magic:
68 """Magic functions for InteractiveShell.
68 """Magic functions for InteractiveShell.
69
69
70 Shell functions which can be reached as %function_name. All magic
70 Shell functions which can be reached as %function_name. All magic
71 functions should accept a string, which they can parse for their own
71 functions should accept a string, which they can parse for their own
72 needs. This can make some functions easier to type, eg `%cd ../`
72 needs. This can make some functions easier to type, eg `%cd ../`
73 vs. `%cd("../")`
73 vs. `%cd("../")`
74
74
75 ALL definitions MUST begin with the prefix magic_. The user won't need it
75 ALL definitions MUST begin with the prefix magic_. The user won't need it
76 at the command line, but it is is needed in the definition. """
76 at the command line, but it is is needed in the definition. """
77
77
78 # class globals
78 # class globals
79 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
79 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
80 'Automagic is ON, % prefix NOT needed for magic functions.']
80 'Automagic is ON, % prefix NOT needed for magic functions.']
81
81
82 #......................................................................
82 #......................................................................
83 # some utility functions
83 # some utility functions
84
84
85 def __init__(self,shell):
85 def __init__(self,shell):
86
86
87 self.options_table = {}
87 self.options_table = {}
88 if profile is None:
88 if profile is None:
89 self.magic_prun = self.profile_missing_notice
89 self.magic_prun = self.profile_missing_notice
90 self.shell = shell
90 self.shell = shell
91
91
92 # namespace for holding state we may need
92 # namespace for holding state we may need
93 self._magic_state = Bunch()
93 self._magic_state = Bunch()
94
94
95 def profile_missing_notice(self, *args, **kwargs):
95 def profile_missing_notice(self, *args, **kwargs):
96 error("""\
96 error("""\
97 The profile module could not be found. If you are a Debian user,
97 The profile module could not be found. If you are a Debian user,
98 it has been removed from the standard Debian package because of its non-free
98 it has been removed from the standard Debian package because of its non-free
99 license. To use profiling, please install"python2.3-profiler" from non-free.""")
99 license. To use profiling, please install"python2.3-profiler" from non-free.""")
100
100
101 def default_option(self,fn,optstr):
101 def default_option(self,fn,optstr):
102 """Make an entry in the options_table for fn, with value optstr"""
102 """Make an entry in the options_table for fn, with value optstr"""
103
103
104 if fn not in self.lsmagic():
104 if fn not in self.lsmagic():
105 error("%s is not a magic function" % fn)
105 error("%s is not a magic function" % fn)
106 self.options_table[fn] = optstr
106 self.options_table[fn] = optstr
107
107
108 def lsmagic(self):
108 def lsmagic(self):
109 """Return a list of currently available magic functions.
109 """Return a list of currently available magic functions.
110
110
111 Gives a list of the bare names after mangling (['ls','cd', ...], not
111 Gives a list of the bare names after mangling (['ls','cd', ...], not
112 ['magic_ls','magic_cd',...]"""
112 ['magic_ls','magic_cd',...]"""
113
113
114 # FIXME. This needs a cleanup, in the way the magics list is built.
114 # FIXME. This needs a cleanup, in the way the magics list is built.
115
115
116 # magics in class definition
116 # magics in class definition
117 class_magic = lambda fn: fn.startswith('magic_') and \
117 class_magic = lambda fn: fn.startswith('magic_') and \
118 callable(Magic.__dict__[fn])
118 callable(Magic.__dict__[fn])
119 # in instance namespace (run-time user additions)
119 # in instance namespace (run-time user additions)
120 inst_magic = lambda fn: fn.startswith('magic_') and \
120 inst_magic = lambda fn: fn.startswith('magic_') and \
121 callable(self.__dict__[fn])
121 callable(self.__dict__[fn])
122 # and bound magics by user (so they can access self):
122 # and bound magics by user (so they can access self):
123 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
123 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
124 callable(self.__class__.__dict__[fn])
124 callable(self.__class__.__dict__[fn])
125 magics = filter(class_magic,Magic.__dict__.keys()) + \
125 magics = filter(class_magic,Magic.__dict__.keys()) + \
126 filter(inst_magic,self.__dict__.keys()) + \
126 filter(inst_magic,self.__dict__.keys()) + \
127 filter(inst_bound_magic,self.__class__.__dict__.keys())
127 filter(inst_bound_magic,self.__class__.__dict__.keys())
128 out = []
128 out = []
129 for fn in magics:
129 for fn in magics:
130 out.append(fn.replace('magic_','',1))
130 out.append(fn.replace('magic_','',1))
131 out.sort()
131 out.sort()
132 return out
132 return out
133
133
134 def extract_input_slices(self,slices,raw=False):
134 def extract_input_slices(self,slices,raw=False):
135 """Return as a string a set of input history slices.
135 """Return as a string a set of input history slices.
136
136
137 Inputs:
137 Inputs:
138
138
139 - slices: the set of slices is given as a list of strings (like
139 - slices: the set of slices is given as a list of strings (like
140 ['1','4:8','9'], since this function is for use by magic functions
140 ['1','4:8','9'], since this function is for use by magic functions
141 which get their arguments as strings.
141 which get their arguments as strings.
142
142
143 Optional inputs:
143 Optional inputs:
144
144
145 - raw(False): by default, the processed input is used. If this is
145 - raw(False): by default, the processed input is used. If this is
146 true, the raw input history is used instead.
146 true, the raw input history is used instead.
147
147
148 Note that slices can be called with two notations:
148 Note that slices can be called with two notations:
149
149
150 N:M -> standard python form, means including items N...(M-1).
150 N:M -> standard python form, means including items N...(M-1).
151
151
152 N-M -> include items N..M (closed endpoint)."""
152 N-M -> include items N..M (closed endpoint)."""
153
153
154 if raw:
154 if raw:
155 hist = self.shell.input_hist_raw
155 hist = self.shell.input_hist_raw
156 else:
156 else:
157 hist = self.shell.input_hist
157 hist = self.shell.input_hist
158
158
159 cmds = []
159 cmds = []
160 for chunk in slices:
160 for chunk in slices:
161 if ':' in chunk:
161 if ':' in chunk:
162 ini,fin = map(int,chunk.split(':'))
162 ini,fin = map(int,chunk.split(':'))
163 elif '-' in chunk:
163 elif '-' in chunk:
164 ini,fin = map(int,chunk.split('-'))
164 ini,fin = map(int,chunk.split('-'))
165 fin += 1
165 fin += 1
166 else:
166 else:
167 ini = int(chunk)
167 ini = int(chunk)
168 fin = ini+1
168 fin = ini+1
169 cmds.append(hist[ini:fin])
169 cmds.append(hist[ini:fin])
170 return cmds
170 return cmds
171
171
172 def _ofind(self,oname):
172 def _ofind(self,oname):
173 """Find an object in the available namespaces.
173 """Find an object in the available namespaces.
174
174
175 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
175 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
176
176
177 Has special code to detect magic functions.
177 Has special code to detect magic functions.
178 """
178 """
179
179
180 oname = oname.strip()
180 oname = oname.strip()
181
181
182 # Namespaces to search in:
182 # Namespaces to search in:
183 user_ns = self.shell.user_ns
183 user_ns = self.shell.user_ns
184 internal_ns = self.shell.internal_ns
184 internal_ns = self.shell.internal_ns
185 builtin_ns = __builtin__.__dict__
185 builtin_ns = __builtin__.__dict__
186 alias_ns = self.shell.alias_table
186 alias_ns = self.shell.alias_table
187
187
188 # Put them in a list. The order is important so that we find things in
188 # Put them in a list. The order is important so that we find things in
189 # the same order that Python finds them.
189 # the same order that Python finds them.
190 namespaces = [ ('Interactive',user_ns),
190 namespaces = [ ('Interactive',user_ns),
191 ('IPython internal',internal_ns),
191 ('IPython internal',internal_ns),
192 ('Python builtin',builtin_ns),
192 ('Python builtin',builtin_ns),
193 ('Alias',alias_ns),
193 ('Alias',alias_ns),
194 ]
194 ]
195
195
196 # initialize results to 'null'
196 # initialize results to 'null'
197 found = 0; obj = None; ospace = None; ds = None;
197 found = 0; obj = None; ospace = None; ds = None;
198 ismagic = 0; isalias = 0
198 ismagic = 0; isalias = 0
199
199
200 # Look for the given name by splitting it in parts. If the head is
200 # Look for the given name by splitting it in parts. If the head is
201 # found, then we look for all the remaining parts as members, and only
201 # found, then we look for all the remaining parts as members, and only
202 # declare success if we can find them all.
202 # declare success if we can find them all.
203 oname_parts = oname.split('.')
203 oname_parts = oname.split('.')
204 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
204 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
205 for nsname,ns in namespaces:
205 for nsname,ns in namespaces:
206 try:
206 try:
207 obj = ns[oname_head]
207 obj = ns[oname_head]
208 except KeyError:
208 except KeyError:
209 continue
209 continue
210 else:
210 else:
211 for part in oname_rest:
211 for part in oname_rest:
212 try:
212 try:
213 obj = getattr(obj,part)
213 obj = getattr(obj,part)
214 except:
214 except:
215 # Blanket except b/c some badly implemented objects
215 # Blanket except b/c some badly implemented objects
216 # allow __getattr__ to raise exceptions other than
216 # allow __getattr__ to raise exceptions other than
217 # AttributeError, which then crashes IPython.
217 # AttributeError, which then crashes IPython.
218 break
218 break
219 else:
219 else:
220 # If we finish the for loop (no break), we got all members
220 # If we finish the for loop (no break), we got all members
221 found = 1
221 found = 1
222 ospace = nsname
222 ospace = nsname
223 if ns == alias_ns:
223 if ns == alias_ns:
224 isalias = 1
224 isalias = 1
225 break # namespace loop
225 break # namespace loop
226
226
227 # Try to see if it's magic
227 # Try to see if it's magic
228 if not found:
228 if not found:
229 if oname.startswith(self.shell.ESC_MAGIC):
229 if oname.startswith(self.shell.ESC_MAGIC):
230 oname = oname[1:]
230 oname = oname[1:]
231 obj = getattr(self,'magic_'+oname,None)
231 obj = getattr(self,'magic_'+oname,None)
232 if obj is not None:
232 if obj is not None:
233 found = 1
233 found = 1
234 ospace = 'IPython internal'
234 ospace = 'IPython internal'
235 ismagic = 1
235 ismagic = 1
236
236
237 # Last try: special-case some literals like '', [], {}, etc:
237 # Last try: special-case some literals like '', [], {}, etc:
238 if not found and oname_head in ["''",'""','[]','{}','()']:
238 if not found and oname_head in ["''",'""','[]','{}','()']:
239 obj = eval(oname_head)
239 obj = eval(oname_head)
240 found = 1
240 found = 1
241 ospace = 'Interactive'
241 ospace = 'Interactive'
242
242
243 return {'found':found, 'obj':obj, 'namespace':ospace,
243 return {'found':found, 'obj':obj, 'namespace':ospace,
244 'ismagic':ismagic, 'isalias':isalias}
244 'ismagic':ismagic, 'isalias':isalias}
245
245
246 def arg_err(self,func):
246 def arg_err(self,func):
247 """Print docstring if incorrect arguments were passed"""
247 """Print docstring if incorrect arguments were passed"""
248 print 'Error in arguments:'
248 print 'Error in arguments:'
249 print OInspect.getdoc(func)
249 print OInspect.getdoc(func)
250
250
251 def format_latex(self,strng):
251 def format_latex(self,strng):
252 """Format a string for latex inclusion."""
252 """Format a string for latex inclusion."""
253
253
254 # Characters that need to be escaped for latex:
254 # Characters that need to be escaped for latex:
255 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
255 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
256 # Magic command names as headers:
256 # Magic command names as headers:
257 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
257 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
258 re.MULTILINE)
258 re.MULTILINE)
259 # Magic commands
259 # Magic commands
260 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
260 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
261 re.MULTILINE)
261 re.MULTILINE)
262 # Paragraph continue
262 # Paragraph continue
263 par_re = re.compile(r'\\$',re.MULTILINE)
263 par_re = re.compile(r'\\$',re.MULTILINE)
264
264
265 # The "\n" symbol
265 # The "\n" symbol
266 newline_re = re.compile(r'\\n')
266 newline_re = re.compile(r'\\n')
267
267
268 # Now build the string for output:
268 # Now build the string for output:
269 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
269 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
270 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
270 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
271 strng)
271 strng)
272 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
272 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
273 strng = par_re.sub(r'\\\\',strng)
273 strng = par_re.sub(r'\\\\',strng)
274 strng = escape_re.sub(r'\\\1',strng)
274 strng = escape_re.sub(r'\\\1',strng)
275 strng = newline_re.sub(r'\\textbackslash{}n',strng)
275 strng = newline_re.sub(r'\\textbackslash{}n',strng)
276 return strng
276 return strng
277
277
278 def format_screen(self,strng):
278 def format_screen(self,strng):
279 """Format a string for screen printing.
279 """Format a string for screen printing.
280
280
281 This removes some latex-type format codes."""
281 This removes some latex-type format codes."""
282 # Paragraph continue
282 # Paragraph continue
283 par_re = re.compile(r'\\$',re.MULTILINE)
283 par_re = re.compile(r'\\$',re.MULTILINE)
284 strng = par_re.sub('',strng)
284 strng = par_re.sub('',strng)
285 return strng
285 return strng
286
286
287 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
287 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
288 """Parse options passed to an argument string.
288 """Parse options passed to an argument string.
289
289
290 The interface is similar to that of getopt(), but it returns back a
290 The interface is similar to that of getopt(), but it returns back a
291 Struct with the options as keys and the stripped argument string still
291 Struct with the options as keys and the stripped argument string still
292 as a string.
292 as a string.
293
293
294 arg_str is quoted as a true sys.argv vector by using shlex.split.
294 arg_str is quoted as a true sys.argv vector by using shlex.split.
295 This allows us to easily expand variables, glob files, quote
295 This allows us to easily expand variables, glob files, quote
296 arguments, etc.
296 arguments, etc.
297
297
298 Options:
298 Options:
299 -mode: default 'string'. If given as 'list', the argument string is
299 -mode: default 'string'. If given as 'list', the argument string is
300 returned as a list (split on whitespace) instead of a string.
300 returned as a list (split on whitespace) instead of a string.
301
301
302 -list_all: put all option values in lists. Normally only options
302 -list_all: put all option values in lists. Normally only options
303 appearing more than once are put in a list."""
303 appearing more than once are put in a list."""
304
304
305 # inject default options at the beginning of the input line
305 # inject default options at the beginning of the input line
306 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
306 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
307 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
307 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
308
308
309 mode = kw.get('mode','string')
309 mode = kw.get('mode','string')
310 if mode not in ['string','list']:
310 if mode not in ['string','list']:
311 raise ValueError,'incorrect mode given: %s' % mode
311 raise ValueError,'incorrect mode given: %s' % mode
312 # Get options
312 # Get options
313 list_all = kw.get('list_all',0)
313 list_all = kw.get('list_all',0)
314
314
315 # Check if we have more than one argument to warrant extra processing:
315 # Check if we have more than one argument to warrant extra processing:
316 odict = {} # Dictionary with options
316 odict = {} # Dictionary with options
317 args = arg_str.split()
317 args = arg_str.split()
318 if len(args) >= 1:
318 if len(args) >= 1:
319 # If the list of inputs only has 0 or 1 thing in it, there's no
319 # If the list of inputs only has 0 or 1 thing in it, there's no
320 # need to look for options
320 # need to look for options
321 argv = shlex.split(arg_str)
321 argv = shlex.split(arg_str)
322 # Do regular option processing
322 # Do regular option processing
323 try:
323 try:
324 opts,args = getopt(argv,opt_str,*long_opts)
324 opts,args = getopt(argv,opt_str,*long_opts)
325 except GetoptError,e:
325 except GetoptError,e:
326 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
326 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
327 " ".join(long_opts)))
327 " ".join(long_opts)))
328 for o,a in opts:
328 for o,a in opts:
329 if o.startswith('--'):
329 if o.startswith('--'):
330 o = o[2:]
330 o = o[2:]
331 else:
331 else:
332 o = o[1:]
332 o = o[1:]
333 try:
333 try:
334 odict[o].append(a)
334 odict[o].append(a)
335 except AttributeError:
335 except AttributeError:
336 odict[o] = [odict[o],a]
336 odict[o] = [odict[o],a]
337 except KeyError:
337 except KeyError:
338 if list_all:
338 if list_all:
339 odict[o] = [a]
339 odict[o] = [a]
340 else:
340 else:
341 odict[o] = a
341 odict[o] = a
342
342
343 # Prepare opts,args for return
343 # Prepare opts,args for return
344 opts = Struct(odict)
344 opts = Struct(odict)
345 if mode == 'string':
345 if mode == 'string':
346 args = ' '.join(args)
346 args = ' '.join(args)
347
347
348 return opts,args
348 return opts,args
349
349
350 #......................................................................
350 #......................................................................
351 # And now the actual magic functions
351 # And now the actual magic functions
352
352
353 # Functions for IPython shell work (vars,funcs, config, etc)
353 # Functions for IPython shell work (vars,funcs, config, etc)
354 def magic_lsmagic(self, parameter_s = ''):
354 def magic_lsmagic(self, parameter_s = ''):
355 """List currently available magic functions."""
355 """List currently available magic functions."""
356 mesc = self.shell.ESC_MAGIC
356 mesc = self.shell.ESC_MAGIC
357 print 'Available magic functions:\n'+mesc+\
357 print 'Available magic functions:\n'+mesc+\
358 (' '+mesc).join(self.lsmagic())
358 (' '+mesc).join(self.lsmagic())
359 print '\n' + Magic.auto_status[self.shell.rc.automagic]
359 print '\n' + Magic.auto_status[self.shell.rc.automagic]
360 return None
360 return None
361
361
362 def magic_magic(self, parameter_s = ''):
362 def magic_magic(self, parameter_s = ''):
363 """Print information about the magic function system."""
363 """Print information about the magic function system."""
364
364
365 mode = ''
365 mode = ''
366 try:
366 try:
367 if parameter_s.split()[0] == '-latex':
367 if parameter_s.split()[0] == '-latex':
368 mode = 'latex'
368 mode = 'latex'
369 if parameter_s.split()[0] == '-brief':
369 if parameter_s.split()[0] == '-brief':
370 mode = 'brief'
370 mode = 'brief'
371 except:
371 except:
372 pass
372 pass
373
373
374 magic_docs = []
374 magic_docs = []
375 for fname in self.lsmagic():
375 for fname in self.lsmagic():
376 mname = 'magic_' + fname
376 mname = 'magic_' + fname
377 for space in (Magic,self,self.__class__):
377 for space in (Magic,self,self.__class__):
378 try:
378 try:
379 fn = space.__dict__[mname]
379 fn = space.__dict__[mname]
380 except KeyError:
380 except KeyError:
381 pass
381 pass
382 else:
382 else:
383 break
383 break
384 if mode == 'brief':
384 if mode == 'brief':
385 # only first line
385 # only first line
386 fndoc = fn.__doc__.split('\n',1)[0]
386 fndoc = fn.__doc__.split('\n',1)[0]
387 else:
387 else:
388 fndoc = fn.__doc__
388 fndoc = fn.__doc__
389
389
390 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
390 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
391 fname,fndoc))
391 fname,fndoc))
392 magic_docs = ''.join(magic_docs)
392 magic_docs = ''.join(magic_docs)
393
393
394 if mode == 'latex':
394 if mode == 'latex':
395 print self.format_latex(magic_docs)
395 print self.format_latex(magic_docs)
396 return
396 return
397 else:
397 else:
398 magic_docs = self.format_screen(magic_docs)
398 magic_docs = self.format_screen(magic_docs)
399 if mode == 'brief':
399 if mode == 'brief':
400 return magic_docs
400 return magic_docs
401
401
402 outmsg = """
402 outmsg = """
403 IPython's 'magic' functions
403 IPython's 'magic' functions
404 ===========================
404 ===========================
405
405
406 The magic function system provides a series of functions which allow you to
406 The magic function system provides a series of functions which allow you to
407 control the behavior of IPython itself, plus a lot of system-type
407 control the behavior of IPython itself, plus a lot of system-type
408 features. All these functions are prefixed with a % character, but parameters
408 features. All these functions are prefixed with a % character, but parameters
409 are given without parentheses or quotes.
409 are given without parentheses or quotes.
410
410
411 NOTE: If you have 'automagic' enabled (via the command line option or with the
411 NOTE: If you have 'automagic' enabled (via the command line option or with the
412 %automagic function), you don't need to type in the % explicitly. By default,
412 %automagic function), you don't need to type in the % explicitly. By default,
413 IPython ships with automagic on, so you should only rarely need the % escape.
413 IPython ships with automagic on, so you should only rarely need the % escape.
414
414
415 Example: typing '%cd mydir' (without the quotes) changes you working directory
415 Example: typing '%cd mydir' (without the quotes) changes you working directory
416 to 'mydir', if it exists.
416 to 'mydir', if it exists.
417
417
418 You can define your own magic functions to extend the system. See the supplied
418 You can define your own magic functions to extend the system. See the supplied
419 ipythonrc and example-magic.py files for details (in your ipython
419 ipythonrc and example-magic.py files for details (in your ipython
420 configuration directory, typically $HOME/.ipython/).
420 configuration directory, typically $HOME/.ipython/).
421
421
422 You can also define your own aliased names for magic functions. In your
422 You can also define your own aliased names for magic functions. In your
423 ipythonrc file, placing a line like:
423 ipythonrc file, placing a line like:
424
424
425 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
425 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
426
426
427 will define %pf as a new name for %profile.
427 will define %pf as a new name for %profile.
428
428
429 You can also call magics in code using the ipmagic() function, which IPython
429 You can also call magics in code using the ipmagic() function, which IPython
430 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
430 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
431
431
432 For a list of the available magic functions, use %lsmagic. For a description
432 For a list of the available magic functions, use %lsmagic. For a description
433 of any of them, type %magic_name?, e.g. '%cd?'.
433 of any of them, type %magic_name?, e.g. '%cd?'.
434
434
435 Currently the magic system has the following functions:\n"""
435 Currently the magic system has the following functions:\n"""
436
436
437 mesc = self.shell.ESC_MAGIC
437 mesc = self.shell.ESC_MAGIC
438 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
438 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
439 "\n\n%s%s\n\n%s" % (outmsg,
439 "\n\n%s%s\n\n%s" % (outmsg,
440 magic_docs,mesc,mesc,
440 magic_docs,mesc,mesc,
441 (' '+mesc).join(self.lsmagic()),
441 (' '+mesc).join(self.lsmagic()),
442 Magic.auto_status[self.shell.rc.automagic] ) )
442 Magic.auto_status[self.shell.rc.automagic] ) )
443
443
444 page(outmsg,screen_lines=self.shell.rc.screen_length)
444 page(outmsg,screen_lines=self.shell.rc.screen_length)
445
445
446 def magic_automagic(self, parameter_s = ''):
446 def magic_automagic(self, parameter_s = ''):
447 """Make magic functions callable without having to type the initial %.
447 """Make magic functions callable without having to type the initial %.
448
448
449 Toggles on/off (when off, you must call it as %automagic, of
449 Toggles on/off (when off, you must call it as %automagic, of
450 course). Note that magic functions have lowest priority, so if there's
450 course). Note that magic functions have lowest priority, so if there's
451 a variable whose name collides with that of a magic fn, automagic
451 a variable whose name collides with that of a magic fn, automagic
452 won't work for that function (you get the variable instead). However,
452 won't work for that function (you get the variable instead). However,
453 if you delete the variable (del var), the previously shadowed magic
453 if you delete the variable (del var), the previously shadowed magic
454 function becomes visible to automagic again."""
454 function becomes visible to automagic again."""
455
455
456 rc = self.shell.rc
456 rc = self.shell.rc
457 rc.automagic = not rc.automagic
457 rc.automagic = not rc.automagic
458 print '\n' + Magic.auto_status[rc.automagic]
458 print '\n' + Magic.auto_status[rc.automagic]
459
459
460 def magic_autocall(self, parameter_s = ''):
460 def magic_autocall(self, parameter_s = ''):
461 """Make functions callable without having to type parentheses.
461 """Make functions callable without having to type parentheses.
462
462
463 Usage:
463 Usage:
464
464
465 %autocall [mode]
465 %autocall [mode]
466
466
467 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
467 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
468 value is toggled on and off (remembering the previous state)."""
468 value is toggled on and off (remembering the previous state)."""
469
469
470 rc = self.shell.rc
470 rc = self.shell.rc
471
471
472 if parameter_s:
472 if parameter_s:
473 arg = int(parameter_s)
473 arg = int(parameter_s)
474 else:
474 else:
475 arg = 'toggle'
475 arg = 'toggle'
476
476
477 if not arg in (0,1,2,'toggle'):
477 if not arg in (0,1,2,'toggle'):
478 error('Valid modes: (0->Off, 1->Smart, 2->Full')
478 error('Valid modes: (0->Off, 1->Smart, 2->Full')
479 return
479 return
480
480
481 if arg in (0,1,2):
481 if arg in (0,1,2):
482 rc.autocall = arg
482 rc.autocall = arg
483 else: # toggle
483 else: # toggle
484 if rc.autocall:
484 if rc.autocall:
485 self._magic_state.autocall_save = rc.autocall
485 self._magic_state.autocall_save = rc.autocall
486 rc.autocall = 0
486 rc.autocall = 0
487 else:
487 else:
488 try:
488 try:
489 rc.autocall = self._magic_state.autocall_save
489 rc.autocall = self._magic_state.autocall_save
490 except AttributeError:
490 except AttributeError:
491 rc.autocall = self._magic_state.autocall_save = 1
491 rc.autocall = self._magic_state.autocall_save = 1
492
492
493 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
493 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
494
494
495 def magic_autoindent(self, parameter_s = ''):
495 def magic_autoindent(self, parameter_s = ''):
496 """Toggle autoindent on/off (if available)."""
496 """Toggle autoindent on/off (if available)."""
497
497
498 self.shell.set_autoindent()
498 self.shell.set_autoindent()
499 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
499 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
500
500
501 def magic_system_verbose(self, parameter_s = ''):
501 def magic_system_verbose(self, parameter_s = ''):
502 """Toggle verbose printing of system calls on/off."""
502 """Toggle verbose printing of system calls on/off."""
503
503
504 self.shell.rc_set_toggle('system_verbose')
504 self.shell.rc_set_toggle('system_verbose')
505 print "System verbose printing is:",\
505 print "System verbose printing is:",\
506 ['OFF','ON'][self.shell.rc.system_verbose]
506 ['OFF','ON'][self.shell.rc.system_verbose]
507
507
508 def magic_history(self, parameter_s = ''):
508 def magic_history(self, parameter_s = ''):
509 """Print input history (_i<n> variables), with most recent last.
509 """Print input history (_i<n> variables), with most recent last.
510
510
511 %history -> print at most 40 inputs (some may be multi-line)\\
511 %history -> print at most 40 inputs (some may be multi-line)\\
512 %history n -> print at most n inputs\\
512 %history n -> print at most n inputs\\
513 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
513 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
514
514
515 Each input's number <n> is shown, and is accessible as the
515 Each input's number <n> is shown, and is accessible as the
516 automatically generated variable _i<n>. Multi-line statements are
516 automatically generated variable _i<n>. Multi-line statements are
517 printed starting at a new line for easy copy/paste.
517 printed starting at a new line for easy copy/paste.
518
518
519
519
520 Options:
520 Options:
521
521
522 -n: do NOT print line numbers. This is useful if you want to get a
522 -n: do NOT print line numbers. This is useful if you want to get a
523 printout of many lines which can be directly pasted into a text
523 printout of many lines which can be directly pasted into a text
524 editor.
524 editor.
525
525
526 This feature is only available if numbered prompts are in use.
526 This feature is only available if numbered prompts are in use.
527
527
528 -r: print the 'raw' history. IPython filters your input and
528 -r: print the 'raw' history. IPython filters your input and
529 converts it all into valid Python source before executing it (things
529 converts it all into valid Python source before executing it (things
530 like magics or aliases are turned into function calls, for
530 like magics or aliases are turned into function calls, for
531 example). With this option, you'll see the unfiltered history
531 example). With this option, you'll see the unfiltered history
532 instead of the filtered version: '%cd /' will be seen as '%cd /'
532 instead of the filtered version: '%cd /' will be seen as '%cd /'
533 instead of '_ip.magic("%cd /")'.
533 instead of '_ip.magic("%cd /")'.
534 """
534 """
535
535
536 shell = self.shell
536 shell = self.shell
537 if not shell.outputcache.do_full_cache:
537 if not shell.outputcache.do_full_cache:
538 print 'This feature is only available if numbered prompts are in use.'
538 print 'This feature is only available if numbered prompts are in use.'
539 return
539 return
540 opts,args = self.parse_options(parameter_s,'nr',mode='list')
540 opts,args = self.parse_options(parameter_s,'nr',mode='list')
541
541
542 if opts.has_key('r'):
542 if opts.has_key('r'):
543 input_hist = shell.input_hist_raw
543 input_hist = shell.input_hist_raw
544 else:
544 else:
545 input_hist = shell.input_hist
545 input_hist = shell.input_hist
546
546
547 default_length = 40
547 default_length = 40
548 if len(args) == 0:
548 if len(args) == 0:
549 final = len(input_hist)
549 final = len(input_hist)
550 init = max(1,final-default_length)
550 init = max(1,final-default_length)
551 elif len(args) == 1:
551 elif len(args) == 1:
552 final = len(input_hist)
552 final = len(input_hist)
553 init = max(1,final-int(args[0]))
553 init = max(1,final-int(args[0]))
554 elif len(args) == 2:
554 elif len(args) == 2:
555 init,final = map(int,args)
555 init,final = map(int,args)
556 else:
556 else:
557 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
557 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
558 print self.magic_hist.__doc__
558 print self.magic_hist.__doc__
559 return
559 return
560 width = len(str(final))
560 width = len(str(final))
561 line_sep = ['','\n']
561 line_sep = ['','\n']
562 print_nums = not opts.has_key('n')
562 print_nums = not opts.has_key('n')
563 for in_num in range(init,final):
563 for in_num in range(init,final):
564 inline = input_hist[in_num]
564 inline = input_hist[in_num]
565 multiline = int(inline.count('\n') > 1)
565 multiline = int(inline.count('\n') > 1)
566 if print_nums:
566 if print_nums:
567 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
567 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
568 print inline,
568 print inline,
569
569
570 def magic_hist(self, parameter_s=''):
570 def magic_hist(self, parameter_s=''):
571 """Alternate name for %history."""
571 """Alternate name for %history."""
572 return self.magic_history(parameter_s)
572 return self.magic_history(parameter_s)
573
573
574 def magic_p(self, parameter_s=''):
574 def magic_p(self, parameter_s=''):
575 """Just a short alias for Python's 'print'."""
575 """Just a short alias for Python's 'print'."""
576 exec 'print ' + parameter_s in self.shell.user_ns
576 exec 'print ' + parameter_s in self.shell.user_ns
577
577
578 def magic_r(self, parameter_s=''):
578 def magic_r(self, parameter_s=''):
579 """Repeat previous input.
579 """Repeat previous input.
580
580
581 If given an argument, repeats the previous command which starts with
581 If given an argument, repeats the previous command which starts with
582 the same string, otherwise it just repeats the previous input.
582 the same string, otherwise it just repeats the previous input.
583
583
584 Shell escaped commands (with ! as first character) are not recognized
584 Shell escaped commands (with ! as first character) are not recognized
585 by this system, only pure python code and magic commands.
585 by this system, only pure python code and magic commands.
586 """
586 """
587
587
588 start = parameter_s.strip()
588 start = parameter_s.strip()
589 esc_magic = self.shell.ESC_MAGIC
589 esc_magic = self.shell.ESC_MAGIC
590 # Identify magic commands even if automagic is on (which means
590 # Identify magic commands even if automagic is on (which means
591 # the in-memory version is different from that typed by the user).
591 # the in-memory version is different from that typed by the user).
592 if self.shell.rc.automagic:
592 if self.shell.rc.automagic:
593 start_magic = esc_magic+start
593 start_magic = esc_magic+start
594 else:
594 else:
595 start_magic = start
595 start_magic = start
596 # Look through the input history in reverse
596 # Look through the input history in reverse
597 for n in range(len(self.shell.input_hist)-2,0,-1):
597 for n in range(len(self.shell.input_hist)-2,0,-1):
598 input = self.shell.input_hist[n]
598 input = self.shell.input_hist[n]
599 # skip plain 'r' lines so we don't recurse to infinity
599 # skip plain 'r' lines so we don't recurse to infinity
600 if input != '_ip.magic("r")\n' and \
600 if input != '_ip.magic("r")\n' and \
601 (input.startswith(start) or input.startswith(start_magic)):
601 (input.startswith(start) or input.startswith(start_magic)):
602 #print 'match',`input` # dbg
602 #print 'match',`input` # dbg
603 print 'Executing:',input,
603 print 'Executing:',input,
604 self.shell.runlines(input)
604 self.shell.runlines(input)
605 return
605 return
606 print 'No previous input matching `%s` found.' % start
606 print 'No previous input matching `%s` found.' % start
607
607
608 def magic_page(self, parameter_s=''):
608 def magic_page(self, parameter_s=''):
609 """Pretty print the object and display it through a pager.
609 """Pretty print the object and display it through a pager.
610
610
611 If no parameter is given, use _ (last output)."""
611 If no parameter is given, use _ (last output)."""
612 # After a function contributed by Olivier Aubert, slightly modified.
612 # After a function contributed by Olivier Aubert, slightly modified.
613
613
614 oname = parameter_s and parameter_s or '_'
614 oname = parameter_s and parameter_s or '_'
615 info = self._ofind(oname)
615 info = self._ofind(oname)
616 if info['found']:
616 if info['found']:
617 page(pformat(info['obj']))
617 page(pformat(info['obj']))
618 else:
618 else:
619 print 'Object `%s` not found' % oname
619 print 'Object `%s` not found' % oname
620
620
621 def magic_profile(self, parameter_s=''):
621 def magic_profile(self, parameter_s=''):
622 """Print your currently active IPyhton profile."""
622 """Print your currently active IPyhton profile."""
623 if self.shell.rc.profile:
623 if self.shell.rc.profile:
624 printpl('Current IPython profile: $self.shell.rc.profile.')
624 printpl('Current IPython profile: $self.shell.rc.profile.')
625 else:
625 else:
626 print 'No profile active.'
626 print 'No profile active.'
627
627
628 def _inspect(self,meth,oname,**kw):
628 def _inspect(self,meth,oname,**kw):
629 """Generic interface to the inspector system.
629 """Generic interface to the inspector system.
630
630
631 This function is meant to be called by pdef, pdoc & friends."""
631 This function is meant to be called by pdef, pdoc & friends."""
632
632
633 oname = oname.strip()
633 oname = oname.strip()
634 info = Struct(self._ofind(oname))
634 info = Struct(self._ofind(oname))
635 if info.found:
635 if info.found:
636 pmethod = getattr(self.shell.inspector,meth)
636 pmethod = getattr(self.shell.inspector,meth)
637 formatter = info.ismagic and self.format_screen or None
637 formatter = info.ismagic and self.format_screen or None
638 if meth == 'pdoc':
638 if meth == 'pdoc':
639 pmethod(info.obj,oname,formatter)
639 pmethod(info.obj,oname,formatter)
640 elif meth == 'pinfo':
640 elif meth == 'pinfo':
641 pmethod(info.obj,oname,formatter,info,**kw)
641 pmethod(info.obj,oname,formatter,info,**kw)
642 else:
642 else:
643 pmethod(info.obj,oname)
643 pmethod(info.obj,oname)
644 else:
644 else:
645 print 'Object `%s` not found.' % oname
645 print 'Object `%s` not found.' % oname
646 return 'not found' # so callers can take other action
646 return 'not found' # so callers can take other action
647
647
648 def magic_pdef(self, parameter_s=''):
648 def magic_pdef(self, parameter_s=''):
649 """Print the definition header for any callable object.
649 """Print the definition header for any callable object.
650
650
651 If the object is a class, print the constructor information."""
651 If the object is a class, print the constructor information."""
652 self._inspect('pdef',parameter_s)
652 self._inspect('pdef',parameter_s)
653
653
654 def magic_pdoc(self, parameter_s=''):
654 def magic_pdoc(self, parameter_s=''):
655 """Print the docstring for an object.
655 """Print the docstring for an object.
656
656
657 If the given object is a class, it will print both the class and the
657 If the given object is a class, it will print both the class and the
658 constructor docstrings."""
658 constructor docstrings."""
659 self._inspect('pdoc',parameter_s)
659 self._inspect('pdoc',parameter_s)
660
660
661 def magic_psource(self, parameter_s=''):
661 def magic_psource(self, parameter_s=''):
662 """Print (or run through pager) the source code for an object."""
662 """Print (or run through pager) the source code for an object."""
663 self._inspect('psource',parameter_s)
663 self._inspect('psource',parameter_s)
664
664
665 def magic_pfile(self, parameter_s=''):
665 def magic_pfile(self, parameter_s=''):
666 """Print (or run through pager) the file where an object is defined.
666 """Print (or run through pager) the file where an object is defined.
667
667
668 The file opens at the line where the object definition begins. IPython
668 The file opens at the line where the object definition begins. IPython
669 will honor the environment variable PAGER if set, and otherwise will
669 will honor the environment variable PAGER if set, and otherwise will
670 do its best to print the file in a convenient form.
670 do its best to print the file in a convenient form.
671
671
672 If the given argument is not an object currently defined, IPython will
672 If the given argument is not an object currently defined, IPython will
673 try to interpret it as a filename (automatically adding a .py extension
673 try to interpret it as a filename (automatically adding a .py extension
674 if needed). You can thus use %pfile as a syntax highlighting code
674 if needed). You can thus use %pfile as a syntax highlighting code
675 viewer."""
675 viewer."""
676
676
677 # first interpret argument as an object name
677 # first interpret argument as an object name
678 out = self._inspect('pfile',parameter_s)
678 out = self._inspect('pfile',parameter_s)
679 # if not, try the input as a filename
679 # if not, try the input as a filename
680 if out == 'not found':
680 if out == 'not found':
681 try:
681 try:
682 filename = get_py_filename(parameter_s)
682 filename = get_py_filename(parameter_s)
683 except IOError,msg:
683 except IOError,msg:
684 print msg
684 print msg
685 return
685 return
686 page(self.shell.inspector.format(file(filename).read()))
686 page(self.shell.inspector.format(file(filename).read()))
687
687
688 def magic_pinfo(self, parameter_s=''):
688 def magic_pinfo(self, parameter_s=''):
689 """Provide detailed information about an object.
689 """Provide detailed information about an object.
690
690
691 '%pinfo object' is just a synonym for object? or ?object."""
691 '%pinfo object' is just a synonym for object? or ?object."""
692
692
693 #print 'pinfo par: <%s>' % parameter_s # dbg
693 #print 'pinfo par: <%s>' % parameter_s # dbg
694
694
695 # detail_level: 0 -> obj? , 1 -> obj??
695 # detail_level: 0 -> obj? , 1 -> obj??
696 detail_level = 0
696 detail_level = 0
697 # We need to detect if we got called as 'pinfo pinfo foo', which can
697 # We need to detect if we got called as 'pinfo pinfo foo', which can
698 # happen if the user types 'pinfo foo?' at the cmd line.
698 # happen if the user types 'pinfo foo?' at the cmd line.
699 pinfo,qmark1,oname,qmark2 = \
699 pinfo,qmark1,oname,qmark2 = \
700 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
700 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
701 if pinfo or qmark1 or qmark2:
701 if pinfo or qmark1 or qmark2:
702 detail_level = 1
702 detail_level = 1
703 if "*" in oname:
703 if "*" in oname:
704 self.magic_psearch(oname)
704 self.magic_psearch(oname)
705 else:
705 else:
706 self._inspect('pinfo',oname,detail_level=detail_level)
706 self._inspect('pinfo',oname,detail_level=detail_level)
707
707
708 def magic_psearch(self, parameter_s=''):
708 def magic_psearch(self, parameter_s=''):
709 """Search for object in namespaces by wildcard.
709 """Search for object in namespaces by wildcard.
710
710
711 %psearch [options] PATTERN [OBJECT TYPE]
711 %psearch [options] PATTERN [OBJECT TYPE]
712
712
713 Note: ? can be used as a synonym for %psearch, at the beginning or at
713 Note: ? can be used as a synonym for %psearch, at the beginning or at
714 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
714 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
715 rest of the command line must be unchanged (options come first), so
715 rest of the command line must be unchanged (options come first), so
716 for example the following forms are equivalent
716 for example the following forms are equivalent
717
717
718 %psearch -i a* function
718 %psearch -i a* function
719 -i a* function?
719 -i a* function?
720 ?-i a* function
720 ?-i a* function
721
721
722 Arguments:
722 Arguments:
723
723
724 PATTERN
724 PATTERN
725
725
726 where PATTERN is a string containing * as a wildcard similar to its
726 where PATTERN is a string containing * as a wildcard similar to its
727 use in a shell. The pattern is matched in all namespaces on the
727 use in a shell. The pattern is matched in all namespaces on the
728 search path. By default objects starting with a single _ are not
728 search path. By default objects starting with a single _ are not
729 matched, many IPython generated objects have a single
729 matched, many IPython generated objects have a single
730 underscore. The default is case insensitive matching. Matching is
730 underscore. The default is case insensitive matching. Matching is
731 also done on the attributes of objects and not only on the objects
731 also done on the attributes of objects and not only on the objects
732 in a module.
732 in a module.
733
733
734 [OBJECT TYPE]
734 [OBJECT TYPE]
735
735
736 Is the name of a python type from the types module. The name is
736 Is the name of a python type from the types module. The name is
737 given in lowercase without the ending type, ex. StringType is
737 given in lowercase without the ending type, ex. StringType is
738 written string. By adding a type here only objects matching the
738 written string. By adding a type here only objects matching the
739 given type are matched. Using all here makes the pattern match all
739 given type are matched. Using all here makes the pattern match all
740 types (this is the default).
740 types (this is the default).
741
741
742 Options:
742 Options:
743
743
744 -a: makes the pattern match even objects whose names start with a
744 -a: makes the pattern match even objects whose names start with a
745 single underscore. These names are normally ommitted from the
745 single underscore. These names are normally ommitted from the
746 search.
746 search.
747
747
748 -i/-c: make the pattern case insensitive/sensitive. If neither of
748 -i/-c: make the pattern case insensitive/sensitive. If neither of
749 these options is given, the default is read from your ipythonrc
749 these options is given, the default is read from your ipythonrc
750 file. The option name which sets this value is
750 file. The option name which sets this value is
751 'wildcards_case_sensitive'. If this option is not specified in your
751 'wildcards_case_sensitive'. If this option is not specified in your
752 ipythonrc file, IPython's internal default is to do a case sensitive
752 ipythonrc file, IPython's internal default is to do a case sensitive
753 search.
753 search.
754
754
755 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
755 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
756 specifiy can be searched in any of the following namespaces:
756 specifiy can be searched in any of the following namespaces:
757 'builtin', 'user', 'user_global','internal', 'alias', where
757 'builtin', 'user', 'user_global','internal', 'alias', where
758 'builtin' and 'user' are the search defaults. Note that you should
758 'builtin' and 'user' are the search defaults. Note that you should
759 not use quotes when specifying namespaces.
759 not use quotes when specifying namespaces.
760
760
761 'Builtin' contains the python module builtin, 'user' contains all
761 'Builtin' contains the python module builtin, 'user' contains all
762 user data, 'alias' only contain the shell aliases and no python
762 user data, 'alias' only contain the shell aliases and no python
763 objects, 'internal' contains objects used by IPython. The
763 objects, 'internal' contains objects used by IPython. The
764 'user_global' namespace is only used by embedded IPython instances,
764 'user_global' namespace is only used by embedded IPython instances,
765 and it contains module-level globals. You can add namespaces to the
765 and it contains module-level globals. You can add namespaces to the
766 search with -s or exclude them with -e (these options can be given
766 search with -s or exclude them with -e (these options can be given
767 more than once).
767 more than once).
768
768
769 Examples:
769 Examples:
770
770
771 %psearch a* -> objects beginning with an a
771 %psearch a* -> objects beginning with an a
772 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
772 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
773 %psearch a* function -> all functions beginning with an a
773 %psearch a* function -> all functions beginning with an a
774 %psearch re.e* -> objects beginning with an e in module re
774 %psearch re.e* -> objects beginning with an e in module re
775 %psearch r*.e* -> objects that start with e in modules starting in r
775 %psearch r*.e* -> objects that start with e in modules starting in r
776 %psearch r*.* string -> all strings in modules beginning with r
776 %psearch r*.* string -> all strings in modules beginning with r
777
777
778 Case sensitve search:
778 Case sensitve search:
779
779
780 %psearch -c a* list all object beginning with lower case a
780 %psearch -c a* list all object beginning with lower case a
781
781
782 Show objects beginning with a single _:
782 Show objects beginning with a single _:
783
783
784 %psearch -a _* list objects beginning with a single underscore"""
784 %psearch -a _* list objects beginning with a single underscore"""
785
785
786 # default namespaces to be searched
786 # default namespaces to be searched
787 def_search = ['user','builtin']
787 def_search = ['user','builtin']
788
788
789 # Process options/args
789 # Process options/args
790 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
790 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
791 opt = opts.get
791 opt = opts.get
792 shell = self.shell
792 shell = self.shell
793 psearch = shell.inspector.psearch
793 psearch = shell.inspector.psearch
794
794
795 # select case options
795 # select case options
796 if opts.has_key('i'):
796 if opts.has_key('i'):
797 ignore_case = True
797 ignore_case = True
798 elif opts.has_key('c'):
798 elif opts.has_key('c'):
799 ignore_case = False
799 ignore_case = False
800 else:
800 else:
801 ignore_case = not shell.rc.wildcards_case_sensitive
801 ignore_case = not shell.rc.wildcards_case_sensitive
802
802
803 # Build list of namespaces to search from user options
803 # Build list of namespaces to search from user options
804 def_search.extend(opt('s',[]))
804 def_search.extend(opt('s',[]))
805 ns_exclude = ns_exclude=opt('e',[])
805 ns_exclude = ns_exclude=opt('e',[])
806 ns_search = [nm for nm in def_search if nm not in ns_exclude]
806 ns_search = [nm for nm in def_search if nm not in ns_exclude]
807
807
808 # Call the actual search
808 # Call the actual search
809 try:
809 try:
810 psearch(args,shell.ns_table,ns_search,
810 psearch(args,shell.ns_table,ns_search,
811 show_all=opt('a'),ignore_case=ignore_case)
811 show_all=opt('a'),ignore_case=ignore_case)
812 except:
812 except:
813 shell.showtraceback()
813 shell.showtraceback()
814
814
815 def magic_who_ls(self, parameter_s=''):
815 def magic_who_ls(self, parameter_s=''):
816 """Return a sorted list of all interactive variables.
816 """Return a sorted list of all interactive variables.
817
817
818 If arguments are given, only variables of types matching these
818 If arguments are given, only variables of types matching these
819 arguments are returned."""
819 arguments are returned."""
820
820
821 user_ns = self.shell.user_ns
821 user_ns = self.shell.user_ns
822 internal_ns = self.shell.internal_ns
822 internal_ns = self.shell.internal_ns
823 user_config_ns = self.shell.user_config_ns
823 user_config_ns = self.shell.user_config_ns
824 out = []
824 out = []
825 typelist = parameter_s.split()
825 typelist = parameter_s.split()
826
826
827 for i in user_ns:
827 for i in user_ns:
828 if not (i.startswith('_') or i.startswith('_i')) \
828 if not (i.startswith('_') or i.startswith('_i')) \
829 and not (i in internal_ns or i in user_config_ns):
829 and not (i in internal_ns or i in user_config_ns):
830 if typelist:
830 if typelist:
831 if type(user_ns[i]).__name__ in typelist:
831 if type(user_ns[i]).__name__ in typelist:
832 out.append(i)
832 out.append(i)
833 else:
833 else:
834 out.append(i)
834 out.append(i)
835 out.sort()
835 out.sort()
836 return out
836 return out
837
837
838 def magic_who(self, parameter_s=''):
838 def magic_who(self, parameter_s=''):
839 """Print all interactive variables, with some minimal formatting.
839 """Print all interactive variables, with some minimal formatting.
840
840
841 If any arguments are given, only variables whose type matches one of
841 If any arguments are given, only variables whose type matches one of
842 these are printed. For example:
842 these are printed. For example:
843
843
844 %who function str
844 %who function str
845
845
846 will only list functions and strings, excluding all other types of
846 will only list functions and strings, excluding all other types of
847 variables. To find the proper type names, simply use type(var) at a
847 variables. To find the proper type names, simply use type(var) at a
848 command line to see how python prints type names. For example:
848 command line to see how python prints type names. For example:
849
849
850 In [1]: type('hello')\\
850 In [1]: type('hello')\\
851 Out[1]: <type 'str'>
851 Out[1]: <type 'str'>
852
852
853 indicates that the type name for strings is 'str'.
853 indicates that the type name for strings is 'str'.
854
854
855 %who always excludes executed names loaded through your configuration
855 %who always excludes executed names loaded through your configuration
856 file and things which are internal to IPython.
856 file and things which are internal to IPython.
857
857
858 This is deliberate, as typically you may load many modules and the
858 This is deliberate, as typically you may load many modules and the
859 purpose of %who is to show you only what you've manually defined."""
859 purpose of %who is to show you only what you've manually defined."""
860
860
861 varlist = self.magic_who_ls(parameter_s)
861 varlist = self.magic_who_ls(parameter_s)
862 if not varlist:
862 if not varlist:
863 print 'Interactive namespace is empty.'
863 print 'Interactive namespace is empty.'
864 return
864 return
865
865
866 # if we have variables, move on...
866 # if we have variables, move on...
867
867
868 # stupid flushing problem: when prompts have no separators, stdout is
868 # stupid flushing problem: when prompts have no separators, stdout is
869 # getting lost. I'm starting to think this is a python bug. I'm having
869 # getting lost. I'm starting to think this is a python bug. I'm having
870 # to force a flush with a print because even a sys.stdout.flush
870 # to force a flush with a print because even a sys.stdout.flush
871 # doesn't seem to do anything!
871 # doesn't seem to do anything!
872
872
873 count = 0
873 count = 0
874 for i in varlist:
874 for i in varlist:
875 print i+'\t',
875 print i+'\t',
876 count += 1
876 count += 1
877 if count > 8:
877 if count > 8:
878 count = 0
878 count = 0
879 print
879 print
880 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
880 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
881
881
882 print # well, this does force a flush at the expense of an extra \n
882 print # well, this does force a flush at the expense of an extra \n
883
883
884 def magic_whos(self, parameter_s=''):
884 def magic_whos(self, parameter_s=''):
885 """Like %who, but gives some extra information about each variable.
885 """Like %who, but gives some extra information about each variable.
886
886
887 The same type filtering of %who can be applied here.
887 The same type filtering of %who can be applied here.
888
888
889 For all variables, the type is printed. Additionally it prints:
889 For all variables, the type is printed. Additionally it prints:
890
890
891 - For {},[],(): their length.
891 - For {},[],(): their length.
892
892
893 - For Numeric arrays, a summary with shape, number of elements,
893 - For Numeric arrays, a summary with shape, number of elements,
894 typecode and size in memory.
894 typecode and size in memory.
895
895
896 - Everything else: a string representation, snipping their middle if
896 - Everything else: a string representation, snipping their middle if
897 too long."""
897 too long."""
898
898
899 varnames = self.magic_who_ls(parameter_s)
899 varnames = self.magic_who_ls(parameter_s)
900 if not varnames:
900 if not varnames:
901 print 'Interactive namespace is empty.'
901 print 'Interactive namespace is empty.'
902 return
902 return
903
903
904 # if we have variables, move on...
904 # if we have variables, move on...
905
905
906 # for these types, show len() instead of data:
906 # for these types, show len() instead of data:
907 seq_types = [types.DictType,types.ListType,types.TupleType]
907 seq_types = [types.DictType,types.ListType,types.TupleType]
908
908
909 # for Numeric arrays, display summary info
909 # for Numeric arrays, display summary info
910 try:
910 try:
911 import Numeric
911 import Numeric
912 except ImportError:
912 except ImportError:
913 array_type = None
913 array_type = None
914 else:
914 else:
915 array_type = Numeric.ArrayType.__name__
915 array_type = Numeric.ArrayType.__name__
916
916
917 # Find all variable names and types so we can figure out column sizes
917 # Find all variable names and types so we can figure out column sizes
918 get_vars = lambda i: self.shell.user_ns[i]
918 get_vars = lambda i: self.shell.user_ns[i]
919 type_name = lambda v: type(v).__name__
919 type_name = lambda v: type(v).__name__
920 varlist = map(get_vars,varnames)
920 varlist = map(get_vars,varnames)
921
921
922 typelist = []
922 typelist = []
923 for vv in varlist:
923 for vv in varlist:
924 tt = type_name(vv)
924 tt = type_name(vv)
925 if tt=='instance':
925 if tt=='instance':
926 typelist.append(str(vv.__class__))
926 typelist.append(str(vv.__class__))
927 else:
927 else:
928 typelist.append(tt)
928 typelist.append(tt)
929
929
930 # column labels and # of spaces as separator
930 # column labels and # of spaces as separator
931 varlabel = 'Variable'
931 varlabel = 'Variable'
932 typelabel = 'Type'
932 typelabel = 'Type'
933 datalabel = 'Data/Info'
933 datalabel = 'Data/Info'
934 colsep = 3
934 colsep = 3
935 # variable format strings
935 # variable format strings
936 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
936 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
937 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
937 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
938 aformat = "%s: %s elems, type `%s`, %s bytes"
938 aformat = "%s: %s elems, type `%s`, %s bytes"
939 # find the size of the columns to format the output nicely
939 # find the size of the columns to format the output nicely
940 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
940 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
941 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
941 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
942 # table header
942 # table header
943 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
943 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
944 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
944 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
945 # and the table itself
945 # and the table itself
946 kb = 1024
946 kb = 1024
947 Mb = 1048576 # kb**2
947 Mb = 1048576 # kb**2
948 for vname,var,vtype in zip(varnames,varlist,typelist):
948 for vname,var,vtype in zip(varnames,varlist,typelist):
949 print itpl(vformat),
949 print itpl(vformat),
950 if vtype in seq_types:
950 if vtype in seq_types:
951 print len(var)
951 print len(var)
952 elif vtype==array_type:
952 elif vtype==array_type:
953 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
953 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
954 vsize = Numeric.size(var)
954 vsize = Numeric.size(var)
955 vbytes = vsize*var.itemsize()
955 vbytes = vsize*var.itemsize()
956 if vbytes < 100000:
956 if vbytes < 100000:
957 print aformat % (vshape,vsize,var.typecode(),vbytes)
957 print aformat % (vshape,vsize,var.typecode(),vbytes)
958 else:
958 else:
959 print aformat % (vshape,vsize,var.typecode(),vbytes),
959 print aformat % (vshape,vsize,var.typecode(),vbytes),
960 if vbytes < Mb:
960 if vbytes < Mb:
961 print '(%s kb)' % (vbytes/kb,)
961 print '(%s kb)' % (vbytes/kb,)
962 else:
962 else:
963 print '(%s Mb)' % (vbytes/Mb,)
963 print '(%s Mb)' % (vbytes/Mb,)
964 else:
964 else:
965 vstr = str(var).replace('\n','\\n')
965 vstr = str(var).replace('\n','\\n')
966 if len(vstr) < 50:
966 if len(vstr) < 50:
967 print vstr
967 print vstr
968 else:
968 else:
969 printpl(vfmt_short)
969 printpl(vfmt_short)
970
970
971 def magic_reset(self, parameter_s=''):
971 def magic_reset(self, parameter_s=''):
972 """Resets the namespace by removing all names defined by the user.
972 """Resets the namespace by removing all names defined by the user.
973
973
974 Input/Output history are left around in case you need them."""
974 Input/Output history are left around in case you need them."""
975
975
976 ans = raw_input(
976 ans = raw_input(
977 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
977 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
978 if not ans.lower() == 'y':
978 if not ans.lower() == 'y':
979 print 'Nothing done.'
979 print 'Nothing done.'
980 return
980 return
981 user_ns = self.shell.user_ns
981 user_ns = self.shell.user_ns
982 for i in self.magic_who_ls():
982 for i in self.magic_who_ls():
983 del(user_ns[i])
983 del(user_ns[i])
984
984
985 def magic_config(self,parameter_s=''):
985 def magic_config(self,parameter_s=''):
986 """Show IPython's internal configuration."""
986 """Show IPython's internal configuration."""
987
987
988 page('Current configuration structure:\n'+
988 page('Current configuration structure:\n'+
989 pformat(self.shell.rc.dict()))
989 pformat(self.shell.rc.dict()))
990
990
991 def magic_logstart(self,parameter_s=''):
991 def magic_logstart(self,parameter_s=''):
992 """Start logging anywhere in a session.
992 """Start logging anywhere in a session.
993
993
994 %logstart [-o|-t] [log_name [log_mode]]
994 %logstart [-o|-t] [log_name [log_mode]]
995
995
996 If no name is given, it defaults to a file named 'ipython_log.py' in your
996 If no name is given, it defaults to a file named 'ipython_log.py' in your
997 current directory, in 'rotate' mode (see below).
997 current directory, in 'rotate' mode (see below).
998
998
999 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
999 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1000 history up to that point and then continues logging.
1000 history up to that point and then continues logging.
1001
1001
1002 %logstart takes a second optional parameter: logging mode. This can be one
1002 %logstart takes a second optional parameter: logging mode. This can be one
1003 of (note that the modes are given unquoted):\\
1003 of (note that the modes are given unquoted):\\
1004 append: well, that says it.\\
1004 append: well, that says it.\\
1005 backup: rename (if exists) to name~ and start name.\\
1005 backup: rename (if exists) to name~ and start name.\\
1006 global: single logfile in your home dir, appended to.\\
1006 global: single logfile in your home dir, appended to.\\
1007 over : overwrite existing log.\\
1007 over : overwrite existing log.\\
1008 rotate: create rotating logs name.1~, name.2~, etc.
1008 rotate: create rotating logs name.1~, name.2~, etc.
1009
1009
1010 Options:
1010 Options:
1011
1011
1012 -o: log also IPython's output. In this mode, all commands which
1012 -o: log also IPython's output. In this mode, all commands which
1013 generate an Out[NN] prompt are recorded to the logfile, right after
1013 generate an Out[NN] prompt are recorded to the logfile, right after
1014 their corresponding input line. The output lines are always
1014 their corresponding input line. The output lines are always
1015 prepended with a '#[Out]# ' marker, so that the log remains valid
1015 prepended with a '#[Out]# ' marker, so that the log remains valid
1016 Python code.
1016 Python code.
1017
1017
1018 Since this marker is always the same, filtering only the output from
1018 Since this marker is always the same, filtering only the output from
1019 a log is very easy, using for example a simple awk call:
1019 a log is very easy, using for example a simple awk call:
1020
1020
1021 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1021 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1022
1022
1023 -t: put timestamps before each input line logged (these are put in
1023 -t: put timestamps before each input line logged (these are put in
1024 comments)."""
1024 comments)."""
1025
1025
1026 opts,par = self.parse_options(parameter_s,'ot')
1026 opts,par = self.parse_options(parameter_s,'ot')
1027 log_output = 'o' in opts
1027 log_output = 'o' in opts
1028 timestamp = 't' in opts
1028 timestamp = 't' in opts
1029
1029
1030 rc = self.shell.rc
1030 rc = self.shell.rc
1031 logger = self.shell.logger
1031 logger = self.shell.logger
1032
1032
1033 # if no args are given, the defaults set in the logger constructor by
1033 # if no args are given, the defaults set in the logger constructor by
1034 # ipytohn remain valid
1034 # ipytohn remain valid
1035 if par:
1035 if par:
1036 try:
1036 try:
1037 logfname,logmode = par.split()
1037 logfname,logmode = par.split()
1038 except:
1038 except:
1039 logfname = par
1039 logfname = par
1040 logmode = 'backup'
1040 logmode = 'backup'
1041 else:
1041 else:
1042 logfname = logger.logfname
1042 logfname = logger.logfname
1043 logmode = logger.logmode
1043 logmode = logger.logmode
1044 # put logfname into rc struct as if it had been called on the command
1044 # put logfname into rc struct as if it had been called on the command
1045 # line, so it ends up saved in the log header Save it in case we need
1045 # line, so it ends up saved in the log header Save it in case we need
1046 # to restore it...
1046 # to restore it...
1047 old_logfile = rc.opts.get('logfile','')
1047 old_logfile = rc.opts.get('logfile','')
1048 if logfname:
1048 if logfname:
1049 logfname = os.path.expanduser(logfname)
1049 logfname = os.path.expanduser(logfname)
1050 rc.opts.logfile = logfname
1050 rc.opts.logfile = logfname
1051 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1051 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1052 try:
1052 try:
1053 started = logger.logstart(logfname,loghead,logmode,
1053 started = logger.logstart(logfname,loghead,logmode,
1054 log_output,timestamp)
1054 log_output,timestamp)
1055 except:
1055 except:
1056 rc.opts.logfile = old_logfile
1056 rc.opts.logfile = old_logfile
1057 warn("Couldn't start log: %s" % sys.exc_info()[1])
1057 warn("Couldn't start log: %s" % sys.exc_info()[1])
1058 else:
1058 else:
1059 # log input history up to this point, optionally interleaving
1059 # log input history up to this point, optionally interleaving
1060 # output if requested
1060 # output if requested
1061
1061
1062 if timestamp:
1062 if timestamp:
1063 # disable timestamping for the previous history, since we've
1063 # disable timestamping for the previous history, since we've
1064 # lost those already (no time machine here).
1064 # lost those already (no time machine here).
1065 logger.timestamp = False
1065 logger.timestamp = False
1066 if log_output:
1066 if log_output:
1067 log_write = logger.log_write
1067 log_write = logger.log_write
1068 input_hist = self.shell.input_hist
1068 input_hist = self.shell.input_hist
1069 output_hist = self.shell.output_hist
1069 output_hist = self.shell.output_hist
1070 for n in range(1,len(input_hist)-1):
1070 for n in range(1,len(input_hist)-1):
1071 log_write(input_hist[n].rstrip())
1071 log_write(input_hist[n].rstrip())
1072 if n in output_hist:
1072 if n in output_hist:
1073 log_write(repr(output_hist[n]),'output')
1073 log_write(repr(output_hist[n]),'output')
1074 else:
1074 else:
1075 logger.log_write(self.shell.input_hist[1:])
1075 logger.log_write(self.shell.input_hist[1:])
1076 if timestamp:
1076 if timestamp:
1077 # re-enable timestamping
1077 # re-enable timestamping
1078 logger.timestamp = True
1078 logger.timestamp = True
1079
1079
1080 print ('Activating auto-logging. '
1080 print ('Activating auto-logging. '
1081 'Current session state plus future input saved.')
1081 'Current session state plus future input saved.')
1082 logger.logstate()
1082 logger.logstate()
1083
1083
1084 def magic_logoff(self,parameter_s=''):
1084 def magic_logoff(self,parameter_s=''):
1085 """Temporarily stop logging.
1085 """Temporarily stop logging.
1086
1086
1087 You must have previously started logging."""
1087 You must have previously started logging."""
1088 self.shell.logger.switch_log(0)
1088 self.shell.logger.switch_log(0)
1089
1089
1090 def magic_logon(self,parameter_s=''):
1090 def magic_logon(self,parameter_s=''):
1091 """Restart logging.
1091 """Restart logging.
1092
1092
1093 This function is for restarting logging which you've temporarily
1093 This function is for restarting logging which you've temporarily
1094 stopped with %logoff. For starting logging for the first time, you
1094 stopped with %logoff. For starting logging for the first time, you
1095 must use the %logstart function, which allows you to specify an
1095 must use the %logstart function, which allows you to specify an
1096 optional log filename."""
1096 optional log filename."""
1097
1097
1098 self.shell.logger.switch_log(1)
1098 self.shell.logger.switch_log(1)
1099
1099
1100 def magic_logstate(self,parameter_s=''):
1100 def magic_logstate(self,parameter_s=''):
1101 """Print the status of the logging system."""
1101 """Print the status of the logging system."""
1102
1102
1103 self.shell.logger.logstate()
1103 self.shell.logger.logstate()
1104
1104
1105 def magic_pdb(self, parameter_s=''):
1105 def magic_pdb(self, parameter_s=''):
1106 """Control the calling of the pdb interactive debugger.
1106 """Control the calling of the pdb interactive debugger.
1107
1107
1108 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1108 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1109 argument it works as a toggle.
1109 argument it works as a toggle.
1110
1110
1111 When an exception is triggered, IPython can optionally call the
1111 When an exception is triggered, IPython can optionally call the
1112 interactive pdb debugger after the traceback printout. %pdb toggles
1112 interactive pdb debugger after the traceback printout. %pdb toggles
1113 this feature on and off."""
1113 this feature on and off."""
1114
1114
1115 par = parameter_s.strip().lower()
1115 par = parameter_s.strip().lower()
1116
1116
1117 if par:
1117 if par:
1118 try:
1118 try:
1119 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1119 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1120 except KeyError:
1120 except KeyError:
1121 print ('Incorrect argument. Use on/1, off/0, '
1121 print ('Incorrect argument. Use on/1, off/0, '
1122 'or nothing for a toggle.')
1122 'or nothing for a toggle.')
1123 return
1123 return
1124 else:
1124 else:
1125 # toggle
1125 # toggle
1126 new_pdb = not self.shell.InteractiveTB.call_pdb
1126 new_pdb = not self.shell.InteractiveTB.call_pdb
1127
1127
1128 # set on the shell
1128 # set on the shell
1129 self.shell.call_pdb = new_pdb
1129 self.shell.call_pdb = new_pdb
1130 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1130 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1131
1131
1132 def magic_prun(self, parameter_s ='',user_mode=1,
1132 def magic_prun(self, parameter_s ='',user_mode=1,
1133 opts=None,arg_lst=None,prog_ns=None):
1133 opts=None,arg_lst=None,prog_ns=None):
1134
1134
1135 """Run a statement through the python code profiler.
1135 """Run a statement through the python code profiler.
1136
1136
1137 Usage:\\
1137 Usage:\\
1138 %prun [options] statement
1138 %prun [options] statement
1139
1139
1140 The given statement (which doesn't require quote marks) is run via the
1140 The given statement (which doesn't require quote marks) is run via the
1141 python profiler in a manner similar to the profile.run() function.
1141 python profiler in a manner similar to the profile.run() function.
1142 Namespaces are internally managed to work correctly; profile.run
1142 Namespaces are internally managed to work correctly; profile.run
1143 cannot be used in IPython because it makes certain assumptions about
1143 cannot be used in IPython because it makes certain assumptions about
1144 namespaces which do not hold under IPython.
1144 namespaces which do not hold under IPython.
1145
1145
1146 Options:
1146 Options:
1147
1147
1148 -l <limit>: you can place restrictions on what or how much of the
1148 -l <limit>: you can place restrictions on what or how much of the
1149 profile gets printed. The limit value can be:
1149 profile gets printed. The limit value can be:
1150
1150
1151 * A string: only information for function names containing this string
1151 * A string: only information for function names containing this string
1152 is printed.
1152 is printed.
1153
1153
1154 * An integer: only these many lines are printed.
1154 * An integer: only these many lines are printed.
1155
1155
1156 * A float (between 0 and 1): this fraction of the report is printed
1156 * A float (between 0 and 1): this fraction of the report is printed
1157 (for example, use a limit of 0.4 to see the topmost 40% only).
1157 (for example, use a limit of 0.4 to see the topmost 40% only).
1158
1158
1159 You can combine several limits with repeated use of the option. For
1159 You can combine several limits with repeated use of the option. For
1160 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1160 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1161 information about class constructors.
1161 information about class constructors.
1162
1162
1163 -r: return the pstats.Stats object generated by the profiling. This
1163 -r: return the pstats.Stats object generated by the profiling. This
1164 object has all the information about the profile in it, and you can
1164 object has all the information about the profile in it, and you can
1165 later use it for further analysis or in other functions.
1165 later use it for further analysis or in other functions.
1166
1166
1167 Since magic functions have a particular form of calling which prevents
1167 Since magic functions have a particular form of calling which prevents
1168 you from writing something like:\\
1168 you from writing something like:\\
1169 In [1]: p = %prun -r print 4 # invalid!\\
1169 In [1]: p = %prun -r print 4 # invalid!\\
1170 you must instead use IPython's automatic variables to assign this:\\
1170 you must instead use IPython's automatic variables to assign this:\\
1171 In [1]: %prun -r print 4 \\
1171 In [1]: %prun -r print 4 \\
1172 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1172 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1173 In [2]: stats = _
1173 In [2]: stats = _
1174
1174
1175 If you really need to assign this value via an explicit function call,
1175 If you really need to assign this value via an explicit function call,
1176 you can always tap directly into the true name of the magic function
1176 you can always tap directly into the true name of the magic function
1177 by using the _ip.magic function:\\
1177 by using the _ip.magic function:\\
1178 In [3]: stats = _ip.magic('prun','-r print 4')
1178 In [3]: stats = _ip.magic('prun','-r print 4')
1179
1179
1180 You can type _ip.magic? for more details.
1180 You can type _ip.magic? for more details.
1181
1181
1182 -s <key>: sort profile by given key. You can provide more than one key
1182 -s <key>: sort profile by given key. You can provide more than one key
1183 by using the option several times: '-s key1 -s key2 -s key3...'. The
1183 by using the option several times: '-s key1 -s key2 -s key3...'. The
1184 default sorting key is 'time'.
1184 default sorting key is 'time'.
1185
1185
1186 The following is copied verbatim from the profile documentation
1186 The following is copied verbatim from the profile documentation
1187 referenced below:
1187 referenced below:
1188
1188
1189 When more than one key is provided, additional keys are used as
1189 When more than one key is provided, additional keys are used as
1190 secondary criteria when the there is equality in all keys selected
1190 secondary criteria when the there is equality in all keys selected
1191 before them.
1191 before them.
1192
1192
1193 Abbreviations can be used for any key names, as long as the
1193 Abbreviations can be used for any key names, as long as the
1194 abbreviation is unambiguous. The following are the keys currently
1194 abbreviation is unambiguous. The following are the keys currently
1195 defined:
1195 defined:
1196
1196
1197 Valid Arg Meaning\\
1197 Valid Arg Meaning\\
1198 "calls" call count\\
1198 "calls" call count\\
1199 "cumulative" cumulative time\\
1199 "cumulative" cumulative time\\
1200 "file" file name\\
1200 "file" file name\\
1201 "module" file name\\
1201 "module" file name\\
1202 "pcalls" primitive call count\\
1202 "pcalls" primitive call count\\
1203 "line" line number\\
1203 "line" line number\\
1204 "name" function name\\
1204 "name" function name\\
1205 "nfl" name/file/line\\
1205 "nfl" name/file/line\\
1206 "stdname" standard name\\
1206 "stdname" standard name\\
1207 "time" internal time
1207 "time" internal time
1208
1208
1209 Note that all sorts on statistics are in descending order (placing
1209 Note that all sorts on statistics are in descending order (placing
1210 most time consuming items first), where as name, file, and line number
1210 most time consuming items first), where as name, file, and line number
1211 searches are in ascending order (i.e., alphabetical). The subtle
1211 searches are in ascending order (i.e., alphabetical). The subtle
1212 distinction between "nfl" and "stdname" is that the standard name is a
1212 distinction between "nfl" and "stdname" is that the standard name is a
1213 sort of the name as printed, which means that the embedded line
1213 sort of the name as printed, which means that the embedded line
1214 numbers get compared in an odd way. For example, lines 3, 20, and 40
1214 numbers get compared in an odd way. For example, lines 3, 20, and 40
1215 would (if the file names were the same) appear in the string order
1215 would (if the file names were the same) appear in the string order
1216 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1216 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1217 line numbers. In fact, sort_stats("nfl") is the same as
1217 line numbers. In fact, sort_stats("nfl") is the same as
1218 sort_stats("name", "file", "line").
1218 sort_stats("name", "file", "line").
1219
1219
1220 -T <filename>: save profile results as shown on screen to a text
1220 -T <filename>: save profile results as shown on screen to a text
1221 file. The profile is still shown on screen.
1221 file. The profile is still shown on screen.
1222
1222
1223 -D <filename>: save (via dump_stats) profile statistics to given
1223 -D <filename>: save (via dump_stats) profile statistics to given
1224 filename. This data is in a format understod by the pstats module, and
1224 filename. This data is in a format understod by the pstats module, and
1225 is generated by a call to the dump_stats() method of profile
1225 is generated by a call to the dump_stats() method of profile
1226 objects. The profile is still shown on screen.
1226 objects. The profile is still shown on screen.
1227
1227
1228 If you want to run complete programs under the profiler's control, use
1228 If you want to run complete programs under the profiler's control, use
1229 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1229 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1230 contains profiler specific options as described here.
1230 contains profiler specific options as described here.
1231
1231
1232 You can read the complete documentation for the profile module with:\\
1232 You can read the complete documentation for the profile module with:\\
1233 In [1]: import profile; profile.help() """
1233 In [1]: import profile; profile.help() """
1234
1234
1235 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1235 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1236 # protect user quote marks
1236 # protect user quote marks
1237 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1237 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1238
1238
1239 if user_mode: # regular user call
1239 if user_mode: # regular user call
1240 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1240 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1241 list_all=1)
1241 list_all=1)
1242 namespace = self.shell.user_ns
1242 namespace = self.shell.user_ns
1243 else: # called to run a program by %run -p
1243 else: # called to run a program by %run -p
1244 try:
1244 try:
1245 filename = get_py_filename(arg_lst[0])
1245 filename = get_py_filename(arg_lst[0])
1246 except IOError,msg:
1246 except IOError,msg:
1247 error(msg)
1247 error(msg)
1248 return
1248 return
1249
1249
1250 arg_str = 'execfile(filename,prog_ns)'
1250 arg_str = 'execfile(filename,prog_ns)'
1251 namespace = locals()
1251 namespace = locals()
1252
1252
1253 opts.merge(opts_def)
1253 opts.merge(opts_def)
1254
1254
1255 prof = profile.Profile()
1255 prof = profile.Profile()
1256 try:
1256 try:
1257 prof = prof.runctx(arg_str,namespace,namespace)
1257 prof = prof.runctx(arg_str,namespace,namespace)
1258 sys_exit = ''
1258 sys_exit = ''
1259 except SystemExit:
1259 except SystemExit:
1260 sys_exit = """*** SystemExit exception caught in code being profiled."""
1260 sys_exit = """*** SystemExit exception caught in code being profiled."""
1261
1261
1262 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1262 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1263
1263
1264 lims = opts.l
1264 lims = opts.l
1265 if lims:
1265 if lims:
1266 lims = [] # rebuild lims with ints/floats/strings
1266 lims = [] # rebuild lims with ints/floats/strings
1267 for lim in opts.l:
1267 for lim in opts.l:
1268 try:
1268 try:
1269 lims.append(int(lim))
1269 lims.append(int(lim))
1270 except ValueError:
1270 except ValueError:
1271 try:
1271 try:
1272 lims.append(float(lim))
1272 lims.append(float(lim))
1273 except ValueError:
1273 except ValueError:
1274 lims.append(lim)
1274 lims.append(lim)
1275
1275
1276 # trap output
1276 # trap output
1277 sys_stdout = sys.stdout
1277 sys_stdout = sys.stdout
1278 stdout_trap = StringIO()
1278 stdout_trap = StringIO()
1279 try:
1279 try:
1280 sys.stdout = stdout_trap
1280 sys.stdout = stdout_trap
1281 stats.print_stats(*lims)
1281 stats.print_stats(*lims)
1282 finally:
1282 finally:
1283 sys.stdout = sys_stdout
1283 sys.stdout = sys_stdout
1284 output = stdout_trap.getvalue()
1284 output = stdout_trap.getvalue()
1285 output = output.rstrip()
1285 output = output.rstrip()
1286
1286
1287 page(output,screen_lines=self.shell.rc.screen_length)
1287 page(output,screen_lines=self.shell.rc.screen_length)
1288 print sys_exit,
1288 print sys_exit,
1289
1289
1290 dump_file = opts.D[0]
1290 dump_file = opts.D[0]
1291 text_file = opts.T[0]
1291 text_file = opts.T[0]
1292 if dump_file:
1292 if dump_file:
1293 prof.dump_stats(dump_file)
1293 prof.dump_stats(dump_file)
1294 print '\n*** Profile stats marshalled to file',\
1294 print '\n*** Profile stats marshalled to file',\
1295 `dump_file`+'.',sys_exit
1295 `dump_file`+'.',sys_exit
1296 if text_file:
1296 if text_file:
1297 file(text_file,'w').write(output)
1297 file(text_file,'w').write(output)
1298 print '\n*** Profile printout saved to text file',\
1298 print '\n*** Profile printout saved to text file',\
1299 `text_file`+'.',sys_exit
1299 `text_file`+'.',sys_exit
1300
1300
1301 if opts.has_key('r'):
1301 if opts.has_key('r'):
1302 return stats
1302 return stats
1303 else:
1303 else:
1304 return None
1304 return None
1305
1305
1306 def magic_run(self, parameter_s ='',runner=None):
1306 def magic_run(self, parameter_s ='',runner=None):
1307 """Run the named file inside IPython as a program.
1307 """Run the named file inside IPython as a program.
1308
1308
1309 Usage:\\
1309 Usage:\\
1310 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1310 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1311
1311
1312 Parameters after the filename are passed as command-line arguments to
1312 Parameters after the filename are passed as command-line arguments to
1313 the program (put in sys.argv). Then, control returns to IPython's
1313 the program (put in sys.argv). Then, control returns to IPython's
1314 prompt.
1314 prompt.
1315
1315
1316 This is similar to running at a system prompt:\\
1316 This is similar to running at a system prompt:\\
1317 $ python file args\\
1317 $ python file args\\
1318 but with the advantage of giving you IPython's tracebacks, and of
1318 but with the advantage of giving you IPython's tracebacks, and of
1319 loading all variables into your interactive namespace for further use
1319 loading all variables into your interactive namespace for further use
1320 (unless -p is used, see below).
1320 (unless -p is used, see below).
1321
1321
1322 The file is executed in a namespace initially consisting only of
1322 The file is executed in a namespace initially consisting only of
1323 __name__=='__main__' and sys.argv constructed as indicated. It thus
1323 __name__=='__main__' and sys.argv constructed as indicated. It thus
1324 sees its environment as if it were being run as a stand-alone
1324 sees its environment as if it were being run as a stand-alone
1325 program. But after execution, the IPython interactive namespace gets
1325 program. But after execution, the IPython interactive namespace gets
1326 updated with all variables defined in the program (except for __name__
1326 updated with all variables defined in the program (except for __name__
1327 and sys.argv). This allows for very convenient loading of code for
1327 and sys.argv). This allows for very convenient loading of code for
1328 interactive work, while giving each program a 'clean sheet' to run in.
1328 interactive work, while giving each program a 'clean sheet' to run in.
1329
1329
1330 Options:
1330 Options:
1331
1331
1332 -n: __name__ is NOT set to '__main__', but to the running file's name
1332 -n: __name__ is NOT set to '__main__', but to the running file's name
1333 without extension (as python does under import). This allows running
1333 without extension (as python does under import). This allows running
1334 scripts and reloading the definitions in them without calling code
1334 scripts and reloading the definitions in them without calling code
1335 protected by an ' if __name__ == "__main__" ' clause.
1335 protected by an ' if __name__ == "__main__" ' clause.
1336
1336
1337 -i: run the file in IPython's namespace instead of an empty one. This
1337 -i: run the file in IPython's namespace instead of an empty one. This
1338 is useful if you are experimenting with code written in a text editor
1338 is useful if you are experimenting with code written in a text editor
1339 which depends on variables defined interactively.
1339 which depends on variables defined interactively.
1340
1340
1341 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1341 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1342 being run. This is particularly useful if IPython is being used to
1342 being run. This is particularly useful if IPython is being used to
1343 run unittests, which always exit with a sys.exit() call. In such
1343 run unittests, which always exit with a sys.exit() call. In such
1344 cases you are interested in the output of the test results, not in
1344 cases you are interested in the output of the test results, not in
1345 seeing a traceback of the unittest module.
1345 seeing a traceback of the unittest module.
1346
1346
1347 -t: print timing information at the end of the run. IPython will give
1347 -t: print timing information at the end of the run. IPython will give
1348 you an estimated CPU time consumption for your script, which under
1348 you an estimated CPU time consumption for your script, which under
1349 Unix uses the resource module to avoid the wraparound problems of
1349 Unix uses the resource module to avoid the wraparound problems of
1350 time.clock(). Under Unix, an estimate of time spent on system tasks
1350 time.clock(). Under Unix, an estimate of time spent on system tasks
1351 is also given (for Windows platforms this is reported as 0.0).
1351 is also given (for Windows platforms this is reported as 0.0).
1352
1352
1353 If -t is given, an additional -N<N> option can be given, where <N>
1353 If -t is given, an additional -N<N> option can be given, where <N>
1354 must be an integer indicating how many times you want the script to
1354 must be an integer indicating how many times you want the script to
1355 run. The final timing report will include total and per run results.
1355 run. The final timing report will include total and per run results.
1356
1356
1357 For example (testing the script uniq_stable.py):
1357 For example (testing the script uniq_stable.py):
1358
1358
1359 In [1]: run -t uniq_stable
1359 In [1]: run -t uniq_stable
1360
1360
1361 IPython CPU timings (estimated):\\
1361 IPython CPU timings (estimated):\\
1362 User : 0.19597 s.\\
1362 User : 0.19597 s.\\
1363 System: 0.0 s.\\
1363 System: 0.0 s.\\
1364
1364
1365 In [2]: run -t -N5 uniq_stable
1365 In [2]: run -t -N5 uniq_stable
1366
1366
1367 IPython CPU timings (estimated):\\
1367 IPython CPU timings (estimated):\\
1368 Total runs performed: 5\\
1368 Total runs performed: 5\\
1369 Times : Total Per run\\
1369 Times : Total Per run\\
1370 User : 0.910862 s, 0.1821724 s.\\
1370 User : 0.910862 s, 0.1821724 s.\\
1371 System: 0.0 s, 0.0 s.
1371 System: 0.0 s, 0.0 s.
1372
1372
1373 -d: run your program under the control of pdb, the Python debugger.
1373 -d: run your program under the control of pdb, the Python debugger.
1374 This allows you to execute your program step by step, watch variables,
1374 This allows you to execute your program step by step, watch variables,
1375 etc. Internally, what IPython does is similar to calling:
1375 etc. Internally, what IPython does is similar to calling:
1376
1376
1377 pdb.run('execfile("YOURFILENAME")')
1377 pdb.run('execfile("YOURFILENAME")')
1378
1378
1379 with a breakpoint set on line 1 of your file. You can change the line
1379 with a breakpoint set on line 1 of your file. You can change the line
1380 number for this automatic breakpoint to be <N> by using the -bN option
1380 number for this automatic breakpoint to be <N> by using the -bN option
1381 (where N must be an integer). For example:
1381 (where N must be an integer). For example:
1382
1382
1383 %run -d -b40 myscript
1383 %run -d -b40 myscript
1384
1384
1385 will set the first breakpoint at line 40 in myscript.py. Note that
1385 will set the first breakpoint at line 40 in myscript.py. Note that
1386 the first breakpoint must be set on a line which actually does
1386 the first breakpoint must be set on a line which actually does
1387 something (not a comment or docstring) for it to stop execution.
1387 something (not a comment or docstring) for it to stop execution.
1388
1388
1389 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1389 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1390 first enter 'c' (without qoutes) to start execution up to the first
1390 first enter 'c' (without qoutes) to start execution up to the first
1391 breakpoint.
1391 breakpoint.
1392
1392
1393 Entering 'help' gives information about the use of the debugger. You
1393 Entering 'help' gives information about the use of the debugger. You
1394 can easily see pdb's full documentation with "import pdb;pdb.help()"
1394 can easily see pdb's full documentation with "import pdb;pdb.help()"
1395 at a prompt.
1395 at a prompt.
1396
1396
1397 -p: run program under the control of the Python profiler module (which
1397 -p: run program under the control of the Python profiler module (which
1398 prints a detailed report of execution times, function calls, etc).
1398 prints a detailed report of execution times, function calls, etc).
1399
1399
1400 You can pass other options after -p which affect the behavior of the
1400 You can pass other options after -p which affect the behavior of the
1401 profiler itself. See the docs for %prun for details.
1401 profiler itself. See the docs for %prun for details.
1402
1402
1403 In this mode, the program's variables do NOT propagate back to the
1403 In this mode, the program's variables do NOT propagate back to the
1404 IPython interactive namespace (because they remain in the namespace
1404 IPython interactive namespace (because they remain in the namespace
1405 where the profiler executes them).
1405 where the profiler executes them).
1406
1406
1407 Internally this triggers a call to %prun, see its documentation for
1407 Internally this triggers a call to %prun, see its documentation for
1408 details on the options available specifically for profiling."""
1408 details on the options available specifically for profiling."""
1409
1409
1410 # get arguments and set sys.argv for program to be run.
1410 # get arguments and set sys.argv for program to be run.
1411 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1411 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1412 mode='list',list_all=1)
1412 mode='list',list_all=1)
1413
1413
1414 try:
1414 try:
1415 filename = get_py_filename(arg_lst[0])
1415 filename = get_py_filename(arg_lst[0])
1416 except IndexError:
1416 except IndexError:
1417 warn('you must provide at least a filename.')
1417 warn('you must provide at least a filename.')
1418 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1418 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1419 return
1419 return
1420 except IOError,msg:
1420 except IOError,msg:
1421 error(msg)
1421 error(msg)
1422 return
1422 return
1423
1423
1424 # Control the response to exit() calls made by the script being run
1424 # Control the response to exit() calls made by the script being run
1425 exit_ignore = opts.has_key('e')
1425 exit_ignore = opts.has_key('e')
1426
1426
1427 # Make sure that the running script gets a proper sys.argv as if it
1427 # Make sure that the running script gets a proper sys.argv as if it
1428 # were run from a system shell.
1428 # were run from a system shell.
1429 save_argv = sys.argv # save it for later restoring
1429 save_argv = sys.argv # save it for later restoring
1430 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1430 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1431
1431
1432 if opts.has_key('i'):
1432 if opts.has_key('i'):
1433 prog_ns = self.shell.user_ns
1433 prog_ns = self.shell.user_ns
1434 __name__save = self.shell.user_ns['__name__']
1434 __name__save = self.shell.user_ns['__name__']
1435 prog_ns['__name__'] = '__main__'
1435 prog_ns['__name__'] = '__main__'
1436 else:
1436 else:
1437 if opts.has_key('n'):
1437 if opts.has_key('n'):
1438 name = os.path.splitext(os.path.basename(filename))[0]
1438 name = os.path.splitext(os.path.basename(filename))[0]
1439 else:
1439 else:
1440 name = '__main__'
1440 name = '__main__'
1441 prog_ns = {'__name__':name}
1441 prog_ns = {'__name__':name}
1442
1442
1443 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1443 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1444 # set the __file__ global in the script's namespace
1444 # set the __file__ global in the script's namespace
1445 prog_ns['__file__'] = filename
1445 prog_ns['__file__'] = filename
1446
1446
1447 # pickle fix. See iplib for an explanation. But we need to make sure
1447 # pickle fix. See iplib for an explanation. But we need to make sure
1448 # that, if we overwrite __main__, we replace it at the end
1448 # that, if we overwrite __main__, we replace it at the end
1449 if prog_ns['__name__'] == '__main__':
1449 if prog_ns['__name__'] == '__main__':
1450 restore_main = sys.modules['__main__']
1450 restore_main = sys.modules['__main__']
1451 else:
1451 else:
1452 restore_main = False
1452 restore_main = False
1453
1453
1454 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1454 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1455
1455
1456 stats = None
1456 stats = None
1457 try:
1457 try:
1458 if opts.has_key('p'):
1458 if opts.has_key('p'):
1459 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1459 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1460 else:
1460 else:
1461 if opts.has_key('d'):
1461 if opts.has_key('d'):
1462 deb = Debugger.Pdb(self.shell.rc.colors)
1462 deb = Debugger.Pdb(self.shell.rc.colors)
1463 # reset Breakpoint state, which is moronically kept
1463 # reset Breakpoint state, which is moronically kept
1464 # in a class
1464 # in a class
1465 bdb.Breakpoint.next = 1
1465 bdb.Breakpoint.next = 1
1466 bdb.Breakpoint.bplist = {}
1466 bdb.Breakpoint.bplist = {}
1467 bdb.Breakpoint.bpbynumber = [None]
1467 bdb.Breakpoint.bpbynumber = [None]
1468 # Set an initial breakpoint to stop execution
1468 # Set an initial breakpoint to stop execution
1469 maxtries = 10
1469 maxtries = 10
1470 bp = int(opts.get('b',[1])[0])
1470 bp = int(opts.get('b',[1])[0])
1471 checkline = deb.checkline(filename,bp)
1471 checkline = deb.checkline(filename,bp)
1472 if not checkline:
1472 if not checkline:
1473 for bp in range(bp+1,bp+maxtries+1):
1473 for bp in range(bp+1,bp+maxtries+1):
1474 if deb.checkline(filename,bp):
1474 if deb.checkline(filename,bp):
1475 break
1475 break
1476 else:
1476 else:
1477 msg = ("\nI failed to find a valid line to set "
1477 msg = ("\nI failed to find a valid line to set "
1478 "a breakpoint\n"
1478 "a breakpoint\n"
1479 "after trying up to line: %s.\n"
1479 "after trying up to line: %s.\n"
1480 "Please set a valid breakpoint manually "
1480 "Please set a valid breakpoint manually "
1481 "with the -b option." % bp)
1481 "with the -b option." % bp)
1482 error(msg)
1482 error(msg)
1483 return
1483 return
1484 # if we find a good linenumber, set the breakpoint
1484 # if we find a good linenumber, set the breakpoint
1485 deb.do_break('%s:%s' % (filename,bp))
1485 deb.do_break('%s:%s' % (filename,bp))
1486 # Start file run
1486 # Start file run
1487 print "NOTE: Enter 'c' at the",
1487 print "NOTE: Enter 'c' at the",
1488 print "ipdb> prompt to start your script."
1488 print "ipdb> prompt to start your script."
1489 try:
1489 try:
1490 deb.run('execfile("%s")' % filename,prog_ns)
1490 deb.run('execfile("%s")' % filename,prog_ns)
1491 except:
1491 except:
1492 etype, value, tb = sys.exc_info()
1492 etype, value, tb = sys.exc_info()
1493 # Skip three frames in the traceback: the %run one,
1493 # Skip three frames in the traceback: the %run one,
1494 # one inside bdb.py, and the command-line typed by the
1494 # one inside bdb.py, and the command-line typed by the
1495 # user (run by exec in pdb itself).
1495 # user (run by exec in pdb itself).
1496 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1496 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1497 else:
1497 else:
1498 if runner is None:
1498 if runner is None:
1499 runner = self.shell.safe_execfile
1499 runner = self.shell.safe_execfile
1500 if opts.has_key('t'):
1500 if opts.has_key('t'):
1501 try:
1501 try:
1502 nruns = int(opts['N'][0])
1502 nruns = int(opts['N'][0])
1503 if nruns < 1:
1503 if nruns < 1:
1504 error('Number of runs must be >=1')
1504 error('Number of runs must be >=1')
1505 return
1505 return
1506 except (KeyError):
1506 except (KeyError):
1507 nruns = 1
1507 nruns = 1
1508 if nruns == 1:
1508 if nruns == 1:
1509 t0 = clock2()
1509 t0 = clock2()
1510 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1510 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1511 t1 = clock2()
1511 t1 = clock2()
1512 t_usr = t1[0]-t0[0]
1512 t_usr = t1[0]-t0[0]
1513 t_sys = t1[1]-t1[1]
1513 t_sys = t1[1]-t1[1]
1514 print "\nIPython CPU timings (estimated):"
1514 print "\nIPython CPU timings (estimated):"
1515 print " User : %10s s." % t_usr
1515 print " User : %10s s." % t_usr
1516 print " System: %10s s." % t_sys
1516 print " System: %10s s." % t_sys
1517 else:
1517 else:
1518 runs = range(nruns)
1518 runs = range(nruns)
1519 t0 = clock2()
1519 t0 = clock2()
1520 for nr in runs:
1520 for nr in runs:
1521 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1521 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1522 t1 = clock2()
1522 t1 = clock2()
1523 t_usr = t1[0]-t0[0]
1523 t_usr = t1[0]-t0[0]
1524 t_sys = t1[1]-t1[1]
1524 t_sys = t1[1]-t1[1]
1525 print "\nIPython CPU timings (estimated):"
1525 print "\nIPython CPU timings (estimated):"
1526 print "Total runs performed:",nruns
1526 print "Total runs performed:",nruns
1527 print " Times : %10s %10s" % ('Total','Per run')
1527 print " Times : %10s %10s" % ('Total','Per run')
1528 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1528 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1529 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1529 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1530
1530
1531 else:
1531 else:
1532 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1532 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1533 if opts.has_key('i'):
1533 if opts.has_key('i'):
1534 self.shell.user_ns['__name__'] = __name__save
1534 self.shell.user_ns['__name__'] = __name__save
1535 else:
1535 else:
1536 # update IPython interactive namespace
1536 # update IPython interactive namespace
1537 del prog_ns['__name__']
1537 del prog_ns['__name__']
1538 self.shell.user_ns.update(prog_ns)
1538 self.shell.user_ns.update(prog_ns)
1539 finally:
1539 finally:
1540 sys.argv = save_argv
1540 sys.argv = save_argv
1541 if restore_main:
1541 if restore_main:
1542 sys.modules['__main__'] = restore_main
1542 sys.modules['__main__'] = restore_main
1543 return stats
1543 return stats
1544
1544
1545 def magic_runlog(self, parameter_s =''):
1545 def magic_runlog(self, parameter_s =''):
1546 """Run files as logs.
1546 """Run files as logs.
1547
1547
1548 Usage:\\
1548 Usage:\\
1549 %runlog file1 file2 ...
1549 %runlog file1 file2 ...
1550
1550
1551 Run the named files (treating them as log files) in sequence inside
1551 Run the named files (treating them as log files) in sequence inside
1552 the interpreter, and return to the prompt. This is much slower than
1552 the interpreter, and return to the prompt. This is much slower than
1553 %run because each line is executed in a try/except block, but it
1553 %run because each line is executed in a try/except block, but it
1554 allows running files with syntax errors in them.
1554 allows running files with syntax errors in them.
1555
1555
1556 Normally IPython will guess when a file is one of its own logfiles, so
1556 Normally IPython will guess when a file is one of its own logfiles, so
1557 you can typically use %run even for logs. This shorthand allows you to
1557 you can typically use %run even for logs. This shorthand allows you to
1558 force any file to be treated as a log file."""
1558 force any file to be treated as a log file."""
1559
1559
1560 for f in parameter_s.split():
1560 for f in parameter_s.split():
1561 self.shell.safe_execfile(f,self.shell.user_ns,
1561 self.shell.safe_execfile(f,self.shell.user_ns,
1562 self.shell.user_ns,islog=1)
1562 self.shell.user_ns,islog=1)
1563
1563
1564 def magic_timeit(self, parameter_s =''):
1564 def magic_timeit(self, parameter_s =''):
1565 """Time execution of a Python statement or expression
1565 """Time execution of a Python statement or expression
1566
1566
1567 Usage:\\
1567 Usage:\\
1568 %timeit [-n<N> -r<R> [-t|-c]] statement
1568 %timeit [-n<N> -r<R> [-t|-c]] statement
1569
1569
1570 Time execution of a Python statement or expression using the timeit
1570 Time execution of a Python statement or expression using the timeit
1571 module.
1571 module.
1572
1572
1573 Options:
1573 Options:
1574 -n<N>: execute the given statement <N> times in a loop. If this value
1574 -n<N>: execute the given statement <N> times in a loop. If this value
1575 is not given, a fitting value is chosen.
1575 is not given, a fitting value is chosen.
1576
1576
1577 -r<R>: repeat the loop iteration <R> times and take the best result.
1577 -r<R>: repeat the loop iteration <R> times and take the best result.
1578 Default: 3
1578 Default: 3
1579
1579
1580 -t: use time.time to measure the time, which is the default on Unix.
1580 -t: use time.time to measure the time, which is the default on Unix.
1581 This function measures wall time.
1581 This function measures wall time.
1582
1582
1583 -c: use time.clock to measure the time, which is the default on
1583 -c: use time.clock to measure the time, which is the default on
1584 Windows and measures wall time. On Unix, resource.getrusage is used
1584 Windows and measures wall time. On Unix, resource.getrusage is used
1585 instead and returns the CPU user time.
1585 instead and returns the CPU user time.
1586
1586
1587 -p<P>: use a precision of <P> digits to display the timing result.
1587 -p<P>: use a precision of <P> digits to display the timing result.
1588 Default: 3
1588 Default: 3
1589
1589
1590
1590
1591 Examples:\\
1591 Examples:\\
1592 In [1]: %timeit pass
1592 In [1]: %timeit pass
1593 10000000 loops, best of 3: 53.3 ns per loop
1593 10000000 loops, best of 3: 53.3 ns per loop
1594
1594
1595 In [2]: u = None
1595 In [2]: u = None
1596
1596
1597 In [3]: %timeit u is None
1597 In [3]: %timeit u is None
1598 10000000 loops, best of 3: 184 ns per loop
1598 10000000 loops, best of 3: 184 ns per loop
1599
1599
1600 In [4]: %timeit -r 4 u == None
1600 In [4]: %timeit -r 4 u == None
1601 1000000 loops, best of 4: 242 ns per loop
1601 1000000 loops, best of 4: 242 ns per loop
1602
1602
1603 In [5]: import time
1603 In [5]: import time
1604
1604
1605 In [6]: %timeit -n1 time.sleep(2)
1605 In [6]: %timeit -n1 time.sleep(2)
1606 1 loops, best of 3: 2 s per loop
1606 1 loops, best of 3: 2 s per loop
1607
1607
1608
1608
1609 The times reported by %timeit will be slightly higher than those reported
1609 The times reported by %timeit will be slightly higher than those reported
1610 by the timeit.py script when variables are accessed. This is due to the
1610 by the timeit.py script when variables are accessed. This is due to the
1611 fact that %timeit executes the statement in the namespace of the shell,
1611 fact that %timeit executes the statement in the namespace of the shell,
1612 compared with timeit.py, which uses a single setup statement to import
1612 compared with timeit.py, which uses a single setup statement to import
1613 function or create variables. Generally, the bias does not matter as long
1613 function or create variables. Generally, the bias does not matter as long
1614 as results from timeit.py are not mixed with those from %timeit."""
1614 as results from timeit.py are not mixed with those from %timeit."""
1615 import timeit
1615 import timeit
1616 import math
1616 import math
1617
1617
1618 units = ["s", "ms", "\xc2\xb5s", "ns"]
1618 units = ["s", "ms", "\xc2\xb5s", "ns"]
1619 scaling = [1, 1e3, 1e6, 1e9]
1619 scaling = [1, 1e3, 1e6, 1e9]
1620
1620
1621 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:')
1621 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:')
1622 if stmt == "":
1622 if stmt == "":
1623 return
1623 return
1624 timefunc = timeit.default_timer
1624 timefunc = timeit.default_timer
1625 number = int(getattr(opts, "n", 0))
1625 number = int(getattr(opts, "n", 0))
1626 repeat = int(getattr(opts, "r", timeit.default_repeat))
1626 repeat = int(getattr(opts, "r", timeit.default_repeat))
1627 precision = int(getattr(opts, "p", 3))
1627 precision = int(getattr(opts, "p", 3))
1628 if hasattr(opts, "t"):
1628 if hasattr(opts, "t"):
1629 timefunc = time.time
1629 timefunc = time.time
1630 if hasattr(opts, "c"):
1630 if hasattr(opts, "c"):
1631 timefunc = clock
1631 timefunc = clock
1632
1632
1633 timer = timeit.Timer(timer=timefunc)
1633 timer = timeit.Timer(timer=timefunc)
1634 # this code has tight coupling to the inner workings of timeit.Timer,
1634 # this code has tight coupling to the inner workings of timeit.Timer,
1635 # but is there a better way to achieve that the code stmt has access
1635 # but is there a better way to achieve that the code stmt has access
1636 # to the shell namespace?
1636 # to the shell namespace?
1637
1637
1638 src = timeit.template % {'stmt': timeit.reindent(stmt, 8), 'setup': "pass"}
1638 src = timeit.template % {'stmt': timeit.reindent(stmt, 8), 'setup': "pass"}
1639 code = compile(src, "<magic-timeit>", "exec")
1639 code = compile(src, "<magic-timeit>", "exec")
1640 ns = {}
1640 ns = {}
1641 exec code in self.shell.user_ns, ns
1641 exec code in self.shell.user_ns, ns
1642 timer.inner = ns["inner"]
1642 timer.inner = ns["inner"]
1643
1643
1644 if number == 0:
1644 if number == 0:
1645 # determine number so that 0.2 <= total time < 2.0
1645 # determine number so that 0.2 <= total time < 2.0
1646 number = 1
1646 number = 1
1647 for i in range(1, 10):
1647 for i in range(1, 10):
1648 number *= 10
1648 number *= 10
1649 if timer.timeit(number) >= 0.2:
1649 if timer.timeit(number) >= 0.2:
1650 break
1650 break
1651
1651
1652 best = min(timer.repeat(repeat, number)) / number
1652 best = min(timer.repeat(repeat, number)) / number
1653
1653
1654 if best > 0.0:
1654 if best > 0.0:
1655 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1655 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1656 else:
1656 else:
1657 order = 3
1657 order = 3
1658 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1658 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1659 precision,
1659 precision,
1660 best * scaling[order],
1660 best * scaling[order],
1661 units[order])
1661 units[order])
1662
1662
1663 def magic_time(self,parameter_s = ''):
1663 def magic_time(self,parameter_s = ''):
1664 """Time execution of a Python statement or expression.
1664 """Time execution of a Python statement or expression.
1665
1665
1666 The CPU and wall clock times are printed, and the value of the
1666 The CPU and wall clock times are printed, and the value of the
1667 expression (if any) is returned. Note that under Win32, system time
1667 expression (if any) is returned. Note that under Win32, system time
1668 is always reported as 0, since it can not be measured.
1668 is always reported as 0, since it can not be measured.
1669
1669
1670 This function provides very basic timing functionality. In Python
1670 This function provides very basic timing functionality. In Python
1671 2.3, the timeit module offers more control and sophistication, so this
1671 2.3, the timeit module offers more control and sophistication, so this
1672 could be rewritten to use it (patches welcome).
1672 could be rewritten to use it (patches welcome).
1673
1673
1674 Some examples:
1674 Some examples:
1675
1675
1676 In [1]: time 2**128
1676 In [1]: time 2**128
1677 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1677 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1678 Wall time: 0.00
1678 Wall time: 0.00
1679 Out[1]: 340282366920938463463374607431768211456L
1679 Out[1]: 340282366920938463463374607431768211456L
1680
1680
1681 In [2]: n = 1000000
1681 In [2]: n = 1000000
1682
1682
1683 In [3]: time sum(range(n))
1683 In [3]: time sum(range(n))
1684 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1684 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1685 Wall time: 1.37
1685 Wall time: 1.37
1686 Out[3]: 499999500000L
1686 Out[3]: 499999500000L
1687
1687
1688 In [4]: time print 'hello world'
1688 In [4]: time print 'hello world'
1689 hello world
1689 hello world
1690 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1690 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1691 Wall time: 0.00
1691 Wall time: 0.00
1692 """
1692 """
1693
1693
1694 # fail immediately if the given expression can't be compiled
1694 # fail immediately if the given expression can't be compiled
1695 try:
1695 try:
1696 mode = 'eval'
1696 mode = 'eval'
1697 code = compile(parameter_s,'<timed eval>',mode)
1697 code = compile(parameter_s,'<timed eval>',mode)
1698 except SyntaxError:
1698 except SyntaxError:
1699 mode = 'exec'
1699 mode = 'exec'
1700 code = compile(parameter_s,'<timed exec>',mode)
1700 code = compile(parameter_s,'<timed exec>',mode)
1701 # skew measurement as little as possible
1701 # skew measurement as little as possible
1702 glob = self.shell.user_ns
1702 glob = self.shell.user_ns
1703 clk = clock2
1703 clk = clock2
1704 wtime = time.time
1704 wtime = time.time
1705 # time execution
1705 # time execution
1706 wall_st = wtime()
1706 wall_st = wtime()
1707 if mode=='eval':
1707 if mode=='eval':
1708 st = clk()
1708 st = clk()
1709 out = eval(code,glob)
1709 out = eval(code,glob)
1710 end = clk()
1710 end = clk()
1711 else:
1711 else:
1712 st = clk()
1712 st = clk()
1713 exec code in glob
1713 exec code in glob
1714 end = clk()
1714 end = clk()
1715 out = None
1715 out = None
1716 wall_end = wtime()
1716 wall_end = wtime()
1717 # Compute actual times and report
1717 # Compute actual times and report
1718 wall_time = wall_end-wall_st
1718 wall_time = wall_end-wall_st
1719 cpu_user = end[0]-st[0]
1719 cpu_user = end[0]-st[0]
1720 cpu_sys = end[1]-st[1]
1720 cpu_sys = end[1]-st[1]
1721 cpu_tot = cpu_user+cpu_sys
1721 cpu_tot = cpu_user+cpu_sys
1722 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1722 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1723 (cpu_user,cpu_sys,cpu_tot)
1723 (cpu_user,cpu_sys,cpu_tot)
1724 print "Wall time: %.2f" % wall_time
1724 print "Wall time: %.2f" % wall_time
1725 return out
1725 return out
1726
1726
1727 def magic_macro(self,parameter_s = ''):
1727 def magic_macro(self,parameter_s = ''):
1728 """Define a set of input lines as a macro for future re-execution.
1728 """Define a set of input lines as a macro for future re-execution.
1729
1729
1730 Usage:\\
1730 Usage:\\
1731 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1731 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1732
1732
1733 Options:
1733 Options:
1734
1734
1735 -r: use 'raw' input. By default, the 'processed' history is used,
1735 -r: use 'raw' input. By default, the 'processed' history is used,
1736 so that magics are loaded in their transformed version to valid
1736 so that magics are loaded in their transformed version to valid
1737 Python. If this option is given, the raw input as typed as the
1737 Python. If this option is given, the raw input as typed as the
1738 command line is used instead.
1738 command line is used instead.
1739
1739
1740 This will define a global variable called `name` which is a string
1740 This will define a global variable called `name` which is a string
1741 made of joining the slices and lines you specify (n1,n2,... numbers
1741 made of joining the slices and lines you specify (n1,n2,... numbers
1742 above) from your input history into a single string. This variable
1742 above) from your input history into a single string. This variable
1743 acts like an automatic function which re-executes those lines as if
1743 acts like an automatic function which re-executes those lines as if
1744 you had typed them. You just type 'name' at the prompt and the code
1744 you had typed them. You just type 'name' at the prompt and the code
1745 executes.
1745 executes.
1746
1746
1747 The notation for indicating number ranges is: n1-n2 means 'use line
1747 The notation for indicating number ranges is: n1-n2 means 'use line
1748 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1748 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1749 using the lines numbered 5,6 and 7.
1749 using the lines numbered 5,6 and 7.
1750
1750
1751 Note: as a 'hidden' feature, you can also use traditional python slice
1751 Note: as a 'hidden' feature, you can also use traditional python slice
1752 notation, where N:M means numbers N through M-1.
1752 notation, where N:M means numbers N through M-1.
1753
1753
1754 For example, if your history contains (%hist prints it):
1754 For example, if your history contains (%hist prints it):
1755
1755
1756 44: x=1\\
1756 44: x=1\\
1757 45: y=3\\
1757 45: y=3\\
1758 46: z=x+y\\
1758 46: z=x+y\\
1759 47: print x\\
1759 47: print x\\
1760 48: a=5\\
1760 48: a=5\\
1761 49: print 'x',x,'y',y\\
1761 49: print 'x',x,'y',y\\
1762
1762
1763 you can create a macro with lines 44 through 47 (included) and line 49
1763 you can create a macro with lines 44 through 47 (included) and line 49
1764 called my_macro with:
1764 called my_macro with:
1765
1765
1766 In [51]: %macro my_macro 44-47 49
1766 In [51]: %macro my_macro 44-47 49
1767
1767
1768 Now, typing `my_macro` (without quotes) will re-execute all this code
1768 Now, typing `my_macro` (without quotes) will re-execute all this code
1769 in one pass.
1769 in one pass.
1770
1770
1771 You don't need to give the line-numbers in order, and any given line
1771 You don't need to give the line-numbers in order, and any given line
1772 number can appear multiple times. You can assemble macros with any
1772 number can appear multiple times. You can assemble macros with any
1773 lines from your input history in any order.
1773 lines from your input history in any order.
1774
1774
1775 The macro is a simple object which holds its value in an attribute,
1775 The macro is a simple object which holds its value in an attribute,
1776 but IPython's display system checks for macros and executes them as
1776 but IPython's display system checks for macros and executes them as
1777 code instead of printing them when you type their name.
1777 code instead of printing them when you type their name.
1778
1778
1779 You can view a macro's contents by explicitly printing it with:
1779 You can view a macro's contents by explicitly printing it with:
1780
1780
1781 'print macro_name'.
1781 'print macro_name'.
1782
1782
1783 For one-off cases which DON'T contain magic function calls in them you
1783 For one-off cases which DON'T contain magic function calls in them you
1784 can obtain similar results by explicitly executing slices from your
1784 can obtain similar results by explicitly executing slices from your
1785 input history with:
1785 input history with:
1786
1786
1787 In [60]: exec In[44:48]+In[49]"""
1787 In [60]: exec In[44:48]+In[49]"""
1788
1788
1789 opts,args = self.parse_options(parameter_s,'r',mode='list')
1789 opts,args = self.parse_options(parameter_s,'r',mode='list')
1790 name,ranges = args[0], args[1:]
1790 name,ranges = args[0], args[1:]
1791 #print 'rng',ranges # dbg
1791 #print 'rng',ranges # dbg
1792 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1792 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1793 macro = Macro(lines)
1793 macro = Macro(lines)
1794 self.shell.user_ns.update({name:macro})
1794 self.shell.user_ns.update({name:macro})
1795 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1795 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1796 print 'Macro contents:'
1796 print 'Macro contents:'
1797 print macro,
1797 print macro,
1798
1798
1799 def magic_save(self,parameter_s = ''):
1799 def magic_save(self,parameter_s = ''):
1800 """Save a set of lines to a given filename.
1800 """Save a set of lines to a given filename.
1801
1801
1802 Usage:\\
1802 Usage:\\
1803 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1803 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1804
1804
1805 Options:
1805 Options:
1806
1806
1807 -r: use 'raw' input. By default, the 'processed' history is used,
1807 -r: use 'raw' input. By default, the 'processed' history is used,
1808 so that magics are loaded in their transformed version to valid
1808 so that magics are loaded in their transformed version to valid
1809 Python. If this option is given, the raw input as typed as the
1809 Python. If this option is given, the raw input as typed as the
1810 command line is used instead.
1810 command line is used instead.
1811
1811
1812 This function uses the same syntax as %macro for line extraction, but
1812 This function uses the same syntax as %macro for line extraction, but
1813 instead of creating a macro it saves the resulting string to the
1813 instead of creating a macro it saves the resulting string to the
1814 filename you specify.
1814 filename you specify.
1815
1815
1816 It adds a '.py' extension to the file if you don't do so yourself, and
1816 It adds a '.py' extension to the file if you don't do so yourself, and
1817 it asks for confirmation before overwriting existing files."""
1817 it asks for confirmation before overwriting existing files."""
1818
1818
1819 opts,args = self.parse_options(parameter_s,'r',mode='list')
1819 opts,args = self.parse_options(parameter_s,'r',mode='list')
1820 fname,ranges = args[0], args[1:]
1820 fname,ranges = args[0], args[1:]
1821 if not fname.endswith('.py'):
1821 if not fname.endswith('.py'):
1822 fname += '.py'
1822 fname += '.py'
1823 if os.path.isfile(fname):
1823 if os.path.isfile(fname):
1824 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1824 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1825 if ans.lower() not in ['y','yes']:
1825 if ans.lower() not in ['y','yes']:
1826 print 'Operation cancelled.'
1826 print 'Operation cancelled.'
1827 return
1827 return
1828 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1828 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1829 f = file(fname,'w')
1829 f = file(fname,'w')
1830 f.write(cmds)
1830 f.write(cmds)
1831 f.close()
1831 f.close()
1832 print 'The following commands were written to file `%s`:' % fname
1832 print 'The following commands were written to file `%s`:' % fname
1833 print cmds
1833 print cmds
1834
1834
1835 def _edit_macro(self,mname,macro):
1835 def _edit_macro(self,mname,macro):
1836 """open an editor with the macro data in a file"""
1836 """open an editor with the macro data in a file"""
1837 filename = self.shell.mktempfile(macro.value)
1837 filename = self.shell.mktempfile(macro.value)
1838 self.shell.hooks.editor(filename)
1838 self.shell.hooks.editor(filename)
1839
1839
1840 # and make a new macro object, to replace the old one
1840 # and make a new macro object, to replace the old one
1841 mfile = open(filename)
1841 mfile = open(filename)
1842 mvalue = mfile.read()
1842 mvalue = mfile.read()
1843 mfile.close()
1843 mfile.close()
1844 self.shell.user_ns[mname] = Macro(mvalue)
1844 self.shell.user_ns[mname] = Macro(mvalue)
1845
1845
1846 def magic_ed(self,parameter_s=''):
1846 def magic_ed(self,parameter_s=''):
1847 """Alias to %edit."""
1847 """Alias to %edit."""
1848 return self.magic_edit(parameter_s)
1848 return self.magic_edit(parameter_s)
1849
1849
1850 def magic_edit(self,parameter_s='',last_call=['','']):
1850 def magic_edit(self,parameter_s='',last_call=['','']):
1851 """Bring up an editor and execute the resulting code.
1851 """Bring up an editor and execute the resulting code.
1852
1852
1853 Usage:
1853 Usage:
1854 %edit [options] [args]
1854 %edit [options] [args]
1855
1855
1856 %edit runs IPython's editor hook. The default version of this hook is
1856 %edit runs IPython's editor hook. The default version of this hook is
1857 set to call the __IPYTHON__.rc.editor command. This is read from your
1857 set to call the __IPYTHON__.rc.editor command. This is read from your
1858 environment variable $EDITOR. If this isn't found, it will default to
1858 environment variable $EDITOR. If this isn't found, it will default to
1859 vi under Linux/Unix and to notepad under Windows. See the end of this
1859 vi under Linux/Unix and to notepad under Windows. See the end of this
1860 docstring for how to change the editor hook.
1860 docstring for how to change the editor hook.
1861
1861
1862 You can also set the value of this editor via the command line option
1862 You can also set the value of this editor via the command line option
1863 '-editor' or in your ipythonrc file. This is useful if you wish to use
1863 '-editor' or in your ipythonrc file. This is useful if you wish to use
1864 specifically for IPython an editor different from your typical default
1864 specifically for IPython an editor different from your typical default
1865 (and for Windows users who typically don't set environment variables).
1865 (and for Windows users who typically don't set environment variables).
1866
1866
1867 This command allows you to conveniently edit multi-line code right in
1867 This command allows you to conveniently edit multi-line code right in
1868 your IPython session.
1868 your IPython session.
1869
1869
1870 If called without arguments, %edit opens up an empty editor with a
1870 If called without arguments, %edit opens up an empty editor with a
1871 temporary file and will execute the contents of this file when you
1871 temporary file and will execute the contents of this file when you
1872 close it (don't forget to save it!).
1872 close it (don't forget to save it!).
1873
1873
1874
1874
1875 Options:
1875 Options:
1876
1876
1877 -n <number>: open the editor at a specified line number. By default,
1878 the IPython editor hook uses the unix syntax 'editor +N filename', but
1879 you can configure this by providing your own modified hook if your
1880 favorite editor supports line-number specifications with a different
1881 syntax.
1882
1877 -p: this will call the editor with the same data as the previous time
1883 -p: this will call the editor with the same data as the previous time
1878 it was used, regardless of how long ago (in your current session) it
1884 it was used, regardless of how long ago (in your current session) it
1879 was.
1885 was.
1880
1886
1881 -r: use 'raw' input. This option only applies to input taken from the
1887 -r: use 'raw' input. This option only applies to input taken from the
1882 user's history. By default, the 'processed' history is used, so that
1888 user's history. By default, the 'processed' history is used, so that
1883 magics are loaded in their transformed version to valid Python. If
1889 magics are loaded in their transformed version to valid Python. If
1884 this option is given, the raw input as typed as the command line is
1890 this option is given, the raw input as typed as the command line is
1885 used instead. When you exit the editor, it will be executed by
1891 used instead. When you exit the editor, it will be executed by
1886 IPython's own processor.
1892 IPython's own processor.
1887
1893
1888 -x: do not execute the edited code immediately upon exit. This is
1894 -x: do not execute the edited code immediately upon exit. This is
1889 mainly useful if you are editing programs which need to be called with
1895 mainly useful if you are editing programs which need to be called with
1890 command line arguments, which you can then do using %run.
1896 command line arguments, which you can then do using %run.
1891
1897
1892
1898
1893 Arguments:
1899 Arguments:
1894
1900
1895 If arguments are given, the following possibilites exist:
1901 If arguments are given, the following possibilites exist:
1896
1902
1897 - The arguments are numbers or pairs of colon-separated numbers (like
1903 - The arguments are numbers or pairs of colon-separated numbers (like
1898 1 4:8 9). These are interpreted as lines of previous input to be
1904 1 4:8 9). These are interpreted as lines of previous input to be
1899 loaded into the editor. The syntax is the same of the %macro command.
1905 loaded into the editor. The syntax is the same of the %macro command.
1900
1906
1901 - If the argument doesn't start with a number, it is evaluated as a
1907 - If the argument doesn't start with a number, it is evaluated as a
1902 variable and its contents loaded into the editor. You can thus edit
1908 variable and its contents loaded into the editor. You can thus edit
1903 any string which contains python code (including the result of
1909 any string which contains python code (including the result of
1904 previous edits).
1910 previous edits).
1905
1911
1906 - If the argument is the name of an object (other than a string),
1912 - If the argument is the name of an object (other than a string),
1907 IPython will try to locate the file where it was defined and open the
1913 IPython will try to locate the file where it was defined and open the
1908 editor at the point where it is defined. You can use `%edit function`
1914 editor at the point where it is defined. You can use `%edit function`
1909 to load an editor exactly at the point where 'function' is defined,
1915 to load an editor exactly at the point where 'function' is defined,
1910 edit it and have the file be executed automatically.
1916 edit it and have the file be executed automatically.
1911
1917
1912 If the object is a macro (see %macro for details), this opens up your
1918 If the object is a macro (see %macro for details), this opens up your
1913 specified editor with a temporary file containing the macro's data.
1919 specified editor with a temporary file containing the macro's data.
1914 Upon exit, the macro is reloaded with the contents of the file.
1920 Upon exit, the macro is reloaded with the contents of the file.
1915
1921
1916 Note: opening at an exact line is only supported under Unix, and some
1922 Note: opening at an exact line is only supported under Unix, and some
1917 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1923 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1918 '+NUMBER' parameter necessary for this feature. Good editors like
1924 '+NUMBER' parameter necessary for this feature. Good editors like
1919 (X)Emacs, vi, jed, pico and joe all do.
1925 (X)Emacs, vi, jed, pico and joe all do.
1920
1926
1921 - If the argument is not found as a variable, IPython will look for a
1927 - If the argument is not found as a variable, IPython will look for a
1922 file with that name (adding .py if necessary) and load it into the
1928 file with that name (adding .py if necessary) and load it into the
1923 editor. It will execute its contents with execfile() when you exit,
1929 editor. It will execute its contents with execfile() when you exit,
1924 loading any code in the file into your interactive namespace.
1930 loading any code in the file into your interactive namespace.
1925
1931
1926 After executing your code, %edit will return as output the code you
1932 After executing your code, %edit will return as output the code you
1927 typed in the editor (except when it was an existing file). This way
1933 typed in the editor (except when it was an existing file). This way
1928 you can reload the code in further invocations of %edit as a variable,
1934 you can reload the code in further invocations of %edit as a variable,
1929 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1935 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1930 the output.
1936 the output.
1931
1937
1932 Note that %edit is also available through the alias %ed.
1938 Note that %edit is also available through the alias %ed.
1933
1939
1934 This is an example of creating a simple function inside the editor and
1940 This is an example of creating a simple function inside the editor and
1935 then modifying it. First, start up the editor:
1941 then modifying it. First, start up the editor:
1936
1942
1937 In [1]: ed\\
1943 In [1]: ed\\
1938 Editing... done. Executing edited code...\\
1944 Editing... done. Executing edited code...\\
1939 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1945 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1940
1946
1941 We can then call the function foo():
1947 We can then call the function foo():
1942
1948
1943 In [2]: foo()\\
1949 In [2]: foo()\\
1944 foo() was defined in an editing session
1950 foo() was defined in an editing session
1945
1951
1946 Now we edit foo. IPython automatically loads the editor with the
1952 Now we edit foo. IPython automatically loads the editor with the
1947 (temporary) file where foo() was previously defined:
1953 (temporary) file where foo() was previously defined:
1948
1954
1949 In [3]: ed foo\\
1955 In [3]: ed foo\\
1950 Editing... done. Executing edited code...
1956 Editing... done. Executing edited code...
1951
1957
1952 And if we call foo() again we get the modified version:
1958 And if we call foo() again we get the modified version:
1953
1959
1954 In [4]: foo()\\
1960 In [4]: foo()\\
1955 foo() has now been changed!
1961 foo() has now been changed!
1956
1962
1957 Here is an example of how to edit a code snippet successive
1963 Here is an example of how to edit a code snippet successive
1958 times. First we call the editor:
1964 times. First we call the editor:
1959
1965
1960 In [8]: ed\\
1966 In [8]: ed\\
1961 Editing... done. Executing edited code...\\
1967 Editing... done. Executing edited code...\\
1962 hello\\
1968 hello\\
1963 Out[8]: "print 'hello'\\n"
1969 Out[8]: "print 'hello'\\n"
1964
1970
1965 Now we call it again with the previous output (stored in _):
1971 Now we call it again with the previous output (stored in _):
1966
1972
1967 In [9]: ed _\\
1973 In [9]: ed _\\
1968 Editing... done. Executing edited code...\\
1974 Editing... done. Executing edited code...\\
1969 hello world\\
1975 hello world\\
1970 Out[9]: "print 'hello world'\\n"
1976 Out[9]: "print 'hello world'\\n"
1971
1977
1972 Now we call it with the output #8 (stored in _8, also as Out[8]):
1978 Now we call it with the output #8 (stored in _8, also as Out[8]):
1973
1979
1974 In [10]: ed _8\\
1980 In [10]: ed _8\\
1975 Editing... done. Executing edited code...\\
1981 Editing... done. Executing edited code...\\
1976 hello again\\
1982 hello again\\
1977 Out[10]: "print 'hello again'\\n"
1983 Out[10]: "print 'hello again'\\n"
1978
1984
1979
1985
1980 Changing the default editor hook:
1986 Changing the default editor hook:
1981
1987
1982 If you wish to write your own editor hook, you can put it in a
1988 If you wish to write your own editor hook, you can put it in a
1983 configuration file which you load at startup time. The default hook
1989 configuration file which you load at startup time. The default hook
1984 is defined in the IPython.hooks module, and you can use that as a
1990 is defined in the IPython.hooks module, and you can use that as a
1985 starting example for further modifications. That file also has
1991 starting example for further modifications. That file also has
1986 general instructions on how to set a new hook for use once you've
1992 general instructions on how to set a new hook for use once you've
1987 defined it."""
1993 defined it."""
1988
1994
1989 # FIXME: This function has become a convoluted mess. It needs a
1995 # FIXME: This function has become a convoluted mess. It needs a
1990 # ground-up rewrite with clean, simple logic.
1996 # ground-up rewrite with clean, simple logic.
1991
1997
1992 def make_filename(arg):
1998 def make_filename(arg):
1993 "Make a filename from the given args"
1999 "Make a filename from the given args"
1994 try:
2000 try:
1995 filename = get_py_filename(arg)
2001 filename = get_py_filename(arg)
1996 except IOError:
2002 except IOError:
1997 if args.endswith('.py'):
2003 if args.endswith('.py'):
1998 filename = arg
2004 filename = arg
1999 else:
2005 else:
2000 filename = None
2006 filename = None
2001 return filename
2007 return filename
2002
2008
2003 # custom exceptions
2009 # custom exceptions
2004 class DataIsObject(Exception): pass
2010 class DataIsObject(Exception): pass
2005
2011
2006 opts,args = self.parse_options(parameter_s,'prxn=i')
2012 opts,args = self.parse_options(parameter_s,'prxn:')
2007
2008 print 'opt.n: <%r>' % opts.n # dbg
2009
2010 # Set a few locals from the options for convenience:
2013 # Set a few locals from the options for convenience:
2011 opts_p = opts.has_key('p')
2014 opts_p = opts.has_key('p')
2012 opts_r = opts.has_key('r')
2015 opts_r = opts.has_key('r')
2013
2016
2014 # Default line number value
2017 # Default line number value
2015 lineno = None
2018 lineno = opts.get('n',None)
2019
2016 if opts_p:
2020 if opts_p:
2017 args = '_%s' % last_call[0]
2021 args = '_%s' % last_call[0]
2018 if not self.shell.user_ns.has_key(args):
2022 if not self.shell.user_ns.has_key(args):
2019 args = last_call[1]
2023 args = last_call[1]
2020
2024
2021 # use last_call to remember the state of the previous call, but don't
2025 # use last_call to remember the state of the previous call, but don't
2022 # let it be clobbered by successive '-p' calls.
2026 # let it be clobbered by successive '-p' calls.
2023 try:
2027 try:
2024 last_call[0] = self.shell.outputcache.prompt_count
2028 last_call[0] = self.shell.outputcache.prompt_count
2025 if not opts_p:
2029 if not opts_p:
2026 last_call[1] = parameter_s
2030 last_call[1] = parameter_s
2027 except:
2031 except:
2028 pass
2032 pass
2029
2033
2030 # by default this is done with temp files, except when the given
2034 # by default this is done with temp files, except when the given
2031 # arg is a filename
2035 # arg is a filename
2032 use_temp = 1
2036 use_temp = 1
2033
2037
2034 if re.match(r'\d',args):
2038 if re.match(r'\d',args):
2035 # Mode where user specifies ranges of lines, like in %macro.
2039 # Mode where user specifies ranges of lines, like in %macro.
2036 # This means that you can't edit files whose names begin with
2040 # This means that you can't edit files whose names begin with
2037 # numbers this way. Tough.
2041 # numbers this way. Tough.
2038 ranges = args.split()
2042 ranges = args.split()
2039 data = ''.join(self.extract_input_slices(ranges,opts_r))
2043 data = ''.join(self.extract_input_slices(ranges,opts_r))
2040 elif args.endswith('.py'):
2044 elif args.endswith('.py'):
2041 filename = make_filename(args)
2045 filename = make_filename(args)
2042 data = ''
2046 data = ''
2043 use_temp = 0
2047 use_temp = 0
2044 elif args:
2048 elif args:
2045 try:
2049 try:
2046 # Load the parameter given as a variable. If not a string,
2050 # Load the parameter given as a variable. If not a string,
2047 # process it as an object instead (below)
2051 # process it as an object instead (below)
2048
2052
2049 #print '*** args',args,'type',type(args) # dbg
2053 #print '*** args',args,'type',type(args) # dbg
2050 data = eval(args,self.shell.user_ns)
2054 data = eval(args,self.shell.user_ns)
2051 if not type(data) in StringTypes:
2055 if not type(data) in StringTypes:
2052 raise DataIsObject
2056 raise DataIsObject
2053
2057
2054 except (NameError,SyntaxError):
2058 except (NameError,SyntaxError):
2055 # given argument is not a variable, try as a filename
2059 # given argument is not a variable, try as a filename
2056 filename = make_filename(args)
2060 filename = make_filename(args)
2057 if filename is None:
2061 if filename is None:
2058 warn("Argument given (%s) can't be found as a variable "
2062 warn("Argument given (%s) can't be found as a variable "
2059 "or as a filename." % args)
2063 "or as a filename." % args)
2060 return
2064 return
2061
2065
2062 data = ''
2066 data = ''
2063 use_temp = 0
2067 use_temp = 0
2064 except DataIsObject:
2068 except DataIsObject:
2065
2069
2066 # macros have a special edit function
2070 # macros have a special edit function
2067 if isinstance(data,Macro):
2071 if isinstance(data,Macro):
2068 self._edit_macro(args,data)
2072 self._edit_macro(args,data)
2069 return
2073 return
2070
2074
2071 # For objects, try to edit the file where they are defined
2075 # For objects, try to edit the file where they are defined
2072 try:
2076 try:
2073 filename = inspect.getabsfile(data)
2077 filename = inspect.getabsfile(data)
2074 datafile = 1
2078 datafile = 1
2075 except TypeError:
2079 except TypeError:
2076 filename = make_filename(args)
2080 filename = make_filename(args)
2077 datafile = 1
2081 datafile = 1
2078 warn('Could not find file where `%s` is defined.\n'
2082 warn('Could not find file where `%s` is defined.\n'
2079 'Opening a file named `%s`' % (args,filename))
2083 'Opening a file named `%s`' % (args,filename))
2080 # Now, make sure we can actually read the source (if it was in
2084 # Now, make sure we can actually read the source (if it was in
2081 # a temp file it's gone by now).
2085 # a temp file it's gone by now).
2082 if datafile:
2086 if datafile:
2083 try:
2087 try:
2084 lineno = inspect.getsourcelines(data)[1]
2088 if lineno is None:
2089 lineno = inspect.getsourcelines(data)[1]
2085 except IOError:
2090 except IOError:
2086 filename = make_filename(args)
2091 filename = make_filename(args)
2087 if filename is None:
2092 if filename is None:
2088 warn('The file `%s` where `%s` was defined cannot '
2093 warn('The file `%s` where `%s` was defined cannot '
2089 'be read.' % (filename,data))
2094 'be read.' % (filename,data))
2090 return
2095 return
2091 use_temp = 0
2096 use_temp = 0
2092 else:
2097 else:
2093 data = ''
2098 data = ''
2094
2099
2095 if use_temp:
2100 if use_temp:
2096 filename = self.shell.mktempfile(data)
2101 filename = self.shell.mktempfile(data)
2097 print 'IPython will make a temporary file named:',filename
2102 print 'IPython will make a temporary file named:',filename
2098
2103
2099 # do actual editing here
2104 # do actual editing here
2100 print 'Editing...',
2105 print 'Editing...',
2101 sys.stdout.flush()
2106 sys.stdout.flush()
2102 self.shell.hooks.editor(filename,lineno)
2107 self.shell.hooks.editor(filename,lineno)
2103 if opts.has_key('x'): # -x prevents actual execution
2108 if opts.has_key('x'): # -x prevents actual execution
2104 print
2109 print
2105 else:
2110 else:
2106 print 'done. Executing edited code...'
2111 print 'done. Executing edited code...'
2107 if opts_r:
2112 if opts_r:
2108 self.shell.runlines(file_read(filename))
2113 self.shell.runlines(file_read(filename))
2109 else:
2114 else:
2110 self.shell.safe_execfile(filename,self.shell.user_ns)
2115 self.shell.safe_execfile(filename,self.shell.user_ns)
2111 if use_temp:
2116 if use_temp:
2112 try:
2117 try:
2113 return open(filename).read()
2118 return open(filename).read()
2114 except IOError,msg:
2119 except IOError,msg:
2115 if msg.filename == filename:
2120 if msg.filename == filename:
2116 warn('File not found. Did you forget to save?')
2121 warn('File not found. Did you forget to save?')
2117 return
2122 return
2118 else:
2123 else:
2119 self.shell.showtraceback()
2124 self.shell.showtraceback()
2120
2125
2121 def magic_xmode(self,parameter_s = ''):
2126 def magic_xmode(self,parameter_s = ''):
2122 """Switch modes for the exception handlers.
2127 """Switch modes for the exception handlers.
2123
2128
2124 Valid modes: Plain, Context and Verbose.
2129 Valid modes: Plain, Context and Verbose.
2125
2130
2126 If called without arguments, acts as a toggle."""
2131 If called without arguments, acts as a toggle."""
2127
2132
2128 def xmode_switch_err(name):
2133 def xmode_switch_err(name):
2129 warn('Error changing %s exception modes.\n%s' %
2134 warn('Error changing %s exception modes.\n%s' %
2130 (name,sys.exc_info()[1]))
2135 (name,sys.exc_info()[1]))
2131
2136
2132 shell = self.shell
2137 shell = self.shell
2133 new_mode = parameter_s.strip().capitalize()
2138 new_mode = parameter_s.strip().capitalize()
2134 try:
2139 try:
2135 shell.InteractiveTB.set_mode(mode=new_mode)
2140 shell.InteractiveTB.set_mode(mode=new_mode)
2136 print 'Exception reporting mode:',shell.InteractiveTB.mode
2141 print 'Exception reporting mode:',shell.InteractiveTB.mode
2137 except:
2142 except:
2138 xmode_switch_err('user')
2143 xmode_switch_err('user')
2139
2144
2140 # threaded shells use a special handler in sys.excepthook
2145 # threaded shells use a special handler in sys.excepthook
2141 if shell.isthreaded:
2146 if shell.isthreaded:
2142 try:
2147 try:
2143 shell.sys_excepthook.set_mode(mode=new_mode)
2148 shell.sys_excepthook.set_mode(mode=new_mode)
2144 except:
2149 except:
2145 xmode_switch_err('threaded')
2150 xmode_switch_err('threaded')
2146
2151
2147 def magic_colors(self,parameter_s = ''):
2152 def magic_colors(self,parameter_s = ''):
2148 """Switch color scheme for prompts, info system and exception handlers.
2153 """Switch color scheme for prompts, info system and exception handlers.
2149
2154
2150 Currently implemented schemes: NoColor, Linux, LightBG.
2155 Currently implemented schemes: NoColor, Linux, LightBG.
2151
2156
2152 Color scheme names are not case-sensitive."""
2157 Color scheme names are not case-sensitive."""
2153
2158
2154 def color_switch_err(name):
2159 def color_switch_err(name):
2155 warn('Error changing %s color schemes.\n%s' %
2160 warn('Error changing %s color schemes.\n%s' %
2156 (name,sys.exc_info()[1]))
2161 (name,sys.exc_info()[1]))
2157
2162
2158
2163
2159 new_scheme = parameter_s.strip()
2164 new_scheme = parameter_s.strip()
2160 if not new_scheme:
2165 if not new_scheme:
2161 print 'You must specify a color scheme.'
2166 print 'You must specify a color scheme.'
2162 return
2167 return
2163 import IPython.rlineimpl as readline
2168 import IPython.rlineimpl as readline
2164 if not readline.have_readline:
2169 if not readline.have_readline:
2165 msg = """\
2170 msg = """\
2166 Proper color support under MS Windows requires Gary Bishop's readline library.
2171 Proper color support under MS Windows requires Gary Bishop's readline library.
2167 You can find it at:
2172 You can find it at:
2168 http://sourceforge.net/projects/uncpythontools
2173 http://sourceforge.net/projects/uncpythontools
2169 Gary's readline needs the ctypes module, from:
2174 Gary's readline needs the ctypes module, from:
2170 http://starship.python.net/crew/theller/ctypes
2175 http://starship.python.net/crew/theller/ctypes
2171
2176
2172 Defaulting color scheme to 'NoColor'"""
2177 Defaulting color scheme to 'NoColor'"""
2173 new_scheme = 'NoColor'
2178 new_scheme = 'NoColor'
2174 warn(msg)
2179 warn(msg)
2175 # local shortcut
2180 # local shortcut
2176 shell = self.shell
2181 shell = self.shell
2177
2182
2178 # Set prompt colors
2183 # Set prompt colors
2179 try:
2184 try:
2180 shell.outputcache.set_colors(new_scheme)
2185 shell.outputcache.set_colors(new_scheme)
2181 except:
2186 except:
2182 color_switch_err('prompt')
2187 color_switch_err('prompt')
2183 else:
2188 else:
2184 shell.rc.colors = \
2189 shell.rc.colors = \
2185 shell.outputcache.color_table.active_scheme_name
2190 shell.outputcache.color_table.active_scheme_name
2186 # Set exception colors
2191 # Set exception colors
2187 try:
2192 try:
2188 shell.InteractiveTB.set_colors(scheme = new_scheme)
2193 shell.InteractiveTB.set_colors(scheme = new_scheme)
2189 shell.SyntaxTB.set_colors(scheme = new_scheme)
2194 shell.SyntaxTB.set_colors(scheme = new_scheme)
2190 except:
2195 except:
2191 color_switch_err('exception')
2196 color_switch_err('exception')
2192
2197
2193 # threaded shells use a verbose traceback in sys.excepthook
2198 # threaded shells use a verbose traceback in sys.excepthook
2194 if shell.isthreaded:
2199 if shell.isthreaded:
2195 try:
2200 try:
2196 shell.sys_excepthook.set_colors(scheme=new_scheme)
2201 shell.sys_excepthook.set_colors(scheme=new_scheme)
2197 except:
2202 except:
2198 color_switch_err('system exception handler')
2203 color_switch_err('system exception handler')
2199
2204
2200 # Set info (for 'object?') colors
2205 # Set info (for 'object?') colors
2201 if shell.rc.color_info:
2206 if shell.rc.color_info:
2202 try:
2207 try:
2203 shell.inspector.set_active_scheme(new_scheme)
2208 shell.inspector.set_active_scheme(new_scheme)
2204 except:
2209 except:
2205 color_switch_err('object inspector')
2210 color_switch_err('object inspector')
2206 else:
2211 else:
2207 shell.inspector.set_active_scheme('NoColor')
2212 shell.inspector.set_active_scheme('NoColor')
2208
2213
2209 def magic_color_info(self,parameter_s = ''):
2214 def magic_color_info(self,parameter_s = ''):
2210 """Toggle color_info.
2215 """Toggle color_info.
2211
2216
2212 The color_info configuration parameter controls whether colors are
2217 The color_info configuration parameter controls whether colors are
2213 used for displaying object details (by things like %psource, %pfile or
2218 used for displaying object details (by things like %psource, %pfile or
2214 the '?' system). This function toggles this value with each call.
2219 the '?' system). This function toggles this value with each call.
2215
2220
2216 Note that unless you have a fairly recent pager (less works better
2221 Note that unless you have a fairly recent pager (less works better
2217 than more) in your system, using colored object information displays
2222 than more) in your system, using colored object information displays
2218 will not work properly. Test it and see."""
2223 will not work properly. Test it and see."""
2219
2224
2220 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2225 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2221 self.magic_colors(self.shell.rc.colors)
2226 self.magic_colors(self.shell.rc.colors)
2222 print 'Object introspection functions have now coloring:',
2227 print 'Object introspection functions have now coloring:',
2223 print ['OFF','ON'][self.shell.rc.color_info]
2228 print ['OFF','ON'][self.shell.rc.color_info]
2224
2229
2225 def magic_Pprint(self, parameter_s=''):
2230 def magic_Pprint(self, parameter_s=''):
2226 """Toggle pretty printing on/off."""
2231 """Toggle pretty printing on/off."""
2227
2232
2228 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2233 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2229 print 'Pretty printing has been turned', \
2234 print 'Pretty printing has been turned', \
2230 ['OFF','ON'][self.shell.rc.pprint]
2235 ['OFF','ON'][self.shell.rc.pprint]
2231
2236
2232 def magic_exit(self, parameter_s=''):
2237 def magic_exit(self, parameter_s=''):
2233 """Exit IPython, confirming if configured to do so.
2238 """Exit IPython, confirming if configured to do so.
2234
2239
2235 You can configure whether IPython asks for confirmation upon exit by
2240 You can configure whether IPython asks for confirmation upon exit by
2236 setting the confirm_exit flag in the ipythonrc file."""
2241 setting the confirm_exit flag in the ipythonrc file."""
2237
2242
2238 self.shell.exit()
2243 self.shell.exit()
2239
2244
2240 def magic_quit(self, parameter_s=''):
2245 def magic_quit(self, parameter_s=''):
2241 """Exit IPython, confirming if configured to do so (like %exit)"""
2246 """Exit IPython, confirming if configured to do so (like %exit)"""
2242
2247
2243 self.shell.exit()
2248 self.shell.exit()
2244
2249
2245 def magic_Exit(self, parameter_s=''):
2250 def magic_Exit(self, parameter_s=''):
2246 """Exit IPython without confirmation."""
2251 """Exit IPython without confirmation."""
2247
2252
2248 self.shell.exit_now = True
2253 self.shell.exit_now = True
2249
2254
2250 def magic_Quit(self, parameter_s=''):
2255 def magic_Quit(self, parameter_s=''):
2251 """Exit IPython without confirmation (like %Exit)."""
2256 """Exit IPython without confirmation (like %Exit)."""
2252
2257
2253 self.shell.exit_now = True
2258 self.shell.exit_now = True
2254
2259
2255 #......................................................................
2260 #......................................................................
2256 # Functions to implement unix shell-type things
2261 # Functions to implement unix shell-type things
2257
2262
2258 def magic_alias(self, parameter_s = ''):
2263 def magic_alias(self, parameter_s = ''):
2259 """Define an alias for a system command.
2264 """Define an alias for a system command.
2260
2265
2261 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2266 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2262
2267
2263 Then, typing 'alias_name params' will execute the system command 'cmd
2268 Then, typing 'alias_name params' will execute the system command 'cmd
2264 params' (from your underlying operating system).
2269 params' (from your underlying operating system).
2265
2270
2266 Aliases have lower precedence than magic functions and Python normal
2271 Aliases have lower precedence than magic functions and Python normal
2267 variables, so if 'foo' is both a Python variable and an alias, the
2272 variables, so if 'foo' is both a Python variable and an alias, the
2268 alias can not be executed until 'del foo' removes the Python variable.
2273 alias can not be executed until 'del foo' removes the Python variable.
2269
2274
2270 You can use the %l specifier in an alias definition to represent the
2275 You can use the %l specifier in an alias definition to represent the
2271 whole line when the alias is called. For example:
2276 whole line when the alias is called. For example:
2272
2277
2273 In [2]: alias all echo "Input in brackets: <%l>"\\
2278 In [2]: alias all echo "Input in brackets: <%l>"\\
2274 In [3]: all hello world\\
2279 In [3]: all hello world\\
2275 Input in brackets: <hello world>
2280 Input in brackets: <hello world>
2276
2281
2277 You can also define aliases with parameters using %s specifiers (one
2282 You can also define aliases with parameters using %s specifiers (one
2278 per parameter):
2283 per parameter):
2279
2284
2280 In [1]: alias parts echo first %s second %s\\
2285 In [1]: alias parts echo first %s second %s\\
2281 In [2]: %parts A B\\
2286 In [2]: %parts A B\\
2282 first A second B\\
2287 first A second B\\
2283 In [3]: %parts A\\
2288 In [3]: %parts A\\
2284 Incorrect number of arguments: 2 expected.\\
2289 Incorrect number of arguments: 2 expected.\\
2285 parts is an alias to: 'echo first %s second %s'
2290 parts is an alias to: 'echo first %s second %s'
2286
2291
2287 Note that %l and %s are mutually exclusive. You can only use one or
2292 Note that %l and %s are mutually exclusive. You can only use one or
2288 the other in your aliases.
2293 the other in your aliases.
2289
2294
2290 Aliases expand Python variables just like system calls using ! or !!
2295 Aliases expand Python variables just like system calls using ! or !!
2291 do: all expressions prefixed with '$' get expanded. For details of
2296 do: all expressions prefixed with '$' get expanded. For details of
2292 the semantic rules, see PEP-215:
2297 the semantic rules, see PEP-215:
2293 http://www.python.org/peps/pep-0215.html. This is the library used by
2298 http://www.python.org/peps/pep-0215.html. This is the library used by
2294 IPython for variable expansion. If you want to access a true shell
2299 IPython for variable expansion. If you want to access a true shell
2295 variable, an extra $ is necessary to prevent its expansion by IPython:
2300 variable, an extra $ is necessary to prevent its expansion by IPython:
2296
2301
2297 In [6]: alias show echo\\
2302 In [6]: alias show echo\\
2298 In [7]: PATH='A Python string'\\
2303 In [7]: PATH='A Python string'\\
2299 In [8]: show $PATH\\
2304 In [8]: show $PATH\\
2300 A Python string\\
2305 A Python string\\
2301 In [9]: show $$PATH\\
2306 In [9]: show $$PATH\\
2302 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2307 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2303
2308
2304 You can use the alias facility to acess all of $PATH. See the %rehash
2309 You can use the alias facility to acess all of $PATH. See the %rehash
2305 and %rehashx functions, which automatically create aliases for the
2310 and %rehashx functions, which automatically create aliases for the
2306 contents of your $PATH.
2311 contents of your $PATH.
2307
2312
2308 If called with no parameters, %alias prints the current alias table."""
2313 If called with no parameters, %alias prints the current alias table."""
2309
2314
2310 par = parameter_s.strip()
2315 par = parameter_s.strip()
2311 if not par:
2316 if not par:
2312 if self.shell.rc.automagic:
2317 if self.shell.rc.automagic:
2313 prechar = ''
2318 prechar = ''
2314 else:
2319 else:
2315 prechar = self.shell.ESC_MAGIC
2320 prechar = self.shell.ESC_MAGIC
2316 #print 'Alias\t\tSystem Command\n'+'-'*30
2321 #print 'Alias\t\tSystem Command\n'+'-'*30
2317 atab = self.shell.alias_table
2322 atab = self.shell.alias_table
2318 aliases = atab.keys()
2323 aliases = atab.keys()
2319 aliases.sort()
2324 aliases.sort()
2320 res = []
2325 res = []
2321 for alias in aliases:
2326 for alias in aliases:
2322 res.append((alias, atab[alias][1]))
2327 res.append((alias, atab[alias][1]))
2323 print "Total number of aliases:",len(aliases)
2328 print "Total number of aliases:",len(aliases)
2324 return res
2329 return res
2325 try:
2330 try:
2326 alias,cmd = par.split(None,1)
2331 alias,cmd = par.split(None,1)
2327 except:
2332 except:
2328 print OInspect.getdoc(self.magic_alias)
2333 print OInspect.getdoc(self.magic_alias)
2329 else:
2334 else:
2330 nargs = cmd.count('%s')
2335 nargs = cmd.count('%s')
2331 if nargs>0 and cmd.find('%l')>=0:
2336 if nargs>0 and cmd.find('%l')>=0:
2332 error('The %s and %l specifiers are mutually exclusive '
2337 error('The %s and %l specifiers are mutually exclusive '
2333 'in alias definitions.')
2338 'in alias definitions.')
2334 else: # all looks OK
2339 else: # all looks OK
2335 self.shell.alias_table[alias] = (nargs,cmd)
2340 self.shell.alias_table[alias] = (nargs,cmd)
2336 self.shell.alias_table_validate(verbose=0)
2341 self.shell.alias_table_validate(verbose=0)
2337 # end magic_alias
2342 # end magic_alias
2338
2343
2339 def magic_unalias(self, parameter_s = ''):
2344 def magic_unalias(self, parameter_s = ''):
2340 """Remove an alias"""
2345 """Remove an alias"""
2341
2346
2342 aname = parameter_s.strip()
2347 aname = parameter_s.strip()
2343 if aname in self.shell.alias_table:
2348 if aname in self.shell.alias_table:
2344 del self.shell.alias_table[aname]
2349 del self.shell.alias_table[aname]
2345
2350
2346 def magic_rehash(self, parameter_s = ''):
2351 def magic_rehash(self, parameter_s = ''):
2347 """Update the alias table with all entries in $PATH.
2352 """Update the alias table with all entries in $PATH.
2348
2353
2349 This version does no checks on execute permissions or whether the
2354 This version does no checks on execute permissions or whether the
2350 contents of $PATH are truly files (instead of directories or something
2355 contents of $PATH are truly files (instead of directories or something
2351 else). For such a safer (but slower) version, use %rehashx."""
2356 else). For such a safer (but slower) version, use %rehashx."""
2352
2357
2353 # This function (and rehashx) manipulate the alias_table directly
2358 # This function (and rehashx) manipulate the alias_table directly
2354 # rather than calling magic_alias, for speed reasons. A rehash on a
2359 # rather than calling magic_alias, for speed reasons. A rehash on a
2355 # typical Linux box involves several thousand entries, so efficiency
2360 # typical Linux box involves several thousand entries, so efficiency
2356 # here is a top concern.
2361 # here is a top concern.
2357
2362
2358 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2363 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2359 alias_table = self.shell.alias_table
2364 alias_table = self.shell.alias_table
2360 for pdir in path:
2365 for pdir in path:
2361 for ff in os.listdir(pdir):
2366 for ff in os.listdir(pdir):
2362 # each entry in the alias table must be (N,name), where
2367 # each entry in the alias table must be (N,name), where
2363 # N is the number of positional arguments of the alias.
2368 # N is the number of positional arguments of the alias.
2364 alias_table[ff] = (0,ff)
2369 alias_table[ff] = (0,ff)
2365 # Make sure the alias table doesn't contain keywords or builtins
2370 # Make sure the alias table doesn't contain keywords or builtins
2366 self.shell.alias_table_validate()
2371 self.shell.alias_table_validate()
2367 # Call again init_auto_alias() so we get 'rm -i' and other modified
2372 # Call again init_auto_alias() so we get 'rm -i' and other modified
2368 # aliases since %rehash will probably clobber them
2373 # aliases since %rehash will probably clobber them
2369 self.shell.init_auto_alias()
2374 self.shell.init_auto_alias()
2370
2375
2371 def magic_rehashx(self, parameter_s = ''):
2376 def magic_rehashx(self, parameter_s = ''):
2372 """Update the alias table with all executable files in $PATH.
2377 """Update the alias table with all executable files in $PATH.
2373
2378
2374 This version explicitly checks that every entry in $PATH is a file
2379 This version explicitly checks that every entry in $PATH is a file
2375 with execute access (os.X_OK), so it is much slower than %rehash.
2380 with execute access (os.X_OK), so it is much slower than %rehash.
2376
2381
2377 Under Windows, it checks executability as a match agains a
2382 Under Windows, it checks executability as a match agains a
2378 '|'-separated string of extensions, stored in the IPython config
2383 '|'-separated string of extensions, stored in the IPython config
2379 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2384 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2380
2385
2381 path = [os.path.abspath(os.path.expanduser(p)) for p in
2386 path = [os.path.abspath(os.path.expanduser(p)) for p in
2382 os.environ['PATH'].split(os.pathsep)]
2387 os.environ['PATH'].split(os.pathsep)]
2383 path = filter(os.path.isdir,path)
2388 path = filter(os.path.isdir,path)
2384
2389
2385 alias_table = self.shell.alias_table
2390 alias_table = self.shell.alias_table
2386 syscmdlist = []
2391 syscmdlist = []
2387 if os.name == 'posix':
2392 if os.name == 'posix':
2388 isexec = lambda fname:os.path.isfile(fname) and \
2393 isexec = lambda fname:os.path.isfile(fname) and \
2389 os.access(fname,os.X_OK)
2394 os.access(fname,os.X_OK)
2390 else:
2395 else:
2391
2396
2392 try:
2397 try:
2393 winext = os.environ['pathext'].replace(';','|').replace('.','')
2398 winext = os.environ['pathext'].replace(';','|').replace('.','')
2394 except KeyError:
2399 except KeyError:
2395 winext = 'exe|com|bat'
2400 winext = 'exe|com|bat'
2396
2401
2397 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2402 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2398 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2403 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2399 savedir = os.getcwd()
2404 savedir = os.getcwd()
2400 try:
2405 try:
2401 # write the whole loop for posix/Windows so we don't have an if in
2406 # write the whole loop for posix/Windows so we don't have an if in
2402 # the innermost part
2407 # the innermost part
2403 if os.name == 'posix':
2408 if os.name == 'posix':
2404 for pdir in path:
2409 for pdir in path:
2405 os.chdir(pdir)
2410 os.chdir(pdir)
2406 for ff in os.listdir(pdir):
2411 for ff in os.listdir(pdir):
2407 if isexec(ff):
2412 if isexec(ff):
2408 # each entry in the alias table must be (N,name),
2413 # each entry in the alias table must be (N,name),
2409 # where N is the number of positional arguments of the
2414 # where N is the number of positional arguments of the
2410 # alias.
2415 # alias.
2411 alias_table[ff] = (0,ff)
2416 alias_table[ff] = (0,ff)
2412 syscmdlist.append(ff)
2417 syscmdlist.append(ff)
2413 else:
2418 else:
2414 for pdir in path:
2419 for pdir in path:
2415 os.chdir(pdir)
2420 os.chdir(pdir)
2416 for ff in os.listdir(pdir):
2421 for ff in os.listdir(pdir):
2417 if isexec(ff):
2422 if isexec(ff):
2418 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2423 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2419 syscmdlist.append(ff)
2424 syscmdlist.append(ff)
2420 # Make sure the alias table doesn't contain keywords or builtins
2425 # Make sure the alias table doesn't contain keywords or builtins
2421 self.shell.alias_table_validate()
2426 self.shell.alias_table_validate()
2422 # Call again init_auto_alias() so we get 'rm -i' and other
2427 # Call again init_auto_alias() so we get 'rm -i' and other
2423 # modified aliases since %rehashx will probably clobber them
2428 # modified aliases since %rehashx will probably clobber them
2424 self.shell.init_auto_alias()
2429 self.shell.init_auto_alias()
2425 db = self.getapi().db
2430 db = self.getapi().db
2426 db['syscmdlist'] = syscmdlist
2431 db['syscmdlist'] = syscmdlist
2427 finally:
2432 finally:
2428 os.chdir(savedir)
2433 os.chdir(savedir)
2429
2434
2430 def magic_pwd(self, parameter_s = ''):
2435 def magic_pwd(self, parameter_s = ''):
2431 """Return the current working directory path."""
2436 """Return the current working directory path."""
2432 return os.getcwd()
2437 return os.getcwd()
2433
2438
2434 def magic_cd(self, parameter_s=''):
2439 def magic_cd(self, parameter_s=''):
2435 """Change the current working directory.
2440 """Change the current working directory.
2436
2441
2437 This command automatically maintains an internal list of directories
2442 This command automatically maintains an internal list of directories
2438 you visit during your IPython session, in the variable _dh. The
2443 you visit during your IPython session, in the variable _dh. The
2439 command %dhist shows this history nicely formatted.
2444 command %dhist shows this history nicely formatted.
2440
2445
2441 Usage:
2446 Usage:
2442
2447
2443 cd 'dir': changes to directory 'dir'.
2448 cd 'dir': changes to directory 'dir'.
2444
2449
2445 cd -: changes to the last visited directory.
2450 cd -: changes to the last visited directory.
2446
2451
2447 cd -<n>: changes to the n-th directory in the directory history.
2452 cd -<n>: changes to the n-th directory in the directory history.
2448
2453
2449 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2454 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2450 (note: cd <bookmark_name> is enough if there is no
2455 (note: cd <bookmark_name> is enough if there is no
2451 directory <bookmark_name>, but a bookmark with the name exists.)
2456 directory <bookmark_name>, but a bookmark with the name exists.)
2452
2457
2453 Options:
2458 Options:
2454
2459
2455 -q: quiet. Do not print the working directory after the cd command is
2460 -q: quiet. Do not print the working directory after the cd command is
2456 executed. By default IPython's cd command does print this directory,
2461 executed. By default IPython's cd command does print this directory,
2457 since the default prompts do not display path information.
2462 since the default prompts do not display path information.
2458
2463
2459 Note that !cd doesn't work for this purpose because the shell where
2464 Note that !cd doesn't work for this purpose because the shell where
2460 !command runs is immediately discarded after executing 'command'."""
2465 !command runs is immediately discarded after executing 'command'."""
2461
2466
2462 parameter_s = parameter_s.strip()
2467 parameter_s = parameter_s.strip()
2463 #bkms = self.shell.persist.get("bookmarks",{})
2468 #bkms = self.shell.persist.get("bookmarks",{})
2464
2469
2465 numcd = re.match(r'(-)(\d+)$',parameter_s)
2470 numcd = re.match(r'(-)(\d+)$',parameter_s)
2466 # jump in directory history by number
2471 # jump in directory history by number
2467 if numcd:
2472 if numcd:
2468 nn = int(numcd.group(2))
2473 nn = int(numcd.group(2))
2469 try:
2474 try:
2470 ps = self.shell.user_ns['_dh'][nn]
2475 ps = self.shell.user_ns['_dh'][nn]
2471 except IndexError:
2476 except IndexError:
2472 print 'The requested directory does not exist in history.'
2477 print 'The requested directory does not exist in history.'
2473 return
2478 return
2474 else:
2479 else:
2475 opts = {}
2480 opts = {}
2476 else:
2481 else:
2477 #turn all non-space-escaping backslashes to slashes,
2482 #turn all non-space-escaping backslashes to slashes,
2478 # for c:\windows\directory\names\
2483 # for c:\windows\directory\names\
2479 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2484 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2480 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2485 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2481 # jump to previous
2486 # jump to previous
2482 if ps == '-':
2487 if ps == '-':
2483 try:
2488 try:
2484 ps = self.shell.user_ns['_dh'][-2]
2489 ps = self.shell.user_ns['_dh'][-2]
2485 except IndexError:
2490 except IndexError:
2486 print 'No previous directory to change to.'
2491 print 'No previous directory to change to.'
2487 return
2492 return
2488 # jump to bookmark if needed
2493 # jump to bookmark if needed
2489 else:
2494 else:
2490 if not os.path.isdir(ps) or opts.has_key('b'):
2495 if not os.path.isdir(ps) or opts.has_key('b'):
2491 bkms = self.db.get('bookmarks', {})
2496 bkms = self.db.get('bookmarks', {})
2492
2497
2493 if bkms.has_key(ps):
2498 if bkms.has_key(ps):
2494 target = bkms[ps]
2499 target = bkms[ps]
2495 print '(bookmark:%s) -> %s' % (ps,target)
2500 print '(bookmark:%s) -> %s' % (ps,target)
2496 ps = target
2501 ps = target
2497 else:
2502 else:
2498 if opts.has_key('b'):
2503 if opts.has_key('b'):
2499 error("Bookmark '%s' not found. "
2504 error("Bookmark '%s' not found. "
2500 "Use '%%bookmark -l' to see your bookmarks." % ps)
2505 "Use '%%bookmark -l' to see your bookmarks." % ps)
2501 return
2506 return
2502
2507
2503 # at this point ps should point to the target dir
2508 # at this point ps should point to the target dir
2504 if ps:
2509 if ps:
2505 try:
2510 try:
2506 os.chdir(os.path.expanduser(ps))
2511 os.chdir(os.path.expanduser(ps))
2507 ttitle = ("IPy:" + (
2512 ttitle = ("IPy:" + (
2508 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2513 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2509 platutils.set_term_title(ttitle)
2514 platutils.set_term_title(ttitle)
2510 except OSError:
2515 except OSError:
2511 print sys.exc_info()[1]
2516 print sys.exc_info()[1]
2512 else:
2517 else:
2513 self.shell.user_ns['_dh'].append(os.getcwd())
2518 self.shell.user_ns['_dh'].append(os.getcwd())
2514 else:
2519 else:
2515 os.chdir(self.shell.home_dir)
2520 os.chdir(self.shell.home_dir)
2516 platutils.set_term_title("IPy:~")
2521 platutils.set_term_title("IPy:~")
2517 self.shell.user_ns['_dh'].append(os.getcwd())
2522 self.shell.user_ns['_dh'].append(os.getcwd())
2518 if not 'q' in opts:
2523 if not 'q' in opts:
2519 print self.shell.user_ns['_dh'][-1]
2524 print self.shell.user_ns['_dh'][-1]
2520
2525
2521 def magic_dhist(self, parameter_s=''):
2526 def magic_dhist(self, parameter_s=''):
2522 """Print your history of visited directories.
2527 """Print your history of visited directories.
2523
2528
2524 %dhist -> print full history\\
2529 %dhist -> print full history\\
2525 %dhist n -> print last n entries only\\
2530 %dhist n -> print last n entries only\\
2526 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2531 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2527
2532
2528 This history is automatically maintained by the %cd command, and
2533 This history is automatically maintained by the %cd command, and
2529 always available as the global list variable _dh. You can use %cd -<n>
2534 always available as the global list variable _dh. You can use %cd -<n>
2530 to go to directory number <n>."""
2535 to go to directory number <n>."""
2531
2536
2532 dh = self.shell.user_ns['_dh']
2537 dh = self.shell.user_ns['_dh']
2533 if parameter_s:
2538 if parameter_s:
2534 try:
2539 try:
2535 args = map(int,parameter_s.split())
2540 args = map(int,parameter_s.split())
2536 except:
2541 except:
2537 self.arg_err(Magic.magic_dhist)
2542 self.arg_err(Magic.magic_dhist)
2538 return
2543 return
2539 if len(args) == 1:
2544 if len(args) == 1:
2540 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2545 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2541 elif len(args) == 2:
2546 elif len(args) == 2:
2542 ini,fin = args
2547 ini,fin = args
2543 else:
2548 else:
2544 self.arg_err(Magic.magic_dhist)
2549 self.arg_err(Magic.magic_dhist)
2545 return
2550 return
2546 else:
2551 else:
2547 ini,fin = 0,len(dh)
2552 ini,fin = 0,len(dh)
2548 nlprint(dh,
2553 nlprint(dh,
2549 header = 'Directory history (kept in _dh)',
2554 header = 'Directory history (kept in _dh)',
2550 start=ini,stop=fin)
2555 start=ini,stop=fin)
2551
2556
2552 def magic_env(self, parameter_s=''):
2557 def magic_env(self, parameter_s=''):
2553 """List environment variables."""
2558 """List environment variables."""
2554
2559
2555 return os.environ.data
2560 return os.environ.data
2556
2561
2557 def magic_pushd(self, parameter_s=''):
2562 def magic_pushd(self, parameter_s=''):
2558 """Place the current dir on stack and change directory.
2563 """Place the current dir on stack and change directory.
2559
2564
2560 Usage:\\
2565 Usage:\\
2561 %pushd ['dirname']
2566 %pushd ['dirname']
2562
2567
2563 %pushd with no arguments does a %pushd to your home directory.
2568 %pushd with no arguments does a %pushd to your home directory.
2564 """
2569 """
2565 if parameter_s == '': parameter_s = '~'
2570 if parameter_s == '': parameter_s = '~'
2566 dir_s = self.shell.dir_stack
2571 dir_s = self.shell.dir_stack
2567 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2572 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2568 os.path.expanduser(self.shell.dir_stack[0]):
2573 os.path.expanduser(self.shell.dir_stack[0]):
2569 try:
2574 try:
2570 self.magic_cd(parameter_s)
2575 self.magic_cd(parameter_s)
2571 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2576 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2572 self.magic_dirs()
2577 self.magic_dirs()
2573 except:
2578 except:
2574 print 'Invalid directory'
2579 print 'Invalid directory'
2575 else:
2580 else:
2576 print 'You are already there!'
2581 print 'You are already there!'
2577
2582
2578 def magic_popd(self, parameter_s=''):
2583 def magic_popd(self, parameter_s=''):
2579 """Change to directory popped off the top of the stack.
2584 """Change to directory popped off the top of the stack.
2580 """
2585 """
2581 if len (self.shell.dir_stack) > 1:
2586 if len (self.shell.dir_stack) > 1:
2582 self.shell.dir_stack.pop(0)
2587 self.shell.dir_stack.pop(0)
2583 self.magic_cd(self.shell.dir_stack[0])
2588 self.magic_cd(self.shell.dir_stack[0])
2584 print self.shell.dir_stack[0]
2589 print self.shell.dir_stack[0]
2585 else:
2590 else:
2586 print "You can't remove the starting directory from the stack:",\
2591 print "You can't remove the starting directory from the stack:",\
2587 self.shell.dir_stack
2592 self.shell.dir_stack
2588
2593
2589 def magic_dirs(self, parameter_s=''):
2594 def magic_dirs(self, parameter_s=''):
2590 """Return the current directory stack."""
2595 """Return the current directory stack."""
2591
2596
2592 return self.shell.dir_stack[:]
2597 return self.shell.dir_stack[:]
2593
2598
2594 def magic_sc(self, parameter_s=''):
2599 def magic_sc(self, parameter_s=''):
2595 """Shell capture - execute a shell command and capture its output.
2600 """Shell capture - execute a shell command and capture its output.
2596
2601
2597 DEPRECATED. Suboptimal, retained for backwards compatibility.
2602 DEPRECATED. Suboptimal, retained for backwards compatibility.
2598
2603
2599 You should use the form 'var = !command' instead. Example:
2604 You should use the form 'var = !command' instead. Example:
2600
2605
2601 "%sc -l myfiles = ls ~" should now be written as
2606 "%sc -l myfiles = ls ~" should now be written as
2602
2607
2603 "myfiles = !ls ~"
2608 "myfiles = !ls ~"
2604
2609
2605 myfiles.s, myfiles.l and myfiles.n still apply as documented
2610 myfiles.s, myfiles.l and myfiles.n still apply as documented
2606 below.
2611 below.
2607
2612
2608 --
2613 --
2609 %sc [options] varname=command
2614 %sc [options] varname=command
2610
2615
2611 IPython will run the given command using commands.getoutput(), and
2616 IPython will run the given command using commands.getoutput(), and
2612 will then update the user's interactive namespace with a variable
2617 will then update the user's interactive namespace with a variable
2613 called varname, containing the value of the call. Your command can
2618 called varname, containing the value of the call. Your command can
2614 contain shell wildcards, pipes, etc.
2619 contain shell wildcards, pipes, etc.
2615
2620
2616 The '=' sign in the syntax is mandatory, and the variable name you
2621 The '=' sign in the syntax is mandatory, and the variable name you
2617 supply must follow Python's standard conventions for valid names.
2622 supply must follow Python's standard conventions for valid names.
2618
2623
2619 (A special format without variable name exists for internal use)
2624 (A special format without variable name exists for internal use)
2620
2625
2621 Options:
2626 Options:
2622
2627
2623 -l: list output. Split the output on newlines into a list before
2628 -l: list output. Split the output on newlines into a list before
2624 assigning it to the given variable. By default the output is stored
2629 assigning it to the given variable. By default the output is stored
2625 as a single string.
2630 as a single string.
2626
2631
2627 -v: verbose. Print the contents of the variable.
2632 -v: verbose. Print the contents of the variable.
2628
2633
2629 In most cases you should not need to split as a list, because the
2634 In most cases you should not need to split as a list, because the
2630 returned value is a special type of string which can automatically
2635 returned value is a special type of string which can automatically
2631 provide its contents either as a list (split on newlines) or as a
2636 provide its contents either as a list (split on newlines) or as a
2632 space-separated string. These are convenient, respectively, either
2637 space-separated string. These are convenient, respectively, either
2633 for sequential processing or to be passed to a shell command.
2638 for sequential processing or to be passed to a shell command.
2634
2639
2635 For example:
2640 For example:
2636
2641
2637 # Capture into variable a
2642 # Capture into variable a
2638 In [9]: sc a=ls *py
2643 In [9]: sc a=ls *py
2639
2644
2640 # a is a string with embedded newlines
2645 # a is a string with embedded newlines
2641 In [10]: a
2646 In [10]: a
2642 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2647 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2643
2648
2644 # which can be seen as a list:
2649 # which can be seen as a list:
2645 In [11]: a.l
2650 In [11]: a.l
2646 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2651 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2647
2652
2648 # or as a whitespace-separated string:
2653 # or as a whitespace-separated string:
2649 In [12]: a.s
2654 In [12]: a.s
2650 Out[12]: 'setup.py win32_manual_post_install.py'
2655 Out[12]: 'setup.py win32_manual_post_install.py'
2651
2656
2652 # a.s is useful to pass as a single command line:
2657 # a.s is useful to pass as a single command line:
2653 In [13]: !wc -l $a.s
2658 In [13]: !wc -l $a.s
2654 146 setup.py
2659 146 setup.py
2655 130 win32_manual_post_install.py
2660 130 win32_manual_post_install.py
2656 276 total
2661 276 total
2657
2662
2658 # while the list form is useful to loop over:
2663 # while the list form is useful to loop over:
2659 In [14]: for f in a.l:
2664 In [14]: for f in a.l:
2660 ....: !wc -l $f
2665 ....: !wc -l $f
2661 ....:
2666 ....:
2662 146 setup.py
2667 146 setup.py
2663 130 win32_manual_post_install.py
2668 130 win32_manual_post_install.py
2664
2669
2665 Similiarly, the lists returned by the -l option are also special, in
2670 Similiarly, the lists returned by the -l option are also special, in
2666 the sense that you can equally invoke the .s attribute on them to
2671 the sense that you can equally invoke the .s attribute on them to
2667 automatically get a whitespace-separated string from their contents:
2672 automatically get a whitespace-separated string from their contents:
2668
2673
2669 In [1]: sc -l b=ls *py
2674 In [1]: sc -l b=ls *py
2670
2675
2671 In [2]: b
2676 In [2]: b
2672 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2677 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2673
2678
2674 In [3]: b.s
2679 In [3]: b.s
2675 Out[3]: 'setup.py win32_manual_post_install.py'
2680 Out[3]: 'setup.py win32_manual_post_install.py'
2676
2681
2677 In summary, both the lists and strings used for ouptut capture have
2682 In summary, both the lists and strings used for ouptut capture have
2678 the following special attributes:
2683 the following special attributes:
2679
2684
2680 .l (or .list) : value as list.
2685 .l (or .list) : value as list.
2681 .n (or .nlstr): value as newline-separated string.
2686 .n (or .nlstr): value as newline-separated string.
2682 .s (or .spstr): value as space-separated string.
2687 .s (or .spstr): value as space-separated string.
2683 """
2688 """
2684
2689
2685 opts,args = self.parse_options(parameter_s,'lv')
2690 opts,args = self.parse_options(parameter_s,'lv')
2686 # Try to get a variable name and command to run
2691 # Try to get a variable name and command to run
2687 try:
2692 try:
2688 # the variable name must be obtained from the parse_options
2693 # the variable name must be obtained from the parse_options
2689 # output, which uses shlex.split to strip options out.
2694 # output, which uses shlex.split to strip options out.
2690 var,_ = args.split('=',1)
2695 var,_ = args.split('=',1)
2691 var = var.strip()
2696 var = var.strip()
2692 # But the the command has to be extracted from the original input
2697 # But the the command has to be extracted from the original input
2693 # parameter_s, not on what parse_options returns, to avoid the
2698 # parameter_s, not on what parse_options returns, to avoid the
2694 # quote stripping which shlex.split performs on it.
2699 # quote stripping which shlex.split performs on it.
2695 _,cmd = parameter_s.split('=',1)
2700 _,cmd = parameter_s.split('=',1)
2696 except ValueError:
2701 except ValueError:
2697 var,cmd = '',''
2702 var,cmd = '',''
2698 # If all looks ok, proceed
2703 # If all looks ok, proceed
2699 out,err = self.shell.getoutputerror(cmd)
2704 out,err = self.shell.getoutputerror(cmd)
2700 if err:
2705 if err:
2701 print >> Term.cerr,err
2706 print >> Term.cerr,err
2702 if opts.has_key('l'):
2707 if opts.has_key('l'):
2703 out = SList(out.split('\n'))
2708 out = SList(out.split('\n'))
2704 else:
2709 else:
2705 out = LSString(out)
2710 out = LSString(out)
2706 if opts.has_key('v'):
2711 if opts.has_key('v'):
2707 print '%s ==\n%s' % (var,pformat(out))
2712 print '%s ==\n%s' % (var,pformat(out))
2708 if var:
2713 if var:
2709 self.shell.user_ns.update({var:out})
2714 self.shell.user_ns.update({var:out})
2710 else:
2715 else:
2711 return out
2716 return out
2712
2717
2713 def magic_sx(self, parameter_s=''):
2718 def magic_sx(self, parameter_s=''):
2714 """Shell execute - run a shell command and capture its output.
2719 """Shell execute - run a shell command and capture its output.
2715
2720
2716 %sx command
2721 %sx command
2717
2722
2718 IPython will run the given command using commands.getoutput(), and
2723 IPython will run the given command using commands.getoutput(), and
2719 return the result formatted as a list (split on '\\n'). Since the
2724 return the result formatted as a list (split on '\\n'). Since the
2720 output is _returned_, it will be stored in ipython's regular output
2725 output is _returned_, it will be stored in ipython's regular output
2721 cache Out[N] and in the '_N' automatic variables.
2726 cache Out[N] and in the '_N' automatic variables.
2722
2727
2723 Notes:
2728 Notes:
2724
2729
2725 1) If an input line begins with '!!', then %sx is automatically
2730 1) If an input line begins with '!!', then %sx is automatically
2726 invoked. That is, while:
2731 invoked. That is, while:
2727 !ls
2732 !ls
2728 causes ipython to simply issue system('ls'), typing
2733 causes ipython to simply issue system('ls'), typing
2729 !!ls
2734 !!ls
2730 is a shorthand equivalent to:
2735 is a shorthand equivalent to:
2731 %sx ls
2736 %sx ls
2732
2737
2733 2) %sx differs from %sc in that %sx automatically splits into a list,
2738 2) %sx differs from %sc in that %sx automatically splits into a list,
2734 like '%sc -l'. The reason for this is to make it as easy as possible
2739 like '%sc -l'. The reason for this is to make it as easy as possible
2735 to process line-oriented shell output via further python commands.
2740 to process line-oriented shell output via further python commands.
2736 %sc is meant to provide much finer control, but requires more
2741 %sc is meant to provide much finer control, but requires more
2737 typing.
2742 typing.
2738
2743
2739 3) Just like %sc -l, this is a list with special attributes:
2744 3) Just like %sc -l, this is a list with special attributes:
2740
2745
2741 .l (or .list) : value as list.
2746 .l (or .list) : value as list.
2742 .n (or .nlstr): value as newline-separated string.
2747 .n (or .nlstr): value as newline-separated string.
2743 .s (or .spstr): value as whitespace-separated string.
2748 .s (or .spstr): value as whitespace-separated string.
2744
2749
2745 This is very useful when trying to use such lists as arguments to
2750 This is very useful when trying to use such lists as arguments to
2746 system commands."""
2751 system commands."""
2747
2752
2748 if parameter_s:
2753 if parameter_s:
2749 out,err = self.shell.getoutputerror(parameter_s)
2754 out,err = self.shell.getoutputerror(parameter_s)
2750 if err:
2755 if err:
2751 print >> Term.cerr,err
2756 print >> Term.cerr,err
2752 return SList(out.split('\n'))
2757 return SList(out.split('\n'))
2753
2758
2754 def magic_bg(self, parameter_s=''):
2759 def magic_bg(self, parameter_s=''):
2755 """Run a job in the background, in a separate thread.
2760 """Run a job in the background, in a separate thread.
2756
2761
2757 For example,
2762 For example,
2758
2763
2759 %bg myfunc(x,y,z=1)
2764 %bg myfunc(x,y,z=1)
2760
2765
2761 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2766 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2762 execution starts, a message will be printed indicating the job
2767 execution starts, a message will be printed indicating the job
2763 number. If your job number is 5, you can use
2768 number. If your job number is 5, you can use
2764
2769
2765 myvar = jobs.result(5) or myvar = jobs[5].result
2770 myvar = jobs.result(5) or myvar = jobs[5].result
2766
2771
2767 to assign this result to variable 'myvar'.
2772 to assign this result to variable 'myvar'.
2768
2773
2769 IPython has a job manager, accessible via the 'jobs' object. You can
2774 IPython has a job manager, accessible via the 'jobs' object. You can
2770 type jobs? to get more information about it, and use jobs.<TAB> to see
2775 type jobs? to get more information about it, and use jobs.<TAB> to see
2771 its attributes. All attributes not starting with an underscore are
2776 its attributes. All attributes not starting with an underscore are
2772 meant for public use.
2777 meant for public use.
2773
2778
2774 In particular, look at the jobs.new() method, which is used to create
2779 In particular, look at the jobs.new() method, which is used to create
2775 new jobs. This magic %bg function is just a convenience wrapper
2780 new jobs. This magic %bg function is just a convenience wrapper
2776 around jobs.new(), for expression-based jobs. If you want to create a
2781 around jobs.new(), for expression-based jobs. If you want to create a
2777 new job with an explicit function object and arguments, you must call
2782 new job with an explicit function object and arguments, you must call
2778 jobs.new() directly.
2783 jobs.new() directly.
2779
2784
2780 The jobs.new docstring also describes in detail several important
2785 The jobs.new docstring also describes in detail several important
2781 caveats associated with a thread-based model for background job
2786 caveats associated with a thread-based model for background job
2782 execution. Type jobs.new? for details.
2787 execution. Type jobs.new? for details.
2783
2788
2784 You can check the status of all jobs with jobs.status().
2789 You can check the status of all jobs with jobs.status().
2785
2790
2786 The jobs variable is set by IPython into the Python builtin namespace.
2791 The jobs variable is set by IPython into the Python builtin namespace.
2787 If you ever declare a variable named 'jobs', you will shadow this
2792 If you ever declare a variable named 'jobs', you will shadow this
2788 name. You can either delete your global jobs variable to regain
2793 name. You can either delete your global jobs variable to regain
2789 access to the job manager, or make a new name and assign it manually
2794 access to the job manager, or make a new name and assign it manually
2790 to the manager (stored in IPython's namespace). For example, to
2795 to the manager (stored in IPython's namespace). For example, to
2791 assign the job manager to the Jobs name, use:
2796 assign the job manager to the Jobs name, use:
2792
2797
2793 Jobs = __builtins__.jobs"""
2798 Jobs = __builtins__.jobs"""
2794
2799
2795 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2800 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2796
2801
2797
2802
2798 def magic_bookmark(self, parameter_s=''):
2803 def magic_bookmark(self, parameter_s=''):
2799 """Manage IPython's bookmark system.
2804 """Manage IPython's bookmark system.
2800
2805
2801 %bookmark <name> - set bookmark to current dir
2806 %bookmark <name> - set bookmark to current dir
2802 %bookmark <name> <dir> - set bookmark to <dir>
2807 %bookmark <name> <dir> - set bookmark to <dir>
2803 %bookmark -l - list all bookmarks
2808 %bookmark -l - list all bookmarks
2804 %bookmark -d <name> - remove bookmark
2809 %bookmark -d <name> - remove bookmark
2805 %bookmark -r - remove all bookmarks
2810 %bookmark -r - remove all bookmarks
2806
2811
2807 You can later on access a bookmarked folder with:
2812 You can later on access a bookmarked folder with:
2808 %cd -b <name>
2813 %cd -b <name>
2809 or simply '%cd <name>' if there is no directory called <name> AND
2814 or simply '%cd <name>' if there is no directory called <name> AND
2810 there is such a bookmark defined.
2815 there is such a bookmark defined.
2811
2816
2812 Your bookmarks persist through IPython sessions, but they are
2817 Your bookmarks persist through IPython sessions, but they are
2813 associated with each profile."""
2818 associated with each profile."""
2814
2819
2815 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2820 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2816 if len(args) > 2:
2821 if len(args) > 2:
2817 error('You can only give at most two arguments')
2822 error('You can only give at most two arguments')
2818 return
2823 return
2819
2824
2820 bkms = self.db.get('bookmarks',{})
2825 bkms = self.db.get('bookmarks',{})
2821
2826
2822 if opts.has_key('d'):
2827 if opts.has_key('d'):
2823 try:
2828 try:
2824 todel = args[0]
2829 todel = args[0]
2825 except IndexError:
2830 except IndexError:
2826 error('You must provide a bookmark to delete')
2831 error('You must provide a bookmark to delete')
2827 else:
2832 else:
2828 try:
2833 try:
2829 del bkms[todel]
2834 del bkms[todel]
2830 except:
2835 except:
2831 error("Can't delete bookmark '%s'" % todel)
2836 error("Can't delete bookmark '%s'" % todel)
2832 elif opts.has_key('r'):
2837 elif opts.has_key('r'):
2833 bkms = {}
2838 bkms = {}
2834 elif opts.has_key('l'):
2839 elif opts.has_key('l'):
2835 bks = bkms.keys()
2840 bks = bkms.keys()
2836 bks.sort()
2841 bks.sort()
2837 if bks:
2842 if bks:
2838 size = max(map(len,bks))
2843 size = max(map(len,bks))
2839 else:
2844 else:
2840 size = 0
2845 size = 0
2841 fmt = '%-'+str(size)+'s -> %s'
2846 fmt = '%-'+str(size)+'s -> %s'
2842 print 'Current bookmarks:'
2847 print 'Current bookmarks:'
2843 for bk in bks:
2848 for bk in bks:
2844 print fmt % (bk,bkms[bk])
2849 print fmt % (bk,bkms[bk])
2845 else:
2850 else:
2846 if not args:
2851 if not args:
2847 error("You must specify the bookmark name")
2852 error("You must specify the bookmark name")
2848 elif len(args)==1:
2853 elif len(args)==1:
2849 bkms[args[0]] = os.getcwd()
2854 bkms[args[0]] = os.getcwd()
2850 elif len(args)==2:
2855 elif len(args)==2:
2851 bkms[args[0]] = args[1]
2856 bkms[args[0]] = args[1]
2852 self.db['bookmarks'] = bkms
2857 self.db['bookmarks'] = bkms
2853
2858
2854 def magic_pycat(self, parameter_s=''):
2859 def magic_pycat(self, parameter_s=''):
2855 """Show a syntax-highlighted file through a pager.
2860 """Show a syntax-highlighted file through a pager.
2856
2861
2857 This magic is similar to the cat utility, but it will assume the file
2862 This magic is similar to the cat utility, but it will assume the file
2858 to be Python source and will show it with syntax highlighting. """
2863 to be Python source and will show it with syntax highlighting. """
2859
2864
2860 try:
2865 try:
2861 filename = get_py_filename(parameter_s)
2866 filename = get_py_filename(parameter_s)
2862 cont = file_read(filename)
2867 cont = file_read(filename)
2863 except IOError:
2868 except IOError:
2864 try:
2869 try:
2865 cont = eval(parameter_s,self.user_ns)
2870 cont = eval(parameter_s,self.user_ns)
2866 except NameError:
2871 except NameError:
2867 cont = None
2872 cont = None
2868 if cont is None:
2873 if cont is None:
2869 print "Error: no such file or variable"
2874 print "Error: no such file or variable"
2870 return
2875 return
2871
2876
2872 page(self.shell.pycolorize(cont),
2877 page(self.shell.pycolorize(cont),
2873 screen_lines=self.shell.rc.screen_length)
2878 screen_lines=self.shell.rc.screen_length)
2874
2879
2875 def magic_cpaste(self, parameter_s=''):
2880 def magic_cpaste(self, parameter_s=''):
2876 """Allows you to paste & execute a pre-formatted code block from clipboard
2881 """Allows you to paste & execute a pre-formatted code block from clipboard
2877
2882
2878 You must terminate the block with '--' (two minus-signs) alone on the
2883 You must terminate the block with '--' (two minus-signs) alone on the
2879 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2884 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2880 is the new sentinel for this operation)
2885 is the new sentinel for this operation)
2881
2886
2882 The block is dedented prior to execution to enable execution of
2887 The block is dedented prior to execution to enable execution of
2883 method definitions. The executed block is also assigned to variable
2888 method definitions. The executed block is also assigned to variable
2884 named 'pasted_block' for later editing with '%edit pasted_block'.
2889 named 'pasted_block' for later editing with '%edit pasted_block'.
2885
2890
2886 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2891 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2887 This assigns the pasted block to variable 'foo' as string, without
2892 This assigns the pasted block to variable 'foo' as string, without
2888 dedenting or executing it.
2893 dedenting or executing it.
2889
2894
2890 Do not be alarmed by garbled output on Windows (it's a readline bug).
2895 Do not be alarmed by garbled output on Windows (it's a readline bug).
2891 Just press enter and type -- (and press enter again) and the block
2896 Just press enter and type -- (and press enter again) and the block
2892 will be what was just pasted.
2897 will be what was just pasted.
2893
2898
2894 IPython statements (magics, shell escapes) are not supported (yet).
2899 IPython statements (magics, shell escapes) are not supported (yet).
2895 """
2900 """
2896 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2901 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2897 par = args.strip()
2902 par = args.strip()
2898 sentinel = opts.get('s','--')
2903 sentinel = opts.get('s','--')
2899
2904
2900 from IPython import iplib
2905 from IPython import iplib
2901 lines = []
2906 lines = []
2902 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2907 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2903 while 1:
2908 while 1:
2904 l = iplib.raw_input_original(':')
2909 l = iplib.raw_input_original(':')
2905 if l ==sentinel:
2910 if l ==sentinel:
2906 break
2911 break
2907 lines.append(l)
2912 lines.append(l)
2908 block = "\n".join(lines) + '\n'
2913 block = "\n".join(lines) + '\n'
2909 #print "block:\n",block
2914 #print "block:\n",block
2910 if not par:
2915 if not par:
2911 b = textwrap.dedent(block)
2916 b = textwrap.dedent(block)
2912 exec b in self.user_ns
2917 exec b in self.user_ns
2913 self.user_ns['pasted_block'] = b
2918 self.user_ns['pasted_block'] = b
2914 else:
2919 else:
2915 self.user_ns[par] = block
2920 self.user_ns[par] = block
2916 print "Block assigned to '%s'" % par
2921 print "Block assigned to '%s'" % par
2917
2922
2918 def magic_quickref(self,arg):
2923 def magic_quickref(self,arg):
2919 """ Show a quick reference sheet """
2924 """ Show a quick reference sheet """
2920 import IPython.usage
2925 import IPython.usage
2921 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2926 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2922
2927
2923 page(qr)
2928 page(qr)
2924
2929
2925 def magic_upgrade(self,arg):
2930 def magic_upgrade(self,arg):
2926 """ Upgrade your IPython installation
2931 """ Upgrade your IPython installation
2927
2932
2928 This will copy the config files that don't yet exist in your
2933 This will copy the config files that don't yet exist in your
2929 ipython dir from the system config dir. Use this after upgrading
2934 ipython dir from the system config dir. Use this after upgrading
2930 IPython if you don't wish to delete your .ipython dir.
2935 IPython if you don't wish to delete your .ipython dir.
2931
2936
2932 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2937 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2933 new users)
2938 new users)
2934
2939
2935 """
2940 """
2936 ip = self.getapi()
2941 ip = self.getapi()
2937 ipinstallation = path(IPython.__file__).dirname()
2942 ipinstallation = path(IPython.__file__).dirname()
2938 upgrade_script = sys.executable + " " + ipinstallation / 'upgrade_dir.py'
2943 upgrade_script = sys.executable + " " + ipinstallation / 'upgrade_dir.py'
2939 src_config = ipinstallation / 'UserConfig'
2944 src_config = ipinstallation / 'UserConfig'
2940 userdir = path(ip.options.ipythondir)
2945 userdir = path(ip.options.ipythondir)
2941 cmd = upgrade_script + " " + src_config + " " + userdir
2946 cmd = upgrade_script + " " + src_config + " " + userdir
2942 print ">",cmd
2947 print ">",cmd
2943 shell(cmd)
2948 shell(cmd)
2944 if arg == '-nolegacy':
2949 if arg == '-nolegacy':
2945 legacy = userdir.files('ipythonrc*')
2950 legacy = userdir.files('ipythonrc*')
2946 print "Nuking legacy files:",legacy
2951 print "Nuking legacy files:",legacy
2947
2952
2948 [p.remove() for p in legacy]
2953 [p.remove() for p in legacy]
2949 suffix = (sys.platform == 'win32' and '.ini' or '')
2954 suffix = (sys.platform == 'win32' and '.ini' or '')
2950 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
2955 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
2951
2956
2952
2957
2953 # end Magic
2958 # end Magic
@@ -1,570 +1,581 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 ---------------------------------------------------------------------------
9 ---------------------------------------------------------------------------
10 Original rlcompleter documentation:
10 Original rlcompleter documentation:
11
11
12 This requires the latest extension to the readline module (the
12 This requires the latest extension to the readline module (the
13 completes keywords, built-ins and globals in __main__; when completing
13 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
15 completes its attributes.
16
16
17 It's very cool to do "import string" type "string.", hit the
17 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
18 completion key (twice), and see the list of names defined by the
19 string module!
19 string module!
20
20
21 Tip: to use the tab key as the completion key, call
21 Tip: to use the tab key as the completion key, call
22
22
23 readline.parse_and_bind("tab: complete")
23 readline.parse_and_bind("tab: complete")
24
24
25 Notes:
25 Notes:
26
26
27 - Exceptions raised by the completer function are *ignored* (and
27 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
28 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
29 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
30 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
31 reset and restore the tty state.
32
32
33 - The evaluation of the NAME.NAME... form may cause arbitrary
33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
34 application defined code to be executed if an object with a
35 __getattr__ hook is found. Since it is the responsibility of the
35 __getattr__ hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
36 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
37 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
38 indexing operations) are *not* evaluated.
39
39
40 - GNU readline is also used by the built-in functions input() and
40 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
41 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
42 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
43 specifying its own completer function and using raw_input() for all
44 its input.
44 its input.
45
45
46 - When the original stdin is not a tty device, GNU readline is never
46 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
47 used, and this module (and the readline module) are silently inactive.
48
48
49 """
49 """
50
50
51 #*****************************************************************************
51 #*****************************************************************************
52 #
52 #
53 # Since this file is essentially a minimally modified copy of the rlcompleter
53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 # module which is part of the standard Python distribution, I assume that the
54 # module which is part of the standard Python distribution, I assume that the
55 # proper procedure is to maintain its copyright as belonging to the Python
55 # proper procedure is to maintain its copyright as belonging to the Python
56 # Software Foundation (in addition to my own, for all new code).
56 # Software Foundation (in addition to my own, for all new code).
57 #
57 #
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
60 #
60 #
61 # Distributed under the terms of the BSD License. The full license is in
61 # Distributed under the terms of the BSD License. The full license is in
62 # the file COPYING, distributed as part of this software.
62 # the file COPYING, distributed as part of this software.
63 #
63 #
64 #*****************************************************************************
64 #*****************************************************************************
65
65
66 import __builtin__
66 import __builtin__
67 import __main__
67 import __main__
68 import glob
68 import glob
69 import keyword
69 import keyword
70 import os
70 import os
71 import re
71 import re
72 import shlex
72 import shlex
73 import sys
73 import sys
74 import IPython.rlineimpl as readline
74 import IPython.rlineimpl as readline
75
75
76 import types
76 import types
77
77
78 # Python 2.4 offers sets as a builtin
78 # Python 2.4 offers sets as a builtin
79 try:
79 try:
80 set([1,2])
80 set([1,2])
81 except NameError:
81 except NameError:
82 from sets import Set as set
82 from sets import Set as set
83
83
84 from IPython.genutils import debugx
84 from IPython.genutils import debugx
85
85
86 __all__ = ['Completer','IPCompleter']
86 __all__ = ['Completer','IPCompleter']
87
87
88 def get_class_members(cls):
88 def get_class_members(cls):
89 ret = dir(cls)
89 ret = dir(cls)
90 if hasattr(cls,'__bases__'):
90 if hasattr(cls,'__bases__'):
91 for base in cls.__bases__:
91 for base in cls.__bases__:
92 ret.extend(get_class_members(base))
92 ret.extend(get_class_members(base))
93 return ret
93 return ret
94
94
95 class Completer:
95 class Completer:
96 def __init__(self,namespace=None,global_namespace=None):
96 def __init__(self,namespace=None,global_namespace=None):
97 """Create a new completer for the command line.
97 """Create a new completer for the command line.
98
98
99 Completer([namespace,global_namespace]) -> completer instance.
99 Completer([namespace,global_namespace]) -> completer instance.
100
100
101 If unspecified, the default namespace where completions are performed
101 If unspecified, the default namespace where completions are performed
102 is __main__ (technically, __main__.__dict__). Namespaces should be
102 is __main__ (technically, __main__.__dict__). Namespaces should be
103 given as dictionaries.
103 given as dictionaries.
104
104
105 An optional second namespace can be given. This allows the completer
105 An optional second namespace can be given. This allows the completer
106 to handle cases where both the local and global scopes need to be
106 to handle cases where both the local and global scopes need to be
107 distinguished.
107 distinguished.
108
108
109 Completer instances should be used as the completion mechanism of
109 Completer instances should be used as the completion mechanism of
110 readline via the set_completer() call:
110 readline via the set_completer() call:
111
111
112 readline.set_completer(Completer(my_namespace).complete)
112 readline.set_completer(Completer(my_namespace).complete)
113 """
113 """
114
114
115 # some minimal strict typechecks. For some core data structures, I
115 # some minimal strict typechecks. For some core data structures, I
116 # want actual basic python types, not just anything that looks like
116 # want actual basic python types, not just anything that looks like
117 # one. This is especially true for namespaces.
117 # one. This is especially true for namespaces.
118 for ns in (namespace,global_namespace):
118 for ns in (namespace,global_namespace):
119 if ns is not None and type(ns) != types.DictType:
119 if ns is not None and type(ns) != types.DictType:
120 raise TypeError,'namespace must be a dictionary'
120 raise TypeError,'namespace must be a dictionary'
121
121
122 # Don't bind to namespace quite yet, but flag whether the user wants a
122 # Don't bind to namespace quite yet, but flag whether the user wants a
123 # specific namespace or to use __main__.__dict__. This will allow us
123 # specific namespace or to use __main__.__dict__. This will allow us
124 # to bind to __main__.__dict__ at completion time, not now.
124 # to bind to __main__.__dict__ at completion time, not now.
125 if namespace is None:
125 if namespace is None:
126 self.use_main_ns = 1
126 self.use_main_ns = 1
127 else:
127 else:
128 self.use_main_ns = 0
128 self.use_main_ns = 0
129 self.namespace = namespace
129 self.namespace = namespace
130
130
131 # The global namespace, if given, can be bound directly
131 # The global namespace, if given, can be bound directly
132 if global_namespace is None:
132 if global_namespace is None:
133 self.global_namespace = {}
133 self.global_namespace = {}
134 else:
134 else:
135 self.global_namespace = global_namespace
135 self.global_namespace = global_namespace
136
136
137 def complete(self, text, state):
137 def complete(self, text, state):
138 """Return the next possible completion for 'text'.
138 """Return the next possible completion for 'text'.
139
139
140 This is called successively with state == 0, 1, 2, ... until it
140 This is called successively with state == 0, 1, 2, ... until it
141 returns None. The completion should begin with 'text'.
141 returns None. The completion should begin with 'text'.
142
142
143 """
143 """
144 if self.use_main_ns:
144 if self.use_main_ns:
145 self.namespace = __main__.__dict__
145 self.namespace = __main__.__dict__
146
146
147 if state == 0:
147 if state == 0:
148 if "." in text:
148 if "." in text:
149 self.matches = self.attr_matches(text)
149 self.matches = self.attr_matches(text)
150 else:
150 else:
151 self.matches = self.global_matches(text)
151 self.matches = self.global_matches(text)
152 try:
152 try:
153 return self.matches[state]
153 return self.matches[state]
154 except IndexError:
154 except IndexError:
155 return None
155 return None
156
156
157 def global_matches(self, text):
157 def global_matches(self, text):
158 """Compute matches when text is a simple name.
158 """Compute matches when text is a simple name.
159
159
160 Return a list of all keywords, built-in functions and names currently
160 Return a list of all keywords, built-in functions and names currently
161 defined in self.namespace or self.global_namespace that match.
161 defined in self.namespace or self.global_namespace that match.
162
162
163 """
163 """
164 matches = []
164 matches = []
165 match_append = matches.append
165 match_append = matches.append
166 n = len(text)
166 n = len(text)
167 for lst in [keyword.kwlist,
167 for lst in [keyword.kwlist,
168 __builtin__.__dict__.keys(),
168 __builtin__.__dict__.keys(),
169 self.namespace.keys(),
169 self.namespace.keys(),
170 self.global_namespace.keys()]:
170 self.global_namespace.keys()]:
171 for word in lst:
171 for word in lst:
172 if word[:n] == text and word != "__builtins__":
172 if word[:n] == text and word != "__builtins__":
173 match_append(word)
173 match_append(word)
174 return matches
174 return matches
175
175
176 def attr_matches(self, text):
176 def attr_matches(self, text):
177 """Compute matches when text contains a dot.
177 """Compute matches when text contains a dot.
178
178
179 Assuming the text is of the form NAME.NAME....[NAME], and is
179 Assuming the text is of the form NAME.NAME....[NAME], and is
180 evaluatable in self.namespace or self.global_namespace, it will be
180 evaluatable in self.namespace or self.global_namespace, it will be
181 evaluated and its attributes (as revealed by dir()) are used as
181 evaluated and its attributes (as revealed by dir()) are used as
182 possible completions. (For class instances, class members are are
182 possible completions. (For class instances, class members are are
183 also considered.)
183 also considered.)
184
184
185 WARNING: this can still invoke arbitrary C code, if an object
185 WARNING: this can still invoke arbitrary C code, if an object
186 with a __getattr__ hook is evaluated.
186 with a __getattr__ hook is evaluated.
187
187
188 """
188 """
189 import re
189 import re
190
190
191 # Another option, seems to work great. Catches things like ''.<tab>
191 # Another option, seems to work great. Catches things like ''.<tab>
192 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
192 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
193
193
194 if not m:
194 if not m:
195 return []
195 return []
196
196
197 expr, attr = m.group(1, 3)
197 expr, attr = m.group(1, 3)
198 try:
198 try:
199 object = eval(expr, self.namespace)
199 object = eval(expr, self.namespace)
200 except:
200 except:
201 object = eval(expr, self.global_namespace)
201 object = eval(expr, self.global_namespace)
202
202
203 # Start building the attribute list via dir(), and then complete it
203 # Start building the attribute list via dir(), and then complete it
204 # with a few extra special-purpose calls.
204 # with a few extra special-purpose calls.
205 words = dir(object)
205 words = dir(object)
206
206
207 if hasattr(object,'__class__'):
207 if hasattr(object,'__class__'):
208 words.append('__class__')
208 words.append('__class__')
209 words.extend(get_class_members(object.__class__))
209 words.extend(get_class_members(object.__class__))
210
210
211 # this is the 'dir' function for objects with Enthought's traits
211 # this is the 'dir' function for objects with Enthought's traits
212 if hasattr(object, 'trait_names'):
212 if hasattr(object, 'trait_names'):
213 try:
213 try:
214 words.extend(object.trait_names())
214 words.extend(object.trait_names())
215 # eliminate possible duplicates, as some traits may also
215 # eliminate possible duplicates, as some traits may also
216 # appear as normal attributes in the dir() call.
216 # appear as normal attributes in the dir() call.
217 words = set(words)
217 words = set(words)
218 except TypeError:
218 except TypeError:
219 # This will happen if `object` is a class and not an instance.
219 # This will happen if `object` is a class and not an instance.
220 pass
220 pass
221
221
222 # Support for PyCrust-style _getAttributeNames magic method.
223 if hasattr(object, '_getAttributeNames'):
224 try:
225 words.extend(object._getAttributeNames())
226 # Eliminate duplicates.
227 words = set(words)
228 except TypeError:
229 # `object` is a class and not an instance. Ignore
230 # this error.
231 pass
232
222 # filter out non-string attributes which may be stuffed by dir() calls
233 # filter out non-string attributes which may be stuffed by dir() calls
223 # and poor coding in third-party modules
234 # and poor coding in third-party modules
224 words = [w for w in words
235 words = [w for w in words
225 if isinstance(w, basestring) and w != "__builtins__"]
236 if isinstance(w, basestring) and w != "__builtins__"]
226 # Build match list to return
237 # Build match list to return
227 n = len(attr)
238 n = len(attr)
228 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
239 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
229
240
230 class IPCompleter(Completer):
241 class IPCompleter(Completer):
231 """Extension of the completer class with IPython-specific features"""
242 """Extension of the completer class with IPython-specific features"""
232
243
233 def __init__(self,shell,namespace=None,global_namespace=None,
244 def __init__(self,shell,namespace=None,global_namespace=None,
234 omit__names=0,alias_table=None):
245 omit__names=0,alias_table=None):
235 """IPCompleter() -> completer
246 """IPCompleter() -> completer
236
247
237 Return a completer object suitable for use by the readline library
248 Return a completer object suitable for use by the readline library
238 via readline.set_completer().
249 via readline.set_completer().
239
250
240 Inputs:
251 Inputs:
241
252
242 - shell: a pointer to the ipython shell itself. This is needed
253 - shell: a pointer to the ipython shell itself. This is needed
243 because this completer knows about magic functions, and those can
254 because this completer knows about magic functions, and those can
244 only be accessed via the ipython instance.
255 only be accessed via the ipython instance.
245
256
246 - namespace: an optional dict where completions are performed.
257 - namespace: an optional dict where completions are performed.
247
258
248 - global_namespace: secondary optional dict for completions, to
259 - global_namespace: secondary optional dict for completions, to
249 handle cases (such as IPython embedded inside functions) where
260 handle cases (such as IPython embedded inside functions) where
250 both Python scopes are visible.
261 both Python scopes are visible.
251
262
252 - The optional omit__names parameter sets the completer to omit the
263 - The optional omit__names parameter sets the completer to omit the
253 'magic' names (__magicname__) for python objects unless the text
264 'magic' names (__magicname__) for python objects unless the text
254 to be completed explicitly starts with one or more underscores.
265 to be completed explicitly starts with one or more underscores.
255
266
256 - If alias_table is supplied, it should be a dictionary of aliases
267 - If alias_table is supplied, it should be a dictionary of aliases
257 to complete. """
268 to complete. """
258
269
259 Completer.__init__(self,namespace,global_namespace)
270 Completer.__init__(self,namespace,global_namespace)
260 self.magic_prefix = shell.name+'.magic_'
271 self.magic_prefix = shell.name+'.magic_'
261 self.magic_escape = shell.ESC_MAGIC
272 self.magic_escape = shell.ESC_MAGIC
262 self.readline = readline
273 self.readline = readline
263 delims = self.readline.get_completer_delims()
274 delims = self.readline.get_completer_delims()
264 delims = delims.replace(self.magic_escape,'')
275 delims = delims.replace(self.magic_escape,'')
265 self.readline.set_completer_delims(delims)
276 self.readline.set_completer_delims(delims)
266 self.get_line_buffer = self.readline.get_line_buffer
277 self.get_line_buffer = self.readline.get_line_buffer
267 self.omit__names = omit__names
278 self.omit__names = omit__names
268 self.merge_completions = shell.rc.readline_merge_completions
279 self.merge_completions = shell.rc.readline_merge_completions
269
280
270 if alias_table is None:
281 if alias_table is None:
271 alias_table = {}
282 alias_table = {}
272 self.alias_table = alias_table
283 self.alias_table = alias_table
273 # Regexp to split filenames with spaces in them
284 # Regexp to split filenames with spaces in them
274 self.space_name_re = re.compile(r'([^\\] )')
285 self.space_name_re = re.compile(r'([^\\] )')
275 # Hold a local ref. to glob.glob for speed
286 # Hold a local ref. to glob.glob for speed
276 self.glob = glob.glob
287 self.glob = glob.glob
277
288
278 # Determine if we are running on 'dumb' terminals, like (X)Emacs
289 # Determine if we are running on 'dumb' terminals, like (X)Emacs
279 # buffers, to avoid completion problems.
290 # buffers, to avoid completion problems.
280 term = os.environ.get('TERM','xterm')
291 term = os.environ.get('TERM','xterm')
281 self.dumb_terminal = term in ['dumb','emacs']
292 self.dumb_terminal = term in ['dumb','emacs']
282
293
283 # Special handling of backslashes needed in win32 platforms
294 # Special handling of backslashes needed in win32 platforms
284 if sys.platform == "win32":
295 if sys.platform == "win32":
285 self.clean_glob = self._clean_glob_win32
296 self.clean_glob = self._clean_glob_win32
286 else:
297 else:
287 self.clean_glob = self._clean_glob
298 self.clean_glob = self._clean_glob
288 self.matchers = [self.python_matches,
299 self.matchers = [self.python_matches,
289 self.file_matches,
300 self.file_matches,
290 self.alias_matches,
301 self.alias_matches,
291 self.python_func_kw_matches]
302 self.python_func_kw_matches]
292
303
293 # Code contributed by Alex Schmolck, for ipython/emacs integration
304 # Code contributed by Alex Schmolck, for ipython/emacs integration
294 def all_completions(self, text):
305 def all_completions(self, text):
295 """Return all possible completions for the benefit of emacs."""
306 """Return all possible completions for the benefit of emacs."""
296
307
297 completions = []
308 completions = []
298 comp_append = completions.append
309 comp_append = completions.append
299 try:
310 try:
300 for i in xrange(sys.maxint):
311 for i in xrange(sys.maxint):
301 res = self.complete(text, i)
312 res = self.complete(text, i)
302
313
303 if not res: break
314 if not res: break
304
315
305 comp_append(res)
316 comp_append(res)
306 #XXX workaround for ``notDefined.<tab>``
317 #XXX workaround for ``notDefined.<tab>``
307 except NameError:
318 except NameError:
308 pass
319 pass
309 return completions
320 return completions
310 # /end Alex Schmolck code.
321 # /end Alex Schmolck code.
311
322
312 def _clean_glob(self,text):
323 def _clean_glob(self,text):
313 return self.glob("%s*" % text)
324 return self.glob("%s*" % text)
314
325
315 def _clean_glob_win32(self,text):
326 def _clean_glob_win32(self,text):
316 return [f.replace("\\","/")
327 return [f.replace("\\","/")
317 for f in self.glob("%s*" % text)]
328 for f in self.glob("%s*" % text)]
318
329
319 def file_matches(self, text):
330 def file_matches(self, text):
320 """Match filneames, expanding ~USER type strings.
331 """Match filneames, expanding ~USER type strings.
321
332
322 Most of the seemingly convoluted logic in this completer is an
333 Most of the seemingly convoluted logic in this completer is an
323 attempt to handle filenames with spaces in them. And yet it's not
334 attempt to handle filenames with spaces in them. And yet it's not
324 quite perfect, because Python's readline doesn't expose all of the
335 quite perfect, because Python's readline doesn't expose all of the
325 GNU readline details needed for this to be done correctly.
336 GNU readline details needed for this to be done correctly.
326
337
327 For a filename with a space in it, the printed completions will be
338 For a filename with a space in it, the printed completions will be
328 only the parts after what's already been typed (instead of the
339 only the parts after what's already been typed (instead of the
329 full completions, as is normally done). I don't think with the
340 full completions, as is normally done). I don't think with the
330 current (as of Python 2.3) Python readline it's possible to do
341 current (as of Python 2.3) Python readline it's possible to do
331 better."""
342 better."""
332
343
333 #print 'Completer->file_matches: <%s>' % text # dbg
344 #print 'Completer->file_matches: <%s>' % text # dbg
334
345
335 # chars that require escaping with backslash - i.e. chars
346 # chars that require escaping with backslash - i.e. chars
336 # that readline treats incorrectly as delimiters, but we
347 # that readline treats incorrectly as delimiters, but we
337 # don't want to treat as delimiters in filename matching
348 # don't want to treat as delimiters in filename matching
338 # when escaped with backslash
349 # when escaped with backslash
339
350
340 protectables = ' ()[]{}'
351 protectables = ' ()[]{}'
341
352
342 def protect_filename(s):
353 def protect_filename(s):
343 return "".join([(ch in protectables and '\\' + ch or ch)
354 return "".join([(ch in protectables and '\\' + ch or ch)
344 for ch in s])
355 for ch in s])
345
356
346 lbuf = self.lbuf
357 lbuf = self.lbuf
347 open_quotes = 0 # track strings with open quotes
358 open_quotes = 0 # track strings with open quotes
348 try:
359 try:
349 lsplit = shlex.split(lbuf)[-1]
360 lsplit = shlex.split(lbuf)[-1]
350 except ValueError:
361 except ValueError:
351 # typically an unmatched ", or backslash without escaped char.
362 # typically an unmatched ", or backslash without escaped char.
352 if lbuf.count('"')==1:
363 if lbuf.count('"')==1:
353 open_quotes = 1
364 open_quotes = 1
354 lsplit = lbuf.split('"')[-1]
365 lsplit = lbuf.split('"')[-1]
355 elif lbuf.count("'")==1:
366 elif lbuf.count("'")==1:
356 open_quotes = 1
367 open_quotes = 1
357 lsplit = lbuf.split("'")[-1]
368 lsplit = lbuf.split("'")[-1]
358 else:
369 else:
359 return None
370 return None
360 except IndexError:
371 except IndexError:
361 # tab pressed on empty line
372 # tab pressed on empty line
362 lsplit = ""
373 lsplit = ""
363
374
364 if lsplit != protect_filename(lsplit):
375 if lsplit != protect_filename(lsplit):
365 # if protectables are found, do matching on the whole escaped
376 # if protectables are found, do matching on the whole escaped
366 # name
377 # name
367 has_protectables = 1
378 has_protectables = 1
368 text0,text = text,lsplit
379 text0,text = text,lsplit
369 else:
380 else:
370 has_protectables = 0
381 has_protectables = 0
371 text = os.path.expanduser(text)
382 text = os.path.expanduser(text)
372
383
373 if text == "":
384 if text == "":
374 return [protect_filename(f) for f in self.glob("*")]
385 return [protect_filename(f) for f in self.glob("*")]
375
386
376 m0 = self.clean_glob(text.replace('\\',''))
387 m0 = self.clean_glob(text.replace('\\',''))
377 if has_protectables:
388 if has_protectables:
378 # If we had protectables, we need to revert our changes to the
389 # If we had protectables, we need to revert our changes to the
379 # beginning of filename so that we don't double-write the part
390 # beginning of filename so that we don't double-write the part
380 # of the filename we have so far
391 # of the filename we have so far
381 len_lsplit = len(lsplit)
392 len_lsplit = len(lsplit)
382 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
393 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
383 else:
394 else:
384 if open_quotes:
395 if open_quotes:
385 # if we have a string with an open quote, we don't need to
396 # if we have a string with an open quote, we don't need to
386 # protect the names at all (and we _shouldn't_, as it
397 # protect the names at all (and we _shouldn't_, as it
387 # would cause bugs when the filesystem call is made).
398 # would cause bugs when the filesystem call is made).
388 matches = m0
399 matches = m0
389 else:
400 else:
390 matches = [protect_filename(f) for f in m0]
401 matches = [protect_filename(f) for f in m0]
391 if len(matches) == 1 and os.path.isdir(matches[0]):
402 if len(matches) == 1 and os.path.isdir(matches[0]):
392 # Takes care of links to directories also. Use '/'
403 # Takes care of links to directories also. Use '/'
393 # explicitly, even under Windows, so that name completions
404 # explicitly, even under Windows, so that name completions
394 # don't end up escaped.
405 # don't end up escaped.
395 matches[0] += '/'
406 matches[0] += '/'
396 return matches
407 return matches
397
408
398 def alias_matches(self, text):
409 def alias_matches(self, text):
399 """Match internal system aliases"""
410 """Match internal system aliases"""
400 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
411 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
401
412
402 # if we are not in the first 'item', alias matching
413 # if we are not in the first 'item', alias matching
403 # doesn't make sense
414 # doesn't make sense
404 if ' ' in self.lbuf:
415 if ' ' in self.lbuf:
405 return []
416 return []
406 text = os.path.expanduser(text)
417 text = os.path.expanduser(text)
407 aliases = self.alias_table.keys()
418 aliases = self.alias_table.keys()
408 if text == "":
419 if text == "":
409 return aliases
420 return aliases
410 else:
421 else:
411 return [alias for alias in aliases if alias.startswith(text)]
422 return [alias for alias in aliases if alias.startswith(text)]
412
423
413 def python_matches(self,text):
424 def python_matches(self,text):
414 """Match attributes or global python names"""
425 """Match attributes or global python names"""
415
426
416 #print 'Completer->python_matches, txt=<%s>' % text # dbg
427 #print 'Completer->python_matches, txt=<%s>' % text # dbg
417 if "." in text:
428 if "." in text:
418 try:
429 try:
419 matches = self.attr_matches(text)
430 matches = self.attr_matches(text)
420 if text.endswith('.') and self.omit__names:
431 if text.endswith('.') and self.omit__names:
421 if self.omit__names == 1:
432 if self.omit__names == 1:
422 # true if txt is _not_ a __ name, false otherwise:
433 # true if txt is _not_ a __ name, false otherwise:
423 no__name = (lambda txt:
434 no__name = (lambda txt:
424 re.match(r'.*\.__.*?__',txt) is None)
435 re.match(r'.*\.__.*?__',txt) is None)
425 else:
436 else:
426 # true if txt is _not_ a _ name, false otherwise:
437 # true if txt is _not_ a _ name, false otherwise:
427 no__name = (lambda txt:
438 no__name = (lambda txt:
428 re.match(r'.*\._.*?',txt) is None)
439 re.match(r'.*\._.*?',txt) is None)
429 matches = filter(no__name, matches)
440 matches = filter(no__name, matches)
430 except NameError:
441 except NameError:
431 # catches <undefined attributes>.<tab>
442 # catches <undefined attributes>.<tab>
432 matches = []
443 matches = []
433 else:
444 else:
434 matches = self.global_matches(text)
445 matches = self.global_matches(text)
435 # this is so completion finds magics when automagic is on:
446 # this is so completion finds magics when automagic is on:
436 if (matches == [] and
447 if (matches == [] and
437 not text.startswith(os.sep) and
448 not text.startswith(os.sep) and
438 not ' ' in self.lbuf):
449 not ' ' in self.lbuf):
439 matches = self.attr_matches(self.magic_prefix+text)
450 matches = self.attr_matches(self.magic_prefix+text)
440 return matches
451 return matches
441
452
442 def _default_arguments(self, obj):
453 def _default_arguments(self, obj):
443 """Return the list of default arguments of obj if it is callable,
454 """Return the list of default arguments of obj if it is callable,
444 or empty list otherwise."""
455 or empty list otherwise."""
445
456
446 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
457 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
447 # for classes, check for __init__,__new__
458 # for classes, check for __init__,__new__
448 if inspect.isclass(obj):
459 if inspect.isclass(obj):
449 obj = (getattr(obj,'__init__',None) or
460 obj = (getattr(obj,'__init__',None) or
450 getattr(obj,'__new__',None))
461 getattr(obj,'__new__',None))
451 # for all others, check if they are __call__able
462 # for all others, check if they are __call__able
452 elif hasattr(obj, '__call__'):
463 elif hasattr(obj, '__call__'):
453 obj = obj.__call__
464 obj = obj.__call__
454 # XXX: is there a way to handle the builtins ?
465 # XXX: is there a way to handle the builtins ?
455 try:
466 try:
456 args,_,_1,defaults = inspect.getargspec(obj)
467 args,_,_1,defaults = inspect.getargspec(obj)
457 if defaults:
468 if defaults:
458 return args[-len(defaults):]
469 return args[-len(defaults):]
459 except TypeError: pass
470 except TypeError: pass
460 return []
471 return []
461
472
462 def python_func_kw_matches(self,text):
473 def python_func_kw_matches(self,text):
463 """Match named parameters (kwargs) of the last open function"""
474 """Match named parameters (kwargs) of the last open function"""
464
475
465 if "." in text: # a parameter cannot be dotted
476 if "." in text: # a parameter cannot be dotted
466 return []
477 return []
467 try: regexp = self.__funcParamsRegex
478 try: regexp = self.__funcParamsRegex
468 except AttributeError:
479 except AttributeError:
469 regexp = self.__funcParamsRegex = re.compile(r'''
480 regexp = self.__funcParamsRegex = re.compile(r'''
470 '.*?' | # single quoted strings or
481 '.*?' | # single quoted strings or
471 ".*?" | # double quoted strings or
482 ".*?" | # double quoted strings or
472 \w+ | # identifier
483 \w+ | # identifier
473 \S # other characters
484 \S # other characters
474 ''', re.VERBOSE | re.DOTALL)
485 ''', re.VERBOSE | re.DOTALL)
475 # 1. find the nearest identifier that comes before an unclosed
486 # 1. find the nearest identifier that comes before an unclosed
476 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
487 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
477 tokens = regexp.findall(self.get_line_buffer())
488 tokens = regexp.findall(self.get_line_buffer())
478 tokens.reverse()
489 tokens.reverse()
479 iterTokens = iter(tokens); openPar = 0
490 iterTokens = iter(tokens); openPar = 0
480 for token in iterTokens:
491 for token in iterTokens:
481 if token == ')':
492 if token == ')':
482 openPar -= 1
493 openPar -= 1
483 elif token == '(':
494 elif token == '(':
484 openPar += 1
495 openPar += 1
485 if openPar > 0:
496 if openPar > 0:
486 # found the last unclosed parenthesis
497 # found the last unclosed parenthesis
487 break
498 break
488 else:
499 else:
489 return []
500 return []
490 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
501 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
491 ids = []
502 ids = []
492 isId = re.compile(r'\w+$').match
503 isId = re.compile(r'\w+$').match
493 while True:
504 while True:
494 try:
505 try:
495 ids.append(iterTokens.next())
506 ids.append(iterTokens.next())
496 if not isId(ids[-1]):
507 if not isId(ids[-1]):
497 ids.pop(); break
508 ids.pop(); break
498 if not iterTokens.next() == '.':
509 if not iterTokens.next() == '.':
499 break
510 break
500 except StopIteration:
511 except StopIteration:
501 break
512 break
502 # lookup the candidate callable matches either using global_matches
513 # lookup the candidate callable matches either using global_matches
503 # or attr_matches for dotted names
514 # or attr_matches for dotted names
504 if len(ids) == 1:
515 if len(ids) == 1:
505 callableMatches = self.global_matches(ids[0])
516 callableMatches = self.global_matches(ids[0])
506 else:
517 else:
507 callableMatches = self.attr_matches('.'.join(ids[::-1]))
518 callableMatches = self.attr_matches('.'.join(ids[::-1]))
508 argMatches = []
519 argMatches = []
509 for callableMatch in callableMatches:
520 for callableMatch in callableMatches:
510 try: namedArgs = self._default_arguments(eval(callableMatch,
521 try: namedArgs = self._default_arguments(eval(callableMatch,
511 self.namespace))
522 self.namespace))
512 except: continue
523 except: continue
513 for namedArg in namedArgs:
524 for namedArg in namedArgs:
514 if namedArg.startswith(text):
525 if namedArg.startswith(text):
515 argMatches.append("%s=" %namedArg)
526 argMatches.append("%s=" %namedArg)
516 return argMatches
527 return argMatches
517
528
518 def complete(self, text, state):
529 def complete(self, text, state):
519 """Return the next possible completion for 'text'.
530 """Return the next possible completion for 'text'.
520
531
521 This is called successively with state == 0, 1, 2, ... until it
532 This is called successively with state == 0, 1, 2, ... until it
522 returns None. The completion should begin with 'text'. """
533 returns None. The completion should begin with 'text'. """
523
534
524 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
535 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
525
536
526 # if there is only a tab on a line with only whitespace, instead
537 # if there is only a tab on a line with only whitespace, instead
527 # of the mostly useless 'do you want to see all million
538 # of the mostly useless 'do you want to see all million
528 # completions' message, just do the right thing and give the user
539 # completions' message, just do the right thing and give the user
529 # his tab! Incidentally, this enables pasting of tabbed text from
540 # his tab! Incidentally, this enables pasting of tabbed text from
530 # an editor (as long as autoindent is off).
541 # an editor (as long as autoindent is off).
531
542
532 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
543 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
533 # don't interfere with their own tab-completion mechanism.
544 # don't interfere with their own tab-completion mechanism.
534 self.lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
545 self.lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
535 if not (self.dumb_terminal or self.get_line_buffer().strip()):
546 if not (self.dumb_terminal or self.get_line_buffer().strip()):
536 self.readline.insert_text('\t')
547 self.readline.insert_text('\t')
537 return None
548 return None
538
549
539 magic_escape = self.magic_escape
550 magic_escape = self.magic_escape
540 magic_prefix = self.magic_prefix
551 magic_prefix = self.magic_prefix
541
552
542 try:
553 try:
543 if text.startswith(magic_escape):
554 if text.startswith(magic_escape):
544 text = text.replace(magic_escape,magic_prefix)
555 text = text.replace(magic_escape,magic_prefix)
545 elif text.startswith('~'):
556 elif text.startswith('~'):
546 text = os.path.expanduser(text)
557 text = os.path.expanduser(text)
547 if state == 0:
558 if state == 0:
548 # Extend the list of completions with the results of each
559 # Extend the list of completions with the results of each
549 # matcher, so we return results to the user from all
560 # matcher, so we return results to the user from all
550 # namespaces.
561 # namespaces.
551 if self.merge_completions:
562 if self.merge_completions:
552 self.matches = []
563 self.matches = []
553 for matcher in self.matchers:
564 for matcher in self.matchers:
554 self.matches.extend(matcher(text))
565 self.matches.extend(matcher(text))
555 else:
566 else:
556 for matcher in self.matchers:
567 for matcher in self.matchers:
557 self.matches = matcher(text)
568 self.matches = matcher(text)
558 if self.matches:
569 if self.matches:
559 break
570 break
560
571
561 try:
572 try:
562 return self.matches[state].replace(magic_prefix,magic_escape)
573 return self.matches[state].replace(magic_prefix,magic_escape)
563 except IndexError:
574 except IndexError:
564 return None
575 return None
565 except:
576 except:
566 #from IPython.ultraTB import AutoFormattedTB; # dbg
577 #from IPython.ultraTB import AutoFormattedTB; # dbg
567 #tb=AutoFormattedTB('Verbose');tb() #dbg
578 #tb=AutoFormattedTB('Verbose');tb() #dbg
568
579
569 # If completion fails, don't annoy the user.
580 # If completion fails, don't annoy the user.
570 return None
581 return None
@@ -1,1703 +1,1708 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 1314 2006-05-19 18:24:14Z fperez $"""
8 $Id: genutils.py 1322 2006-05-24 07:51:39Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __license__ = Release.license
19 __license__ = Release.license
20
20
21 #****************************************************************************
21 #****************************************************************************
22 # required modules from the Python standard library
22 # required modules from the Python standard library
23 import __main__
23 import __main__
24 import commands
24 import commands
25 import os
25 import os
26 import re
26 import re
27 import shutil
27 import shutil
28 import sys
28 import sys
29 import tempfile
29 import tempfile
30 import time
30 import time
31 import types
31 import types
32
32
33 # Other IPython utilities
33 # Other IPython utilities
34 from IPython.Itpl import Itpl,itpl,printpl
34 from IPython.Itpl import Itpl,itpl,printpl
35 from IPython import DPyGetOpt
35 from IPython import DPyGetOpt
36 from path import path
36 from path import path
37 if os.name == "nt":
37 if os.name == "nt":
38 from IPython.winconsole import get_console_size
38 from IPython.winconsole import get_console_size
39
39
40 #****************************************************************************
40 #****************************************************************************
41 # Exceptions
41 # Exceptions
42 class Error(Exception):
42 class Error(Exception):
43 """Base class for exceptions in this module."""
43 """Base class for exceptions in this module."""
44 pass
44 pass
45
45
46 #----------------------------------------------------------------------------
46 #----------------------------------------------------------------------------
47 class IOStream:
47 class IOStream:
48 def __init__(self,stream,fallback):
48 def __init__(self,stream,fallback):
49 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
49 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
50 stream = fallback
50 stream = fallback
51 self.stream = stream
51 self.stream = stream
52 self._swrite = stream.write
52 self._swrite = stream.write
53 self.flush = stream.flush
53 self.flush = stream.flush
54
54
55 def write(self,data):
55 def write(self,data):
56 try:
56 try:
57 self._swrite(data)
57 self._swrite(data)
58 except:
58 except:
59 try:
59 try:
60 # print handles some unicode issues which may trip a plain
60 # print handles some unicode issues which may trip a plain
61 # write() call. Attempt to emulate write() by using a
61 # write() call. Attempt to emulate write() by using a
62 # trailing comma
62 # trailing comma
63 print >> self.stream, data,
63 print >> self.stream, data,
64 except:
64 except:
65 # if we get here, something is seriously broken.
65 # if we get here, something is seriously broken.
66 print >> sys.stderr, \
66 print >> sys.stderr, \
67 'ERROR - failed to write data to stream:', self.stream
67 'ERROR - failed to write data to stream:', self.stream
68
68
69 class IOTerm:
69 class IOTerm:
70 """ Term holds the file or file-like objects for handling I/O operations.
70 """ Term holds the file or file-like objects for handling I/O operations.
71
71
72 These are normally just sys.stdin, sys.stdout and sys.stderr but for
72 These are normally just sys.stdin, sys.stdout and sys.stderr but for
73 Windows they can can replaced to allow editing the strings before they are
73 Windows they can can replaced to allow editing the strings before they are
74 displayed."""
74 displayed."""
75
75
76 # In the future, having IPython channel all its I/O operations through
76 # In the future, having IPython channel all its I/O operations through
77 # this class will make it easier to embed it into other environments which
77 # this class will make it easier to embed it into other environments which
78 # are not a normal terminal (such as a GUI-based shell)
78 # are not a normal terminal (such as a GUI-based shell)
79 def __init__(self,cin=None,cout=None,cerr=None):
79 def __init__(self,cin=None,cout=None,cerr=None):
80 self.cin = IOStream(cin,sys.stdin)
80 self.cin = IOStream(cin,sys.stdin)
81 self.cout = IOStream(cout,sys.stdout)
81 self.cout = IOStream(cout,sys.stdout)
82 self.cerr = IOStream(cerr,sys.stderr)
82 self.cerr = IOStream(cerr,sys.stderr)
83
83
84 # Global variable to be used for all I/O
84 # Global variable to be used for all I/O
85 Term = IOTerm()
85 Term = IOTerm()
86
86
87 import IPython.rlineimpl as readline
87 import IPython.rlineimpl as readline
88 # Remake Term to use the readline i/o facilities
88 # Remake Term to use the readline i/o facilities
89 if sys.platform == 'win32' and readline.have_readline:
89 if sys.platform == 'win32' and readline.have_readline:
90
90
91 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
91 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
92
92
93
93
94 #****************************************************************************
94 #****************************************************************************
95 # Generic warning/error printer, used by everything else
95 # Generic warning/error printer, used by everything else
96 def warn(msg,level=2,exit_val=1):
96 def warn(msg,level=2,exit_val=1):
97 """Standard warning printer. Gives formatting consistency.
97 """Standard warning printer. Gives formatting consistency.
98
98
99 Output is sent to Term.cerr (sys.stderr by default).
99 Output is sent to Term.cerr (sys.stderr by default).
100
100
101 Options:
101 Options:
102
102
103 -level(2): allows finer control:
103 -level(2): allows finer control:
104 0 -> Do nothing, dummy function.
104 0 -> Do nothing, dummy function.
105 1 -> Print message.
105 1 -> Print message.
106 2 -> Print 'WARNING:' + message. (Default level).
106 2 -> Print 'WARNING:' + message. (Default level).
107 3 -> Print 'ERROR:' + message.
107 3 -> Print 'ERROR:' + message.
108 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
108 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
109
109
110 -exit_val (1): exit value returned by sys.exit() for a level 4
110 -exit_val (1): exit value returned by sys.exit() for a level 4
111 warning. Ignored for all other levels."""
111 warning. Ignored for all other levels."""
112
112
113 if level>0:
113 if level>0:
114 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
114 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
115 print >> Term.cerr, '%s%s' % (header[level],msg)
115 print >> Term.cerr, '%s%s' % (header[level],msg)
116 if level == 4:
116 if level == 4:
117 print >> Term.cerr,'Exiting.\n'
117 print >> Term.cerr,'Exiting.\n'
118 sys.exit(exit_val)
118 sys.exit(exit_val)
119
119
120 def info(msg):
120 def info(msg):
121 """Equivalent to warn(msg,level=1)."""
121 """Equivalent to warn(msg,level=1)."""
122
122
123 warn(msg,level=1)
123 warn(msg,level=1)
124
124
125 def error(msg):
125 def error(msg):
126 """Equivalent to warn(msg,level=3)."""
126 """Equivalent to warn(msg,level=3)."""
127
127
128 warn(msg,level=3)
128 warn(msg,level=3)
129
129
130 def fatal(msg,exit_val=1):
130 def fatal(msg,exit_val=1):
131 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
131 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
132
132
133 warn(msg,exit_val=exit_val,level=4)
133 warn(msg,exit_val=exit_val,level=4)
134
134
135 #---------------------------------------------------------------------------
135 #---------------------------------------------------------------------------
136 # Debugging routines
136 # Debugging routines
137 #
137 #
138 def debugx(expr,pre_msg=''):
138 def debugx(expr,pre_msg=''):
139 """Print the value of an expression from the caller's frame.
139 """Print the value of an expression from the caller's frame.
140
140
141 Takes an expression, evaluates it in the caller's frame and prints both
141 Takes an expression, evaluates it in the caller's frame and prints both
142 the given expression and the resulting value (as well as a debug mark
142 the given expression and the resulting value (as well as a debug mark
143 indicating the name of the calling function. The input must be of a form
143 indicating the name of the calling function. The input must be of a form
144 suitable for eval().
144 suitable for eval().
145
145
146 An optional message can be passed, which will be prepended to the printed
146 An optional message can be passed, which will be prepended to the printed
147 expr->value pair."""
147 expr->value pair."""
148
148
149 cf = sys._getframe(1)
149 cf = sys._getframe(1)
150 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
150 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
151 eval(expr,cf.f_globals,cf.f_locals))
151 eval(expr,cf.f_globals,cf.f_locals))
152
152
153 # deactivate it by uncommenting the following line, which makes it a no-op
153 # deactivate it by uncommenting the following line, which makes it a no-op
154 #def debugx(expr,pre_msg=''): pass
154 #def debugx(expr,pre_msg=''): pass
155
155
156 #----------------------------------------------------------------------------
156 #----------------------------------------------------------------------------
157 StringTypes = types.StringTypes
157 StringTypes = types.StringTypes
158
158
159 # Basic timing functionality
159 # Basic timing functionality
160
160
161 # If possible (Unix), use the resource module instead of time.clock()
161 # If possible (Unix), use the resource module instead of time.clock()
162 try:
162 try:
163 import resource
163 import resource
164 def clock():
164 def clock():
165 """clock() -> floating point number
165 """clock() -> floating point number
166
166
167 Return the CPU time in seconds (user time only, system time is
167 Return the CPU time in seconds (user time only, system time is
168 ignored) since the start of the process. This is done via a call to
168 ignored) since the start of the process. This is done via a call to
169 resource.getrusage, so it avoids the wraparound problems in
169 resource.getrusage, so it avoids the wraparound problems in
170 time.clock()."""
170 time.clock()."""
171
171
172 return resource.getrusage(resource.RUSAGE_SELF)[0]
172 return resource.getrusage(resource.RUSAGE_SELF)[0]
173
173
174 def clock2():
174 def clock2():
175 """clock2() -> (t_user,t_system)
175 """clock2() -> (t_user,t_system)
176
176
177 Similar to clock(), but return a tuple of user/system times."""
177 Similar to clock(), but return a tuple of user/system times."""
178 return resource.getrusage(resource.RUSAGE_SELF)[:2]
178 return resource.getrusage(resource.RUSAGE_SELF)[:2]
179
179
180 except ImportError:
180 except ImportError:
181 clock = time.clock
181 clock = time.clock
182 def clock2():
182 def clock2():
183 """Under windows, system CPU time can't be measured.
183 """Under windows, system CPU time can't be measured.
184
184
185 This just returns clock() and zero."""
185 This just returns clock() and zero."""
186 return time.clock(),0.0
186 return time.clock(),0.0
187
187
188 def timings_out(reps,func,*args,**kw):
188 def timings_out(reps,func,*args,**kw):
189 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
189 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
190
190
191 Execute a function reps times, return a tuple with the elapsed total
191 Execute a function reps times, return a tuple with the elapsed total
192 CPU time in seconds, the time per call and the function's output.
192 CPU time in seconds, the time per call and the function's output.
193
193
194 Under Unix, the return value is the sum of user+system time consumed by
194 Under Unix, the return value is the sum of user+system time consumed by
195 the process, computed via the resource module. This prevents problems
195 the process, computed via the resource module. This prevents problems
196 related to the wraparound effect which the time.clock() function has.
196 related to the wraparound effect which the time.clock() function has.
197
197
198 Under Windows the return value is in wall clock seconds. See the
198 Under Windows the return value is in wall clock seconds. See the
199 documentation for the time module for more details."""
199 documentation for the time module for more details."""
200
200
201 reps = int(reps)
201 reps = int(reps)
202 assert reps >=1, 'reps must be >= 1'
202 assert reps >=1, 'reps must be >= 1'
203 if reps==1:
203 if reps==1:
204 start = clock()
204 start = clock()
205 out = func(*args,**kw)
205 out = func(*args,**kw)
206 tot_time = clock()-start
206 tot_time = clock()-start
207 else:
207 else:
208 rng = xrange(reps-1) # the last time is executed separately to store output
208 rng = xrange(reps-1) # the last time is executed separately to store output
209 start = clock()
209 start = clock()
210 for dummy in rng: func(*args,**kw)
210 for dummy in rng: func(*args,**kw)
211 out = func(*args,**kw) # one last time
211 out = func(*args,**kw) # one last time
212 tot_time = clock()-start
212 tot_time = clock()-start
213 av_time = tot_time / reps
213 av_time = tot_time / reps
214 return tot_time,av_time,out
214 return tot_time,av_time,out
215
215
216 def timings(reps,func,*args,**kw):
216 def timings(reps,func,*args,**kw):
217 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
217 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
218
218
219 Execute a function reps times, return a tuple with the elapsed total CPU
219 Execute a function reps times, return a tuple with the elapsed total CPU
220 time in seconds and the time per call. These are just the first two values
220 time in seconds and the time per call. These are just the first two values
221 in timings_out()."""
221 in timings_out()."""
222
222
223 return timings_out(reps,func,*args,**kw)[0:2]
223 return timings_out(reps,func,*args,**kw)[0:2]
224
224
225 def timing(func,*args,**kw):
225 def timing(func,*args,**kw):
226 """timing(func,*args,**kw) -> t_total
226 """timing(func,*args,**kw) -> t_total
227
227
228 Execute a function once, return the elapsed total CPU time in
228 Execute a function once, return the elapsed total CPU time in
229 seconds. This is just the first value in timings_out()."""
229 seconds. This is just the first value in timings_out()."""
230
230
231 return timings_out(1,func,*args,**kw)[0]
231 return timings_out(1,func,*args,**kw)[0]
232
232
233 #****************************************************************************
233 #****************************************************************************
234 # file and system
234 # file and system
235
235
236 def system(cmd,verbose=0,debug=0,header=''):
236 def system(cmd,verbose=0,debug=0,header=''):
237 """Execute a system command, return its exit status.
237 """Execute a system command, return its exit status.
238
238
239 Options:
239 Options:
240
240
241 - verbose (0): print the command to be executed.
241 - verbose (0): print the command to be executed.
242
242
243 - debug (0): only print, do not actually execute.
243 - debug (0): only print, do not actually execute.
244
244
245 - header (''): Header to print on screen prior to the executed command (it
245 - header (''): Header to print on screen prior to the executed command (it
246 is only prepended to the command, no newlines are added).
246 is only prepended to the command, no newlines are added).
247
247
248 Note: a stateful version of this function is available through the
248 Note: a stateful version of this function is available through the
249 SystemExec class."""
249 SystemExec class."""
250
250
251 stat = 0
251 stat = 0
252 if verbose or debug: print header+cmd
252 if verbose or debug: print header+cmd
253 sys.stdout.flush()
253 sys.stdout.flush()
254 if not debug: stat = os.system(cmd)
254 if not debug: stat = os.system(cmd)
255 return stat
255 return stat
256
256
257 # This function is used by ipython in a lot of places to make system calls.
257 # This function is used by ipython in a lot of places to make system calls.
258 # We need it to be slightly different under win32, due to the vagaries of
258 # We need it to be slightly different under win32, due to the vagaries of
259 # 'network shares'. A win32 override is below.
259 # 'network shares'. A win32 override is below.
260
260
261 def shell(cmd,verbose=0,debug=0,header=''):
261 def shell(cmd,verbose=0,debug=0,header=''):
262 """Execute a command in the system shell, always return None.
262 """Execute a command in the system shell, always return None.
263
263
264 Options:
264 Options:
265
265
266 - verbose (0): print the command to be executed.
266 - verbose (0): print the command to be executed.
267
267
268 - debug (0): only print, do not actually execute.
268 - debug (0): only print, do not actually execute.
269
269
270 - header (''): Header to print on screen prior to the executed command (it
270 - header (''): Header to print on screen prior to the executed command (it
271 is only prepended to the command, no newlines are added).
271 is only prepended to the command, no newlines are added).
272
272
273 Note: this is similar to genutils.system(), but it returns None so it can
273 Note: this is similar to genutils.system(), but it returns None so it can
274 be conveniently used in interactive loops without getting the return value
274 be conveniently used in interactive loops without getting the return value
275 (typically 0) printed many times."""
275 (typically 0) printed many times."""
276
276
277 stat = 0
277 stat = 0
278 if verbose or debug: print header+cmd
278 if verbose or debug: print header+cmd
279 # flush stdout so we don't mangle python's buffering
279 # flush stdout so we don't mangle python's buffering
280 sys.stdout.flush()
280 sys.stdout.flush()
281 if not debug:
281 if not debug:
282 os.system(cmd)
282 os.system(cmd)
283
283
284 # override shell() for win32 to deal with network shares
284 # override shell() for win32 to deal with network shares
285 if os.name in ('nt','dos'):
285 if os.name in ('nt','dos'):
286
286
287 shell_ori = shell
287 shell_ori = shell
288
288
289 def shell(cmd,verbose=0,debug=0,header=''):
289 def shell(cmd,verbose=0,debug=0,header=''):
290 if os.getcwd().startswith(r"\\"):
290 if os.getcwd().startswith(r"\\"):
291 path = os.getcwd()
291 path = os.getcwd()
292 # change to c drive (cannot be on UNC-share when issuing os.system,
292 # change to c drive (cannot be on UNC-share when issuing os.system,
293 # as cmd.exe cannot handle UNC addresses)
293 # as cmd.exe cannot handle UNC addresses)
294 os.chdir("c:")
294 os.chdir("c:")
295 # issue pushd to the UNC-share and then run the command
295 # issue pushd to the UNC-share and then run the command
296 try:
296 try:
297 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
297 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
298 finally:
298 finally:
299 os.chdir(path)
299 os.chdir(path)
300 else:
300 else:
301 shell_ori(cmd,verbose,debug,header)
301 shell_ori(cmd,verbose,debug,header)
302
302
303 shell.__doc__ = shell_ori.__doc__
303 shell.__doc__ = shell_ori.__doc__
304
304
305 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
305 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
306 """Dummy substitute for perl's backquotes.
306 """Dummy substitute for perl's backquotes.
307
307
308 Executes a command and returns the output.
308 Executes a command and returns the output.
309
309
310 Accepts the same arguments as system(), plus:
310 Accepts the same arguments as system(), plus:
311
311
312 - split(0): if true, the output is returned as a list split on newlines.
312 - split(0): if true, the output is returned as a list split on newlines.
313
313
314 Note: a stateful version of this function is available through the
314 Note: a stateful version of this function is available through the
315 SystemExec class.
315 SystemExec class.
316
316
317 This is pretty much deprecated and rarely used,
317 This is pretty much deprecated and rarely used,
318 genutils.getoutputerror may be what you need.
318 genutils.getoutputerror may be what you need.
319
319
320 """
320 """
321
321
322 if verbose or debug: print header+cmd
322 if verbose or debug: print header+cmd
323 if not debug:
323 if not debug:
324 output = os.popen(cmd).read()
324 output = os.popen(cmd).read()
325 # stipping last \n is here for backwards compat.
325 # stipping last \n is here for backwards compat.
326 if output.endswith('\n'):
326 if output.endswith('\n'):
327 output = output[:-1]
327 output = output[:-1]
328 if split:
328 if split:
329 return output.split('\n')
329 return output.split('\n')
330 else:
330 else:
331 return output
331 return output
332
332
333 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
333 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
334 """Return (standard output,standard error) of executing cmd in a shell.
334 """Return (standard output,standard error) of executing cmd in a shell.
335
335
336 Accepts the same arguments as system(), plus:
336 Accepts the same arguments as system(), plus:
337
337
338 - split(0): if true, each of stdout/err is returned as a list split on
338 - split(0): if true, each of stdout/err is returned as a list split on
339 newlines.
339 newlines.
340
340
341 Note: a stateful version of this function is available through the
341 Note: a stateful version of this function is available through the
342 SystemExec class."""
342 SystemExec class."""
343
343
344 if verbose or debug: print header+cmd
344 if verbose or debug: print header+cmd
345 if not cmd:
345 if not cmd:
346 if split:
346 if split:
347 return [],[]
347 return [],[]
348 else:
348 else:
349 return '',''
349 return '',''
350 if not debug:
350 if not debug:
351 pin,pout,perr = os.popen3(cmd)
351 pin,pout,perr = os.popen3(cmd)
352 tout = pout.read().rstrip()
352 tout = pout.read().rstrip()
353 terr = perr.read().rstrip()
353 terr = perr.read().rstrip()
354 pin.close()
354 pin.close()
355 pout.close()
355 pout.close()
356 perr.close()
356 perr.close()
357 if split:
357 if split:
358 return tout.split('\n'),terr.split('\n')
358 return tout.split('\n'),terr.split('\n')
359 else:
359 else:
360 return tout,terr
360 return tout,terr
361
361
362 # for compatibility with older naming conventions
362 # for compatibility with older naming conventions
363 xsys = system
363 xsys = system
364 bq = getoutput
364 bq = getoutput
365
365
366 class SystemExec:
366 class SystemExec:
367 """Access the system and getoutput functions through a stateful interface.
367 """Access the system and getoutput functions through a stateful interface.
368
368
369 Note: here we refer to the system and getoutput functions from this
369 Note: here we refer to the system and getoutput functions from this
370 library, not the ones from the standard python library.
370 library, not the ones from the standard python library.
371
371
372 This class offers the system and getoutput functions as methods, but the
372 This class offers the system and getoutput functions as methods, but the
373 verbose, debug and header parameters can be set for the instance (at
373 verbose, debug and header parameters can be set for the instance (at
374 creation time or later) so that they don't need to be specified on each
374 creation time or later) so that they don't need to be specified on each
375 call.
375 call.
376
376
377 For efficiency reasons, there's no way to override the parameters on a
377 For efficiency reasons, there's no way to override the parameters on a
378 per-call basis other than by setting instance attributes. If you need
378 per-call basis other than by setting instance attributes. If you need
379 local overrides, it's best to directly call system() or getoutput().
379 local overrides, it's best to directly call system() or getoutput().
380
380
381 The following names are provided as alternate options:
381 The following names are provided as alternate options:
382 - xsys: alias to system
382 - xsys: alias to system
383 - bq: alias to getoutput
383 - bq: alias to getoutput
384
384
385 An instance can then be created as:
385 An instance can then be created as:
386 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
386 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
387
387
388 And used as:
388 And used as:
389 >>> sysexec.xsys('pwd')
389 >>> sysexec.xsys('pwd')
390 >>> dirlist = sysexec.bq('ls -l')
390 >>> dirlist = sysexec.bq('ls -l')
391 """
391 """
392
392
393 def __init__(self,verbose=0,debug=0,header='',split=0):
393 def __init__(self,verbose=0,debug=0,header='',split=0):
394 """Specify the instance's values for verbose, debug and header."""
394 """Specify the instance's values for verbose, debug and header."""
395 setattr_list(self,'verbose debug header split')
395 setattr_list(self,'verbose debug header split')
396
396
397 def system(self,cmd):
397 def system(self,cmd):
398 """Stateful interface to system(), with the same keyword parameters."""
398 """Stateful interface to system(), with the same keyword parameters."""
399
399
400 system(cmd,self.verbose,self.debug,self.header)
400 system(cmd,self.verbose,self.debug,self.header)
401
401
402 def shell(self,cmd):
402 def shell(self,cmd):
403 """Stateful interface to shell(), with the same keyword parameters."""
403 """Stateful interface to shell(), with the same keyword parameters."""
404
404
405 shell(cmd,self.verbose,self.debug,self.header)
405 shell(cmd,self.verbose,self.debug,self.header)
406
406
407 xsys = system # alias
407 xsys = system # alias
408
408
409 def getoutput(self,cmd):
409 def getoutput(self,cmd):
410 """Stateful interface to getoutput()."""
410 """Stateful interface to getoutput()."""
411
411
412 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
412 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
413
413
414 def getoutputerror(self,cmd):
414 def getoutputerror(self,cmd):
415 """Stateful interface to getoutputerror()."""
415 """Stateful interface to getoutputerror()."""
416
416
417 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
417 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
418
418
419 bq = getoutput # alias
419 bq = getoutput # alias
420
420
421 #-----------------------------------------------------------------------------
421 #-----------------------------------------------------------------------------
422 def mutex_opts(dict,ex_op):
422 def mutex_opts(dict,ex_op):
423 """Check for presence of mutually exclusive keys in a dict.
423 """Check for presence of mutually exclusive keys in a dict.
424
424
425 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
425 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
426 for op1,op2 in ex_op:
426 for op1,op2 in ex_op:
427 if op1 in dict and op2 in dict:
427 if op1 in dict and op2 in dict:
428 raise ValueError,'\n*** ERROR in Arguments *** '\
428 raise ValueError,'\n*** ERROR in Arguments *** '\
429 'Options '+op1+' and '+op2+' are mutually exclusive.'
429 'Options '+op1+' and '+op2+' are mutually exclusive.'
430
430
431 #-----------------------------------------------------------------------------
431 #-----------------------------------------------------------------------------
432 def get_py_filename(name):
432 def get_py_filename(name):
433 """Return a valid python filename in the current directory.
433 """Return a valid python filename in the current directory.
434
434
435 If the given name is not a file, it adds '.py' and searches again.
435 If the given name is not a file, it adds '.py' and searches again.
436 Raises IOError with an informative message if the file isn't found."""
436 Raises IOError with an informative message if the file isn't found."""
437
437
438 name = os.path.expanduser(name)
438 name = os.path.expanduser(name)
439 if not os.path.isfile(name) and not name.endswith('.py'):
439 if not os.path.isfile(name) and not name.endswith('.py'):
440 name += '.py'
440 name += '.py'
441 if os.path.isfile(name):
441 if os.path.isfile(name):
442 return name
442 return name
443 else:
443 else:
444 raise IOError,'File `%s` not found.' % name
444 raise IOError,'File `%s` not found.' % name
445
445
446 #-----------------------------------------------------------------------------
446 #-----------------------------------------------------------------------------
447 def filefind(fname,alt_dirs = None):
447 def filefind(fname,alt_dirs = None):
448 """Return the given filename either in the current directory, if it
448 """Return the given filename either in the current directory, if it
449 exists, or in a specified list of directories.
449 exists, or in a specified list of directories.
450
450
451 ~ expansion is done on all file and directory names.
451 ~ expansion is done on all file and directory names.
452
452
453 Upon an unsuccessful search, raise an IOError exception."""
453 Upon an unsuccessful search, raise an IOError exception."""
454
454
455 if alt_dirs is None:
455 if alt_dirs is None:
456 try:
456 try:
457 alt_dirs = get_home_dir()
457 alt_dirs = get_home_dir()
458 except HomeDirError:
458 except HomeDirError:
459 alt_dirs = os.getcwd()
459 alt_dirs = os.getcwd()
460 search = [fname] + list_strings(alt_dirs)
460 search = [fname] + list_strings(alt_dirs)
461 search = map(os.path.expanduser,search)
461 search = map(os.path.expanduser,search)
462 #print 'search list for',fname,'list:',search # dbg
462 #print 'search list for',fname,'list:',search # dbg
463 fname = search[0]
463 fname = search[0]
464 if os.path.isfile(fname):
464 if os.path.isfile(fname):
465 return fname
465 return fname
466 for direc in search[1:]:
466 for direc in search[1:]:
467 testname = os.path.join(direc,fname)
467 testname = os.path.join(direc,fname)
468 #print 'testname',testname # dbg
468 #print 'testname',testname # dbg
469 if os.path.isfile(testname):
469 if os.path.isfile(testname):
470 return testname
470 return testname
471 raise IOError,'File' + `fname` + \
471 raise IOError,'File' + `fname` + \
472 ' not found in current or supplied directories:' + `alt_dirs`
472 ' not found in current or supplied directories:' + `alt_dirs`
473
473
474 #----------------------------------------------------------------------------
474 #----------------------------------------------------------------------------
475 def file_read(filename):
475 def file_read(filename):
476 """Read a file and close it. Returns the file source."""
476 """Read a file and close it. Returns the file source."""
477 fobj = open(filename,'r');
477 fobj = open(filename,'r');
478 source = fobj.read();
478 source = fobj.read();
479 fobj.close()
479 fobj.close()
480 return source
480 return source
481
481
482 def file_readlines(filename):
482 def file_readlines(filename):
483 """Read a file and close it. Returns the file source using readlines()."""
483 """Read a file and close it. Returns the file source using readlines()."""
484 fobj = open(filename,'r');
484 fobj = open(filename,'r');
485 lines = fobj.readlines();
485 lines = fobj.readlines();
486 fobj.close()
486 fobj.close()
487 return lines
487 return lines
488
488
489 #----------------------------------------------------------------------------
489 #----------------------------------------------------------------------------
490 def target_outdated(target,deps):
490 def target_outdated(target,deps):
491 """Determine whether a target is out of date.
491 """Determine whether a target is out of date.
492
492
493 target_outdated(target,deps) -> 1/0
493 target_outdated(target,deps) -> 1/0
494
494
495 deps: list of filenames which MUST exist.
495 deps: list of filenames which MUST exist.
496 target: single filename which may or may not exist.
496 target: single filename which may or may not exist.
497
497
498 If target doesn't exist or is older than any file listed in deps, return
498 If target doesn't exist or is older than any file listed in deps, return
499 true, otherwise return false.
499 true, otherwise return false.
500 """
500 """
501 try:
501 try:
502 target_time = os.path.getmtime(target)
502 target_time = os.path.getmtime(target)
503 except os.error:
503 except os.error:
504 return 1
504 return 1
505 for dep in deps:
505 for dep in deps:
506 dep_time = os.path.getmtime(dep)
506 dep_time = os.path.getmtime(dep)
507 if dep_time > target_time:
507 if dep_time > target_time:
508 #print "For target",target,"Dep failed:",dep # dbg
508 #print "For target",target,"Dep failed:",dep # dbg
509 #print "times (dep,tar):",dep_time,target_time # dbg
509 #print "times (dep,tar):",dep_time,target_time # dbg
510 return 1
510 return 1
511 return 0
511 return 0
512
512
513 #-----------------------------------------------------------------------------
513 #-----------------------------------------------------------------------------
514 def target_update(target,deps,cmd):
514 def target_update(target,deps,cmd):
515 """Update a target with a given command given a list of dependencies.
515 """Update a target with a given command given a list of dependencies.
516
516
517 target_update(target,deps,cmd) -> runs cmd if target is outdated.
517 target_update(target,deps,cmd) -> runs cmd if target is outdated.
518
518
519 This is just a wrapper around target_outdated() which calls the given
519 This is just a wrapper around target_outdated() which calls the given
520 command if target is outdated."""
520 command if target is outdated."""
521
521
522 if target_outdated(target,deps):
522 if target_outdated(target,deps):
523 xsys(cmd)
523 xsys(cmd)
524
524
525 #----------------------------------------------------------------------------
525 #----------------------------------------------------------------------------
526 def unquote_ends(istr):
526 def unquote_ends(istr):
527 """Remove a single pair of quotes from the endpoints of a string."""
527 """Remove a single pair of quotes from the endpoints of a string."""
528
528
529 if not istr:
529 if not istr:
530 return istr
530 return istr
531 if (istr[0]=="'" and istr[-1]=="'") or \
531 if (istr[0]=="'" and istr[-1]=="'") or \
532 (istr[0]=='"' and istr[-1]=='"'):
532 (istr[0]=='"' and istr[-1]=='"'):
533 return istr[1:-1]
533 return istr[1:-1]
534 else:
534 else:
535 return istr
535 return istr
536
536
537 #----------------------------------------------------------------------------
537 #----------------------------------------------------------------------------
538 def process_cmdline(argv,names=[],defaults={},usage=''):
538 def process_cmdline(argv,names=[],defaults={},usage=''):
539 """ Process command-line options and arguments.
539 """ Process command-line options and arguments.
540
540
541 Arguments:
541 Arguments:
542
542
543 - argv: list of arguments, typically sys.argv.
543 - argv: list of arguments, typically sys.argv.
544
544
545 - names: list of option names. See DPyGetOpt docs for details on options
545 - names: list of option names. See DPyGetOpt docs for details on options
546 syntax.
546 syntax.
547
547
548 - defaults: dict of default values.
548 - defaults: dict of default values.
549
549
550 - usage: optional usage notice to print if a wrong argument is passed.
550 - usage: optional usage notice to print if a wrong argument is passed.
551
551
552 Return a dict of options and a list of free arguments."""
552 Return a dict of options and a list of free arguments."""
553
553
554 getopt = DPyGetOpt.DPyGetOpt()
554 getopt = DPyGetOpt.DPyGetOpt()
555 getopt.setIgnoreCase(0)
555 getopt.setIgnoreCase(0)
556 getopt.parseConfiguration(names)
556 getopt.parseConfiguration(names)
557
557
558 try:
558 try:
559 getopt.processArguments(argv)
559 getopt.processArguments(argv)
560 except:
560 except:
561 print usage
561 print usage
562 warn(`sys.exc_value`,level=4)
562 warn(`sys.exc_value`,level=4)
563
563
564 defaults.update(getopt.optionValues)
564 defaults.update(getopt.optionValues)
565 args = getopt.freeValues
565 args = getopt.freeValues
566
566
567 return defaults,args
567 return defaults,args
568
568
569 #----------------------------------------------------------------------------
569 #----------------------------------------------------------------------------
570 def optstr2types(ostr):
570 def optstr2types(ostr):
571 """Convert a string of option names to a dict of type mappings.
571 """Convert a string of option names to a dict of type mappings.
572
572
573 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
573 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
574
574
575 This is used to get the types of all the options in a string formatted
575 This is used to get the types of all the options in a string formatted
576 with the conventions of DPyGetOpt. The 'type' None is used for options
576 with the conventions of DPyGetOpt. The 'type' None is used for options
577 which are strings (they need no further conversion). This function's main
577 which are strings (they need no further conversion). This function's main
578 use is to get a typemap for use with read_dict().
578 use is to get a typemap for use with read_dict().
579 """
579 """
580
580
581 typeconv = {None:'',int:'',float:''}
581 typeconv = {None:'',int:'',float:''}
582 typemap = {'s':None,'i':int,'f':float}
582 typemap = {'s':None,'i':int,'f':float}
583 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
583 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
584
584
585 for w in ostr.split():
585 for w in ostr.split():
586 oname,alias,otype = opt_re.match(w).groups()
586 oname,alias,otype = opt_re.match(w).groups()
587 if otype == '' or alias == '!': # simple switches are integers too
587 if otype == '' or alias == '!': # simple switches are integers too
588 otype = 'i'
588 otype = 'i'
589 typeconv[typemap[otype]] += oname + ' '
589 typeconv[typemap[otype]] += oname + ' '
590 return typeconv
590 return typeconv
591
591
592 #----------------------------------------------------------------------------
592 #----------------------------------------------------------------------------
593 def read_dict(filename,type_conv=None,**opt):
593 def read_dict(filename,type_conv=None,**opt):
594
594
595 """Read a dictionary of key=value pairs from an input file, optionally
595 """Read a dictionary of key=value pairs from an input file, optionally
596 performing conversions on the resulting values.
596 performing conversions on the resulting values.
597
597
598 read_dict(filename,type_conv,**opt) -> dict
598 read_dict(filename,type_conv,**opt) -> dict
599
599
600 Only one value per line is accepted, the format should be
600 Only one value per line is accepted, the format should be
601 # optional comments are ignored
601 # optional comments are ignored
602 key value\n
602 key value\n
603
603
604 Args:
604 Args:
605
605
606 - type_conv: A dictionary specifying which keys need to be converted to
606 - type_conv: A dictionary specifying which keys need to be converted to
607 which types. By default all keys are read as strings. This dictionary
607 which types. By default all keys are read as strings. This dictionary
608 should have as its keys valid conversion functions for strings
608 should have as its keys valid conversion functions for strings
609 (int,long,float,complex, or your own). The value for each key
609 (int,long,float,complex, or your own). The value for each key
610 (converter) should be a whitespace separated string containing the names
610 (converter) should be a whitespace separated string containing the names
611 of all the entries in the file to be converted using that function. For
611 of all the entries in the file to be converted using that function. For
612 keys to be left alone, use None as the conversion function (only needed
612 keys to be left alone, use None as the conversion function (only needed
613 with purge=1, see below).
613 with purge=1, see below).
614
614
615 - opt: dictionary with extra options as below (default in parens)
615 - opt: dictionary with extra options as below (default in parens)
616
616
617 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
617 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
618 of the dictionary to be returned. If purge is going to be used, the
618 of the dictionary to be returned. If purge is going to be used, the
619 set of keys to be left as strings also has to be explicitly specified
619 set of keys to be left as strings also has to be explicitly specified
620 using the (non-existent) conversion function None.
620 using the (non-existent) conversion function None.
621
621
622 fs(None): field separator. This is the key/value separator to be used
622 fs(None): field separator. This is the key/value separator to be used
623 when parsing the file. The None default means any whitespace [behavior
623 when parsing the file. The None default means any whitespace [behavior
624 of string.split()].
624 of string.split()].
625
625
626 strip(0): if 1, strip string values of leading/trailinig whitespace.
626 strip(0): if 1, strip string values of leading/trailinig whitespace.
627
627
628 warn(1): warning level if requested keys are not found in file.
628 warn(1): warning level if requested keys are not found in file.
629 - 0: silently ignore.
629 - 0: silently ignore.
630 - 1: inform but proceed.
630 - 1: inform but proceed.
631 - 2: raise KeyError exception.
631 - 2: raise KeyError exception.
632
632
633 no_empty(0): if 1, remove keys with whitespace strings as a value.
633 no_empty(0): if 1, remove keys with whitespace strings as a value.
634
634
635 unique([]): list of keys (or space separated string) which can't be
635 unique([]): list of keys (or space separated string) which can't be
636 repeated. If one such key is found in the file, each new instance
636 repeated. If one such key is found in the file, each new instance
637 overwrites the previous one. For keys not listed here, the behavior is
637 overwrites the previous one. For keys not listed here, the behavior is
638 to make a list of all appearances.
638 to make a list of all appearances.
639
639
640 Example:
640 Example:
641 If the input file test.ini has:
641 If the input file test.ini has:
642 i 3
642 i 3
643 x 4.5
643 x 4.5
644 y 5.5
644 y 5.5
645 s hi ho
645 s hi ho
646 Then:
646 Then:
647
647
648 >>> type_conv={int:'i',float:'x',None:'s'}
648 >>> type_conv={int:'i',float:'x',None:'s'}
649 >>> read_dict('test.ini')
649 >>> read_dict('test.ini')
650 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
650 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
651 >>> read_dict('test.ini',type_conv)
651 >>> read_dict('test.ini',type_conv)
652 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
652 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
653 >>> read_dict('test.ini',type_conv,purge=1)
653 >>> read_dict('test.ini',type_conv,purge=1)
654 {'i': 3, 's': 'hi ho', 'x': 4.5}
654 {'i': 3, 's': 'hi ho', 'x': 4.5}
655 """
655 """
656
656
657 # starting config
657 # starting config
658 opt.setdefault('purge',0)
658 opt.setdefault('purge',0)
659 opt.setdefault('fs',None) # field sep defaults to any whitespace
659 opt.setdefault('fs',None) # field sep defaults to any whitespace
660 opt.setdefault('strip',0)
660 opt.setdefault('strip',0)
661 opt.setdefault('warn',1)
661 opt.setdefault('warn',1)
662 opt.setdefault('no_empty',0)
662 opt.setdefault('no_empty',0)
663 opt.setdefault('unique','')
663 opt.setdefault('unique','')
664 if type(opt['unique']) in StringTypes:
664 if type(opt['unique']) in StringTypes:
665 unique_keys = qw(opt['unique'])
665 unique_keys = qw(opt['unique'])
666 elif type(opt['unique']) in (types.TupleType,types.ListType):
666 elif type(opt['unique']) in (types.TupleType,types.ListType):
667 unique_keys = opt['unique']
667 unique_keys = opt['unique']
668 else:
668 else:
669 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
669 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
670
670
671 dict = {}
671 dict = {}
672 # first read in table of values as strings
672 # first read in table of values as strings
673 file = open(filename,'r')
673 file = open(filename,'r')
674 for line in file.readlines():
674 for line in file.readlines():
675 line = line.strip()
675 line = line.strip()
676 if len(line) and line[0]=='#': continue
676 if len(line) and line[0]=='#': continue
677 if len(line)>0:
677 if len(line)>0:
678 lsplit = line.split(opt['fs'],1)
678 lsplit = line.split(opt['fs'],1)
679 try:
679 try:
680 key,val = lsplit
680 key,val = lsplit
681 except ValueError:
681 except ValueError:
682 key,val = lsplit[0],''
682 key,val = lsplit[0],''
683 key = key.strip()
683 key = key.strip()
684 if opt['strip']: val = val.strip()
684 if opt['strip']: val = val.strip()
685 if val == "''" or val == '""': val = ''
685 if val == "''" or val == '""': val = ''
686 if opt['no_empty'] and (val=='' or val.isspace()):
686 if opt['no_empty'] and (val=='' or val.isspace()):
687 continue
687 continue
688 # if a key is found more than once in the file, build a list
688 # if a key is found more than once in the file, build a list
689 # unless it's in the 'unique' list. In that case, last found in file
689 # unless it's in the 'unique' list. In that case, last found in file
690 # takes precedence. User beware.
690 # takes precedence. User beware.
691 try:
691 try:
692 if dict[key] and key in unique_keys:
692 if dict[key] and key in unique_keys:
693 dict[key] = val
693 dict[key] = val
694 elif type(dict[key]) is types.ListType:
694 elif type(dict[key]) is types.ListType:
695 dict[key].append(val)
695 dict[key].append(val)
696 else:
696 else:
697 dict[key] = [dict[key],val]
697 dict[key] = [dict[key],val]
698 except KeyError:
698 except KeyError:
699 dict[key] = val
699 dict[key] = val
700 # purge if requested
700 # purge if requested
701 if opt['purge']:
701 if opt['purge']:
702 accepted_keys = qwflat(type_conv.values())
702 accepted_keys = qwflat(type_conv.values())
703 for key in dict.keys():
703 for key in dict.keys():
704 if key in accepted_keys: continue
704 if key in accepted_keys: continue
705 del(dict[key])
705 del(dict[key])
706 # now convert if requested
706 # now convert if requested
707 if type_conv==None: return dict
707 if type_conv==None: return dict
708 conversions = type_conv.keys()
708 conversions = type_conv.keys()
709 try: conversions.remove(None)
709 try: conversions.remove(None)
710 except: pass
710 except: pass
711 for convert in conversions:
711 for convert in conversions:
712 for val in qw(type_conv[convert]):
712 for val in qw(type_conv[convert]):
713 try:
713 try:
714 dict[val] = convert(dict[val])
714 dict[val] = convert(dict[val])
715 except KeyError,e:
715 except KeyError,e:
716 if opt['warn'] == 0:
716 if opt['warn'] == 0:
717 pass
717 pass
718 elif opt['warn'] == 1:
718 elif opt['warn'] == 1:
719 print >>sys.stderr, 'Warning: key',val,\
719 print >>sys.stderr, 'Warning: key',val,\
720 'not found in file',filename
720 'not found in file',filename
721 elif opt['warn'] == 2:
721 elif opt['warn'] == 2:
722 raise KeyError,e
722 raise KeyError,e
723 else:
723 else:
724 raise ValueError,'Warning level must be 0,1 or 2'
724 raise ValueError,'Warning level must be 0,1 or 2'
725
725
726 return dict
726 return dict
727
727
728 #----------------------------------------------------------------------------
728 #----------------------------------------------------------------------------
729 def flag_calls(func):
729 def flag_calls(func):
730 """Wrap a function to detect and flag when it gets called.
730 """Wrap a function to detect and flag when it gets called.
731
731
732 This is a decorator which takes a function and wraps it in a function with
732 This is a decorator which takes a function and wraps it in a function with
733 a 'called' attribute. wrapper.called is initialized to False.
733 a 'called' attribute. wrapper.called is initialized to False.
734
734
735 The wrapper.called attribute is set to False right before each call to the
735 The wrapper.called attribute is set to False right before each call to the
736 wrapped function, so if the call fails it remains False. After the call
736 wrapped function, so if the call fails it remains False. After the call
737 completes, wrapper.called is set to True and the output is returned.
737 completes, wrapper.called is set to True and the output is returned.
738
738
739 Testing for truth in wrapper.called allows you to determine if a call to
739 Testing for truth in wrapper.called allows you to determine if a call to
740 func() was attempted and succeeded."""
740 func() was attempted and succeeded."""
741
741
742 def wrapper(*args,**kw):
742 def wrapper(*args,**kw):
743 wrapper.called = False
743 wrapper.called = False
744 out = func(*args,**kw)
744 out = func(*args,**kw)
745 wrapper.called = True
745 wrapper.called = True
746 return out
746 return out
747
747
748 wrapper.called = False
748 wrapper.called = False
749 wrapper.__doc__ = func.__doc__
749 wrapper.__doc__ = func.__doc__
750 return wrapper
750 return wrapper
751
751
752 #----------------------------------------------------------------------------
752 #----------------------------------------------------------------------------
753 class HomeDirError(Error):
753 class HomeDirError(Error):
754 pass
754 pass
755
755
756 def get_home_dir():
756 def get_home_dir():
757 """Return the closest possible equivalent to a 'home' directory.
757 """Return the closest possible equivalent to a 'home' directory.
758
758
759 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
759 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
760
760
761 Currently only Posix and NT are implemented, a HomeDirError exception is
761 Currently only Posix and NT are implemented, a HomeDirError exception is
762 raised for all other OSes. """
762 raised for all other OSes. """
763
763
764 isdir = os.path.isdir
764 isdir = os.path.isdir
765 env = os.environ
765 env = os.environ
766 try:
766 try:
767 homedir = env['HOME']
767 homedir = env['HOME']
768 if not isdir(homedir):
768 if not isdir(homedir):
769 # in case a user stuck some string which does NOT resolve to a
769 # in case a user stuck some string which does NOT resolve to a
770 # valid path, it's as good as if we hadn't foud it
770 # valid path, it's as good as if we hadn't foud it
771 raise KeyError
771 raise KeyError
772 return homedir
772 return homedir
773 except KeyError:
773 except KeyError:
774 if os.name == 'posix':
774 if os.name == 'posix':
775 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
775 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
776 elif os.name == 'nt':
776 elif os.name == 'nt':
777 # For some strange reason, win9x returns 'nt' for os.name.
777 # For some strange reason, win9x returns 'nt' for os.name.
778 try:
778 try:
779 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
779 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
780 if not isdir(homedir):
780 if not isdir(homedir):
781 homedir = os.path.join(env['USERPROFILE'])
781 homedir = os.path.join(env['USERPROFILE'])
782 if not isdir(homedir):
782 if not isdir(homedir):
783 raise HomeDirError
783 raise HomeDirError
784 return homedir
784 return homedir
785 except:
785 except:
786 try:
786 try:
787 # Use the registry to get the 'My Documents' folder.
787 # Use the registry to get the 'My Documents' folder.
788 import _winreg as wreg
788 import _winreg as wreg
789 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
789 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
790 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
790 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
791 homedir = wreg.QueryValueEx(key,'Personal')[0]
791 homedir = wreg.QueryValueEx(key,'Personal')[0]
792 key.Close()
792 key.Close()
793 if not isdir(homedir):
793 if not isdir(homedir):
794 e = ('Invalid "Personal" folder registry key '
794 e = ('Invalid "Personal" folder registry key '
795 'typically "My Documents".\n'
795 'typically "My Documents".\n'
796 'Value: %s\n'
796 'Value: %s\n'
797 'This is not a valid directory on your system.' %
797 'This is not a valid directory on your system.' %
798 homedir)
798 homedir)
799 raise HomeDirError(e)
799 raise HomeDirError(e)
800 return homedir
800 return homedir
801 except HomeDirError:
801 except HomeDirError:
802 raise
802 raise
803 except:
803 except:
804 return 'C:\\'
804 return 'C:\\'
805 elif os.name == 'dos':
805 elif os.name == 'dos':
806 # Desperate, may do absurd things in classic MacOS. May work under DOS.
806 # Desperate, may do absurd things in classic MacOS. May work under DOS.
807 return 'C:\\'
807 return 'C:\\'
808 else:
808 else:
809 raise HomeDirError,'support for your operating system not implemented.'
809 raise HomeDirError,'support for your operating system not implemented.'
810
810
811 #****************************************************************************
811 #****************************************************************************
812 # strings and text
812 # strings and text
813
813
814 class LSString(str):
814 class LSString(str):
815 """String derivative with a special access attributes.
815 """String derivative with a special access attributes.
816
816
817 These are normal strings, but with the special attributes:
817 These are normal strings, but with the special attributes:
818
818
819 .l (or .list) : value as list (split on newlines).
819 .l (or .list) : value as list (split on newlines).
820 .n (or .nlstr): original value (the string itself).
820 .n (or .nlstr): original value (the string itself).
821 .s (or .spstr): value as whitespace-separated string.
821 .s (or .spstr): value as whitespace-separated string.
822
822
823 Any values which require transformations are computed only once and
823 Any values which require transformations are computed only once and
824 cached.
824 cached.
825
825
826 Such strings are very useful to efficiently interact with the shell, which
826 Such strings are very useful to efficiently interact with the shell, which
827 typically only understands whitespace-separated options for commands."""
827 typically only understands whitespace-separated options for commands."""
828
828
829 def get_list(self):
829 def get_list(self):
830 try:
830 try:
831 return self.__list
831 return self.__list
832 except AttributeError:
832 except AttributeError:
833 self.__list = self.split('\n')
833 self.__list = self.split('\n')
834 return self.__list
834 return self.__list
835
835
836 l = list = property(get_list)
836 l = list = property(get_list)
837
837
838 def get_spstr(self):
838 def get_spstr(self):
839 try:
839 try:
840 return self.__spstr
840 return self.__spstr
841 except AttributeError:
841 except AttributeError:
842 self.__spstr = self.replace('\n',' ')
842 self.__spstr = self.replace('\n',' ')
843 return self.__spstr
843 return self.__spstr
844
844
845 s = spstr = property(get_spstr)
845 s = spstr = property(get_spstr)
846
846
847 def get_nlstr(self):
847 def get_nlstr(self):
848 return self
848 return self
849
849
850 n = nlstr = property(get_nlstr)
850 n = nlstr = property(get_nlstr)
851
851
852 def get_paths(self):
852 def get_paths(self):
853 try:
853 try:
854 return self.__paths
854 return self.__paths
855 except AttributeError:
855 except AttributeError:
856 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
856 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
857 return self.__paths
857 return self.__paths
858
858
859 p = paths = property(get_paths)
859 p = paths = property(get_paths)
860
860
861
861
862 #----------------------------------------------------------------------------
862 #----------------------------------------------------------------------------
863 class SList(list):
863 class SList(list):
864 """List derivative with a special access attributes.
864 """List derivative with a special access attributes.
865
865
866 These are normal lists, but with the special attributes:
866 These are normal lists, but with the special attributes:
867
867
868 .l (or .list) : value as list (the list itself).
868 .l (or .list) : value as list (the list itself).
869 .n (or .nlstr): value as a string, joined on newlines.
869 .n (or .nlstr): value as a string, joined on newlines.
870 .s (or .spstr): value as a string, joined on spaces.
870 .s (or .spstr): value as a string, joined on spaces.
871
871
872 Any values which require transformations are computed only once and
872 Any values which require transformations are computed only once and
873 cached."""
873 cached."""
874
874
875 def get_list(self):
875 def get_list(self):
876 return self
876 return self
877
877
878 l = list = property(get_list)
878 l = list = property(get_list)
879
879
880 def get_spstr(self):
880 def get_spstr(self):
881 try:
881 try:
882 return self.__spstr
882 return self.__spstr
883 except AttributeError:
883 except AttributeError:
884 self.__spstr = ' '.join(self)
884 self.__spstr = ' '.join(self)
885 return self.__spstr
885 return self.__spstr
886
886
887 s = spstr = property(get_spstr)
887 s = spstr = property(get_spstr)
888
888
889 def get_nlstr(self):
889 def get_nlstr(self):
890 try:
890 try:
891 return self.__nlstr
891 return self.__nlstr
892 except AttributeError:
892 except AttributeError:
893 self.__nlstr = '\n'.join(self)
893 self.__nlstr = '\n'.join(self)
894 return self.__nlstr
894 return self.__nlstr
895
895
896 n = nlstr = property(get_nlstr)
896 n = nlstr = property(get_nlstr)
897
897
898 def get_paths(self):
898 def get_paths(self):
899 try:
899 try:
900 return self.__paths
900 return self.__paths
901 except AttributeError:
901 except AttributeError:
902 self.__paths = [path(p) for p in self if os.path.exists(p)]
902 self.__paths = [path(p) for p in self if os.path.exists(p)]
903 return self.__paths
903 return self.__paths
904
904
905 p = paths = property(get_paths)
905 p = paths = property(get_paths)
906
906
907 #----------------------------------------------------------------------------
907 #----------------------------------------------------------------------------
908 def esc_quotes(strng):
908 def esc_quotes(strng):
909 """Return the input string with single and double quotes escaped out"""
909 """Return the input string with single and double quotes escaped out"""
910
910
911 return strng.replace('"','\\"').replace("'","\\'")
911 return strng.replace('"','\\"').replace("'","\\'")
912
912
913 #----------------------------------------------------------------------------
913 #----------------------------------------------------------------------------
914 def make_quoted_expr(s):
914 def make_quoted_expr(s):
915 """Return string s in appropriate quotes, using raw string if possible.
915 """Return string s in appropriate quotes, using raw string if possible.
916
916
917 Effectively this turns string: cd \ao\ao\
917 Effectively this turns string: cd \ao\ao\
918 to: r"cd \ao\ao\_"[:-1]
918 to: r"cd \ao\ao\_"[:-1]
919
919
920 Note the use of raw string and padding at the end to allow trailing backslash.
920 Note the use of raw string and padding at the end to allow trailing backslash.
921
921
922 """
922 """
923
923
924 tail = ''
924 tail = ''
925 tailpadding = ''
925 tailpadding = ''
926 raw = ''
926 raw = ''
927 if "\\" in s:
927 if "\\" in s:
928 raw = 'r'
928 raw = 'r'
929 if s.endswith('\\'):
929 if s.endswith('\\'):
930 tail = '[:-1]'
930 tail = '[:-1]'
931 tailpadding = '_'
931 tailpadding = '_'
932 if '"' not in s:
932 if '"' not in s:
933 quote = '"'
933 quote = '"'
934 elif "'" not in s:
934 elif "'" not in s:
935 quote = "'"
935 quote = "'"
936 elif '"""' not in s and not s.endswith('"'):
936 elif '"""' not in s and not s.endswith('"'):
937 quote = '"""'
937 quote = '"""'
938 elif "'''" not in s and not s.endswith("'"):
938 elif "'''" not in s and not s.endswith("'"):
939 quote = "'''"
939 quote = "'''"
940 else:
940 else:
941 # give up, backslash-escaped string will do
941 # give up, backslash-escaped string will do
942 return '"%s"' % esc_quotes(s)
942 return '"%s"' % esc_quotes(s)
943 res = itpl("$raw$quote$s$tailpadding$quote$tail")
943 res = itpl("$raw$quote$s$tailpadding$quote$tail")
944 return res
944 return res
945
945
946
946
947 #----------------------------------------------------------------------------
947 #----------------------------------------------------------------------------
948 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
948 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
949 """Take multiple lines of input.
949 """Take multiple lines of input.
950
950
951 A list with each line of input as a separate element is returned when a
951 A list with each line of input as a separate element is returned when a
952 termination string is entered (defaults to a single '.'). Input can also
952 termination string is entered (defaults to a single '.'). Input can also
953 terminate via EOF (^D in Unix, ^Z-RET in Windows).
953 terminate via EOF (^D in Unix, ^Z-RET in Windows).
954
954
955 Lines of input which end in \\ are joined into single entries (and a
955 Lines of input which end in \\ are joined into single entries (and a
956 secondary continuation prompt is issued as long as the user terminates
956 secondary continuation prompt is issued as long as the user terminates
957 lines with \\). This allows entering very long strings which are still
957 lines with \\). This allows entering very long strings which are still
958 meant to be treated as single entities.
958 meant to be treated as single entities.
959 """
959 """
960
960
961 try:
961 try:
962 if header:
962 if header:
963 header += '\n'
963 header += '\n'
964 lines = [raw_input(header + ps1)]
964 lines = [raw_input(header + ps1)]
965 except EOFError:
965 except EOFError:
966 return []
966 return []
967 terminate = [terminate_str]
967 terminate = [terminate_str]
968 try:
968 try:
969 while lines[-1:] != terminate:
969 while lines[-1:] != terminate:
970 new_line = raw_input(ps1)
970 new_line = raw_input(ps1)
971 while new_line.endswith('\\'):
971 while new_line.endswith('\\'):
972 new_line = new_line[:-1] + raw_input(ps2)
972 new_line = new_line[:-1] + raw_input(ps2)
973 lines.append(new_line)
973 lines.append(new_line)
974
974
975 return lines[:-1] # don't return the termination command
975 return lines[:-1] # don't return the termination command
976 except EOFError:
976 except EOFError:
977 print
977 print
978 return lines
978 return lines
979
979
980 #----------------------------------------------------------------------------
980 #----------------------------------------------------------------------------
981 def raw_input_ext(prompt='', ps2='... '):
981 def raw_input_ext(prompt='', ps2='... '):
982 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
982 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
983
983
984 line = raw_input(prompt)
984 line = raw_input(prompt)
985 while line.endswith('\\'):
985 while line.endswith('\\'):
986 line = line[:-1] + raw_input(ps2)
986 line = line[:-1] + raw_input(ps2)
987 return line
987 return line
988
988
989 #----------------------------------------------------------------------------
989 #----------------------------------------------------------------------------
990 def ask_yes_no(prompt,default=None):
990 def ask_yes_no(prompt,default=None):
991 """Asks a question and returns an integer 1/0 (y/n) answer.
991 """Asks a question and returns an integer 1/0 (y/n) answer.
992
992
993 If default is given (one of 'y','n'), it is used if the user input is
993 If default is given (one of 'y','n'), it is used if the user input is
994 empty. Otherwise the question is repeated until an answer is given.
994 empty. Otherwise the question is repeated until an answer is given.
995 If EOF occurs 20 times consecutively, the default answer is assumed,
995 If EOF occurs 20 times consecutively, the default answer is assumed,
996 or if there is no default, an exception is raised to prevent infinite
996 or if there is no default, an exception is raised to prevent infinite
997 loops.
997 loops.
998
998
999 Valid answers are: y/yes/n/no (match is not case sensitive)."""
999 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1000
1000
1001 answers = {'y':True,'n':False,'yes':True,'no':False}
1001 answers = {'y':True,'n':False,'yes':True,'no':False}
1002 ans = None
1002 ans = None
1003 eofs, max_eofs = 0, 20
1003 eofs, max_eofs = 0, 20
1004 while ans not in answers.keys():
1004 while ans not in answers.keys():
1005 try:
1005 try:
1006 ans = raw_input(prompt+' ').lower()
1006 ans = raw_input(prompt+' ').lower()
1007 if not ans: # response was an empty string
1007 if not ans: # response was an empty string
1008 ans = default
1008 ans = default
1009 eofs = 0
1009 eofs = 0
1010 except (EOFError,KeyboardInterrupt):
1010 except (EOFError,KeyboardInterrupt):
1011 eofs = eofs + 1
1011 eofs = eofs + 1
1012 if eofs >= max_eofs:
1012 if eofs >= max_eofs:
1013 if default in answers.keys():
1013 if default in answers.keys():
1014 ans = default
1014 ans = default
1015 else:
1015 else:
1016 raise
1016 raise
1017
1017
1018 return answers[ans]
1018 return answers[ans]
1019
1019
1020 #----------------------------------------------------------------------------
1020 #----------------------------------------------------------------------------
1021 def marquee(txt='',width=78,mark='*'):
1021 def marquee(txt='',width=78,mark='*'):
1022 """Return the input string centered in a 'marquee'."""
1022 """Return the input string centered in a 'marquee'."""
1023 if not txt:
1023 if not txt:
1024 return (mark*width)[:width]
1024 return (mark*width)[:width]
1025 nmark = (width-len(txt)-2)/len(mark)/2
1025 nmark = (width-len(txt)-2)/len(mark)/2
1026 if nmark < 0: nmark =0
1026 if nmark < 0: nmark =0
1027 marks = mark*nmark
1027 marks = mark*nmark
1028 return '%s %s %s' % (marks,txt,marks)
1028 return '%s %s %s' % (marks,txt,marks)
1029
1029
1030 #----------------------------------------------------------------------------
1030 #----------------------------------------------------------------------------
1031 class EvalDict:
1031 class EvalDict:
1032 """
1032 """
1033 Emulate a dict which evaluates its contents in the caller's frame.
1033 Emulate a dict which evaluates its contents in the caller's frame.
1034
1034
1035 Usage:
1035 Usage:
1036 >>>number = 19
1036 >>>number = 19
1037 >>>text = "python"
1037 >>>text = "python"
1038 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1038 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1039 """
1039 """
1040
1040
1041 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1041 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1042 # modified (shorter) version of:
1042 # modified (shorter) version of:
1043 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1043 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1044 # Skip Montanaro (skip@pobox.com).
1044 # Skip Montanaro (skip@pobox.com).
1045
1045
1046 def __getitem__(self, name):
1046 def __getitem__(self, name):
1047 frame = sys._getframe(1)
1047 frame = sys._getframe(1)
1048 return eval(name, frame.f_globals, frame.f_locals)
1048 return eval(name, frame.f_globals, frame.f_locals)
1049
1049
1050 EvalString = EvalDict # for backwards compatibility
1050 EvalString = EvalDict # for backwards compatibility
1051 #----------------------------------------------------------------------------
1051 #----------------------------------------------------------------------------
1052 def qw(words,flat=0,sep=None,maxsplit=-1):
1052 def qw(words,flat=0,sep=None,maxsplit=-1):
1053 """Similar to Perl's qw() operator, but with some more options.
1053 """Similar to Perl's qw() operator, but with some more options.
1054
1054
1055 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1055 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1056
1056
1057 words can also be a list itself, and with flat=1, the output will be
1057 words can also be a list itself, and with flat=1, the output will be
1058 recursively flattened. Examples:
1058 recursively flattened. Examples:
1059
1059
1060 >>> qw('1 2')
1060 >>> qw('1 2')
1061 ['1', '2']
1061 ['1', '2']
1062 >>> qw(['a b','1 2',['m n','p q']])
1062 >>> qw(['a b','1 2',['m n','p q']])
1063 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1063 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1064 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1064 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1065 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1065 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1066
1066
1067 if type(words) in StringTypes:
1067 if type(words) in StringTypes:
1068 return [word.strip() for word in words.split(sep,maxsplit)
1068 return [word.strip() for word in words.split(sep,maxsplit)
1069 if word and not word.isspace() ]
1069 if word and not word.isspace() ]
1070 if flat:
1070 if flat:
1071 return flatten(map(qw,words,[1]*len(words)))
1071 return flatten(map(qw,words,[1]*len(words)))
1072 return map(qw,words)
1072 return map(qw,words)
1073
1073
1074 #----------------------------------------------------------------------------
1074 #----------------------------------------------------------------------------
1075 def qwflat(words,sep=None,maxsplit=-1):
1075 def qwflat(words,sep=None,maxsplit=-1):
1076 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1076 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1077 return qw(words,1,sep,maxsplit)
1077 return qw(words,1,sep,maxsplit)
1078
1078
1079 #----------------------------------------------------------------------------
1079 #----------------------------------------------------------------------------
1080 def qw_lol(indata):
1080 def qw_lol(indata):
1081 """qw_lol('a b') -> [['a','b']],
1081 """qw_lol('a b') -> [['a','b']],
1082 otherwise it's just a call to qw().
1082 otherwise it's just a call to qw().
1083
1083
1084 We need this to make sure the modules_some keys *always* end up as a
1084 We need this to make sure the modules_some keys *always* end up as a
1085 list of lists."""
1085 list of lists."""
1086
1086
1087 if type(indata) in StringTypes:
1087 if type(indata) in StringTypes:
1088 return [qw(indata)]
1088 return [qw(indata)]
1089 else:
1089 else:
1090 return qw(indata)
1090 return qw(indata)
1091
1091
1092 #-----------------------------------------------------------------------------
1092 #-----------------------------------------------------------------------------
1093 def list_strings(arg):
1093 def list_strings(arg):
1094 """Always return a list of strings, given a string or list of strings
1094 """Always return a list of strings, given a string or list of strings
1095 as input."""
1095 as input."""
1096
1096
1097 if type(arg) in StringTypes: return [arg]
1097 if type(arg) in StringTypes: return [arg]
1098 else: return arg
1098 else: return arg
1099
1099
1100 #----------------------------------------------------------------------------
1100 #----------------------------------------------------------------------------
1101 def grep(pat,list,case=1):
1101 def grep(pat,list,case=1):
1102 """Simple minded grep-like function.
1102 """Simple minded grep-like function.
1103 grep(pat,list) returns occurrences of pat in list, None on failure.
1103 grep(pat,list) returns occurrences of pat in list, None on failure.
1104
1104
1105 It only does simple string matching, with no support for regexps. Use the
1105 It only does simple string matching, with no support for regexps. Use the
1106 option case=0 for case-insensitive matching."""
1106 option case=0 for case-insensitive matching."""
1107
1107
1108 # This is pretty crude. At least it should implement copying only references
1108 # This is pretty crude. At least it should implement copying only references
1109 # to the original data in case it's big. Now it copies the data for output.
1109 # to the original data in case it's big. Now it copies the data for output.
1110 out=[]
1110 out=[]
1111 if case:
1111 if case:
1112 for term in list:
1112 for term in list:
1113 if term.find(pat)>-1: out.append(term)
1113 if term.find(pat)>-1: out.append(term)
1114 else:
1114 else:
1115 lpat=pat.lower()
1115 lpat=pat.lower()
1116 for term in list:
1116 for term in list:
1117 if term.lower().find(lpat)>-1: out.append(term)
1117 if term.lower().find(lpat)>-1: out.append(term)
1118
1118
1119 if len(out): return out
1119 if len(out): return out
1120 else: return None
1120 else: return None
1121
1121
1122 #----------------------------------------------------------------------------
1122 #----------------------------------------------------------------------------
1123 def dgrep(pat,*opts):
1123 def dgrep(pat,*opts):
1124 """Return grep() on dir()+dir(__builtins__).
1124 """Return grep() on dir()+dir(__builtins__).
1125
1125
1126 A very common use of grep() when working interactively."""
1126 A very common use of grep() when working interactively."""
1127
1127
1128 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1128 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1129
1129
1130 #----------------------------------------------------------------------------
1130 #----------------------------------------------------------------------------
1131 def idgrep(pat):
1131 def idgrep(pat):
1132 """Case-insensitive dgrep()"""
1132 """Case-insensitive dgrep()"""
1133
1133
1134 return dgrep(pat,0)
1134 return dgrep(pat,0)
1135
1135
1136 #----------------------------------------------------------------------------
1136 #----------------------------------------------------------------------------
1137 def igrep(pat,list):
1137 def igrep(pat,list):
1138 """Synonym for case-insensitive grep."""
1138 """Synonym for case-insensitive grep."""
1139
1139
1140 return grep(pat,list,case=0)
1140 return grep(pat,list,case=0)
1141
1141
1142 #----------------------------------------------------------------------------
1142 #----------------------------------------------------------------------------
1143 def indent(str,nspaces=4,ntabs=0):
1143 def indent(str,nspaces=4,ntabs=0):
1144 """Indent a string a given number of spaces or tabstops.
1144 """Indent a string a given number of spaces or tabstops.
1145
1145
1146 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1146 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1147 """
1147 """
1148 if str is None:
1148 if str is None:
1149 return
1149 return
1150 ind = '\t'*ntabs+' '*nspaces
1150 ind = '\t'*ntabs+' '*nspaces
1151 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1151 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1152 if outstr.endswith(os.linesep+ind):
1152 if outstr.endswith(os.linesep+ind):
1153 return outstr[:-len(ind)]
1153 return outstr[:-len(ind)]
1154 else:
1154 else:
1155 return outstr
1155 return outstr
1156
1156
1157 #-----------------------------------------------------------------------------
1157 #-----------------------------------------------------------------------------
1158 def native_line_ends(filename,backup=1):
1158 def native_line_ends(filename,backup=1):
1159 """Convert (in-place) a file to line-ends native to the current OS.
1159 """Convert (in-place) a file to line-ends native to the current OS.
1160
1160
1161 If the optional backup argument is given as false, no backup of the
1161 If the optional backup argument is given as false, no backup of the
1162 original file is left. """
1162 original file is left. """
1163
1163
1164 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1164 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1165
1165
1166 bak_filename = filename + backup_suffixes[os.name]
1166 bak_filename = filename + backup_suffixes[os.name]
1167
1167
1168 original = open(filename).read()
1168 original = open(filename).read()
1169 shutil.copy2(filename,bak_filename)
1169 shutil.copy2(filename,bak_filename)
1170 try:
1170 try:
1171 new = open(filename,'wb')
1171 new = open(filename,'wb')
1172 new.write(os.linesep.join(original.splitlines()))
1172 new.write(os.linesep.join(original.splitlines()))
1173 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1173 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1174 new.close()
1174 new.close()
1175 except:
1175 except:
1176 os.rename(bak_filename,filename)
1176 os.rename(bak_filename,filename)
1177 if not backup:
1177 if not backup:
1178 try:
1178 try:
1179 os.remove(bak_filename)
1179 os.remove(bak_filename)
1180 except:
1180 except:
1181 pass
1181 pass
1182
1182
1183 #----------------------------------------------------------------------------
1183 #----------------------------------------------------------------------------
1184 def get_pager_cmd(pager_cmd = None):
1184 def get_pager_cmd(pager_cmd = None):
1185 """Return a pager command.
1185 """Return a pager command.
1186
1186
1187 Makes some attempts at finding an OS-correct one."""
1187 Makes some attempts at finding an OS-correct one."""
1188
1188
1189 if os.name == 'posix':
1189 if os.name == 'posix':
1190 default_pager_cmd = 'less -r' # -r for color control sequences
1190 default_pager_cmd = 'less -r' # -r for color control sequences
1191 elif os.name in ['nt','dos']:
1191 elif os.name in ['nt','dos']:
1192 default_pager_cmd = 'type'
1192 default_pager_cmd = 'type'
1193
1193
1194 if pager_cmd is None:
1194 if pager_cmd is None:
1195 try:
1195 try:
1196 pager_cmd = os.environ['PAGER']
1196 pager_cmd = os.environ['PAGER']
1197 except:
1197 except:
1198 pager_cmd = default_pager_cmd
1198 pager_cmd = default_pager_cmd
1199 return pager_cmd
1199 return pager_cmd
1200
1200
1201 #-----------------------------------------------------------------------------
1201 #-----------------------------------------------------------------------------
1202 def get_pager_start(pager,start):
1202 def get_pager_start(pager,start):
1203 """Return the string for paging files with an offset.
1203 """Return the string for paging files with an offset.
1204
1204
1205 This is the '+N' argument which less and more (under Unix) accept.
1205 This is the '+N' argument which less and more (under Unix) accept.
1206 """
1206 """
1207
1207
1208 if pager in ['less','more']:
1208 if pager in ['less','more']:
1209 if start:
1209 if start:
1210 start_string = '+' + str(start)
1210 start_string = '+' + str(start)
1211 else:
1211 else:
1212 start_string = ''
1212 start_string = ''
1213 else:
1213 else:
1214 start_string = ''
1214 start_string = ''
1215 return start_string
1215 return start_string
1216
1216
1217 #----------------------------------------------------------------------------
1217 #----------------------------------------------------------------------------
1218 if os.name == "nt":
1218 if os.name == "nt":
1219 import msvcrt
1219 import msvcrt
1220 def page_more():
1220 def page_more():
1221 """ Smart pausing between pages
1221 """ Smart pausing between pages
1222
1222
1223 @return: True if need print more lines, False if quit
1223 @return: True if need print more lines, False if quit
1224 """
1224 """
1225 Term.cout.write('---Return to continue, q to quit--- ')
1225 Term.cout.write('---Return to continue, q to quit--- ')
1226 ans = msvcrt.getch()
1226 ans = msvcrt.getch()
1227 if ans in ("q", "Q"):
1227 if ans in ("q", "Q"):
1228 result = False
1228 result = False
1229 else:
1229 else:
1230 result = True
1230 result = True
1231 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1231 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1232 return result
1232 return result
1233 else:
1233 else:
1234 def page_more():
1234 def page_more():
1235 ans = raw_input('---Return to continue, q to quit--- ')
1235 ans = raw_input('---Return to continue, q to quit--- ')
1236 if ans.lower().startswith('q'):
1236 if ans.lower().startswith('q'):
1237 return False
1237 return False
1238 else:
1238 else:
1239 return True
1239 return True
1240
1240
1241 esc_re = re.compile(r"(\x1b[^m]+m)")
1241 esc_re = re.compile(r"(\x1b[^m]+m)")
1242
1242
1243 def page_dumb(strng,start=0,screen_lines=25):
1243 def page_dumb(strng,start=0,screen_lines=25):
1244 """Very dumb 'pager' in Python, for when nothing else works.
1244 """Very dumb 'pager' in Python, for when nothing else works.
1245
1245
1246 Only moves forward, same interface as page(), except for pager_cmd and
1246 Only moves forward, same interface as page(), except for pager_cmd and
1247 mode."""
1247 mode."""
1248
1248
1249 out_ln = strng.splitlines()[start:]
1249 out_ln = strng.splitlines()[start:]
1250 screens = chop(out_ln,screen_lines-1)
1250 screens = chop(out_ln,screen_lines-1)
1251 if len(screens) == 1:
1251 if len(screens) == 1:
1252 print >>Term.cout, os.linesep.join(screens[0])
1252 print >>Term.cout, os.linesep.join(screens[0])
1253 else:
1253 else:
1254 last_escape = ""
1254 last_escape = ""
1255 for scr in screens[0:-1]:
1255 for scr in screens[0:-1]:
1256 hunk = os.linesep.join(scr)
1256 hunk = os.linesep.join(scr)
1257 print >>Term.cout, last_escape + hunk
1257 print >>Term.cout, last_escape + hunk
1258 if not page_more():
1258 if not page_more():
1259 return
1259 return
1260 esc_list = esc_re.findall(hunk)
1260 esc_list = esc_re.findall(hunk)
1261 if len(esc_list) > 0:
1261 if len(esc_list) > 0:
1262 last_escape = esc_list[-1]
1262 last_escape = esc_list[-1]
1263 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1263 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1264
1264
1265 #----------------------------------------------------------------------------
1265 #----------------------------------------------------------------------------
1266 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1266 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1267 """Print a string, piping through a pager after a certain length.
1267 """Print a string, piping through a pager after a certain length.
1268
1268
1269 The screen_lines parameter specifies the number of *usable* lines of your
1269 The screen_lines parameter specifies the number of *usable* lines of your
1270 terminal screen (total lines minus lines you need to reserve to show other
1270 terminal screen (total lines minus lines you need to reserve to show other
1271 information).
1271 information).
1272
1272
1273 If you set screen_lines to a number <=0, page() will try to auto-determine
1273 If you set screen_lines to a number <=0, page() will try to auto-determine
1274 your screen size and will only use up to (screen_size+screen_lines) for
1274 your screen size and will only use up to (screen_size+screen_lines) for
1275 printing, paging after that. That is, if you want auto-detection but need
1275 printing, paging after that. That is, if you want auto-detection but need
1276 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1276 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1277 auto-detection without any lines reserved simply use screen_lines = 0.
1277 auto-detection without any lines reserved simply use screen_lines = 0.
1278
1278
1279 If a string won't fit in the allowed lines, it is sent through the
1279 If a string won't fit in the allowed lines, it is sent through the
1280 specified pager command. If none given, look for PAGER in the environment,
1280 specified pager command. If none given, look for PAGER in the environment,
1281 and ultimately default to less.
1281 and ultimately default to less.
1282
1282
1283 If no system pager works, the string is sent through a 'dumb pager'
1283 If no system pager works, the string is sent through a 'dumb pager'
1284 written in python, very simplistic.
1284 written in python, very simplistic.
1285 """
1285 """
1286
1286
1287 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1287 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1288 TERM = os.environ.get('TERM','dumb')
1288 TERM = os.environ.get('TERM','dumb')
1289 if TERM in ['dumb','emacs'] and os.name != 'nt':
1289 if TERM in ['dumb','emacs'] and os.name != 'nt':
1290 print strng
1290 print strng
1291 return
1291 return
1292 # chop off the topmost part of the string we don't want to see
1292 # chop off the topmost part of the string we don't want to see
1293 str_lines = strng.split(os.linesep)[start:]
1293 str_lines = strng.split(os.linesep)[start:]
1294 str_toprint = os.linesep.join(str_lines)
1294 str_toprint = os.linesep.join(str_lines)
1295 num_newlines = len(str_lines)
1295 num_newlines = len(str_lines)
1296 len_str = len(str_toprint)
1296 len_str = len(str_toprint)
1297
1297
1298 # Dumb heuristics to guesstimate number of on-screen lines the string
1298 # Dumb heuristics to guesstimate number of on-screen lines the string
1299 # takes. Very basic, but good enough for docstrings in reasonable
1299 # takes. Very basic, but good enough for docstrings in reasonable
1300 # terminals. If someone later feels like refining it, it's not hard.
1300 # terminals. If someone later feels like refining it, it's not hard.
1301 numlines = max(num_newlines,int(len_str/80)+1)
1301 numlines = max(num_newlines,int(len_str/80)+1)
1302
1302
1303 if os.name == "nt":
1303 if os.name == "nt":
1304 screen_lines_def = get_console_size(defaulty=25)[1]
1304 screen_lines_def = get_console_size(defaulty=25)[1]
1305 else:
1305 else:
1306 screen_lines_def = 25 # default value if we can't auto-determine
1306 screen_lines_def = 25 # default value if we can't auto-determine
1307
1307
1308 # auto-determine screen size
1308 # auto-determine screen size
1309 if screen_lines <= 0:
1309 if screen_lines <= 0:
1310 if TERM=='xterm':
1310 if TERM=='xterm':
1311 try:
1311 try:
1312 import curses
1312 import curses
1313 if hasattr(curses,'initscr'):
1313 if hasattr(curses,'initscr'):
1314 use_curses = 1
1314 use_curses = 1
1315 else:
1315 else:
1316 use_curses = 0
1316 use_curses = 0
1317 except ImportError:
1317 except ImportError:
1318 use_curses = 0
1318 use_curses = 0
1319 else:
1319 else:
1320 # curses causes problems on many terminals other than xterm.
1320 # curses causes problems on many terminals other than xterm.
1321 use_curses = 0
1321 use_curses = 0
1322 if use_curses:
1322 if use_curses:
1323 scr = curses.initscr()
1323 scr = curses.initscr()
1324 screen_lines_real,screen_cols = scr.getmaxyx()
1324 screen_lines_real,screen_cols = scr.getmaxyx()
1325 curses.endwin()
1325 curses.endwin()
1326 screen_lines += screen_lines_real
1326 screen_lines += screen_lines_real
1327 #print '***Screen size:',screen_lines_real,'lines x',\
1327 #print '***Screen size:',screen_lines_real,'lines x',\
1328 #screen_cols,'columns.' # dbg
1328 #screen_cols,'columns.' # dbg
1329 else:
1329 else:
1330 screen_lines += screen_lines_def
1330 screen_lines += screen_lines_def
1331
1331
1332 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1332 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1333 if numlines <= screen_lines :
1333 if numlines <= screen_lines :
1334 #print '*** normal print' # dbg
1334 #print '*** normal print' # dbg
1335 print >>Term.cout, str_toprint
1335 print >>Term.cout, str_toprint
1336 else:
1336 else:
1337 # Try to open pager and default to internal one if that fails.
1337 # Try to open pager and default to internal one if that fails.
1338 # All failure modes are tagged as 'retval=1', to match the return
1338 # All failure modes are tagged as 'retval=1', to match the return
1339 # value of a failed system command. If any intermediate attempt
1339 # value of a failed system command. If any intermediate attempt
1340 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1340 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1341 pager_cmd = get_pager_cmd(pager_cmd)
1341 pager_cmd = get_pager_cmd(pager_cmd)
1342 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1342 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1343 if os.name == 'nt':
1343 if os.name == 'nt':
1344 if pager_cmd.startswith('type'):
1344 if pager_cmd.startswith('type'):
1345 # The default WinXP 'type' command is failing on complex strings.
1345 # The default WinXP 'type' command is failing on complex strings.
1346 retval = 1
1346 retval = 1
1347 else:
1347 else:
1348 tmpname = tempfile.mktemp('.txt')
1348 tmpname = tempfile.mktemp('.txt')
1349 tmpfile = file(tmpname,'wt')
1349 tmpfile = file(tmpname,'wt')
1350 tmpfile.write(strng)
1350 tmpfile.write(strng)
1351 tmpfile.close()
1351 tmpfile.close()
1352 cmd = "%s < %s" % (pager_cmd,tmpname)
1352 cmd = "%s < %s" % (pager_cmd,tmpname)
1353 if os.system(cmd):
1353 if os.system(cmd):
1354 retval = 1
1354 retval = 1
1355 else:
1355 else:
1356 retval = None
1356 retval = None
1357 os.remove(tmpname)
1357 os.remove(tmpname)
1358 else:
1358 else:
1359 try:
1359 try:
1360 retval = None
1360 retval = None
1361 # if I use popen4, things hang. No idea why.
1361 # if I use popen4, things hang. No idea why.
1362 #pager,shell_out = os.popen4(pager_cmd)
1362 #pager,shell_out = os.popen4(pager_cmd)
1363 pager = os.popen(pager_cmd,'w')
1363 pager = os.popen(pager_cmd,'w')
1364 pager.write(strng)
1364 pager.write(strng)
1365 pager.close()
1365 pager.close()
1366 retval = pager.close() # success returns None
1366 retval = pager.close() # success returns None
1367 except IOError,msg: # broken pipe when user quits
1367 except IOError,msg: # broken pipe when user quits
1368 if msg.args == (32,'Broken pipe'):
1368 if msg.args == (32,'Broken pipe'):
1369 retval = None
1369 retval = None
1370 else:
1370 else:
1371 retval = 1
1371 retval = 1
1372 except OSError:
1372 except OSError:
1373 # Other strange problems, sometimes seen in Win2k/cygwin
1373 # Other strange problems, sometimes seen in Win2k/cygwin
1374 retval = 1
1374 retval = 1
1375 if retval is not None:
1375 if retval is not None:
1376 page_dumb(strng,screen_lines=screen_lines)
1376 page_dumb(strng,screen_lines=screen_lines)
1377
1377
1378 #----------------------------------------------------------------------------
1378 #----------------------------------------------------------------------------
1379 def page_file(fname,start = 0, pager_cmd = None):
1379 def page_file(fname,start = 0, pager_cmd = None):
1380 """Page a file, using an optional pager command and starting line.
1380 """Page a file, using an optional pager command and starting line.
1381 """
1381 """
1382
1382
1383 pager_cmd = get_pager_cmd(pager_cmd)
1383 pager_cmd = get_pager_cmd(pager_cmd)
1384 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1384 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1385
1385
1386 try:
1386 try:
1387 if os.environ['TERM'] in ['emacs','dumb']:
1387 if os.environ['TERM'] in ['emacs','dumb']:
1388 raise EnvironmentError
1388 raise EnvironmentError
1389 xsys(pager_cmd + ' ' + fname)
1389 xsys(pager_cmd + ' ' + fname)
1390 except:
1390 except:
1391 try:
1391 try:
1392 if start > 0:
1392 if start > 0:
1393 start -= 1
1393 start -= 1
1394 page(open(fname).read(),start)
1394 page(open(fname).read(),start)
1395 except:
1395 except:
1396 print 'Unable to show file',`fname`
1396 print 'Unable to show file',`fname`
1397
1397
1398 #----------------------------------------------------------------------------
1398 #----------------------------------------------------------------------------
1399 def snip_print(str,width = 75,print_full = 0,header = ''):
1399 def snip_print(str,width = 75,print_full = 0,header = ''):
1400 """Print a string snipping the midsection to fit in width.
1400 """Print a string snipping the midsection to fit in width.
1401
1401
1402 print_full: mode control:
1402 print_full: mode control:
1403 - 0: only snip long strings
1403 - 0: only snip long strings
1404 - 1: send to page() directly.
1404 - 1: send to page() directly.
1405 - 2: snip long strings and ask for full length viewing with page()
1405 - 2: snip long strings and ask for full length viewing with page()
1406 Return 1 if snipping was necessary, 0 otherwise."""
1406 Return 1 if snipping was necessary, 0 otherwise."""
1407
1407
1408 if print_full == 1:
1408 if print_full == 1:
1409 page(header+str)
1409 page(header+str)
1410 return 0
1410 return 0
1411
1411
1412 print header,
1412 print header,
1413 if len(str) < width:
1413 if len(str) < width:
1414 print str
1414 print str
1415 snip = 0
1415 snip = 0
1416 else:
1416 else:
1417 whalf = int((width -5)/2)
1417 whalf = int((width -5)/2)
1418 print str[:whalf] + ' <...> ' + str[-whalf:]
1418 print str[:whalf] + ' <...> ' + str[-whalf:]
1419 snip = 1
1419 snip = 1
1420 if snip and print_full == 2:
1420 if snip and print_full == 2:
1421 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1421 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1422 page(str)
1422 page(str)
1423 return snip
1423 return snip
1424
1424
1425 #****************************************************************************
1425 #****************************************************************************
1426 # lists, dicts and structures
1426 # lists, dicts and structures
1427
1427
1428 def belong(candidates,checklist):
1428 def belong(candidates,checklist):
1429 """Check whether a list of items appear in a given list of options.
1429 """Check whether a list of items appear in a given list of options.
1430
1430
1431 Returns a list of 1 and 0, one for each candidate given."""
1431 Returns a list of 1 and 0, one for each candidate given."""
1432
1432
1433 return [x in checklist for x in candidates]
1433 return [x in checklist for x in candidates]
1434
1434
1435 #----------------------------------------------------------------------------
1435 #----------------------------------------------------------------------------
1436 def uniq_stable(elems):
1436 def uniq_stable(elems):
1437 """uniq_stable(elems) -> list
1437 """uniq_stable(elems) -> list
1438
1438
1439 Return from an iterable, a list of all the unique elements in the input,
1439 Return from an iterable, a list of all the unique elements in the input,
1440 but maintaining the order in which they first appear.
1440 but maintaining the order in which they first appear.
1441
1441
1442 A naive solution to this problem which just makes a dictionary with the
1442 A naive solution to this problem which just makes a dictionary with the
1443 elements as keys fails to respect the stability condition, since
1443 elements as keys fails to respect the stability condition, since
1444 dictionaries are unsorted by nature.
1444 dictionaries are unsorted by nature.
1445
1445
1446 Note: All elements in the input must be valid dictionary keys for this
1446 Note: All elements in the input must be valid dictionary keys for this
1447 routine to work, as it internally uses a dictionary for efficiency
1447 routine to work, as it internally uses a dictionary for efficiency
1448 reasons."""
1448 reasons."""
1449
1449
1450 unique = []
1450 unique = []
1451 unique_dict = {}
1451 unique_dict = {}
1452 for nn in elems:
1452 for nn in elems:
1453 if nn not in unique_dict:
1453 if nn not in unique_dict:
1454 unique.append(nn)
1454 unique.append(nn)
1455 unique_dict[nn] = None
1455 unique_dict[nn] = None
1456 return unique
1456 return unique
1457
1457
1458 #----------------------------------------------------------------------------
1458 #----------------------------------------------------------------------------
1459 class NLprinter:
1459 class NLprinter:
1460 """Print an arbitrarily nested list, indicating index numbers.
1460 """Print an arbitrarily nested list, indicating index numbers.
1461
1461
1462 An instance of this class called nlprint is available and callable as a
1462 An instance of this class called nlprint is available and callable as a
1463 function.
1463 function.
1464
1464
1465 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1465 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1466 and using 'sep' to separate the index from the value. """
1466 and using 'sep' to separate the index from the value. """
1467
1467
1468 def __init__(self):
1468 def __init__(self):
1469 self.depth = 0
1469 self.depth = 0
1470
1470
1471 def __call__(self,lst,pos='',**kw):
1471 def __call__(self,lst,pos='',**kw):
1472 """Prints the nested list numbering levels."""
1472 """Prints the nested list numbering levels."""
1473 kw.setdefault('indent',' ')
1473 kw.setdefault('indent',' ')
1474 kw.setdefault('sep',': ')
1474 kw.setdefault('sep',': ')
1475 kw.setdefault('start',0)
1475 kw.setdefault('start',0)
1476 kw.setdefault('stop',len(lst))
1476 kw.setdefault('stop',len(lst))
1477 # we need to remove start and stop from kw so they don't propagate
1477 # we need to remove start and stop from kw so they don't propagate
1478 # into a recursive call for a nested list.
1478 # into a recursive call for a nested list.
1479 start = kw['start']; del kw['start']
1479 start = kw['start']; del kw['start']
1480 stop = kw['stop']; del kw['stop']
1480 stop = kw['stop']; del kw['stop']
1481 if self.depth == 0 and 'header' in kw.keys():
1481 if self.depth == 0 and 'header' in kw.keys():
1482 print kw['header']
1482 print kw['header']
1483
1483
1484 for idx in range(start,stop):
1484 for idx in range(start,stop):
1485 elem = lst[idx]
1485 elem = lst[idx]
1486 if type(elem)==type([]):
1486 if type(elem)==type([]):
1487 self.depth += 1
1487 self.depth += 1
1488 self.__call__(elem,itpl('$pos$idx,'),**kw)
1488 self.__call__(elem,itpl('$pos$idx,'),**kw)
1489 self.depth -= 1
1489 self.depth -= 1
1490 else:
1490 else:
1491 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1491 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1492
1492
1493 nlprint = NLprinter()
1493 nlprint = NLprinter()
1494 #----------------------------------------------------------------------------
1494 #----------------------------------------------------------------------------
1495 def all_belong(candidates,checklist):
1495 def all_belong(candidates,checklist):
1496 """Check whether a list of items ALL appear in a given list of options.
1496 """Check whether a list of items ALL appear in a given list of options.
1497
1497
1498 Returns a single 1 or 0 value."""
1498 Returns a single 1 or 0 value."""
1499
1499
1500 return 1-(0 in [x in checklist for x in candidates])
1500 return 1-(0 in [x in checklist for x in candidates])
1501
1501
1502 #----------------------------------------------------------------------------
1502 #----------------------------------------------------------------------------
1503 def sort_compare(lst1,lst2,inplace = 1):
1503 def sort_compare(lst1,lst2,inplace = 1):
1504 """Sort and compare two lists.
1504 """Sort and compare two lists.
1505
1505
1506 By default it does it in place, thus modifying the lists. Use inplace = 0
1506 By default it does it in place, thus modifying the lists. Use inplace = 0
1507 to avoid that (at the cost of temporary copy creation)."""
1507 to avoid that (at the cost of temporary copy creation)."""
1508 if not inplace:
1508 if not inplace:
1509 lst1 = lst1[:]
1509 lst1 = lst1[:]
1510 lst2 = lst2[:]
1510 lst2 = lst2[:]
1511 lst1.sort(); lst2.sort()
1511 lst1.sort(); lst2.sort()
1512 return lst1 == lst2
1512 return lst1 == lst2
1513
1513
1514 #----------------------------------------------------------------------------
1514 #----------------------------------------------------------------------------
1515 def mkdict(**kwargs):
1515 def mkdict(**kwargs):
1516 """Return a dict from a keyword list.
1516 """Return a dict from a keyword list.
1517
1517
1518 It's just syntactic sugar for making ditcionary creation more convenient:
1518 It's just syntactic sugar for making ditcionary creation more convenient:
1519 # the standard way
1519 # the standard way
1520 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1520 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1521 # a cleaner way
1521 # a cleaner way
1522 >>>data = dict(red=1, green=2, blue=3)
1522 >>>data = dict(red=1, green=2, blue=3)
1523
1523
1524 If you need more than this, look at the Struct() class."""
1524 If you need more than this, look at the Struct() class."""
1525
1525
1526 return kwargs
1526 return kwargs
1527
1527
1528 #----------------------------------------------------------------------------
1528 #----------------------------------------------------------------------------
1529 def list2dict(lst):
1529 def list2dict(lst):
1530 """Takes a list of (key,value) pairs and turns it into a dict."""
1530 """Takes a list of (key,value) pairs and turns it into a dict."""
1531
1531
1532 dic = {}
1532 dic = {}
1533 for k,v in lst: dic[k] = v
1533 for k,v in lst: dic[k] = v
1534 return dic
1534 return dic
1535
1535
1536 #----------------------------------------------------------------------------
1536 #----------------------------------------------------------------------------
1537 def list2dict2(lst,default=''):
1537 def list2dict2(lst,default=''):
1538 """Takes a list and turns it into a dict.
1538 """Takes a list and turns it into a dict.
1539 Much slower than list2dict, but more versatile. This version can take
1539 Much slower than list2dict, but more versatile. This version can take
1540 lists with sublists of arbitrary length (including sclars)."""
1540 lists with sublists of arbitrary length (including sclars)."""
1541
1541
1542 dic = {}
1542 dic = {}
1543 for elem in lst:
1543 for elem in lst:
1544 if type(elem) in (types.ListType,types.TupleType):
1544 if type(elem) in (types.ListType,types.TupleType):
1545 size = len(elem)
1545 size = len(elem)
1546 if size == 0:
1546 if size == 0:
1547 pass
1547 pass
1548 elif size == 1:
1548 elif size == 1:
1549 dic[elem] = default
1549 dic[elem] = default
1550 else:
1550 else:
1551 k,v = elem[0], elem[1:]
1551 k,v = elem[0], elem[1:]
1552 if len(v) == 1: v = v[0]
1552 if len(v) == 1: v = v[0]
1553 dic[k] = v
1553 dic[k] = v
1554 else:
1554 else:
1555 dic[elem] = default
1555 dic[elem] = default
1556 return dic
1556 return dic
1557
1557
1558 #----------------------------------------------------------------------------
1558 #----------------------------------------------------------------------------
1559 def flatten(seq):
1559 def flatten(seq):
1560 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1560 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1561
1561
1562 return [x for subseq in seq for x in subseq]
1562 return [x for subseq in seq for x in subseq]
1563
1563
1564 #----------------------------------------------------------------------------
1564 #----------------------------------------------------------------------------
1565 def get_slice(seq,start=0,stop=None,step=1):
1565 def get_slice(seq,start=0,stop=None,step=1):
1566 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1566 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1567 if stop == None:
1567 if stop == None:
1568 stop = len(seq)
1568 stop = len(seq)
1569 item = lambda i: seq[i]
1569 item = lambda i: seq[i]
1570 return map(item,xrange(start,stop,step))
1570 return map(item,xrange(start,stop,step))
1571
1571
1572 #----------------------------------------------------------------------------
1572 #----------------------------------------------------------------------------
1573 def chop(seq,size):
1573 def chop(seq,size):
1574 """Chop a sequence into chunks of the given size."""
1574 """Chop a sequence into chunks of the given size."""
1575 chunk = lambda i: seq[i:i+size]
1575 chunk = lambda i: seq[i:i+size]
1576 return map(chunk,xrange(0,len(seq),size))
1576 return map(chunk,xrange(0,len(seq),size))
1577
1577
1578 #----------------------------------------------------------------------------
1578 #----------------------------------------------------------------------------
1579 def with(object, **args):
1579 # with is a keyword as of python 2.5, so this function is renamed to withobj
1580 # from its old 'with' name.
1581 def with_obj(object, **args):
1580 """Set multiple attributes for an object, similar to Pascal's with.
1582 """Set multiple attributes for an object, similar to Pascal's with.
1581
1583
1582 Example:
1584 Example:
1583 with(jim,
1585 with_obj(jim,
1584 born = 1960,
1586 born = 1960,
1585 haircolour = 'Brown',
1587 haircolour = 'Brown',
1586 eyecolour = 'Green')
1588 eyecolour = 'Green')
1587
1589
1588 Credit: Greg Ewing, in
1590 Credit: Greg Ewing, in
1589 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1591 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1592
1593 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1594 has become a keyword for Python 2.5, so we had to rename it."""
1590
1595
1591 object.__dict__.update(args)
1596 object.__dict__.update(args)
1592
1597
1593 #----------------------------------------------------------------------------
1598 #----------------------------------------------------------------------------
1594 def setattr_list(obj,alist,nspace = None):
1599 def setattr_list(obj,alist,nspace = None):
1595 """Set a list of attributes for an object taken from a namespace.
1600 """Set a list of attributes for an object taken from a namespace.
1596
1601
1597 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1602 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1598 alist with their values taken from nspace, which must be a dict (something
1603 alist with their values taken from nspace, which must be a dict (something
1599 like locals() will often do) If nspace isn't given, locals() of the
1604 like locals() will often do) If nspace isn't given, locals() of the
1600 *caller* is used, so in most cases you can omit it.
1605 *caller* is used, so in most cases you can omit it.
1601
1606
1602 Note that alist can be given as a string, which will be automatically
1607 Note that alist can be given as a string, which will be automatically
1603 split into a list on whitespace. If given as a list, it must be a list of
1608 split into a list on whitespace. If given as a list, it must be a list of
1604 *strings* (the variable names themselves), not of variables."""
1609 *strings* (the variable names themselves), not of variables."""
1605
1610
1606 # this grabs the local variables from the *previous* call frame -- that is
1611 # this grabs the local variables from the *previous* call frame -- that is
1607 # the locals from the function that called setattr_list().
1612 # the locals from the function that called setattr_list().
1608 # - snipped from weave.inline()
1613 # - snipped from weave.inline()
1609 if nspace is None:
1614 if nspace is None:
1610 call_frame = sys._getframe().f_back
1615 call_frame = sys._getframe().f_back
1611 nspace = call_frame.f_locals
1616 nspace = call_frame.f_locals
1612
1617
1613 if type(alist) in StringTypes:
1618 if type(alist) in StringTypes:
1614 alist = alist.split()
1619 alist = alist.split()
1615 for attr in alist:
1620 for attr in alist:
1616 val = eval(attr,nspace)
1621 val = eval(attr,nspace)
1617 setattr(obj,attr,val)
1622 setattr(obj,attr,val)
1618
1623
1619 #----------------------------------------------------------------------------
1624 #----------------------------------------------------------------------------
1620 def getattr_list(obj,alist,*args):
1625 def getattr_list(obj,alist,*args):
1621 """getattr_list(obj,alist[, default]) -> attribute list.
1626 """getattr_list(obj,alist[, default]) -> attribute list.
1622
1627
1623 Get a list of named attributes for an object. When a default argument is
1628 Get a list of named attributes for an object. When a default argument is
1624 given, it is returned when the attribute doesn't exist; without it, an
1629 given, it is returned when the attribute doesn't exist; without it, an
1625 exception is raised in that case.
1630 exception is raised in that case.
1626
1631
1627 Note that alist can be given as a string, which will be automatically
1632 Note that alist can be given as a string, which will be automatically
1628 split into a list on whitespace. If given as a list, it must be a list of
1633 split into a list on whitespace. If given as a list, it must be a list of
1629 *strings* (the variable names themselves), not of variables."""
1634 *strings* (the variable names themselves), not of variables."""
1630
1635
1631 if type(alist) in StringTypes:
1636 if type(alist) in StringTypes:
1632 alist = alist.split()
1637 alist = alist.split()
1633 if args:
1638 if args:
1634 if len(args)==1:
1639 if len(args)==1:
1635 default = args[0]
1640 default = args[0]
1636 return map(lambda attr: getattr(obj,attr,default),alist)
1641 return map(lambda attr: getattr(obj,attr,default),alist)
1637 else:
1642 else:
1638 raise ValueError,'getattr_list() takes only one optional argument'
1643 raise ValueError,'getattr_list() takes only one optional argument'
1639 else:
1644 else:
1640 return map(lambda attr: getattr(obj,attr),alist)
1645 return map(lambda attr: getattr(obj,attr),alist)
1641
1646
1642 #----------------------------------------------------------------------------
1647 #----------------------------------------------------------------------------
1643 def map_method(method,object_list,*argseq,**kw):
1648 def map_method(method,object_list,*argseq,**kw):
1644 """map_method(method,object_list,*args,**kw) -> list
1649 """map_method(method,object_list,*args,**kw) -> list
1645
1650
1646 Return a list of the results of applying the methods to the items of the
1651 Return a list of the results of applying the methods to the items of the
1647 argument sequence(s). If more than one sequence is given, the method is
1652 argument sequence(s). If more than one sequence is given, the method is
1648 called with an argument list consisting of the corresponding item of each
1653 called with an argument list consisting of the corresponding item of each
1649 sequence. All sequences must be of the same length.
1654 sequence. All sequences must be of the same length.
1650
1655
1651 Keyword arguments are passed verbatim to all objects called.
1656 Keyword arguments are passed verbatim to all objects called.
1652
1657
1653 This is Python code, so it's not nearly as fast as the builtin map()."""
1658 This is Python code, so it's not nearly as fast as the builtin map()."""
1654
1659
1655 out_list = []
1660 out_list = []
1656 idx = 0
1661 idx = 0
1657 for object in object_list:
1662 for object in object_list:
1658 try:
1663 try:
1659 handler = getattr(object, method)
1664 handler = getattr(object, method)
1660 except AttributeError:
1665 except AttributeError:
1661 out_list.append(None)
1666 out_list.append(None)
1662 else:
1667 else:
1663 if argseq:
1668 if argseq:
1664 args = map(lambda lst:lst[idx],argseq)
1669 args = map(lambda lst:lst[idx],argseq)
1665 #print 'ob',object,'hand',handler,'ar',args # dbg
1670 #print 'ob',object,'hand',handler,'ar',args # dbg
1666 out_list.append(handler(args,**kw))
1671 out_list.append(handler(args,**kw))
1667 else:
1672 else:
1668 out_list.append(handler(**kw))
1673 out_list.append(handler(**kw))
1669 idx += 1
1674 idx += 1
1670 return out_list
1675 return out_list
1671
1676
1672 #----------------------------------------------------------------------------
1677 #----------------------------------------------------------------------------
1673 def import_fail_info(mod_name,fns=None):
1678 def import_fail_info(mod_name,fns=None):
1674 """Inform load failure for a module."""
1679 """Inform load failure for a module."""
1675
1680
1676 if fns == None:
1681 if fns == None:
1677 warn("Loading of %s failed.\n" % (mod_name,))
1682 warn("Loading of %s failed.\n" % (mod_name,))
1678 else:
1683 else:
1679 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1684 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1680
1685
1681 #----------------------------------------------------------------------------
1686 #----------------------------------------------------------------------------
1682 # Proposed popitem() extension, written as a method
1687 # Proposed popitem() extension, written as a method
1683
1688
1684 class NotGiven: pass
1689 class NotGiven: pass
1685
1690
1686 def popkey(dct,key,default=NotGiven):
1691 def popkey(dct,key,default=NotGiven):
1687 """Return dct[key] and delete dct[key].
1692 """Return dct[key] and delete dct[key].
1688
1693
1689 If default is given, return it if dct[key] doesn't exist, otherwise raise
1694 If default is given, return it if dct[key] doesn't exist, otherwise raise
1690 KeyError. """
1695 KeyError. """
1691
1696
1692 try:
1697 try:
1693 val = dct[key]
1698 val = dct[key]
1694 except KeyError:
1699 except KeyError:
1695 if default is NotGiven:
1700 if default is NotGiven:
1696 raise
1701 raise
1697 else:
1702 else:
1698 return default
1703 return default
1699 else:
1704 else:
1700 del dct[key]
1705 del dct[key]
1701 return val
1706 return val
1702 #*************************** end of file <genutils.py> **********************
1707 #*************************** end of file <genutils.py> **********************
1703
1708
@@ -1,196 +1,196 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 import IPython.ipapi
22 import IPython.ipapi
23 ip = IPython.ipapi.get()
23 ip = IPython.ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 os.system('jed +%d %s' % (linenum,filename))
28 os.system('jed +%d %s' % (linenum,filename))
29
29
30 ip.set_hook('editor', calljed)
30 ip.set_hook('editor', calljed)
31
31
32 You can then enable the functionality by doing 'import myiphooks'
32 You can then enable the functionality by doing 'import myiphooks'
33 somewhere in your configuration files or ipython command line.
33 somewhere in your configuration files or ipython command line.
34
34
35 $Id: hooks.py 1303 2006-05-17 03:39:29Z fperez $"""
35 $Id: hooks.py 1322 2006-05-24 07:51:39Z fperez $"""
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 from IPython import Release
44 from IPython import Release
45 from IPython import ipapi
45 from IPython import ipapi
46 __author__ = '%s <%s>' % Release.authors['Fernando']
46 __author__ = '%s <%s>' % Release.authors['Fernando']
47 __license__ = Release.license
47 __license__ = Release.license
48 __version__ = Release.version
48 __version__ = Release.version
49
49
50 import os,bisect
50 import os,bisect
51 from genutils import Term
51 from genutils import Term
52 from pprint import PrettyPrinter
52 from pprint import PrettyPrinter
53
53
54 # List here all the default hooks. For now it's just the editor functions
54 # List here all the default hooks. For now it's just the editor functions
55 # but over time we'll move here all the public API for user-accessible things.
55 # but over time we'll move here all the public API for user-accessible things.
56 __all__ = ['editor', 'fix_error_editor', 'result_display',
56 __all__ = ['editor', 'fix_error_editor', 'result_display',
57 'input_prefilter', 'shutdown_hook', 'late_startup_hook']
57 'input_prefilter', 'shutdown_hook', 'late_startup_hook']
58
58
59 pformat = PrettyPrinter().pformat
59 pformat = PrettyPrinter().pformat
60
60
61 def editor(self,filename, linenum=None):
61 def editor(self,filename, linenum=None):
62 """Open the default editor at the given filename and linenumber.
62 """Open the default editor at the given filename and linenumber.
63
63
64 This is IPython's default editor hook, you can use it as an example to
64 This is IPython's default editor hook, you can use it as an example to
65 write your own modified one. To set your own editor function as the
65 write your own modified one. To set your own editor function as the
66 new editor hook, call ip.set_hook('editor',yourfunc)."""
66 new editor hook, call ip.set_hook('editor',yourfunc)."""
67
67
68 # IPython configures a default editor at startup by reading $EDITOR from
68 # IPython configures a default editor at startup by reading $EDITOR from
69 # the environment, and falling back on vi (unix) or notepad (win32).
69 # the environment, and falling back on vi (unix) or notepad (win32).
70 editor = self.rc.editor
70 editor = self.rc.editor
71
71
72 # marker for at which line to open the file (for existing objects)
72 # marker for at which line to open the file (for existing objects)
73 if linenum is None or editor=='notepad':
73 if linenum is None or editor=='notepad':
74 linemark = ''
74 linemark = ''
75 else:
75 else:
76 linemark = '+%d' % linenum
76 linemark = '+%d' % int(linenum)
77
77
78 # Enclose in quotes if necessary and legal
78 # Enclose in quotes if necessary and legal
79 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
79 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
80 editor = '"%s"' % editor
80 editor = '"%s"' % editor
81
81
82 # Call the actual editor
82 # Call the actual editor
83 os.system('%s %s %s' % (editor,linemark,filename))
83 os.system('%s %s %s' % (editor,linemark,filename))
84
84
85 import tempfile
85 import tempfile
86 def fix_error_editor(self,filename,linenum,column,msg):
86 def fix_error_editor(self,filename,linenum,column,msg):
87 """Open the editor at the given filename, linenumber, column and
87 """Open the editor at the given filename, linenumber, column and
88 show an error message. This is used for correcting syntax errors.
88 show an error message. This is used for correcting syntax errors.
89 The current implementation only has special support for the VIM editor,
89 The current implementation only has special support for the VIM editor,
90 and falls back on the 'editor' hook if VIM is not used.
90 and falls back on the 'editor' hook if VIM is not used.
91
91
92 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
92 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
93 """
93 """
94 def vim_quickfix_file():
94 def vim_quickfix_file():
95 t = tempfile.NamedTemporaryFile()
95 t = tempfile.NamedTemporaryFile()
96 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
96 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
97 t.flush()
97 t.flush()
98 return t
98 return t
99 if os.path.basename(self.rc.editor) != 'vim':
99 if os.path.basename(self.rc.editor) != 'vim':
100 self.hooks.editor(filename,linenum)
100 self.hooks.editor(filename,linenum)
101 return
101 return
102 t = vim_quickfix_file()
102 t = vim_quickfix_file()
103 try:
103 try:
104 os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name)
104 os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name)
105 finally:
105 finally:
106 t.close()
106 t.close()
107
107
108
108
109 class CommandChainDispatcher:
109 class CommandChainDispatcher:
110 """ Dispatch calls to a chain of commands until some func can handle it
110 """ Dispatch calls to a chain of commands until some func can handle it
111
111
112 Usage: instantiate, execute "add" to add commands (with optional
112 Usage: instantiate, execute "add" to add commands (with optional
113 priority), execute normally via f() calling mechanism.
113 priority), execute normally via f() calling mechanism.
114
114
115 """
115 """
116 def __init__(self,commands=None):
116 def __init__(self,commands=None):
117 if commands is None:
117 if commands is None:
118 self.chain = []
118 self.chain = []
119 else:
119 else:
120 self.chain = commands
120 self.chain = commands
121
121
122
122
123 def __call__(self,*args, **kw):
123 def __call__(self,*args, **kw):
124 """ Command chain is called just like normal func.
124 """ Command chain is called just like normal func.
125
125
126 This will call all funcs in chain with the same args as were given to this
126 This will call all funcs in chain with the same args as were given to this
127 function, and return the result of first func that didn't raise
127 function, and return the result of first func that didn't raise
128 TryNext """
128 TryNext """
129
129
130 for prio,cmd in self.chain:
130 for prio,cmd in self.chain:
131 #print "prio",prio,"cmd",cmd #dbg
131 #print "prio",prio,"cmd",cmd #dbg
132 try:
132 try:
133 ret = cmd(*args, **kw)
133 ret = cmd(*args, **kw)
134 return ret
134 return ret
135 except ipapi.TryNext, exc:
135 except ipapi.TryNext, exc:
136 if exc.args or exc.kwargs:
136 if exc.args or exc.kwargs:
137 args = exc.args
137 args = exc.args
138 kw = exc.kwargs
138 kw = exc.kwargs
139
139
140 def __str__(self):
140 def __str__(self):
141 return str(self.chain)
141 return str(self.chain)
142
142
143 def add(self, func, priority=0):
143 def add(self, func, priority=0):
144 """ Add a func to the cmd chain with given priority """
144 """ Add a func to the cmd chain with given priority """
145 bisect.insort(self.chain,(priority,func))
145 bisect.insort(self.chain,(priority,func))
146
146
147 def result_display(self,arg):
147 def result_display(self,arg):
148 """ Default display hook.
148 """ Default display hook.
149
149
150 Called for displaying the result to the user.
150 Called for displaying the result to the user.
151 """
151 """
152
152
153 if self.rc.pprint:
153 if self.rc.pprint:
154 out = pformat(arg)
154 out = pformat(arg)
155 if '\n' in out:
155 if '\n' in out:
156 # So that multi-line strings line up with the left column of
156 # So that multi-line strings line up with the left column of
157 # the screen, instead of having the output prompt mess up
157 # the screen, instead of having the output prompt mess up
158 # their first line.
158 # their first line.
159 Term.cout.write('\n')
159 Term.cout.write('\n')
160 print >>Term.cout, out
160 print >>Term.cout, out
161 else:
161 else:
162 # By default, the interactive prompt uses repr() to display results,
162 # By default, the interactive prompt uses repr() to display results,
163 # so we should honor this. Users who'd rather use a different
163 # so we should honor this. Users who'd rather use a different
164 # mechanism can easily override this hook.
164 # mechanism can easily override this hook.
165 print >>Term.cout, repr(arg)
165 print >>Term.cout, repr(arg)
166 # the default display hook doesn't manipulate the value to put in history
166 # the default display hook doesn't manipulate the value to put in history
167 return None
167 return None
168
168
169 def input_prefilter(self,line):
169 def input_prefilter(self,line):
170 """ Default input prefilter
170 """ Default input prefilter
171
171
172 This returns the line as unchanged, so that the interpreter
172 This returns the line as unchanged, so that the interpreter
173 knows that nothing was done and proceeds with "classic" prefiltering
173 knows that nothing was done and proceeds with "classic" prefiltering
174 (%magics, !shell commands etc.).
174 (%magics, !shell commands etc.).
175
175
176 Note that leading whitespace is not passed to this hook. Prefilter
176 Note that leading whitespace is not passed to this hook. Prefilter
177 can't alter indentation.
177 can't alter indentation.
178
178
179 """
179 """
180 #print "attempt to rewrite",line #dbg
180 #print "attempt to rewrite",line #dbg
181 return line
181 return line
182
182
183 def shutdown_hook(self):
183 def shutdown_hook(self):
184 """ default shutdown hook
184 """ default shutdown hook
185
185
186 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
186 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
187 """
187 """
188
188
189 #print "default shutdown hook ok" # dbg
189 #print "default shutdown hook ok" # dbg
190 return
190 return
191
191
192 def late_startup_hook(self):
192 def late_startup_hook(self):
193 """ Executed after ipython has been constructed and configured
193 """ Executed after ipython has been constructed and configured
194
194
195 """
195 """
196 #print "default startup hook ok" # dbg
196 #print "default startup hook ok" # dbg
@@ -1,294 +1,293 b''
1 ''' IPython customization API
1 ''' IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi
28 import IPython.ipapi
29 ip = IPython.ipapi.get()
29 ip = IPython.ipapi.get()
30
30
31 def ankka_f(self, arg):
31 def ankka_f(self, arg):
32 print "Ankka",self,"says uppercase:",arg.upper()
32 print "Ankka",self,"says uppercase:",arg.upper()
33
33
34 ip.expose_magic("ankka",ankka_f)
34 ip.expose_magic("ankka",ankka_f)
35
35
36 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias sayhi echo "Testing, hi ok"')
37 ip.magic('alias helloworld echo "Hello world"')
37 ip.magic('alias helloworld echo "Hello world"')
38 ip.system('pwd')
38 ip.system('pwd')
39
39
40 ip.ex('import re')
40 ip.ex('import re')
41 ip.ex("""
41 ip.ex("""
42 def funcci(a,b):
42 def funcci(a,b):
43 print a+b
43 print a+b
44 print funcci(3,4)
44 print funcci(3,4)
45 """)
45 """)
46 ip.ex("funcci(348,9)")
46 ip.ex("funcci(348,9)")
47
47
48 def jed_editor(self,filename, linenum=None):
48 def jed_editor(self,filename, linenum=None):
49 print "Calling my own editor, jed ... via hook!"
49 print "Calling my own editor, jed ... via hook!"
50 import os
50 import os
51 if linenum is None: linenum = 0
51 if linenum is None: linenum = 0
52 os.system('jed +%d %s' % (linenum, filename))
52 os.system('jed +%d %s' % (linenum, filename))
53 print "exiting jed"
53 print "exiting jed"
54
54
55 ip.set_hook('editor',jed_editor)
55 ip.set_hook('editor',jed_editor)
56
56
57 o = ip.options
57 o = ip.options
58 o.autocall = 2 # FULL autocall mode
58 o.autocall = 2 # FULL autocall mode
59
59
60 print "done!"
60 print "done!"
61 '''
61 '''
62
62
63 # stdlib imports
63 # stdlib imports
64 import sys
64 import sys
65
65
66 # our own
66 # our own
67 from IPython.genutils import warn,error
67 from IPython.genutils import warn,error
68
68
69 class TryNext(Exception):
69 class TryNext(Exception):
70 """Try next hook exception.
70 """Try next hook exception.
71
71
72 Raise this in your hook function to indicate that the next hook handler
72 Raise this in your hook function to indicate that the next hook handler
73 should be used to handle the operation. If you pass arguments to the
73 should be used to handle the operation. If you pass arguments to the
74 constructor those arguments will be used by the next hook instead of the
74 constructor those arguments will be used by the next hook instead of the
75 original ones.
75 original ones.
76 """
76 """
77
77
78 def __init__(self, *args, **kwargs):
78 def __init__(self, *args, **kwargs):
79 self.args = args
79 self.args = args
80 self.kwargs = kwargs
80 self.kwargs = kwargs
81
81
82 # contains the most recently instantiated IPApi
82 # contains the most recently instantiated IPApi
83
83
84 class IPythonNotRunning:
84 class IPythonNotRunning:
85 """Dummy do-nothing class.
85 """Dummy do-nothing class.
86
86
87 Instances of this class return a dummy attribute on all accesses, which
87 Instances of this class return a dummy attribute on all accesses, which
88 can be called and warns. This makes it easier to write scripts which use
88 can be called and warns. This makes it easier to write scripts which use
89 the ipapi.get() object for informational purposes to operate both with and
89 the ipapi.get() object for informational purposes to operate both with and
90 without ipython. Obviously code which uses the ipython object for
90 without ipython. Obviously code which uses the ipython object for
91 computations will not work, but this allows a wider range of code to
91 computations will not work, but this allows a wider range of code to
92 transparently work whether ipython is being used or not."""
92 transparently work whether ipython is being used or not."""
93
93
94 def __str__(self):
94 def __str__(self):
95 return "<IPythonNotRunning>"
95 return "<IPythonNotRunning>"
96
96
97 __repr__ = __str__
97 __repr__ = __str__
98
98
99 def __getattr__(self,name):
99 def __getattr__(self,name):
100 return self.dummy
100 return self.dummy
101
101
102 def dummy(self,*args,**kw):
102 def dummy(self,*args,**kw):
103 """Dummy function, which doesn't do anything but warn."""
103 """Dummy function, which doesn't do anything but warn."""
104 warn("IPython is not running, this is a dummy no-op function")
104 warn("IPython is not running, this is a dummy no-op function")
105
105
106 _recent = None
106 _recent = None
107
107
108
108
109 def get(allow_dummy=False):
109 def get(allow_dummy=False):
110 """Get an IPApi object.
110 """Get an IPApi object.
111
111
112 If allow_dummy is true, returns an instance of IPythonNotRunning
112 If allow_dummy is true, returns an instance of IPythonNotRunning
113 instead of None if not running under IPython.
113 instead of None if not running under IPython.
114
114
115 Running this should be the first thing you do when writing extensions that
115 Running this should be the first thing you do when writing extensions that
116 can be imported as normal modules. You can then direct all the
116 can be imported as normal modules. You can then direct all the
117 configuration operations against the returned object.
117 configuration operations against the returned object.
118 """
118 """
119 global _recent
119 global _recent
120 if allow_dummy and not _recent:
120 if allow_dummy and not _recent:
121 _recent = IPythonNotRunning()
121 _recent = IPythonNotRunning()
122 return _recent
122 return _recent
123
123
124 class IPApi:
124 class IPApi:
125 """ The actual API class for configuring IPython
125 """ The actual API class for configuring IPython
126
126
127 You should do all of the IPython configuration by getting an IPApi object
127 You should do all of the IPython configuration by getting an IPApi object
128 with IPython.ipapi.get() and using the attributes and methods of the
128 with IPython.ipapi.get() and using the attributes and methods of the
129 returned object."""
129 returned object."""
130
130
131 def __init__(self,ip):
131 def __init__(self,ip):
132
132
133 # All attributes exposed here are considered to be the public API of
133 # All attributes exposed here are considered to be the public API of
134 # IPython. As needs dictate, some of these may be wrapped as
134 # IPython. As needs dictate, some of these may be wrapped as
135 # properties.
135 # properties.
136
136
137 self.magic = ip.ipmagic
137 self.magic = ip.ipmagic
138
138
139 self.system = ip.ipsystem
139 self.system = ip.ipsystem
140
140
141 self.set_hook = ip.set_hook
141 self.set_hook = ip.set_hook
142
142
143 self.set_custom_exc = ip.set_custom_exc
143 self.set_custom_exc = ip.set_custom_exc
144
144
145 self.user_ns = ip.user_ns
145 self.user_ns = ip.user_ns
146
146
147 # Session-specific data store, which can be used to store
147 # Session-specific data store, which can be used to store
148 # data that should persist through the ipython session.
148 # data that should persist through the ipython session.
149 self.meta = ip.meta
149 self.meta = ip.meta
150
150
151 # The ipython instance provided
151 # The ipython instance provided
152 self.IP = ip
152 self.IP = ip
153
153
154 global _recent
154 global _recent
155 _recent = self
155 _recent = self
156
156
157 # Use a property for some things which are added to the instance very
157 # Use a property for some things which are added to the instance very
158 # late. I don't have time right now to disentangle the initialization
158 # late. I don't have time right now to disentangle the initialization
159 # order issues, so a property lets us delay item extraction while
159 # order issues, so a property lets us delay item extraction while
160 # providing a normal attribute API.
160 # providing a normal attribute API.
161 def get_db(self):
161 def get_db(self):
162 """A handle to persistent dict-like database (a PickleShareDB object)"""
162 """A handle to persistent dict-like database (a PickleShareDB object)"""
163 return self.IP.db
163 return self.IP.db
164
164
165 db = property(get_db,None,None,get_db.__doc__)
165 db = property(get_db,None,None,get_db.__doc__)
166
166
167 def get_options(self):
167 def get_options(self):
168 """All configurable variables."""
168 """All configurable variables."""
169 return self.IP.rc
169 return self.IP.rc
170
170
171 options = property(get_options,None,None,get_options.__doc__)
171 options = property(get_options,None,None,get_options.__doc__)
172
172
173 def expose_magic(self,magicname, func):
173 def expose_magic(self,magicname, func):
174 ''' Expose own function as magic function for ipython
174 ''' Expose own function as magic function for ipython
175
175
176 def foo_impl(self,parameter_s=''):
176 def foo_impl(self,parameter_s=''):
177 """My very own magic!. (Use docstrings, IPython reads them)."""
177 """My very own magic!. (Use docstrings, IPython reads them)."""
178 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
178 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
179 print 'The self object is:',self
179 print 'The self object is:',self
180
180
181 ipapi.expose_magic("foo",foo_impl)
181 ipapi.expose_magic("foo",foo_impl)
182 '''
182 '''
183
183
184 import new
184 import new
185 im = new.instancemethod(func,self.IP, self.IP.__class__)
185 im = new.instancemethod(func,self.IP, self.IP.__class__)
186 setattr(self.IP, "magic_" + magicname, im)
186 setattr(self.IP, "magic_" + magicname, im)
187
187
188 def ex(self,cmd):
188 def ex(self,cmd):
189 """ Execute a normal python statement in user namespace """
189 """ Execute a normal python statement in user namespace """
190 exec cmd in self.user_ns
190 exec cmd in self.user_ns
191
191
192 def ev(self,expr):
192 def ev(self,expr):
193 """ Evaluate python expression expr in user namespace
193 """ Evaluate python expression expr in user namespace
194
194
195 Returns the result of evaluation"""
195 Returns the result of evaluation"""
196 return eval(expr,self.user_ns)
196 return eval(expr,self.user_ns)
197
197
198 def runlines(self,lines):
198 def runlines(self,lines):
199 """ Run the specified lines in interpreter, honoring ipython directives.
199 """ Run the specified lines in interpreter, honoring ipython directives.
200
200
201 This allows %magic and !shell escape notations.
201 This allows %magic and !shell escape notations.
202
202
203 Takes either all lines in one string or list of lines.
203 Takes either all lines in one string or list of lines.
204 """
204 """
205 if isinstance(lines,basestring):
205 if isinstance(lines,basestring):
206 self.IP.runlines(lines)
206 self.IP.runlines(lines)
207 else:
207 else:
208 self.IP.runlines('\n'.join(lines))
208 self.IP.runlines('\n'.join(lines))
209
209
210 def to_user_ns(self,vars):
210 def to_user_ns(self,vars):
211 """Inject a group of variables into the IPython user namespace.
211 """Inject a group of variables into the IPython user namespace.
212
212
213 Inputs:
213 Inputs:
214
214
215 - vars: string with variable names separated by whitespace
215 - vars: string with variable names separated by whitespace
216
216
217 This utility routine is meant to ease interactive debugging work,
217 This utility routine is meant to ease interactive debugging work,
218 where you want to easily propagate some internal variable in your code
218 where you want to easily propagate some internal variable in your code
219 up to the interactive namespace for further exploration.
219 up to the interactive namespace for further exploration.
220
220
221 When you run code via %run, globals in your script become visible at
221 When you run code via %run, globals in your script become visible at
222 the interactive prompt, but this doesn't happen for locals inside your
222 the interactive prompt, but this doesn't happen for locals inside your
223 own functions and methods. Yet when debugging, it is common to want
223 own functions and methods. Yet when debugging, it is common to want
224 to explore some internal variables further at the interactive propmt.
224 to explore some internal variables further at the interactive propmt.
225
225
226 Examples:
226 Examples:
227
227
228 To use this, you first must obtain a handle on the ipython object as
228 To use this, you first must obtain a handle on the ipython object as
229 indicated above, via:
229 indicated above, via:
230
230
231 import IPython.ipapi
231 import IPython.ipapi
232 ip = IPython.ipapi.get()
232 ip = IPython.ipapi.get()
233
233
234 Once this is done, inside a routine foo() where you want to expose
234 Once this is done, inside a routine foo() where you want to expose
235 variables x and y, you do the following:
235 variables x and y, you do the following:
236
236
237 def foo():
237 def foo():
238 ...
238 ...
239 x = your_computation()
239 x = your_computation()
240 y = something_else()
240 y = something_else()
241
241
242 # This pushes x and y to the interactive prompt immediately, even
242 # This pushes x and y to the interactive prompt immediately, even
243 # if this routine crashes on the next line after:
243 # if this routine crashes on the next line after:
244 ip.to_user_ns('x y')
244 ip.to_user_ns('x y')
245 ...
245 ...
246 # return
246 # return
247
247
248 If you need to rename variables, just use ip.user_ns with dict
248 If you need to rename variables, just use ip.user_ns with dict
249 and update:
249 and update:
250
250
251 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
251 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
252 # user namespace
252 # user namespace
253 ip.user_ns.update(dict(x=foo,y=bar))
253 ip.user_ns.update(dict(x=foo,y=bar))
254
255 """
254 """
256
255
257 # print 'vars given:',vars # dbg
256 # print 'vars given:',vars # dbg
258 # Get the caller's frame to evaluate the given names in
257 # Get the caller's frame to evaluate the given names in
259 cf = sys._getframe(1)
258 cf = sys._getframe(1)
260
259
261 user_ns = self.user_ns
260 user_ns = self.user_ns
262
261
263 for name in vars.split():
262 for name in vars.split():
264 try:
263 try:
265 user_ns[name] = eval(name,cf.f_globals,cf.f_locals)
264 user_ns[name] = eval(name,cf.f_globals,cf.f_locals)
266 except:
265 except:
267 error('could not get var. %s from %s' %
266 error('could not get var. %s from %s' %
268 (name,cf.f_code.co_name))
267 (name,cf.f_code.co_name))
269
268
270 def launch_new_instance(user_ns = None):
269 def launch_new_instance(user_ns = None):
271 """ Create and start a new ipython instance.
270 """ Create and start a new ipython instance.
272
271
273 This can be called even without having an already initialized
272 This can be called even without having an already initialized
274 ipython session running.
273 ipython session running.
275
274
276 This is also used as the egg entry point for the 'ipython' script.
275 This is also used as the egg entry point for the 'ipython' script.
277
276
278 """
277 """
279 ses = create_session(user_ns)
278 ses = create_session(user_ns)
280 ses.mainloop()
279 ses.mainloop()
281
280
282
281
283 def create_session(user_ns = None):
282 def create_session(user_ns = None):
284 """ Creates, but does not launch an IPython session.
283 """ Creates, but does not launch an IPython session.
285
284
286 Later on you can call obj.mainloop() on the returned object.
285 Later on you can call obj.mainloop() on the returned object.
287
286
288 This should *not* be run when a session exists already.
287 This should *not* be run when a session exists already.
289
288
290 """
289 """
291 if user_ns is not None:
290 if user_ns is not None:
292 user_ns["__name__"] = user_ns.get("__name__",'ipy_session')
291 user_ns["__name__"] = user_ns.get("__name__",'ipy_session')
293 import IPython
292 import IPython
294 return IPython.Shell.start(user_ns = user_ns)
293 return IPython.Shell.start(user_ns = user_ns)
@@ -1,2284 +1,2295 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 1314 2006-05-19 18:24:14Z fperez $
9 $Id: iplib.py 1322 2006-05-24 07:51:39Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import StringIO
40 import StringIO
41 import bdb
41 import bdb
42 import cPickle as pickle
42 import cPickle as pickle
43 import codeop
43 import codeop
44 import exceptions
44 import exceptions
45 import glob
45 import glob
46 import inspect
46 import inspect
47 import keyword
47 import keyword
48 import new
48 import new
49 import os
49 import os
50 import pdb
50 import pdb
51 import pydoc
51 import pydoc
52 import re
52 import re
53 import shutil
53 import shutil
54 import string
54 import string
55 import sys
55 import sys
56 import tempfile
56 import tempfile
57 import traceback
57 import traceback
58 import types
58 import types
59 import pickleshare
59 import pickleshare
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 import IPython.ipapi
76 import IPython.ipapi
77
77
78 # Globals
78 # Globals
79
79
80 # store the builtin raw_input globally, and use this always, in case user code
80 # store the builtin raw_input globally, and use this always, in case user code
81 # overwrites it (like wx.py.PyShell does)
81 # overwrites it (like wx.py.PyShell does)
82 raw_input_original = raw_input
82 raw_input_original = raw_input
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87
87
88 #****************************************************************************
88 #****************************************************************************
89 # Some utility function definitions
89 # Some utility function definitions
90
90
91 ini_spaces_re = re.compile(r'^(\s+)')
91 ini_spaces_re = re.compile(r'^(\s+)')
92
92
93 def num_ini_spaces(strng):
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
94 """Return the number of initial spaces in a string"""
95
95
96 ini_spaces = ini_spaces_re.match(strng)
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
97 if ini_spaces:
98 return ini_spaces.end()
98 return ini_spaces.end()
99 else:
99 else:
100 return 0
100 return 0
101
101
102 def softspace(file, newvalue):
102 def softspace(file, newvalue):
103 """Copied from code.py, to remove the dependency"""
103 """Copied from code.py, to remove the dependency"""
104
104
105 oldvalue = 0
105 oldvalue = 0
106 try:
106 try:
107 oldvalue = file.softspace
107 oldvalue = file.softspace
108 except AttributeError:
108 except AttributeError:
109 pass
109 pass
110 try:
110 try:
111 file.softspace = newvalue
111 file.softspace = newvalue
112 except (AttributeError, TypeError):
112 except (AttributeError, TypeError):
113 # "attribute-less object" or "read-only attributes"
113 # "attribute-less object" or "read-only attributes"
114 pass
114 pass
115 return oldvalue
115 return oldvalue
116
116
117
117
118 #****************************************************************************
118 #****************************************************************************
119 # Local use exceptions
119 # Local use exceptions
120 class SpaceInInput(exceptions.Exception): pass
120 class SpaceInInput(exceptions.Exception): pass
121
121
122
122
123 #****************************************************************************
123 #****************************************************************************
124 # Local use classes
124 # Local use classes
125 class Bunch: pass
125 class Bunch: pass
126
126
127 class Undefined: pass
127 class Undefined: pass
128
128
129 class InputList(list):
129 class InputList(list):
130 """Class to store user input.
130 """Class to store user input.
131
131
132 It's basically a list, but slices return a string instead of a list, thus
132 It's basically a list, but slices return a string instead of a list, thus
133 allowing things like (assuming 'In' is an instance):
133 allowing things like (assuming 'In' is an instance):
134
134
135 exec In[4:7]
135 exec In[4:7]
136
136
137 or
137 or
138
138
139 exec In[5:9] + In[14] + In[21:25]"""
139 exec In[5:9] + In[14] + In[21:25]"""
140
140
141 def __getslice__(self,i,j):
141 def __getslice__(self,i,j):
142 return ''.join(list.__getslice__(self,i,j))
142 return ''.join(list.__getslice__(self,i,j))
143
143
144 class SyntaxTB(ultraTB.ListTB):
144 class SyntaxTB(ultraTB.ListTB):
145 """Extension which holds some state: the last exception value"""
145 """Extension which holds some state: the last exception value"""
146
146
147 def __init__(self,color_scheme = 'NoColor'):
147 def __init__(self,color_scheme = 'NoColor'):
148 ultraTB.ListTB.__init__(self,color_scheme)
148 ultraTB.ListTB.__init__(self,color_scheme)
149 self.last_syntax_error = None
149 self.last_syntax_error = None
150
150
151 def __call__(self, etype, value, elist):
151 def __call__(self, etype, value, elist):
152 self.last_syntax_error = value
152 self.last_syntax_error = value
153 ultraTB.ListTB.__call__(self,etype,value,elist)
153 ultraTB.ListTB.__call__(self,etype,value,elist)
154
154
155 def clear_err_state(self):
155 def clear_err_state(self):
156 """Return the current error state and clear it"""
156 """Return the current error state and clear it"""
157 e = self.last_syntax_error
157 e = self.last_syntax_error
158 self.last_syntax_error = None
158 self.last_syntax_error = None
159 return e
159 return e
160
160
161 #****************************************************************************
161 #****************************************************************************
162 # Main IPython class
162 # Main IPython class
163
163
164 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
164 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
165 # until a full rewrite is made. I've cleaned all cross-class uses of
165 # until a full rewrite is made. I've cleaned all cross-class uses of
166 # attributes and methods, but too much user code out there relies on the
166 # attributes and methods, but too much user code out there relies on the
167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
168 #
168 #
169 # But at least now, all the pieces have been separated and we could, in
169 # But at least now, all the pieces have been separated and we could, in
170 # principle, stop using the mixin. This will ease the transition to the
170 # principle, stop using the mixin. This will ease the transition to the
171 # chainsaw branch.
171 # chainsaw branch.
172
172
173 # For reference, the following is the list of 'self.foo' uses in the Magic
173 # For reference, the following is the list of 'self.foo' uses in the Magic
174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
175 # class, to prevent clashes.
175 # class, to prevent clashes.
176
176
177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
180 # 'self.value']
180 # 'self.value']
181
181
182 class InteractiveShell(object,Magic):
182 class InteractiveShell(object,Magic):
183 """An enhanced console for Python."""
183 """An enhanced console for Python."""
184
184
185 # class attribute to indicate whether the class supports threads or not.
185 # class attribute to indicate whether the class supports threads or not.
186 # Subclasses with thread support should override this as needed.
186 # Subclasses with thread support should override this as needed.
187 isthreaded = False
187 isthreaded = False
188
188
189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
190 user_ns = None,user_global_ns=None,banner2='',
190 user_ns = None,user_global_ns=None,banner2='',
191 custom_exceptions=((),None),embedded=False):
191 custom_exceptions=((),None),embedded=False):
192
192
193
193
194 # log system
194 # log system
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
196
196
197 # some minimal strict typechecks. For some core data structures, I
197 # some minimal strict typechecks. For some core data structures, I
198 # want actual basic python types, not just anything that looks like
198 # want actual basic python types, not just anything that looks like
199 # one. This is especially true for namespaces.
199 # one. This is especially true for namespaces.
200 for ns in (user_ns,user_global_ns):
200 for ns in (user_ns,user_global_ns):
201 if ns is not None and type(ns) != types.DictType:
201 if ns is not None and type(ns) != types.DictType:
202 raise TypeError,'namespace must be a dictionary'
202 raise TypeError,'namespace must be a dictionary'
203
203
204 # Job manager (for jobs run as background threads)
204 # Job manager (for jobs run as background threads)
205 self.jobs = BackgroundJobManager()
205 self.jobs = BackgroundJobManager()
206
206
207 # Do the intuitively correct thing for quit/exit: we remove the
208 # builtins if they exist, and our own magics will deal with this
209 try:
210 del __builtin__.exit, __builtin__.quit
211 except AttributeError:
212 pass
213
214 # Store the actual shell's name
207 # Store the actual shell's name
215 self.name = name
208 self.name = name
216
209
217 # We need to know whether the instance is meant for embedding, since
210 # We need to know whether the instance is meant for embedding, since
218 # global/local namespaces need to be handled differently in that case
211 # global/local namespaces need to be handled differently in that case
219 self.embedded = embedded
212 self.embedded = embedded
220
213
221 # command compiler
214 # command compiler
222 self.compile = codeop.CommandCompiler()
215 self.compile = codeop.CommandCompiler()
223
216
224 # User input buffer
217 # User input buffer
225 self.buffer = []
218 self.buffer = []
226
219
227 # Default name given in compilation of code
220 # Default name given in compilation of code
228 self.filename = '<ipython console>'
221 self.filename = '<ipython console>'
229
222
230 # Make an empty namespace, which extension writers can rely on both
223 # Make an empty namespace, which extension writers can rely on both
231 # existing and NEVER being used by ipython itself. This gives them a
224 # existing and NEVER being used by ipython itself. This gives them a
232 # convenient location for storing additional information and state
225 # convenient location for storing additional information and state
233 # their extensions may require, without fear of collisions with other
226 # their extensions may require, without fear of collisions with other
234 # ipython names that may develop later.
227 # ipython names that may develop later.
235 self.meta = Struct()
228 self.meta = Struct()
236
229
237 # Create the namespace where the user will operate. user_ns is
230 # Create the namespace where the user will operate. user_ns is
238 # normally the only one used, and it is passed to the exec calls as
231 # normally the only one used, and it is passed to the exec calls as
239 # the locals argument. But we do carry a user_global_ns namespace
232 # the locals argument. But we do carry a user_global_ns namespace
240 # given as the exec 'globals' argument, This is useful in embedding
233 # given as the exec 'globals' argument, This is useful in embedding
241 # situations where the ipython shell opens in a context where the
234 # situations where the ipython shell opens in a context where the
242 # distinction between locals and globals is meaningful.
235 # distinction between locals and globals is meaningful.
243
236
244 # FIXME. For some strange reason, __builtins__ is showing up at user
237 # FIXME. For some strange reason, __builtins__ is showing up at user
245 # level as a dict instead of a module. This is a manual fix, but I
238 # level as a dict instead of a module. This is a manual fix, but I
246 # should really track down where the problem is coming from. Alex
239 # should really track down where the problem is coming from. Alex
247 # Schmolck reported this problem first.
240 # Schmolck reported this problem first.
248
241
249 # A useful post by Alex Martelli on this topic:
242 # A useful post by Alex Martelli on this topic:
250 # Re: inconsistent value from __builtins__
243 # Re: inconsistent value from __builtins__
251 # Von: Alex Martelli <aleaxit@yahoo.com>
244 # Von: Alex Martelli <aleaxit@yahoo.com>
252 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
245 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
253 # Gruppen: comp.lang.python
246 # Gruppen: comp.lang.python
254
247
255 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
248 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
256 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
249 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
257 # > <type 'dict'>
250 # > <type 'dict'>
258 # > >>> print type(__builtins__)
251 # > >>> print type(__builtins__)
259 # > <type 'module'>
252 # > <type 'module'>
260 # > Is this difference in return value intentional?
253 # > Is this difference in return value intentional?
261
254
262 # Well, it's documented that '__builtins__' can be either a dictionary
255 # Well, it's documented that '__builtins__' can be either a dictionary
263 # or a module, and it's been that way for a long time. Whether it's
256 # or a module, and it's been that way for a long time. Whether it's
264 # intentional (or sensible), I don't know. In any case, the idea is
257 # intentional (or sensible), I don't know. In any case, the idea is
265 # that if you need to access the built-in namespace directly, you
258 # that if you need to access the built-in namespace directly, you
266 # should start with "import __builtin__" (note, no 's') which will
259 # should start with "import __builtin__" (note, no 's') which will
267 # definitely give you a module. Yeah, it's somewhat confusing:-(.
260 # definitely give you a module. Yeah, it's somewhat confusing:-(.
268
261
269 if user_ns is None:
262 if user_ns is None:
270 # Set __name__ to __main__ to better match the behavior of the
263 # Set __name__ to __main__ to better match the behavior of the
271 # normal interpreter.
264 # normal interpreter.
272 user_ns = {'__name__' :'__main__',
265 user_ns = {'__name__' :'__main__',
273 '__builtins__' : __builtin__,
266 '__builtins__' : __builtin__,
274 }
267 }
275
268
276 if user_global_ns is None:
269 if user_global_ns is None:
277 user_global_ns = {}
270 user_global_ns = {}
278
271
279 # Assign namespaces
272 # Assign namespaces
280 # This is the namespace where all normal user variables live
273 # This is the namespace where all normal user variables live
281 self.user_ns = user_ns
274 self.user_ns = user_ns
282 # Embedded instances require a separate namespace for globals.
275 # Embedded instances require a separate namespace for globals.
283 # Normally this one is unused by non-embedded instances.
276 # Normally this one is unused by non-embedded instances.
284 self.user_global_ns = user_global_ns
277 self.user_global_ns = user_global_ns
285 # A namespace to keep track of internal data structures to prevent
278 # A namespace to keep track of internal data structures to prevent
286 # them from cluttering user-visible stuff. Will be updated later
279 # them from cluttering user-visible stuff. Will be updated later
287 self.internal_ns = {}
280 self.internal_ns = {}
288
281
289 # Namespace of system aliases. Each entry in the alias
282 # Namespace of system aliases. Each entry in the alias
290 # table must be a 2-tuple of the form (N,name), where N is the number
283 # table must be a 2-tuple of the form (N,name), where N is the number
291 # of positional arguments of the alias.
284 # of positional arguments of the alias.
292 self.alias_table = {}
285 self.alias_table = {}
293
286
294 # A table holding all the namespaces IPython deals with, so that
287 # A table holding all the namespaces IPython deals with, so that
295 # introspection facilities can search easily.
288 # introspection facilities can search easily.
296 self.ns_table = {'user':user_ns,
289 self.ns_table = {'user':user_ns,
297 'user_global':user_global_ns,
290 'user_global':user_global_ns,
298 'alias':self.alias_table,
291 'alias':self.alias_table,
299 'internal':self.internal_ns,
292 'internal':self.internal_ns,
300 'builtin':__builtin__.__dict__
293 'builtin':__builtin__.__dict__
301 }
294 }
302
295
303 # The user namespace MUST have a pointer to the shell itself.
296 # The user namespace MUST have a pointer to the shell itself.
304 self.user_ns[name] = self
297 self.user_ns[name] = self
305
298
306 # We need to insert into sys.modules something that looks like a
299 # We need to insert into sys.modules something that looks like a
307 # module but which accesses the IPython namespace, for shelve and
300 # module but which accesses the IPython namespace, for shelve and
308 # pickle to work interactively. Normally they rely on getting
301 # pickle to work interactively. Normally they rely on getting
309 # everything out of __main__, but for embedding purposes each IPython
302 # everything out of __main__, but for embedding purposes each IPython
310 # instance has its own private namespace, so we can't go shoving
303 # instance has its own private namespace, so we can't go shoving
311 # everything into __main__.
304 # everything into __main__.
312
305
313 # note, however, that we should only do this for non-embedded
306 # note, however, that we should only do this for non-embedded
314 # ipythons, which really mimic the __main__.__dict__ with their own
307 # ipythons, which really mimic the __main__.__dict__ with their own
315 # namespace. Embedded instances, on the other hand, should not do
308 # namespace. Embedded instances, on the other hand, should not do
316 # this because they need to manage the user local/global namespaces
309 # this because they need to manage the user local/global namespaces
317 # only, but they live within a 'normal' __main__ (meaning, they
310 # only, but they live within a 'normal' __main__ (meaning, they
318 # shouldn't overtake the execution environment of the script they're
311 # shouldn't overtake the execution environment of the script they're
319 # embedded in).
312 # embedded in).
320
313
321 if not embedded:
314 if not embedded:
322 try:
315 try:
323 main_name = self.user_ns['__name__']
316 main_name = self.user_ns['__name__']
324 except KeyError:
317 except KeyError:
325 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
318 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
326 else:
319 else:
327 #print "pickle hack in place" # dbg
320 #print "pickle hack in place" # dbg
328 #print 'main_name:',main_name # dbg
321 #print 'main_name:',main_name # dbg
329 sys.modules[main_name] = FakeModule(self.user_ns)
322 sys.modules[main_name] = FakeModule(self.user_ns)
330
323
331 # List of input with multi-line handling.
324 # List of input with multi-line handling.
332 # Fill its zero entry, user counter starts at 1
325 # Fill its zero entry, user counter starts at 1
333 self.input_hist = InputList(['\n'])
326 self.input_hist = InputList(['\n'])
334 # This one will hold the 'raw' input history, without any
327 # This one will hold the 'raw' input history, without any
335 # pre-processing. This will allow users to retrieve the input just as
328 # pre-processing. This will allow users to retrieve the input just as
336 # it was exactly typed in by the user, with %hist -r.
329 # it was exactly typed in by the user, with %hist -r.
337 self.input_hist_raw = InputList(['\n'])
330 self.input_hist_raw = InputList(['\n'])
338
331
339 # list of visited directories
332 # list of visited directories
340 try:
333 try:
341 self.dir_hist = [os.getcwd()]
334 self.dir_hist = [os.getcwd()]
342 except IOError, e:
335 except IOError, e:
343 self.dir_hist = []
336 self.dir_hist = []
344
337
345 # dict of output history
338 # dict of output history
346 self.output_hist = {}
339 self.output_hist = {}
347
340
348 # dict of things NOT to alias (keywords, builtins and some magics)
341 # dict of things NOT to alias (keywords, builtins and some magics)
349 no_alias = {}
342 no_alias = {}
350 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
343 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
351 for key in keyword.kwlist + no_alias_magics:
344 for key in keyword.kwlist + no_alias_magics:
352 no_alias[key] = 1
345 no_alias[key] = 1
353 no_alias.update(__builtin__.__dict__)
346 no_alias.update(__builtin__.__dict__)
354 self.no_alias = no_alias
347 self.no_alias = no_alias
355
348
356 # make global variables for user access to these
349 # make global variables for user access to these
357 self.user_ns['_ih'] = self.input_hist
350 self.user_ns['_ih'] = self.input_hist
358 self.user_ns['_oh'] = self.output_hist
351 self.user_ns['_oh'] = self.output_hist
359 self.user_ns['_dh'] = self.dir_hist
352 self.user_ns['_dh'] = self.dir_hist
360
353
361 # user aliases to input and output histories
354 # user aliases to input and output histories
362 self.user_ns['In'] = self.input_hist
355 self.user_ns['In'] = self.input_hist
363 self.user_ns['Out'] = self.output_hist
356 self.user_ns['Out'] = self.output_hist
364
357
365 # Object variable to store code object waiting execution. This is
358 # Object variable to store code object waiting execution. This is
366 # used mainly by the multithreaded shells, but it can come in handy in
359 # used mainly by the multithreaded shells, but it can come in handy in
367 # other situations. No need to use a Queue here, since it's a single
360 # other situations. No need to use a Queue here, since it's a single
368 # item which gets cleared once run.
361 # item which gets cleared once run.
369 self.code_to_run = None
362 self.code_to_run = None
370
363
371 # escapes for automatic behavior on the command line
364 # escapes for automatic behavior on the command line
372 self.ESC_SHELL = '!'
365 self.ESC_SHELL = '!'
373 self.ESC_HELP = '?'
366 self.ESC_HELP = '?'
374 self.ESC_MAGIC = '%'
367 self.ESC_MAGIC = '%'
375 self.ESC_QUOTE = ','
368 self.ESC_QUOTE = ','
376 self.ESC_QUOTE2 = ';'
369 self.ESC_QUOTE2 = ';'
377 self.ESC_PAREN = '/'
370 self.ESC_PAREN = '/'
378
371
379 # And their associated handlers
372 # And their associated handlers
380 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
373 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
381 self.ESC_QUOTE : self.handle_auto,
374 self.ESC_QUOTE : self.handle_auto,
382 self.ESC_QUOTE2 : self.handle_auto,
375 self.ESC_QUOTE2 : self.handle_auto,
383 self.ESC_MAGIC : self.handle_magic,
376 self.ESC_MAGIC : self.handle_magic,
384 self.ESC_HELP : self.handle_help,
377 self.ESC_HELP : self.handle_help,
385 self.ESC_SHELL : self.handle_shell_escape,
378 self.ESC_SHELL : self.handle_shell_escape,
386 }
379 }
387
380
388 # class initializations
381 # class initializations
389 Magic.__init__(self,self)
382 Magic.__init__(self,self)
390
383
391 # Python source parser/formatter for syntax highlighting
384 # Python source parser/formatter for syntax highlighting
392 pyformat = PyColorize.Parser().format
385 pyformat = PyColorize.Parser().format
393 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
386 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
394
387
395 # hooks holds pointers used for user-side customizations
388 # hooks holds pointers used for user-side customizations
396 self.hooks = Struct()
389 self.hooks = Struct()
397
390
398 # Set all default hooks, defined in the IPython.hooks module.
391 # Set all default hooks, defined in the IPython.hooks module.
399 hooks = IPython.hooks
392 hooks = IPython.hooks
400 for hook_name in hooks.__all__:
393 for hook_name in hooks.__all__:
401 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
394 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
402 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
395 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
403 #print "bound hook",hook_name
396 #print "bound hook",hook_name
404
397
405 # Flag to mark unconditional exit
398 # Flag to mark unconditional exit
406 self.exit_now = False
399 self.exit_now = False
407
400
408 self.usage_min = """\
401 self.usage_min = """\
409 An enhanced console for Python.
402 An enhanced console for Python.
410 Some of its features are:
403 Some of its features are:
411 - Readline support if the readline library is present.
404 - Readline support if the readline library is present.
412 - Tab completion in the local namespace.
405 - Tab completion in the local namespace.
413 - Logging of input, see command-line options.
406 - Logging of input, see command-line options.
414 - System shell escape via ! , eg !ls.
407 - System shell escape via ! , eg !ls.
415 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
408 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
416 - Keeps track of locally defined variables via %who, %whos.
409 - Keeps track of locally defined variables via %who, %whos.
417 - Show object information with a ? eg ?x or x? (use ?? for more info).
410 - Show object information with a ? eg ?x or x? (use ?? for more info).
418 """
411 """
419 if usage: self.usage = usage
412 if usage: self.usage = usage
420 else: self.usage = self.usage_min
413 else: self.usage = self.usage_min
421
414
422 # Storage
415 # Storage
423 self.rc = rc # This will hold all configuration information
416 self.rc = rc # This will hold all configuration information
424 self.pager = 'less'
417 self.pager = 'less'
425 # temporary files used for various purposes. Deleted at exit.
418 # temporary files used for various purposes. Deleted at exit.
426 self.tempfiles = []
419 self.tempfiles = []
427
420
428 # Keep track of readline usage (later set by init_readline)
421 # Keep track of readline usage (later set by init_readline)
429 self.has_readline = False
422 self.has_readline = False
430
423
431 # template for logfile headers. It gets resolved at runtime by the
424 # template for logfile headers. It gets resolved at runtime by the
432 # logstart method.
425 # logstart method.
433 self.loghead_tpl = \
426 self.loghead_tpl = \
434 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
427 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
435 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
428 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
436 #log# opts = %s
429 #log# opts = %s
437 #log# args = %s
430 #log# args = %s
438 #log# It is safe to make manual edits below here.
431 #log# It is safe to make manual edits below here.
439 #log#-----------------------------------------------------------------------
432 #log#-----------------------------------------------------------------------
440 """
433 """
441 # for pushd/popd management
434 # for pushd/popd management
442 try:
435 try:
443 self.home_dir = get_home_dir()
436 self.home_dir = get_home_dir()
444 except HomeDirError,msg:
437 except HomeDirError,msg:
445 fatal(msg)
438 fatal(msg)
446
439
447 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
440 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
448
441
449 # Functions to call the underlying shell.
442 # Functions to call the underlying shell.
450
443
451 # utility to expand user variables via Itpl
444 # utility to expand user variables via Itpl
452 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
445 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
453 self.user_ns))
446 self.user_ns))
454 # The first is similar to os.system, but it doesn't return a value,
447 # The first is similar to os.system, but it doesn't return a value,
455 # and it allows interpolation of variables in the user's namespace.
448 # and it allows interpolation of variables in the user's namespace.
456 self.system = lambda cmd: shell(self.var_expand(cmd),
449 self.system = lambda cmd: shell(self.var_expand(cmd),
457 header='IPython system call: ',
450 header='IPython system call: ',
458 verbose=self.rc.system_verbose)
451 verbose=self.rc.system_verbose)
459 # These are for getoutput and getoutputerror:
452 # These are for getoutput and getoutputerror:
460 self.getoutput = lambda cmd: \
453 self.getoutput = lambda cmd: \
461 getoutput(self.var_expand(cmd),
454 getoutput(self.var_expand(cmd),
462 header='IPython system call: ',
455 header='IPython system call: ',
463 verbose=self.rc.system_verbose)
456 verbose=self.rc.system_verbose)
464 self.getoutputerror = lambda cmd: \
457 self.getoutputerror = lambda cmd: \
465 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
458 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
466 self.user_ns)),
459 self.user_ns)),
467 header='IPython system call: ',
460 header='IPython system call: ',
468 verbose=self.rc.system_verbose)
461 verbose=self.rc.system_verbose)
469
462
470 # RegExp for splitting line contents into pre-char//first
463 # RegExp for splitting line contents into pre-char//first
471 # word-method//rest. For clarity, each group in on one line.
464 # word-method//rest. For clarity, each group in on one line.
472
465
473 # WARNING: update the regexp if the above escapes are changed, as they
466 # WARNING: update the regexp if the above escapes are changed, as they
474 # are hardwired in.
467 # are hardwired in.
475
468
476 # Don't get carried away with trying to make the autocalling catch too
469 # Don't get carried away with trying to make the autocalling catch too
477 # much: it's better to be conservative rather than to trigger hidden
470 # much: it's better to be conservative rather than to trigger hidden
478 # evals() somewhere and end up causing side effects.
471 # evals() somewhere and end up causing side effects.
479
472
480 self.line_split = re.compile(r'^([\s*,;/])'
473 self.line_split = re.compile(r'^([\s*,;/])'
481 r'([\?\w\.]+\w*\s*)'
474 r'([\?\w\.]+\w*\s*)'
482 r'(\(?.*$)')
475 r'(\(?.*$)')
483
476
484 # Original re, keep around for a while in case changes break something
477 # Original re, keep around for a while in case changes break something
485 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
478 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
486 # r'(\s*[\?\w\.]+\w*\s*)'
479 # r'(\s*[\?\w\.]+\w*\s*)'
487 # r'(\(?.*$)')
480 # r'(\(?.*$)')
488
481
489 # RegExp to identify potential function names
482 # RegExp to identify potential function names
490 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
483 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
491
484
492 # RegExp to exclude strings with this start from autocalling. In
485 # RegExp to exclude strings with this start from autocalling. In
493 # particular, all binary operators should be excluded, so that if foo
486 # particular, all binary operators should be excluded, so that if foo
494 # is callable, foo OP bar doesn't become foo(OP bar), which is
487 # is callable, foo OP bar doesn't become foo(OP bar), which is
495 # invalid. The characters '!=()' don't need to be checked for, as the
488 # invalid. The characters '!=()' don't need to be checked for, as the
496 # _prefilter routine explicitely does so, to catch direct calls and
489 # _prefilter routine explicitely does so, to catch direct calls and
497 # rebindings of existing names.
490 # rebindings of existing names.
498
491
499 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
492 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
500 # it affects the rest of the group in square brackets.
493 # it affects the rest of the group in square brackets.
501 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
494 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
502 '|^is |^not |^in |^and |^or ')
495 '|^is |^not |^in |^and |^or ')
503
496
504 # try to catch also methods for stuff in lists/tuples/dicts: off
497 # try to catch also methods for stuff in lists/tuples/dicts: off
505 # (experimental). For this to work, the line_split regexp would need
498 # (experimental). For this to work, the line_split regexp would need
506 # to be modified so it wouldn't break things at '['. That line is
499 # to be modified so it wouldn't break things at '['. That line is
507 # nasty enough that I shouldn't change it until I can test it _well_.
500 # nasty enough that I shouldn't change it until I can test it _well_.
508 #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_.\[\]]*) ?$')
509
502
510 # keep track of where we started running (mainly for crash post-mortem)
503 # keep track of where we started running (mainly for crash post-mortem)
511 self.starting_dir = os.getcwd()
504 self.starting_dir = os.getcwd()
512
505
513 # Various switches which can be set
506 # Various switches which can be set
514 self.CACHELENGTH = 5000 # this is cheap, it's just text
507 self.CACHELENGTH = 5000 # this is cheap, it's just text
515 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
508 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
516 self.banner2 = banner2
509 self.banner2 = banner2
517
510
518 # TraceBack handlers:
511 # TraceBack handlers:
519
512
520 # Syntax error handler.
513 # Syntax error handler.
521 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
514 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
522
515
523 # The interactive one is initialized with an offset, meaning we always
516 # The interactive one is initialized with an offset, meaning we always
524 # want to remove the topmost item in the traceback, which is our own
517 # want to remove the topmost item in the traceback, which is our own
525 # internal code. Valid modes: ['Plain','Context','Verbose']
518 # internal code. Valid modes: ['Plain','Context','Verbose']
526 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
519 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
527 color_scheme='NoColor',
520 color_scheme='NoColor',
528 tb_offset = 1)
521 tb_offset = 1)
529
522
530 # IPython itself shouldn't crash. This will produce a detailed
523 # IPython itself shouldn't crash. This will produce a detailed
531 # post-mortem if it does. But we only install the crash handler for
524 # post-mortem if it does. But we only install the crash handler for
532 # non-threaded shells, the threaded ones use a normal verbose reporter
525 # non-threaded shells, the threaded ones use a normal verbose reporter
533 # and lose the crash handler. This is because exceptions in the main
526 # and lose the crash handler. This is because exceptions in the main
534 # thread (such as in GUI code) propagate directly to sys.excepthook,
527 # thread (such as in GUI code) propagate directly to sys.excepthook,
535 # and there's no point in printing crash dumps for every user exception.
528 # and there's no point in printing crash dumps for every user exception.
536 if self.isthreaded:
529 if self.isthreaded:
537 sys.excepthook = ultraTB.FormattedTB()
530 sys.excepthook = ultraTB.FormattedTB()
538 else:
531 else:
539 from IPython import CrashHandler
532 from IPython import CrashHandler
540 sys.excepthook = CrashHandler.CrashHandler(self)
533 sys.excepthook = CrashHandler.CrashHandler(self)
541
534
542 # The instance will store a pointer to this, so that runtime code
535 # The instance will store a pointer to this, so that runtime code
543 # (such as magics) can access it. This is because during the
536 # (such as magics) can access it. This is because during the
544 # read-eval loop, it gets temporarily overwritten (to deal with GUI
537 # read-eval loop, it gets temporarily overwritten (to deal with GUI
545 # frameworks).
538 # frameworks).
546 self.sys_excepthook = sys.excepthook
539 self.sys_excepthook = sys.excepthook
547
540
548 # and add any custom exception handlers the user may have specified
541 # and add any custom exception handlers the user may have specified
549 self.set_custom_exc(*custom_exceptions)
542 self.set_custom_exc(*custom_exceptions)
550
543
551 # Object inspector
544 # Object inspector
552 self.inspector = OInspect.Inspector(OInspect.InspectColors,
545 self.inspector = OInspect.Inspector(OInspect.InspectColors,
553 PyColorize.ANSICodeColors,
546 PyColorize.ANSICodeColors,
554 'NoColor')
547 'NoColor')
555 # indentation management
548 # indentation management
556 self.autoindent = False
549 self.autoindent = False
557 self.indent_current_nsp = 0
550 self.indent_current_nsp = 0
558
551
559 # Make some aliases automatically
552 # Make some aliases automatically
560 # Prepare list of shell aliases to auto-define
553 # Prepare list of shell aliases to auto-define
561 if os.name == 'posix':
554 if os.name == 'posix':
562 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
555 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
563 'mv mv -i','rm rm -i','cp cp -i',
556 'mv mv -i','rm rm -i','cp cp -i',
564 'cat cat','less less','clear clear',
557 'cat cat','less less','clear clear',
565 # a better ls
558 # a better ls
566 'ls ls -F',
559 'ls ls -F',
567 # long ls
560 # long ls
568 'll ls -lF',
561 'll ls -lF',
569 # color ls
562 # color ls
570 'lc ls -F -o --color',
563 'lc ls -F -o --color',
571 # ls normal files only
564 # ls normal files only
572 'lf ls -F -o --color %l | grep ^-',
565 'lf ls -F -o --color %l | grep ^-',
573 # ls symbolic links
566 # ls symbolic links
574 'lk ls -F -o --color %l | grep ^l',
567 'lk ls -F -o --color %l | grep ^l',
575 # directories or links to directories,
568 # directories or links to directories,
576 'ldir ls -F -o --color %l | grep /$',
569 'ldir ls -F -o --color %l | grep /$',
577 # things which are executable
570 # things which are executable
578 'lx ls -F -o --color %l | grep ^-..x',
571 'lx ls -F -o --color %l | grep ^-..x',
579 )
572 )
580 elif os.name in ['nt','dos']:
573 elif os.name in ['nt','dos']:
581 auto_alias = ('dir dir /on', 'ls dir /on',
574 auto_alias = ('dir dir /on', 'ls dir /on',
582 'ddir dir /ad /on', 'ldir dir /ad /on',
575 'ddir dir /ad /on', 'ldir dir /ad /on',
583 'mkdir mkdir','rmdir rmdir','echo echo',
576 'mkdir mkdir','rmdir rmdir','echo echo',
584 'ren ren','cls cls','copy copy')
577 'ren ren','cls cls','copy copy')
585 else:
578 else:
586 auto_alias = ()
579 auto_alias = ()
587 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
580 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
588 # Call the actual (public) initializer
581 # Call the actual (public) initializer
589 self.init_auto_alias()
582 self.init_auto_alias()
590
583
591 # Produce a public API instance
584 # Produce a public API instance
592 self.api = IPython.ipapi.IPApi(self)
585 self.api = IPython.ipapi.IPApi(self)
593
586
594 # track which builtins we add, so we can clean up later
587 # track which builtins we add, so we can clean up later
595 self.builtins_added = {}
588 self.builtins_added = {}
596 # This method will add the necessary builtins for operation, but
589 # This method will add the necessary builtins for operation, but
597 # tracking what it did via the builtins_added dict.
590 # tracking what it did via the builtins_added dict.
598 self.add_builtins()
591 self.add_builtins()
599
592
600 # end __init__
593 # end __init__
601
594
602 def pre_config_initialization(self):
595 def pre_config_initialization(self):
603 """Pre-configuration init method
596 """Pre-configuration init method
604
597
605 This is called before the configuration files are processed to
598 This is called before the configuration files are processed to
606 prepare the services the config files might need.
599 prepare the services the config files might need.
607
600
608 self.rc already has reasonable default values at this point.
601 self.rc already has reasonable default values at this point.
609 """
602 """
610 rc = self.rc
603 rc = self.rc
611
604
612 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
605 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
613
606
614 def post_config_initialization(self):
607 def post_config_initialization(self):
615 """Post configuration init method
608 """Post configuration init method
616
609
617 This is called after the configuration files have been processed to
610 This is called after the configuration files have been processed to
618 'finalize' the initialization."""
611 'finalize' the initialization."""
619
612
620 rc = self.rc
613 rc = self.rc
621
614
622 # Load readline proper
615 # Load readline proper
623 if rc.readline:
616 if rc.readline:
624 self.init_readline()
617 self.init_readline()
625
618
626 # local shortcut, this is used a LOT
619 # local shortcut, this is used a LOT
627 self.log = self.logger.log
620 self.log = self.logger.log
628
621
629 # Initialize cache, set in/out prompts and printing system
622 # Initialize cache, set in/out prompts and printing system
630 self.outputcache = CachedOutput(self,
623 self.outputcache = CachedOutput(self,
631 rc.cache_size,
624 rc.cache_size,
632 rc.pprint,
625 rc.pprint,
633 input_sep = rc.separate_in,
626 input_sep = rc.separate_in,
634 output_sep = rc.separate_out,
627 output_sep = rc.separate_out,
635 output_sep2 = rc.separate_out2,
628 output_sep2 = rc.separate_out2,
636 ps1 = rc.prompt_in1,
629 ps1 = rc.prompt_in1,
637 ps2 = rc.prompt_in2,
630 ps2 = rc.prompt_in2,
638 ps_out = rc.prompt_out,
631 ps_out = rc.prompt_out,
639 pad_left = rc.prompts_pad_left)
632 pad_left = rc.prompts_pad_left)
640
633
641 # user may have over-ridden the default print hook:
634 # user may have over-ridden the default print hook:
642 try:
635 try:
643 self.outputcache.__class__.display = self.hooks.display
636 self.outputcache.__class__.display = self.hooks.display
644 except AttributeError:
637 except AttributeError:
645 pass
638 pass
646
639
647 # I don't like assigning globally to sys, because it means when embedding
640 # I don't like assigning globally to sys, because it means when embedding
648 # instances, each embedded instance overrides the previous choice. But
641 # instances, each embedded instance overrides the previous choice. But
649 # sys.displayhook seems to be called internally by exec, so I don't see a
642 # sys.displayhook seems to be called internally by exec, so I don't see a
650 # way around it.
643 # way around it.
651 sys.displayhook = self.outputcache
644 sys.displayhook = self.outputcache
652
645
653 # Set user colors (don't do it in the constructor above so that it
646 # Set user colors (don't do it in the constructor above so that it
654 # doesn't crash if colors option is invalid)
647 # doesn't crash if colors option is invalid)
655 self.magic_colors(rc.colors)
648 self.magic_colors(rc.colors)
656
649
657 # Set calling of pdb on exceptions
650 # Set calling of pdb on exceptions
658 self.call_pdb = rc.pdb
651 self.call_pdb = rc.pdb
659
652
660 # Load user aliases
653 # Load user aliases
661 for alias in rc.alias:
654 for alias in rc.alias:
662 self.magic_alias(alias)
655 self.magic_alias(alias)
663 self.hooks.late_startup_hook()
656 self.hooks.late_startup_hook()
664
657
665 for batchfile in [path(arg) for arg in self.rc.args
658 for batchfile in [path(arg) for arg in self.rc.args
666 if arg.lower().endswith('.ipy')]:
659 if arg.lower().endswith('.ipy')]:
667 if not batchfile.isfile():
660 if not batchfile.isfile():
668 print "No such batch file:", batchfile
661 print "No such batch file:", batchfile
669 continue
662 continue
670 self.api.runlines(batchfile.text())
663 self.api.runlines(batchfile.text())
671
664
672 def add_builtins(self):
665 def add_builtins(self):
673 """Store ipython references into the builtin namespace.
666 """Store ipython references into the builtin namespace.
674
667
675 Some parts of ipython operate via builtins injected here, which hold a
668 Some parts of ipython operate via builtins injected here, which hold a
676 reference to IPython itself."""
669 reference to IPython itself."""
677
670
678 # TODO: deprecate all except _ip; 'jobs' should be installed
671 # TODO: deprecate all except _ip; 'jobs' should be installed
679 # by an extension and the rest are under _ip, ipalias is redundant
672 # by an extension and the rest are under _ip, ipalias is redundant
680 builtins_new = dict(__IPYTHON__ = self,
673 builtins_new = dict(__IPYTHON__ = self,
681 ip_set_hook = self.set_hook,
674 ip_set_hook = self.set_hook,
682 jobs = self.jobs,
675 jobs = self.jobs,
683 ipmagic = self.ipmagic,
676 ipmagic = self.ipmagic,
684 ipalias = self.ipalias,
677 ipalias = self.ipalias,
685 ipsystem = self.ipsystem,
678 ipsystem = self.ipsystem,
686 _ip = self.api
679 _ip = self.api
687 )
680 )
688 for biname,bival in builtins_new.items():
681 for biname,bival in builtins_new.items():
689 try:
682 try:
690 # store the orignal value so we can restore it
683 # store the orignal value so we can restore it
691 self.builtins_added[biname] = __builtin__.__dict__[biname]
684 self.builtins_added[biname] = __builtin__.__dict__[biname]
692 except KeyError:
685 except KeyError:
693 # or mark that it wasn't defined, and we'll just delete it at
686 # or mark that it wasn't defined, and we'll just delete it at
694 # cleanup
687 # cleanup
695 self.builtins_added[biname] = Undefined
688 self.builtins_added[biname] = Undefined
696 __builtin__.__dict__[biname] = bival
689 __builtin__.__dict__[biname] = bival
697
690
698 # Keep in the builtins a flag for when IPython is active. We set it
691 # Keep in the builtins a flag for when IPython is active. We set it
699 # with setdefault so that multiple nested IPythons don't clobber one
692 # with setdefault so that multiple nested IPythons don't clobber one
700 # another. Each will increase its value by one upon being activated,
693 # another. Each will increase its value by one upon being activated,
701 # which also gives us a way to determine the nesting level.
694 # which also gives us a way to determine the nesting level.
702 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
695 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
703
696
704 def clean_builtins(self):
697 def clean_builtins(self):
705 """Remove any builtins which might have been added by add_builtins, or
698 """Remove any builtins which might have been added by add_builtins, or
706 restore overwritten ones to their previous values."""
699 restore overwritten ones to their previous values."""
707 for biname,bival in self.builtins_added.items():
700 for biname,bival in self.builtins_added.items():
708 if bival is Undefined:
701 if bival is Undefined:
709 del __builtin__.__dict__[biname]
702 del __builtin__.__dict__[biname]
710 else:
703 else:
711 __builtin__.__dict__[biname] = bival
704 __builtin__.__dict__[biname] = bival
712 self.builtins_added.clear()
705 self.builtins_added.clear()
713
706
714 def set_hook(self,name,hook, priority = 50):
707 def set_hook(self,name,hook, priority = 50):
715 """set_hook(name,hook) -> sets an internal IPython hook.
708 """set_hook(name,hook) -> sets an internal IPython hook.
716
709
717 IPython exposes some of its internal API as user-modifiable hooks. By
710 IPython exposes some of its internal API as user-modifiable hooks. By
718 adding your function to one of these hooks, you can modify IPython's
711 adding your function to one of these hooks, you can modify IPython's
719 behavior to call at runtime your own routines."""
712 behavior to call at runtime your own routines."""
720
713
721 # At some point in the future, this should validate the hook before it
714 # At some point in the future, this should validate the hook before it
722 # accepts it. Probably at least check that the hook takes the number
715 # accepts it. Probably at least check that the hook takes the number
723 # of args it's supposed to.
716 # of args it's supposed to.
724 dp = getattr(self.hooks, name, None)
717 dp = getattr(self.hooks, name, None)
725 if name not in IPython.hooks.__all__:
718 if name not in IPython.hooks.__all__:
726 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
719 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
727 if not dp:
720 if not dp:
728 dp = IPython.hooks.CommandChainDispatcher()
721 dp = IPython.hooks.CommandChainDispatcher()
729
722
730 f = new.instancemethod(hook,self,self.__class__)
723 f = new.instancemethod(hook,self,self.__class__)
731 try:
724 try:
732 dp.add(f,priority)
725 dp.add(f,priority)
733 except AttributeError:
726 except AttributeError:
734 # it was not commandchain, plain old func - replace
727 # it was not commandchain, plain old func - replace
735 dp = f
728 dp = f
736
729
737 setattr(self.hooks,name, dp)
730 setattr(self.hooks,name, dp)
738
731
739
732
740 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
733 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
741
734
742 def set_custom_exc(self,exc_tuple,handler):
735 def set_custom_exc(self,exc_tuple,handler):
743 """set_custom_exc(exc_tuple,handler)
736 """set_custom_exc(exc_tuple,handler)
744
737
745 Set a custom exception handler, which will be called if any of the
738 Set a custom exception handler, which will be called if any of the
746 exceptions in exc_tuple occur in the mainloop (specifically, in the
739 exceptions in exc_tuple occur in the mainloop (specifically, in the
747 runcode() method.
740 runcode() method.
748
741
749 Inputs:
742 Inputs:
750
743
751 - exc_tuple: a *tuple* of valid exceptions to call the defined
744 - exc_tuple: a *tuple* of valid exceptions to call the defined
752 handler for. It is very important that you use a tuple, and NOT A
745 handler for. It is very important that you use a tuple, and NOT A
753 LIST here, because of the way Python's except statement works. If
746 LIST here, because of the way Python's except statement works. If
754 you only want to trap a single exception, use a singleton tuple:
747 you only want to trap a single exception, use a singleton tuple:
755
748
756 exc_tuple == (MyCustomException,)
749 exc_tuple == (MyCustomException,)
757
750
758 - handler: this must be defined as a function with the following
751 - handler: this must be defined as a function with the following
759 basic interface: def my_handler(self,etype,value,tb).
752 basic interface: def my_handler(self,etype,value,tb).
760
753
761 This will be made into an instance method (via new.instancemethod)
754 This will be made into an instance method (via new.instancemethod)
762 of IPython itself, and it will be called if any of the exceptions
755 of IPython itself, and it will be called if any of the exceptions
763 listed in the exc_tuple are caught. If the handler is None, an
756 listed in the exc_tuple are caught. If the handler is None, an
764 internal basic one is used, which just prints basic info.
757 internal basic one is used, which just prints basic info.
765
758
766 WARNING: by putting in your own exception handler into IPython's main
759 WARNING: by putting in your own exception handler into IPython's main
767 execution loop, you run a very good chance of nasty crashes. This
760 execution loop, you run a very good chance of nasty crashes. This
768 facility should only be used if you really know what you are doing."""
761 facility should only be used if you really know what you are doing."""
769
762
770 assert type(exc_tuple)==type(()) , \
763 assert type(exc_tuple)==type(()) , \
771 "The custom exceptions must be given AS A TUPLE."
764 "The custom exceptions must be given AS A TUPLE."
772
765
773 def dummy_handler(self,etype,value,tb):
766 def dummy_handler(self,etype,value,tb):
774 print '*** Simple custom exception handler ***'
767 print '*** Simple custom exception handler ***'
775 print 'Exception type :',etype
768 print 'Exception type :',etype
776 print 'Exception value:',value
769 print 'Exception value:',value
777 print 'Traceback :',tb
770 print 'Traceback :',tb
778 print 'Source code :','\n'.join(self.buffer)
771 print 'Source code :','\n'.join(self.buffer)
779
772
780 if handler is None: handler = dummy_handler
773 if handler is None: handler = dummy_handler
781
774
782 self.CustomTB = new.instancemethod(handler,self,self.__class__)
775 self.CustomTB = new.instancemethod(handler,self,self.__class__)
783 self.custom_exceptions = exc_tuple
776 self.custom_exceptions = exc_tuple
784
777
785 def set_custom_completer(self,completer,pos=0):
778 def set_custom_completer(self,completer,pos=0):
786 """set_custom_completer(completer,pos=0)
779 """set_custom_completer(completer,pos=0)
787
780
788 Adds a new custom completer function.
781 Adds a new custom completer function.
789
782
790 The position argument (defaults to 0) is the index in the completers
783 The position argument (defaults to 0) is the index in the completers
791 list where you want the completer to be inserted."""
784 list where you want the completer to be inserted."""
792
785
793 newcomp = new.instancemethod(completer,self.Completer,
786 newcomp = new.instancemethod(completer,self.Completer,
794 self.Completer.__class__)
787 self.Completer.__class__)
795 self.Completer.matchers.insert(pos,newcomp)
788 self.Completer.matchers.insert(pos,newcomp)
796
789
797 def _get_call_pdb(self):
790 def _get_call_pdb(self):
798 return self._call_pdb
791 return self._call_pdb
799
792
800 def _set_call_pdb(self,val):
793 def _set_call_pdb(self,val):
801
794
802 if val not in (0,1,False,True):
795 if val not in (0,1,False,True):
803 raise ValueError,'new call_pdb value must be boolean'
796 raise ValueError,'new call_pdb value must be boolean'
804
797
805 # store value in instance
798 # store value in instance
806 self._call_pdb = val
799 self._call_pdb = val
807
800
808 # notify the actual exception handlers
801 # notify the actual exception handlers
809 self.InteractiveTB.call_pdb = val
802 self.InteractiveTB.call_pdb = val
810 if self.isthreaded:
803 if self.isthreaded:
811 try:
804 try:
812 self.sys_excepthook.call_pdb = val
805 self.sys_excepthook.call_pdb = val
813 except:
806 except:
814 warn('Failed to activate pdb for threaded exception handler')
807 warn('Failed to activate pdb for threaded exception handler')
815
808
816 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
809 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
817 'Control auto-activation of pdb at exceptions')
810 'Control auto-activation of pdb at exceptions')
818
811
819
812
820 # These special functions get installed in the builtin namespace, to
813 # These special functions get installed in the builtin namespace, to
821 # provide programmatic (pure python) access to magics, aliases and system
814 # provide programmatic (pure python) access to magics, aliases and system
822 # calls. This is important for logging, user scripting, and more.
815 # calls. This is important for logging, user scripting, and more.
823
816
824 # We are basically exposing, via normal python functions, the three
817 # We are basically exposing, via normal python functions, the three
825 # mechanisms in which ipython offers special call modes (magics for
818 # mechanisms in which ipython offers special call modes (magics for
826 # internal control, aliases for direct system access via pre-selected
819 # internal control, aliases for direct system access via pre-selected
827 # names, and !cmd for calling arbitrary system commands).
820 # names, and !cmd for calling arbitrary system commands).
828
821
829 def ipmagic(self,arg_s):
822 def ipmagic(self,arg_s):
830 """Call a magic function by name.
823 """Call a magic function by name.
831
824
832 Input: a string containing the name of the magic function to call and any
825 Input: a string containing the name of the magic function to call and any
833 additional arguments to be passed to the magic.
826 additional arguments to be passed to the magic.
834
827
835 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
828 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
836 prompt:
829 prompt:
837
830
838 In[1]: %name -opt foo bar
831 In[1]: %name -opt foo bar
839
832
840 To call a magic without arguments, simply use ipmagic('name').
833 To call a magic without arguments, simply use ipmagic('name').
841
834
842 This provides a proper Python function to call IPython's magics in any
835 This provides a proper Python function to call IPython's magics in any
843 valid Python code you can type at the interpreter, including loops and
836 valid Python code you can type at the interpreter, including loops and
844 compound statements. It is added by IPython to the Python builtin
837 compound statements. It is added by IPython to the Python builtin
845 namespace upon initialization."""
838 namespace upon initialization."""
846
839
847 args = arg_s.split(' ',1)
840 args = arg_s.split(' ',1)
848 magic_name = args[0]
841 magic_name = args[0]
849 magic_name = magic_name.lstrip(self.ESC_MAGIC)
842 magic_name = magic_name.lstrip(self.ESC_MAGIC)
850
843
851 try:
844 try:
852 magic_args = args[1]
845 magic_args = args[1]
853 except IndexError:
846 except IndexError:
854 magic_args = ''
847 magic_args = ''
855 fn = getattr(self,'magic_'+magic_name,None)
848 fn = getattr(self,'magic_'+magic_name,None)
856 if fn is None:
849 if fn is None:
857 error("Magic function `%s` not found." % magic_name)
850 error("Magic function `%s` not found." % magic_name)
858 else:
851 else:
859 magic_args = self.var_expand(magic_args)
852 magic_args = self.var_expand(magic_args)
860 return fn(magic_args)
853 return fn(magic_args)
861
854
862 def ipalias(self,arg_s):
855 def ipalias(self,arg_s):
863 """Call an alias by name.
856 """Call an alias by name.
864
857
865 Input: a string containing the name of the alias to call and any
858 Input: a string containing the name of the alias to call and any
866 additional arguments to be passed to the magic.
859 additional arguments to be passed to the magic.
867
860
868 ipalias('name -opt foo bar') is equivalent to typing at the ipython
861 ipalias('name -opt foo bar') is equivalent to typing at the ipython
869 prompt:
862 prompt:
870
863
871 In[1]: name -opt foo bar
864 In[1]: name -opt foo bar
872
865
873 To call an alias without arguments, simply use ipalias('name').
866 To call an alias without arguments, simply use ipalias('name').
874
867
875 This provides a proper Python function to call IPython's aliases in any
868 This provides a proper Python function to call IPython's aliases in any
876 valid Python code you can type at the interpreter, including loops and
869 valid Python code you can type at the interpreter, including loops and
877 compound statements. It is added by IPython to the Python builtin
870 compound statements. It is added by IPython to the Python builtin
878 namespace upon initialization."""
871 namespace upon initialization."""
879
872
880 args = arg_s.split(' ',1)
873 args = arg_s.split(' ',1)
881 alias_name = args[0]
874 alias_name = args[0]
882 try:
875 try:
883 alias_args = args[1]
876 alias_args = args[1]
884 except IndexError:
877 except IndexError:
885 alias_args = ''
878 alias_args = ''
886 if alias_name in self.alias_table:
879 if alias_name in self.alias_table:
887 self.call_alias(alias_name,alias_args)
880 self.call_alias(alias_name,alias_args)
888 else:
881 else:
889 error("Alias `%s` not found." % alias_name)
882 error("Alias `%s` not found." % alias_name)
890
883
891 def ipsystem(self,arg_s):
884 def ipsystem(self,arg_s):
892 """Make a system call, using IPython."""
885 """Make a system call, using IPython."""
893
886
894 self.system(arg_s)
887 self.system(arg_s)
895
888
896 def complete(self,text):
889 def complete(self,text):
897 """Return a sorted list of all possible completions on text.
890 """Return a sorted list of all possible completions on text.
898
891
899 Inputs:
892 Inputs:
900
893
901 - text: a string of text to be completed on.
894 - text: a string of text to be completed on.
902
895
903 This is a wrapper around the completion mechanism, similar to what
896 This is a wrapper around the completion mechanism, similar to what
904 readline does at the command line when the TAB key is hit. By
897 readline does at the command line when the TAB key is hit. By
905 exposing it as a method, it can be used by other non-readline
898 exposing it as a method, it can be used by other non-readline
906 environments (such as GUIs) for text completion.
899 environments (such as GUIs) for text completion.
907
900
908 Simple usage example:
901 Simple usage example:
909
902
910 In [1]: x = 'hello'
903 In [1]: x = 'hello'
911
904
912 In [2]: __IP.complete('x.l')
905 In [2]: __IP.complete('x.l')
913 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
906 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
914
907
915 complete = self.Completer.complete
908 complete = self.Completer.complete
916 state = 0
909 state = 0
917 # use a dict so we get unique keys, since ipyhton's multiple
910 # use a dict so we get unique keys, since ipyhton's multiple
918 # completers can return duplicates.
911 # completers can return duplicates.
919 comps = {}
912 comps = {}
920 while True:
913 while True:
921 newcomp = complete(text,state)
914 newcomp = complete(text,state)
922 if newcomp is None:
915 if newcomp is None:
923 break
916 break
924 comps[newcomp] = 1
917 comps[newcomp] = 1
925 state += 1
918 state += 1
926 outcomps = comps.keys()
919 outcomps = comps.keys()
927 outcomps.sort()
920 outcomps.sort()
928 return outcomps
921 return outcomps
929
922
930 def set_completer_frame(self, frame=None):
923 def set_completer_frame(self, frame=None):
931 if frame:
924 if frame:
932 self.Completer.namespace = frame.f_locals
925 self.Completer.namespace = frame.f_locals
933 self.Completer.global_namespace = frame.f_globals
926 self.Completer.global_namespace = frame.f_globals
934 else:
927 else:
935 self.Completer.namespace = self.user_ns
928 self.Completer.namespace = self.user_ns
936 self.Completer.global_namespace = self.user_global_ns
929 self.Completer.global_namespace = self.user_global_ns
937
930
938 def init_auto_alias(self):
931 def init_auto_alias(self):
939 """Define some aliases automatically.
932 """Define some aliases automatically.
940
933
941 These are ALL parameter-less aliases"""
934 These are ALL parameter-less aliases"""
942
935
943 for alias,cmd in self.auto_alias:
936 for alias,cmd in self.auto_alias:
944 self.alias_table[alias] = (0,cmd)
937 self.alias_table[alias] = (0,cmd)
945
938
946 def alias_table_validate(self,verbose=0):
939 def alias_table_validate(self,verbose=0):
947 """Update information about the alias table.
940 """Update information about the alias table.
948
941
949 In particular, make sure no Python keywords/builtins are in it."""
942 In particular, make sure no Python keywords/builtins are in it."""
950
943
951 no_alias = self.no_alias
944 no_alias = self.no_alias
952 for k in self.alias_table.keys():
945 for k in self.alias_table.keys():
953 if k in no_alias:
946 if k in no_alias:
954 del self.alias_table[k]
947 del self.alias_table[k]
955 if verbose:
948 if verbose:
956 print ("Deleting alias <%s>, it's a Python "
949 print ("Deleting alias <%s>, it's a Python "
957 "keyword or builtin." % k)
950 "keyword or builtin." % k)
958
951
959 def set_autoindent(self,value=None):
952 def set_autoindent(self,value=None):
960 """Set the autoindent flag, checking for readline support.
953 """Set the autoindent flag, checking for readline support.
961
954
962 If called with no arguments, it acts as a toggle."""
955 If called with no arguments, it acts as a toggle."""
963
956
964 if not self.has_readline:
957 if not self.has_readline:
965 if os.name == 'posix':
958 if os.name == 'posix':
966 warn("The auto-indent feature requires the readline library")
959 warn("The auto-indent feature requires the readline library")
967 self.autoindent = 0
960 self.autoindent = 0
968 return
961 return
969 if value is None:
962 if value is None:
970 self.autoindent = not self.autoindent
963 self.autoindent = not self.autoindent
971 else:
964 else:
972 self.autoindent = value
965 self.autoindent = value
973
966
974 def rc_set_toggle(self,rc_field,value=None):
967 def rc_set_toggle(self,rc_field,value=None):
975 """Set or toggle a field in IPython's rc config. structure.
968 """Set or toggle a field in IPython's rc config. structure.
976
969
977 If called with no arguments, it acts as a toggle.
970 If called with no arguments, it acts as a toggle.
978
971
979 If called with a non-existent field, the resulting AttributeError
972 If called with a non-existent field, the resulting AttributeError
980 exception will propagate out."""
973 exception will propagate out."""
981
974
982 rc_val = getattr(self.rc,rc_field)
975 rc_val = getattr(self.rc,rc_field)
983 if value is None:
976 if value is None:
984 value = not rc_val
977 value = not rc_val
985 setattr(self.rc,rc_field,value)
978 setattr(self.rc,rc_field,value)
986
979
987 def user_setup(self,ipythondir,rc_suffix,mode='install'):
980 def user_setup(self,ipythondir,rc_suffix,mode='install'):
988 """Install the user configuration directory.
981 """Install the user configuration directory.
989
982
990 Can be called when running for the first time or to upgrade the user's
983 Can be called when running for the first time or to upgrade the user's
991 .ipython/ directory with the mode parameter. Valid modes are 'install'
984 .ipython/ directory with the mode parameter. Valid modes are 'install'
992 and 'upgrade'."""
985 and 'upgrade'."""
993
986
994 def wait():
987 def wait():
995 try:
988 try:
996 raw_input("Please press <RETURN> to start IPython.")
989 raw_input("Please press <RETURN> to start IPython.")
997 except EOFError:
990 except EOFError:
998 print >> Term.cout
991 print >> Term.cout
999 print '*'*70
992 print '*'*70
1000
993
1001 cwd = os.getcwd() # remember where we started
994 cwd = os.getcwd() # remember where we started
1002 glb = glob.glob
995 glb = glob.glob
1003 print '*'*70
996 print '*'*70
1004 if mode == 'install':
997 if mode == 'install':
1005 print \
998 print \
1006 """Welcome to IPython. I will try to create a personal configuration directory
999 """Welcome to IPython. I will try to create a personal configuration directory
1007 where you can customize many aspects of IPython's functionality in:\n"""
1000 where you can customize many aspects of IPython's functionality in:\n"""
1008 else:
1001 else:
1009 print 'I am going to upgrade your configuration in:'
1002 print 'I am going to upgrade your configuration in:'
1010
1003
1011 print ipythondir
1004 print ipythondir
1012
1005
1013 rcdirend = os.path.join('IPython','UserConfig')
1006 rcdirend = os.path.join('IPython','UserConfig')
1014 cfg = lambda d: os.path.join(d,rcdirend)
1007 cfg = lambda d: os.path.join(d,rcdirend)
1015 try:
1008 try:
1016 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1009 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1017 except IOError:
1010 except IOError:
1018 warning = """
1011 warning = """
1019 Installation error. IPython's directory was not found.
1012 Installation error. IPython's directory was not found.
1020
1013
1021 Check the following:
1014 Check the following:
1022
1015
1023 The ipython/IPython directory should be in a directory belonging to your
1016 The ipython/IPython directory should be in a directory belonging to your
1024 PYTHONPATH environment variable (that is, it should be in a directory
1017 PYTHONPATH environment variable (that is, it should be in a directory
1025 belonging to sys.path). You can copy it explicitly there or just link to it.
1018 belonging to sys.path). You can copy it explicitly there or just link to it.
1026
1019
1027 IPython will proceed with builtin defaults.
1020 IPython will proceed with builtin defaults.
1028 """
1021 """
1029 warn(warning)
1022 warn(warning)
1030 wait()
1023 wait()
1031 return
1024 return
1032
1025
1033 if mode == 'install':
1026 if mode == 'install':
1034 try:
1027 try:
1035 shutil.copytree(rcdir,ipythondir)
1028 shutil.copytree(rcdir,ipythondir)
1036 os.chdir(ipythondir)
1029 os.chdir(ipythondir)
1037 rc_files = glb("ipythonrc*")
1030 rc_files = glb("ipythonrc*")
1038 for rc_file in rc_files:
1031 for rc_file in rc_files:
1039 os.rename(rc_file,rc_file+rc_suffix)
1032 os.rename(rc_file,rc_file+rc_suffix)
1040 except:
1033 except:
1041 warning = """
1034 warning = """
1042
1035
1043 There was a problem with the installation:
1036 There was a problem with the installation:
1044 %s
1037 %s
1045 Try to correct it or contact the developers if you think it's a bug.
1038 Try to correct it or contact the developers if you think it's a bug.
1046 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1039 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1047 warn(warning)
1040 warn(warning)
1048 wait()
1041 wait()
1049 return
1042 return
1050
1043
1051 elif mode == 'upgrade':
1044 elif mode == 'upgrade':
1052 try:
1045 try:
1053 os.chdir(ipythondir)
1046 os.chdir(ipythondir)
1054 except:
1047 except:
1055 print """
1048 print """
1056 Can not upgrade: changing to directory %s failed. Details:
1049 Can not upgrade: changing to directory %s failed. Details:
1057 %s
1050 %s
1058 """ % (ipythondir,sys.exc_info()[1])
1051 """ % (ipythondir,sys.exc_info()[1])
1059 wait()
1052 wait()
1060 return
1053 return
1061 else:
1054 else:
1062 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1055 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1063 for new_full_path in sources:
1056 for new_full_path in sources:
1064 new_filename = os.path.basename(new_full_path)
1057 new_filename = os.path.basename(new_full_path)
1065 if new_filename.startswith('ipythonrc'):
1058 if new_filename.startswith('ipythonrc'):
1066 new_filename = new_filename + rc_suffix
1059 new_filename = new_filename + rc_suffix
1067 # The config directory should only contain files, skip any
1060 # The config directory should only contain files, skip any
1068 # directories which may be there (like CVS)
1061 # directories which may be there (like CVS)
1069 if os.path.isdir(new_full_path):
1062 if os.path.isdir(new_full_path):
1070 continue
1063 continue
1071 if os.path.exists(new_filename):
1064 if os.path.exists(new_filename):
1072 old_file = new_filename+'.old'
1065 old_file = new_filename+'.old'
1073 if os.path.exists(old_file):
1066 if os.path.exists(old_file):
1074 os.remove(old_file)
1067 os.remove(old_file)
1075 os.rename(new_filename,old_file)
1068 os.rename(new_filename,old_file)
1076 shutil.copy(new_full_path,new_filename)
1069 shutil.copy(new_full_path,new_filename)
1077 else:
1070 else:
1078 raise ValueError,'unrecognized mode for install:',`mode`
1071 raise ValueError,'unrecognized mode for install:',`mode`
1079
1072
1080 # Fix line-endings to those native to each platform in the config
1073 # Fix line-endings to those native to each platform in the config
1081 # directory.
1074 # directory.
1082 try:
1075 try:
1083 os.chdir(ipythondir)
1076 os.chdir(ipythondir)
1084 except:
1077 except:
1085 print """
1078 print """
1086 Problem: changing to directory %s failed.
1079 Problem: changing to directory %s failed.
1087 Details:
1080 Details:
1088 %s
1081 %s
1089
1082
1090 Some configuration files may have incorrect line endings. This should not
1083 Some configuration files may have incorrect line endings. This should not
1091 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1084 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1092 wait()
1085 wait()
1093 else:
1086 else:
1094 for fname in glb('ipythonrc*'):
1087 for fname in glb('ipythonrc*'):
1095 try:
1088 try:
1096 native_line_ends(fname,backup=0)
1089 native_line_ends(fname,backup=0)
1097 except IOError:
1090 except IOError:
1098 pass
1091 pass
1099
1092
1100 if mode == 'install':
1093 if mode == 'install':
1101 print """
1094 print """
1102 Successful installation!
1095 Successful installation!
1103
1096
1104 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1097 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1105 IPython manual (there are both HTML and PDF versions supplied with the
1098 IPython manual (there are both HTML and PDF versions supplied with the
1106 distribution) to make sure that your system environment is properly configured
1099 distribution) to make sure that your system environment is properly configured
1107 to take advantage of IPython's features.
1100 to take advantage of IPython's features.
1108
1101
1109 Important note: the configuration system has changed! The old system is
1102 Important note: the configuration system has changed! The old system is
1110 still in place, but its setting may be partly overridden by the settings in
1103 still in place, but its setting may be partly overridden by the settings in
1111 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1104 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1112 if some of the new settings bother you.
1105 if some of the new settings bother you.
1113
1106
1114 """
1107 """
1115 else:
1108 else:
1116 print """
1109 print """
1117 Successful upgrade!
1110 Successful upgrade!
1118
1111
1119 All files in your directory:
1112 All files in your directory:
1120 %(ipythondir)s
1113 %(ipythondir)s
1121 which would have been overwritten by the upgrade were backed up with a .old
1114 which would have been overwritten by the upgrade were backed up with a .old
1122 extension. If you had made particular customizations in those files you may
1115 extension. If you had made particular customizations in those files you may
1123 want to merge them back into the new files.""" % locals()
1116 want to merge them back into the new files.""" % locals()
1124 wait()
1117 wait()
1125 os.chdir(cwd)
1118 os.chdir(cwd)
1126 # end user_setup()
1119 # end user_setup()
1127
1120
1128 def atexit_operations(self):
1121 def atexit_operations(self):
1129 """This will be executed at the time of exit.
1122 """This will be executed at the time of exit.
1130
1123
1131 Saving of persistent data should be performed here. """
1124 Saving of persistent data should be performed here. """
1132
1125
1133 #print '*** IPython exit cleanup ***' # dbg
1126 #print '*** IPython exit cleanup ***' # dbg
1134 # input history
1127 # input history
1135 self.savehist()
1128 self.savehist()
1136
1129
1137 # Cleanup all tempfiles left around
1130 # Cleanup all tempfiles left around
1138 for tfile in self.tempfiles:
1131 for tfile in self.tempfiles:
1139 try:
1132 try:
1140 os.unlink(tfile)
1133 os.unlink(tfile)
1141 except OSError:
1134 except OSError:
1142 pass
1135 pass
1143
1136
1144 # save the "persistent data" catch-all dictionary
1137 # save the "persistent data" catch-all dictionary
1145 self.hooks.shutdown_hook()
1138 self.hooks.shutdown_hook()
1146
1139
1147 def savehist(self):
1140 def savehist(self):
1148 """Save input history to a file (via readline library)."""
1141 """Save input history to a file (via readline library)."""
1149 try:
1142 try:
1150 self.readline.write_history_file(self.histfile)
1143 self.readline.write_history_file(self.histfile)
1151 except:
1144 except:
1152 print 'Unable to save IPython command history to file: ' + \
1145 print 'Unable to save IPython command history to file: ' + \
1153 `self.histfile`
1146 `self.histfile`
1154
1147
1155 def pre_readline(self):
1148 def pre_readline(self):
1156 """readline hook to be used at the start of each line.
1149 """readline hook to be used at the start of each line.
1157
1150
1158 Currently it handles auto-indent only."""
1151 Currently it handles auto-indent only."""
1159
1152
1160 #debugx('self.indent_current_nsp','pre_readline:')
1153 #debugx('self.indent_current_nsp','pre_readline:')
1161 self.readline.insert_text(self.indent_current_str())
1154 self.readline.insert_text(self.indent_current_str())
1162
1155
1163 def init_readline(self):
1156 def init_readline(self):
1164 """Command history completion/saving/reloading."""
1157 """Command history completion/saving/reloading."""
1165
1158
1166 import IPython.rlineimpl as readline
1159 import IPython.rlineimpl as readline
1167 if not readline.have_readline:
1160 if not readline.have_readline:
1168 self.has_readline = 0
1161 self.has_readline = 0
1169 self.readline = None
1162 self.readline = None
1170 # no point in bugging windows users with this every time:
1163 # no point in bugging windows users with this every time:
1171 warn('Readline services not available on this platform.')
1164 warn('Readline services not available on this platform.')
1172 else:
1165 else:
1173 sys.modules['readline'] = readline
1166 sys.modules['readline'] = readline
1174 import atexit
1167 import atexit
1175 from IPython.completer import IPCompleter
1168 from IPython.completer import IPCompleter
1176 self.Completer = IPCompleter(self,
1169 self.Completer = IPCompleter(self,
1177 self.user_ns,
1170 self.user_ns,
1178 self.user_global_ns,
1171 self.user_global_ns,
1179 self.rc.readline_omit__names,
1172 self.rc.readline_omit__names,
1180 self.alias_table)
1173 self.alias_table)
1181
1174
1182 # Platform-specific configuration
1175 # Platform-specific configuration
1183 if os.name == 'nt':
1176 if os.name == 'nt':
1184 self.readline_startup_hook = readline.set_pre_input_hook
1177 self.readline_startup_hook = readline.set_pre_input_hook
1185 else:
1178 else:
1186 self.readline_startup_hook = readline.set_startup_hook
1179 self.readline_startup_hook = readline.set_startup_hook
1187
1180
1188 # Load user's initrc file (readline config)
1181 # Load user's initrc file (readline config)
1189 inputrc_name = os.environ.get('INPUTRC')
1182 inputrc_name = os.environ.get('INPUTRC')
1190 if inputrc_name is None:
1183 if inputrc_name is None:
1191 home_dir = get_home_dir()
1184 home_dir = get_home_dir()
1192 if home_dir is not None:
1185 if home_dir is not None:
1193 inputrc_name = os.path.join(home_dir,'.inputrc')
1186 inputrc_name = os.path.join(home_dir,'.inputrc')
1194 if os.path.isfile(inputrc_name):
1187 if os.path.isfile(inputrc_name):
1195 try:
1188 try:
1196 readline.read_init_file(inputrc_name)
1189 readline.read_init_file(inputrc_name)
1197 except:
1190 except:
1198 warn('Problems reading readline initialization file <%s>'
1191 warn('Problems reading readline initialization file <%s>'
1199 % inputrc_name)
1192 % inputrc_name)
1200
1193
1201 self.has_readline = 1
1194 self.has_readline = 1
1202 self.readline = readline
1195 self.readline = readline
1203 # save this in sys so embedded copies can restore it properly
1196 # save this in sys so embedded copies can restore it properly
1204 sys.ipcompleter = self.Completer.complete
1197 sys.ipcompleter = self.Completer.complete
1205 readline.set_completer(self.Completer.complete)
1198 readline.set_completer(self.Completer.complete)
1206
1199
1207 # Configure readline according to user's prefs
1200 # Configure readline according to user's prefs
1208 for rlcommand in self.rc.readline_parse_and_bind:
1201 for rlcommand in self.rc.readline_parse_and_bind:
1209 readline.parse_and_bind(rlcommand)
1202 readline.parse_and_bind(rlcommand)
1210
1203
1211 # remove some chars from the delimiters list
1204 # remove some chars from the delimiters list
1212 delims = readline.get_completer_delims()
1205 delims = readline.get_completer_delims()
1213 delims = delims.translate(string._idmap,
1206 delims = delims.translate(string._idmap,
1214 self.rc.readline_remove_delims)
1207 self.rc.readline_remove_delims)
1215 readline.set_completer_delims(delims)
1208 readline.set_completer_delims(delims)
1216 # otherwise we end up with a monster history after a while:
1209 # otherwise we end up with a monster history after a while:
1217 readline.set_history_length(1000)
1210 readline.set_history_length(1000)
1218 try:
1211 try:
1219 #print '*** Reading readline history' # dbg
1212 #print '*** Reading readline history' # dbg
1220 readline.read_history_file(self.histfile)
1213 readline.read_history_file(self.histfile)
1221 except IOError:
1214 except IOError:
1222 pass # It doesn't exist yet.
1215 pass # It doesn't exist yet.
1223
1216
1224 atexit.register(self.atexit_operations)
1217 atexit.register(self.atexit_operations)
1225 del atexit
1218 del atexit
1226
1219
1227 # Configure auto-indent for all platforms
1220 # Configure auto-indent for all platforms
1228 self.set_autoindent(self.rc.autoindent)
1221 self.set_autoindent(self.rc.autoindent)
1229
1222
1230 def _should_recompile(self,e):
1223 def _should_recompile(self,e):
1231 """Utility routine for edit_syntax_error"""
1224 """Utility routine for edit_syntax_error"""
1232
1225
1233 if e.filename in ('<ipython console>','<input>','<string>',
1226 if e.filename in ('<ipython console>','<input>','<string>',
1234 '<console>',None):
1227 '<console>','<BackgroundJob compilation>',
1228 None):
1235
1229
1236 return False
1230 return False
1237 try:
1231 try:
1238 if (self.rc.autoedit_syntax and
1232 if (self.rc.autoedit_syntax and
1239 not ask_yes_no('Return to editor to correct syntax error? '
1233 not ask_yes_no('Return to editor to correct syntax error? '
1240 '[Y/n] ','y')):
1234 '[Y/n] ','y')):
1241 return False
1235 return False
1242 except EOFError:
1236 except EOFError:
1243 return False
1237 return False
1244
1238
1245 def int0(x):
1239 def int0(x):
1246 try:
1240 try:
1247 return int(x)
1241 return int(x)
1248 except TypeError:
1242 except TypeError:
1249 return 0
1243 return 0
1250 # always pass integer line and offset values to editor hook
1244 # always pass integer line and offset values to editor hook
1251 self.hooks.fix_error_editor(e.filename,
1245 self.hooks.fix_error_editor(e.filename,
1252 int0(e.lineno),int0(e.offset),e.msg)
1246 int0(e.lineno),int0(e.offset),e.msg)
1253 return True
1247 return True
1254
1248
1255 def edit_syntax_error(self):
1249 def edit_syntax_error(self):
1256 """The bottom half of the syntax error handler called in the main loop.
1250 """The bottom half of the syntax error handler called in the main loop.
1257
1251
1258 Loop until syntax error is fixed or user cancels.
1252 Loop until syntax error is fixed or user cancels.
1259 """
1253 """
1260
1254
1261 while self.SyntaxTB.last_syntax_error:
1255 while self.SyntaxTB.last_syntax_error:
1262 # copy and clear last_syntax_error
1256 # copy and clear last_syntax_error
1263 err = self.SyntaxTB.clear_err_state()
1257 err = self.SyntaxTB.clear_err_state()
1264 if not self._should_recompile(err):
1258 if not self._should_recompile(err):
1265 return
1259 return
1266 try:
1260 try:
1267 # may set last_syntax_error again if a SyntaxError is raised
1261 # may set last_syntax_error again if a SyntaxError is raised
1268 self.safe_execfile(err.filename,self.shell.user_ns)
1262 self.safe_execfile(err.filename,self.shell.user_ns)
1269 except:
1263 except:
1270 self.showtraceback()
1264 self.showtraceback()
1271 else:
1265 else:
1272 f = file(err.filename)
1273 try:
1266 try:
1274 sys.displayhook(f.read())
1267 f = file(err.filename)
1275 finally:
1268 try:
1276 f.close()
1269 sys.displayhook(f.read())
1270 finally:
1271 f.close()
1272 except:
1273 self.showtraceback()
1277
1274
1278 def showsyntaxerror(self, filename=None):
1275 def showsyntaxerror(self, filename=None):
1279 """Display the syntax error that just occurred.
1276 """Display the syntax error that just occurred.
1280
1277
1281 This doesn't display a stack trace because there isn't one.
1278 This doesn't display a stack trace because there isn't one.
1282
1279
1283 If a filename is given, it is stuffed in the exception instead
1280 If a filename is given, it is stuffed in the exception instead
1284 of what was there before (because Python's parser always uses
1281 of what was there before (because Python's parser always uses
1285 "<string>" when reading from a string).
1282 "<string>" when reading from a string).
1286 """
1283 """
1287 etype, value, last_traceback = sys.exc_info()
1284 etype, value, last_traceback = sys.exc_info()
1288
1285
1289 # See note about these variables in showtraceback() below
1286 # See note about these variables in showtraceback() below
1290 sys.last_type = etype
1287 sys.last_type = etype
1291 sys.last_value = value
1288 sys.last_value = value
1292 sys.last_traceback = last_traceback
1289 sys.last_traceback = last_traceback
1293
1290
1294 if filename and etype is SyntaxError:
1291 if filename and etype is SyntaxError:
1295 # Work hard to stuff the correct filename in the exception
1292 # Work hard to stuff the correct filename in the exception
1296 try:
1293 try:
1297 msg, (dummy_filename, lineno, offset, line) = value
1294 msg, (dummy_filename, lineno, offset, line) = value
1298 except:
1295 except:
1299 # Not the format we expect; leave it alone
1296 # Not the format we expect; leave it alone
1300 pass
1297 pass
1301 else:
1298 else:
1302 # Stuff in the right filename
1299 # Stuff in the right filename
1303 try:
1300 try:
1304 # Assume SyntaxError is a class exception
1301 # Assume SyntaxError is a class exception
1305 value = SyntaxError(msg, (filename, lineno, offset, line))
1302 value = SyntaxError(msg, (filename, lineno, offset, line))
1306 except:
1303 except:
1307 # If that failed, assume SyntaxError is a string
1304 # If that failed, assume SyntaxError is a string
1308 value = msg, (filename, lineno, offset, line)
1305 value = msg, (filename, lineno, offset, line)
1309 self.SyntaxTB(etype,value,[])
1306 self.SyntaxTB(etype,value,[])
1310
1307
1311 def debugger(self):
1308 def debugger(self):
1312 """Call the pdb debugger."""
1309 """Call the pdb debugger."""
1313
1310
1314 if not self.rc.pdb:
1311 if not self.rc.pdb:
1315 return
1312 return
1316 pdb.pm()
1313 pdb.pm()
1317
1314
1318 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1315 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1319 """Display the exception that just occurred."""
1316 """Display the exception that just occurred.
1317
1318 If nothing is known about the exception, this is the method which
1319 should be used throughout the code for presenting user tracebacks,
1320 rather htan directly invoking the InteractiveTB object.
1321
1322 A specific showsyntaxerror() also exists, but this method can take
1323 care of calling it if needed, so unless you are explicitly catching a
1324 SyntaxError exception, don't try to analyze the stack manually and
1325 simply call this method."""
1320
1326
1321 # Though this won't be called by syntax errors in the input line,
1327 # Though this won't be called by syntax errors in the input line,
1322 # there may be SyntaxError cases whith imported code.
1328 # there may be SyntaxError cases whith imported code.
1323 if exc_tuple is None:
1329 if exc_tuple is None:
1324 etype, value, tb = sys.exc_info()
1330 etype, value, tb = sys.exc_info()
1325 else:
1331 else:
1326 etype, value, tb = exc_tuple
1332 etype, value, tb = exc_tuple
1327 if etype is SyntaxError:
1333 if etype is SyntaxError:
1328 self.showsyntaxerror(filename)
1334 self.showsyntaxerror(filename)
1329 else:
1335 else:
1330 # WARNING: these variables are somewhat deprecated and not
1336 # WARNING: these variables are somewhat deprecated and not
1331 # necessarily safe to use in a threaded environment, but tools
1337 # necessarily safe to use in a threaded environment, but tools
1332 # like pdb depend on their existence, so let's set them. If we
1338 # like pdb depend on their existence, so let's set them. If we
1333 # find problems in the field, we'll need to revisit their use.
1339 # find problems in the field, we'll need to revisit their use.
1334 sys.last_type = etype
1340 sys.last_type = etype
1335 sys.last_value = value
1341 sys.last_value = value
1336 sys.last_traceback = tb
1342 sys.last_traceback = tb
1337
1343
1338 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1344 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1339 if self.InteractiveTB.call_pdb and self.has_readline:
1345 if self.InteractiveTB.call_pdb and self.has_readline:
1340 # pdb mucks up readline, fix it back
1346 # pdb mucks up readline, fix it back
1341 self.readline.set_completer(self.Completer.complete)
1347 self.readline.set_completer(self.Completer.complete)
1342
1348
1343 def mainloop(self,banner=None):
1349 def mainloop(self,banner=None):
1344 """Creates the local namespace and starts the mainloop.
1350 """Creates the local namespace and starts the mainloop.
1345
1351
1346 If an optional banner argument is given, it will override the
1352 If an optional banner argument is given, it will override the
1347 internally created default banner."""
1353 internally created default banner."""
1348
1354
1349 if self.rc.c: # Emulate Python's -c option
1355 if self.rc.c: # Emulate Python's -c option
1350 self.exec_init_cmd()
1356 self.exec_init_cmd()
1351 if banner is None:
1357 if banner is None:
1352 if not self.rc.banner:
1358 if not self.rc.banner:
1353 banner = ''
1359 banner = ''
1354 # banner is string? Use it directly!
1360 # banner is string? Use it directly!
1355 elif isinstance(self.rc.banner,basestring):
1361 elif isinstance(self.rc.banner,basestring):
1356 banner = self.rc.banner
1362 banner = self.rc.banner
1357 else:
1363 else:
1358 banner = self.BANNER+self.banner2
1364 banner = self.BANNER+self.banner2
1359
1365
1360 self.interact(banner)
1366 self.interact(banner)
1361
1367
1362 def exec_init_cmd(self):
1368 def exec_init_cmd(self):
1363 """Execute a command given at the command line.
1369 """Execute a command given at the command line.
1364
1370
1365 This emulates Python's -c option."""
1371 This emulates Python's -c option."""
1366
1372
1367 #sys.argv = ['-c']
1373 #sys.argv = ['-c']
1368 self.push(self.rc.c)
1374 self.push(self.rc.c)
1369
1375
1370 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1376 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1371 """Embeds IPython into a running python program.
1377 """Embeds IPython into a running python program.
1372
1378
1373 Input:
1379 Input:
1374
1380
1375 - header: An optional header message can be specified.
1381 - header: An optional header message can be specified.
1376
1382
1377 - local_ns, global_ns: working namespaces. If given as None, the
1383 - local_ns, global_ns: working namespaces. If given as None, the
1378 IPython-initialized one is updated with __main__.__dict__, so that
1384 IPython-initialized one is updated with __main__.__dict__, so that
1379 program variables become visible but user-specific configuration
1385 program variables become visible but user-specific configuration
1380 remains possible.
1386 remains possible.
1381
1387
1382 - stack_depth: specifies how many levels in the stack to go to
1388 - stack_depth: specifies how many levels in the stack to go to
1383 looking for namespaces (when local_ns and global_ns are None). This
1389 looking for namespaces (when local_ns and global_ns are None). This
1384 allows an intermediate caller to make sure that this function gets
1390 allows an intermediate caller to make sure that this function gets
1385 the namespace from the intended level in the stack. By default (0)
1391 the namespace from the intended level in the stack. By default (0)
1386 it will get its locals and globals from the immediate caller.
1392 it will get its locals and globals from the immediate caller.
1387
1393
1388 Warning: it's possible to use this in a program which is being run by
1394 Warning: it's possible to use this in a program which is being run by
1389 IPython itself (via %run), but some funny things will happen (a few
1395 IPython itself (via %run), but some funny things will happen (a few
1390 globals get overwritten). In the future this will be cleaned up, as
1396 globals get overwritten). In the future this will be cleaned up, as
1391 there is no fundamental reason why it can't work perfectly."""
1397 there is no fundamental reason why it can't work perfectly."""
1392
1398
1393 # Get locals and globals from caller
1399 # Get locals and globals from caller
1394 if local_ns is None or global_ns is None:
1400 if local_ns is None or global_ns is None:
1395 call_frame = sys._getframe(stack_depth).f_back
1401 call_frame = sys._getframe(stack_depth).f_back
1396
1402
1397 if local_ns is None:
1403 if local_ns is None:
1398 local_ns = call_frame.f_locals
1404 local_ns = call_frame.f_locals
1399 if global_ns is None:
1405 if global_ns is None:
1400 global_ns = call_frame.f_globals
1406 global_ns = call_frame.f_globals
1401
1407
1402 # Update namespaces and fire up interpreter
1408 # Update namespaces and fire up interpreter
1403
1409
1404 # The global one is easy, we can just throw it in
1410 # The global one is easy, we can just throw it in
1405 self.user_global_ns = global_ns
1411 self.user_global_ns = global_ns
1406
1412
1407 # but the user/local one is tricky: ipython needs it to store internal
1413 # but the user/local one is tricky: ipython needs it to store internal
1408 # data, but we also need the locals. We'll copy locals in the user
1414 # data, but we also need the locals. We'll copy locals in the user
1409 # one, but will track what got copied so we can delete them at exit.
1415 # one, but will track what got copied so we can delete them at exit.
1410 # This is so that a later embedded call doesn't see locals from a
1416 # This is so that a later embedded call doesn't see locals from a
1411 # previous call (which most likely existed in a separate scope).
1417 # previous call (which most likely existed in a separate scope).
1412 local_varnames = local_ns.keys()
1418 local_varnames = local_ns.keys()
1413 self.user_ns.update(local_ns)
1419 self.user_ns.update(local_ns)
1414
1420
1415 # Patch for global embedding to make sure that things don't overwrite
1421 # Patch for global embedding to make sure that things don't overwrite
1416 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1422 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1417 # FIXME. Test this a bit more carefully (the if.. is new)
1423 # FIXME. Test this a bit more carefully (the if.. is new)
1418 if local_ns is None and global_ns is None:
1424 if local_ns is None and global_ns is None:
1419 self.user_global_ns.update(__main__.__dict__)
1425 self.user_global_ns.update(__main__.__dict__)
1420
1426
1421 # make sure the tab-completer has the correct frame information, so it
1427 # make sure the tab-completer has the correct frame information, so it
1422 # actually completes using the frame's locals/globals
1428 # actually completes using the frame's locals/globals
1423 self.set_completer_frame()
1429 self.set_completer_frame()
1424
1430
1425 # before activating the interactive mode, we need to make sure that
1431 # before activating the interactive mode, we need to make sure that
1426 # all names in the builtin namespace needed by ipython point to
1432 # all names in the builtin namespace needed by ipython point to
1427 # ourselves, and not to other instances.
1433 # ourselves, and not to other instances.
1428 self.add_builtins()
1434 self.add_builtins()
1429
1435
1430 self.interact(header)
1436 self.interact(header)
1431
1437
1432 # now, purge out the user namespace from anything we might have added
1438 # now, purge out the user namespace from anything we might have added
1433 # from the caller's local namespace
1439 # from the caller's local namespace
1434 delvar = self.user_ns.pop
1440 delvar = self.user_ns.pop
1435 for var in local_varnames:
1441 for var in local_varnames:
1436 delvar(var,None)
1442 delvar(var,None)
1437 # and clean builtins we may have overridden
1443 # and clean builtins we may have overridden
1438 self.clean_builtins()
1444 self.clean_builtins()
1439
1445
1440 def interact(self, banner=None):
1446 def interact(self, banner=None):
1441 """Closely emulate the interactive Python console.
1447 """Closely emulate the interactive Python console.
1442
1448
1443 The optional banner argument specify the banner to print
1449 The optional banner argument specify the banner to print
1444 before the first interaction; by default it prints a banner
1450 before the first interaction; by default it prints a banner
1445 similar to the one printed by the real Python interpreter,
1451 similar to the one printed by the real Python interpreter,
1446 followed by the current class name in parentheses (so as not
1452 followed by the current class name in parentheses (so as not
1447 to confuse this with the real interpreter -- since it's so
1453 to confuse this with the real interpreter -- since it's so
1448 close!).
1454 close!).
1449
1455
1450 """
1456 """
1451 cprt = 'Type "copyright", "credits" or "license" for more information.'
1457 cprt = 'Type "copyright", "credits" or "license" for more information.'
1452 if banner is None:
1458 if banner is None:
1453 self.write("Python %s on %s\n%s\n(%s)\n" %
1459 self.write("Python %s on %s\n%s\n(%s)\n" %
1454 (sys.version, sys.platform, cprt,
1460 (sys.version, sys.platform, cprt,
1455 self.__class__.__name__))
1461 self.__class__.__name__))
1456 else:
1462 else:
1457 self.write(banner)
1463 self.write(banner)
1458
1464
1459 more = 0
1465 more = 0
1460
1466
1461 # Mark activity in the builtins
1467 # Mark activity in the builtins
1462 __builtin__.__dict__['__IPYTHON__active'] += 1
1468 __builtin__.__dict__['__IPYTHON__active'] += 1
1463
1469
1464 # exit_now is set by a call to %Exit or %Quit
1470 # exit_now is set by a call to %Exit or %Quit
1465 self.exit_now = False
1471 self.exit_now = False
1466 while not self.exit_now:
1472 while not self.exit_now:
1467 if more:
1473 if more:
1468 prompt = self.outputcache.prompt2
1474 prompt = self.outputcache.prompt2
1469 if self.autoindent:
1475 if self.autoindent:
1470 self.readline_startup_hook(self.pre_readline)
1476 self.readline_startup_hook(self.pre_readline)
1471 else:
1477 else:
1472 prompt = self.outputcache.prompt1
1478 prompt = self.outputcache.prompt1
1473 try:
1479 try:
1474 line = self.raw_input(prompt,more)
1480 line = self.raw_input(prompt,more)
1475 if self.autoindent:
1481 if self.autoindent:
1476 self.readline_startup_hook(None)
1482 self.readline_startup_hook(None)
1477 except KeyboardInterrupt:
1483 except KeyboardInterrupt:
1478 self.write('\nKeyboardInterrupt\n')
1484 self.write('\nKeyboardInterrupt\n')
1479 self.resetbuffer()
1485 self.resetbuffer()
1480 # keep cache in sync with the prompt counter:
1486 # keep cache in sync with the prompt counter:
1481 self.outputcache.prompt_count -= 1
1487 self.outputcache.prompt_count -= 1
1482
1488
1483 if self.autoindent:
1489 if self.autoindent:
1484 self.indent_current_nsp = 0
1490 self.indent_current_nsp = 0
1485 more = 0
1491 more = 0
1486 except EOFError:
1492 except EOFError:
1487 if self.autoindent:
1493 if self.autoindent:
1488 self.readline_startup_hook(None)
1494 self.readline_startup_hook(None)
1489 self.write('\n')
1495 self.write('\n')
1490 self.exit()
1496 self.exit()
1491 except bdb.BdbQuit:
1497 except bdb.BdbQuit:
1492 warn('The Python debugger has exited with a BdbQuit exception.\n'
1498 warn('The Python debugger has exited with a BdbQuit exception.\n'
1493 'Because of how pdb handles the stack, it is impossible\n'
1499 'Because of how pdb handles the stack, it is impossible\n'
1494 'for IPython to properly format this particular exception.\n'
1500 'for IPython to properly format this particular exception.\n'
1495 'IPython will resume normal operation.')
1501 'IPython will resume normal operation.')
1496 except:
1502 except:
1497 # exceptions here are VERY RARE, but they can be triggered
1503 # exceptions here are VERY RARE, but they can be triggered
1498 # asynchronously by signal handlers, for example.
1504 # asynchronously by signal handlers, for example.
1499 self.showtraceback()
1505 self.showtraceback()
1500 else:
1506 else:
1501 more = self.push(line)
1507 more = self.push(line)
1502 if (self.SyntaxTB.last_syntax_error and
1508 if (self.SyntaxTB.last_syntax_error and
1503 self.rc.autoedit_syntax):
1509 self.rc.autoedit_syntax):
1504 self.edit_syntax_error()
1510 self.edit_syntax_error()
1505
1511
1506 # We are off again...
1512 # We are off again...
1507 __builtin__.__dict__['__IPYTHON__active'] -= 1
1513 __builtin__.__dict__['__IPYTHON__active'] -= 1
1508
1514
1509 def excepthook(self, etype, value, tb):
1515 def excepthook(self, etype, value, tb):
1510 """One more defense for GUI apps that call sys.excepthook.
1516 """One more defense for GUI apps that call sys.excepthook.
1511
1517
1512 GUI frameworks like wxPython trap exceptions and call
1518 GUI frameworks like wxPython trap exceptions and call
1513 sys.excepthook themselves. I guess this is a feature that
1519 sys.excepthook themselves. I guess this is a feature that
1514 enables them to keep running after exceptions that would
1520 enables them to keep running after exceptions that would
1515 otherwise kill their mainloop. This is a bother for IPython
1521 otherwise kill their mainloop. This is a bother for IPython
1516 which excepts to catch all of the program exceptions with a try:
1522 which excepts to catch all of the program exceptions with a try:
1517 except: statement.
1523 except: statement.
1518
1524
1519 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1525 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1520 any app directly invokes sys.excepthook, it will look to the user like
1526 any app directly invokes sys.excepthook, it will look to the user like
1521 IPython crashed. In order to work around this, we can disable the
1527 IPython crashed. In order to work around this, we can disable the
1522 CrashHandler and replace it with this excepthook instead, which prints a
1528 CrashHandler and replace it with this excepthook instead, which prints a
1523 regular traceback using our InteractiveTB. In this fashion, apps which
1529 regular traceback using our InteractiveTB. In this fashion, apps which
1524 call sys.excepthook will generate a regular-looking exception from
1530 call sys.excepthook will generate a regular-looking exception from
1525 IPython, and the CrashHandler will only be triggered by real IPython
1531 IPython, and the CrashHandler will only be triggered by real IPython
1526 crashes.
1532 crashes.
1527
1533
1528 This hook should be used sparingly, only in places which are not likely
1534 This hook should be used sparingly, only in places which are not likely
1529 to be true IPython errors.
1535 to be true IPython errors.
1530 """
1536 """
1531 self.showtraceback((etype,value,tb),tb_offset=0)
1537 self.showtraceback((etype,value,tb),tb_offset=0)
1532
1538
1533 def transform_alias(self, alias,rest=''):
1539 def transform_alias(self, alias,rest=''):
1534 """ Transform alias to system command string
1540 """ Transform alias to system command string
1535
1541
1536 """
1542 """
1537 nargs,cmd = self.alias_table[alias]
1543 nargs,cmd = self.alias_table[alias]
1538 if ' ' in cmd and os.path.isfile(cmd):
1544 if ' ' in cmd and os.path.isfile(cmd):
1539 cmd = '"%s"' % cmd
1545 cmd = '"%s"' % cmd
1540
1546
1541 # Expand the %l special to be the user's input line
1547 # Expand the %l special to be the user's input line
1542 if cmd.find('%l') >= 0:
1548 if cmd.find('%l') >= 0:
1543 cmd = cmd.replace('%l',rest)
1549 cmd = cmd.replace('%l',rest)
1544 rest = ''
1550 rest = ''
1545 if nargs==0:
1551 if nargs==0:
1546 # Simple, argument-less aliases
1552 # Simple, argument-less aliases
1547 cmd = '%s %s' % (cmd,rest)
1553 cmd = '%s %s' % (cmd,rest)
1548 else:
1554 else:
1549 # Handle aliases with positional arguments
1555 # Handle aliases with positional arguments
1550 args = rest.split(None,nargs)
1556 args = rest.split(None,nargs)
1551 if len(args)< nargs:
1557 if len(args)< nargs:
1552 error('Alias <%s> requires %s arguments, %s given.' %
1558 error('Alias <%s> requires %s arguments, %s given.' %
1553 (alias,nargs,len(args)))
1559 (alias,nargs,len(args)))
1554 return None
1560 return None
1555 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1561 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1556 # Now call the macro, evaluating in the user's namespace
1562 # Now call the macro, evaluating in the user's namespace
1557
1563
1558 return cmd
1564 return cmd
1559
1565
1560 def call_alias(self,alias,rest=''):
1566 def call_alias(self,alias,rest=''):
1561 """Call an alias given its name and the rest of the line.
1567 """Call an alias given its name and the rest of the line.
1562
1568
1563 This is only used to provide backwards compatibility for users of
1569 This is only used to provide backwards compatibility for users of
1564 ipalias(), use of which is not recommended for anymore."""
1570 ipalias(), use of which is not recommended for anymore."""
1565
1571
1566 # Now call the macro, evaluating in the user's namespace
1572 # Now call the macro, evaluating in the user's namespace
1567 cmd = self.transform_alias(alias, rest)
1573 cmd = self.transform_alias(alias, rest)
1568 try:
1574 try:
1569 self.system(cmd)
1575 self.system(cmd)
1570 except:
1576 except:
1571 self.showtraceback()
1577 self.showtraceback()
1572
1578
1573 def indent_current_str(self):
1579 def indent_current_str(self):
1574 """return the current level of indentation as a string"""
1580 """return the current level of indentation as a string"""
1575 return self.indent_current_nsp * ' '
1581 return self.indent_current_nsp * ' '
1576
1582
1577 def autoindent_update(self,line):
1583 def autoindent_update(self,line):
1578 """Keep track of the indent level."""
1584 """Keep track of the indent level."""
1579
1585
1580 #debugx('line')
1586 #debugx('line')
1581 #debugx('self.indent_current_nsp')
1587 #debugx('self.indent_current_nsp')
1582 if self.autoindent:
1588 if self.autoindent:
1583 if line:
1589 if line:
1584 inisp = num_ini_spaces(line)
1590 inisp = num_ini_spaces(line)
1585 if inisp < self.indent_current_nsp:
1591 if inisp < self.indent_current_nsp:
1586 self.indent_current_nsp = inisp
1592 self.indent_current_nsp = inisp
1587
1593
1588 if line[-1] == ':':
1594 if line[-1] == ':':
1589 self.indent_current_nsp += 4
1595 self.indent_current_nsp += 4
1590 elif dedent_re.match(line):
1596 elif dedent_re.match(line):
1591 self.indent_current_nsp -= 4
1597 self.indent_current_nsp -= 4
1592 else:
1598 else:
1593 self.indent_current_nsp = 0
1599 self.indent_current_nsp = 0
1594
1600
1595 def runlines(self,lines):
1601 def runlines(self,lines):
1596 """Run a string of one or more lines of source.
1602 """Run a string of one or more lines of source.
1597
1603
1598 This method is capable of running a string containing multiple source
1604 This method is capable of running a string containing multiple source
1599 lines, as if they had been entered at the IPython prompt. Since it
1605 lines, as if they had been entered at the IPython prompt. Since it
1600 exposes IPython's processing machinery, the given strings can contain
1606 exposes IPython's processing machinery, the given strings can contain
1601 magic calls (%magic), special shell access (!cmd), etc."""
1607 magic calls (%magic), special shell access (!cmd), etc."""
1602
1608
1603 # We must start with a clean buffer, in case this is run from an
1609 # We must start with a clean buffer, in case this is run from an
1604 # interactive IPython session (via a magic, for example).
1610 # interactive IPython session (via a magic, for example).
1605 self.resetbuffer()
1611 self.resetbuffer()
1606 lines = lines.split('\n')
1612 lines = lines.split('\n')
1607 more = 0
1613 more = 0
1608 for line in lines:
1614 for line in lines:
1609 # skip blank lines so we don't mess up the prompt counter, but do
1615 # skip blank lines so we don't mess up the prompt counter, but do
1610 # NOT skip even a blank line if we are in a code block (more is
1616 # NOT skip even a blank line if we are in a code block (more is
1611 # true)
1617 # true)
1612 if line or more:
1618 if line or more:
1613 more = self.push(self.prefilter(line,more))
1619 more = self.push(self.prefilter(line,more))
1614 # IPython's runsource returns None if there was an error
1620 # IPython's runsource returns None if there was an error
1615 # compiling the code. This allows us to stop processing right
1621 # compiling the code. This allows us to stop processing right
1616 # away, so the user gets the error message at the right place.
1622 # away, so the user gets the error message at the right place.
1617 if more is None:
1623 if more is None:
1618 break
1624 break
1619 # final newline in case the input didn't have it, so that the code
1625 # final newline in case the input didn't have it, so that the code
1620 # actually does get executed
1626 # actually does get executed
1621 if more:
1627 if more:
1622 self.push('\n')
1628 self.push('\n')
1623
1629
1624 def runsource(self, source, filename='<input>', symbol='single'):
1630 def runsource(self, source, filename='<input>', symbol='single'):
1625 """Compile and run some source in the interpreter.
1631 """Compile and run some source in the interpreter.
1626
1632
1627 Arguments are as for compile_command().
1633 Arguments are as for compile_command().
1628
1634
1629 One several things can happen:
1635 One several things can happen:
1630
1636
1631 1) The input is incorrect; compile_command() raised an
1637 1) The input is incorrect; compile_command() raised an
1632 exception (SyntaxError or OverflowError). A syntax traceback
1638 exception (SyntaxError or OverflowError). A syntax traceback
1633 will be printed by calling the showsyntaxerror() method.
1639 will be printed by calling the showsyntaxerror() method.
1634
1640
1635 2) The input is incomplete, and more input is required;
1641 2) The input is incomplete, and more input is required;
1636 compile_command() returned None. Nothing happens.
1642 compile_command() returned None. Nothing happens.
1637
1643
1638 3) The input is complete; compile_command() returned a code
1644 3) The input is complete; compile_command() returned a code
1639 object. The code is executed by calling self.runcode() (which
1645 object. The code is executed by calling self.runcode() (which
1640 also handles run-time exceptions, except for SystemExit).
1646 also handles run-time exceptions, except for SystemExit).
1641
1647
1642 The return value is:
1648 The return value is:
1643
1649
1644 - True in case 2
1650 - True in case 2
1645
1651
1646 - False in the other cases, unless an exception is raised, where
1652 - False in the other cases, unless an exception is raised, where
1647 None is returned instead. This can be used by external callers to
1653 None is returned instead. This can be used by external callers to
1648 know whether to continue feeding input or not.
1654 know whether to continue feeding input or not.
1649
1655
1650 The return value can be used to decide whether to use sys.ps1 or
1656 The return value can be used to decide whether to use sys.ps1 or
1651 sys.ps2 to prompt the next line."""
1657 sys.ps2 to prompt the next line."""
1652
1658
1653 try:
1659 try:
1654 code = self.compile(source,filename,symbol)
1660 code = self.compile(source,filename,symbol)
1655 except (OverflowError, SyntaxError, ValueError):
1661 except (OverflowError, SyntaxError, ValueError):
1656 # Case 1
1662 # Case 1
1657 self.showsyntaxerror(filename)
1663 self.showsyntaxerror(filename)
1658 return None
1664 return None
1659
1665
1660 if code is None:
1666 if code is None:
1661 # Case 2
1667 # Case 2
1662 return True
1668 return True
1663
1669
1664 # Case 3
1670 # Case 3
1665 # We store the code object so that threaded shells and
1671 # We store the code object so that threaded shells and
1666 # custom exception handlers can access all this info if needed.
1672 # custom exception handlers can access all this info if needed.
1667 # The source corresponding to this can be obtained from the
1673 # The source corresponding to this can be obtained from the
1668 # buffer attribute as '\n'.join(self.buffer).
1674 # buffer attribute as '\n'.join(self.buffer).
1669 self.code_to_run = code
1675 self.code_to_run = code
1670 # now actually execute the code object
1676 # now actually execute the code object
1671 if self.runcode(code) == 0:
1677 if self.runcode(code) == 0:
1672 return False
1678 return False
1673 else:
1679 else:
1674 return None
1680 return None
1675
1681
1676 def runcode(self,code_obj):
1682 def runcode(self,code_obj):
1677 """Execute a code object.
1683 """Execute a code object.
1678
1684
1679 When an exception occurs, self.showtraceback() is called to display a
1685 When an exception occurs, self.showtraceback() is called to display a
1680 traceback.
1686 traceback.
1681
1687
1682 Return value: a flag indicating whether the code to be run completed
1688 Return value: a flag indicating whether the code to be run completed
1683 successfully:
1689 successfully:
1684
1690
1685 - 0: successful execution.
1691 - 0: successful execution.
1686 - 1: an error occurred.
1692 - 1: an error occurred.
1687 """
1693 """
1688
1694
1689 # Set our own excepthook in case the user code tries to call it
1695 # Set our own excepthook in case the user code tries to call it
1690 # directly, so that the IPython crash handler doesn't get triggered
1696 # directly, so that the IPython crash handler doesn't get triggered
1691 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1697 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1692
1698
1693 # we save the original sys.excepthook in the instance, in case config
1699 # we save the original sys.excepthook in the instance, in case config
1694 # code (such as magics) needs access to it.
1700 # code (such as magics) needs access to it.
1695 self.sys_excepthook = old_excepthook
1701 self.sys_excepthook = old_excepthook
1696 outflag = 1 # happens in more places, so it's easier as default
1702 outflag = 1 # happens in more places, so it's easier as default
1697 try:
1703 try:
1698 try:
1704 try:
1699 # Embedded instances require separate global/local namespaces
1705 # Embedded instances require separate global/local namespaces
1700 # so they can see both the surrounding (local) namespace and
1706 # so they can see both the surrounding (local) namespace and
1701 # the module-level globals when called inside another function.
1707 # the module-level globals when called inside another function.
1702 if self.embedded:
1708 if self.embedded:
1703 exec code_obj in self.user_global_ns, self.user_ns
1709 exec code_obj in self.user_global_ns, self.user_ns
1704 # Normal (non-embedded) instances should only have a single
1710 # Normal (non-embedded) instances should only have a single
1705 # namespace for user code execution, otherwise functions won't
1711 # namespace for user code execution, otherwise functions won't
1706 # see interactive top-level globals.
1712 # see interactive top-level globals.
1707 else:
1713 else:
1708 exec code_obj in self.user_ns
1714 exec code_obj in self.user_ns
1709 finally:
1715 finally:
1710 # Reset our crash handler in place
1716 # Reset our crash handler in place
1711 sys.excepthook = old_excepthook
1717 sys.excepthook = old_excepthook
1712 except SystemExit:
1718 except SystemExit:
1713 self.resetbuffer()
1719 self.resetbuffer()
1714 self.showtraceback()
1720 self.showtraceback()
1715 warn("Type exit or quit to exit IPython "
1721 warn("Type exit or quit to exit IPython "
1716 "(%Exit or %Quit do so unconditionally).",level=1)
1722 "(%Exit or %Quit do so unconditionally).",level=1)
1717 except self.custom_exceptions:
1723 except self.custom_exceptions:
1718 etype,value,tb = sys.exc_info()
1724 etype,value,tb = sys.exc_info()
1719 self.CustomTB(etype,value,tb)
1725 self.CustomTB(etype,value,tb)
1720 except:
1726 except:
1721 self.showtraceback()
1727 self.showtraceback()
1722 else:
1728 else:
1723 outflag = 0
1729 outflag = 0
1724 if softspace(sys.stdout, 0):
1730 if softspace(sys.stdout, 0):
1725 print
1731 print
1726 # Flush out code object which has been run (and source)
1732 # Flush out code object which has been run (and source)
1727 self.code_to_run = None
1733 self.code_to_run = None
1728 return outflag
1734 return outflag
1729
1735
1730 def push(self, line):
1736 def push(self, line):
1731 """Push a line to the interpreter.
1737 """Push a line to the interpreter.
1732
1738
1733 The line should not have a trailing newline; it may have
1739 The line should not have a trailing newline; it may have
1734 internal newlines. The line is appended to a buffer and the
1740 internal newlines. The line is appended to a buffer and the
1735 interpreter's runsource() method is called with the
1741 interpreter's runsource() method is called with the
1736 concatenated contents of the buffer as source. If this
1742 concatenated contents of the buffer as source. If this
1737 indicates that the command was executed or invalid, the buffer
1743 indicates that the command was executed or invalid, the buffer
1738 is reset; otherwise, the command is incomplete, and the buffer
1744 is reset; otherwise, the command is incomplete, and the buffer
1739 is left as it was after the line was appended. The return
1745 is left as it was after the line was appended. The return
1740 value is 1 if more input is required, 0 if the line was dealt
1746 value is 1 if more input is required, 0 if the line was dealt
1741 with in some way (this is the same as runsource()).
1747 with in some way (this is the same as runsource()).
1742 """
1748 """
1743
1749
1744 # autoindent management should be done here, and not in the
1750 # autoindent management should be done here, and not in the
1745 # interactive loop, since that one is only seen by keyboard input. We
1751 # interactive loop, since that one is only seen by keyboard input. We
1746 # need this done correctly even for code run via runlines (which uses
1752 # need this done correctly even for code run via runlines (which uses
1747 # push).
1753 # push).
1748
1754
1749 #print 'push line: <%s>' % line # dbg
1755 #print 'push line: <%s>' % line # dbg
1750 self.autoindent_update(line)
1756 self.autoindent_update(line)
1751
1757
1752 self.buffer.append(line)
1758 self.buffer.append(line)
1753 more = self.runsource('\n'.join(self.buffer), self.filename)
1759 more = self.runsource('\n'.join(self.buffer), self.filename)
1754 if not more:
1760 if not more:
1755 self.resetbuffer()
1761 self.resetbuffer()
1756 return more
1762 return more
1757
1763
1758 def resetbuffer(self):
1764 def resetbuffer(self):
1759 """Reset the input buffer."""
1765 """Reset the input buffer."""
1760 self.buffer[:] = []
1766 self.buffer[:] = []
1761
1767
1762 def raw_input(self,prompt='',continue_prompt=False):
1768 def raw_input(self,prompt='',continue_prompt=False):
1763 """Write a prompt and read a line.
1769 """Write a prompt and read a line.
1764
1770
1765 The returned line does not include the trailing newline.
1771 The returned line does not include the trailing newline.
1766 When the user enters the EOF key sequence, EOFError is raised.
1772 When the user enters the EOF key sequence, EOFError is raised.
1767
1773
1768 Optional inputs:
1774 Optional inputs:
1769
1775
1770 - prompt(''): a string to be printed to prompt the user.
1776 - prompt(''): a string to be printed to prompt the user.
1771
1777
1772 - continue_prompt(False): whether this line is the first one or a
1778 - continue_prompt(False): whether this line is the first one or a
1773 continuation in a sequence of inputs.
1779 continuation in a sequence of inputs.
1774 """
1780 """
1775
1781
1776 line = raw_input_original(prompt)
1782 line = raw_input_original(prompt)
1777
1783
1778 # Try to be reasonably smart about not re-indenting pasted input more
1784 # Try to be reasonably smart about not re-indenting pasted input more
1779 # than necessary. We do this by trimming out the auto-indent initial
1785 # than necessary. We do this by trimming out the auto-indent initial
1780 # spaces, if the user's actual input started itself with whitespace.
1786 # spaces, if the user's actual input started itself with whitespace.
1781 #debugx('self.buffer[-1]')
1787 #debugx('self.buffer[-1]')
1782
1788
1783 if self.autoindent:
1789 if self.autoindent:
1784 if num_ini_spaces(line) > self.indent_current_nsp:
1790 if num_ini_spaces(line) > self.indent_current_nsp:
1785 line = line[self.indent_current_nsp:]
1791 line = line[self.indent_current_nsp:]
1786 self.indent_current_nsp = 0
1792 self.indent_current_nsp = 0
1787
1793
1788 # store the unfiltered input before the user has any chance to modify
1794 # store the unfiltered input before the user has any chance to modify
1789 # it.
1795 # it.
1790 if line.strip():
1796 if line.strip():
1791 if continue_prompt:
1797 if continue_prompt:
1792 self.input_hist_raw[-1] += '%s\n' % line
1798 self.input_hist_raw[-1] += '%s\n' % line
1793 else:
1799 else:
1794 self.input_hist_raw.append('%s\n' % line)
1800 self.input_hist_raw.append('%s\n' % line)
1795
1801
1796 lineout = self.prefilter(line,continue_prompt)
1802 try:
1803 lineout = self.prefilter(line,continue_prompt)
1804 except:
1805 # blanket except, in case a user-defined prefilter crashes, so it
1806 # can't take all of ipython with it.
1807 self.showtraceback()
1797 return lineout
1808 return lineout
1798
1809
1799 def split_user_input(self,line):
1810 def split_user_input(self,line):
1800 """Split user input into pre-char, function part and rest."""
1811 """Split user input into pre-char, function part and rest."""
1801
1812
1802 lsplit = self.line_split.match(line)
1813 lsplit = self.line_split.match(line)
1803 if lsplit is None: # no regexp match returns None
1814 if lsplit is None: # no regexp match returns None
1804 try:
1815 try:
1805 iFun,theRest = line.split(None,1)
1816 iFun,theRest = line.split(None,1)
1806 except ValueError:
1817 except ValueError:
1807 iFun,theRest = line,''
1818 iFun,theRest = line,''
1808 pre = re.match('^(\s*)(.*)',line).groups()[0]
1819 pre = re.match('^(\s*)(.*)',line).groups()[0]
1809 else:
1820 else:
1810 pre,iFun,theRest = lsplit.groups()
1821 pre,iFun,theRest = lsplit.groups()
1811
1822
1812 #print 'line:<%s>' % line # dbg
1823 #print 'line:<%s>' % line # dbg
1813 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1824 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1814 return pre,iFun.strip(),theRest
1825 return pre,iFun.strip(),theRest
1815
1826
1816 def _prefilter(self, line, continue_prompt):
1827 def _prefilter(self, line, continue_prompt):
1817 """Calls different preprocessors, depending on the form of line."""
1828 """Calls different preprocessors, depending on the form of line."""
1818
1829
1819 # All handlers *must* return a value, even if it's blank ('').
1830 # All handlers *must* return a value, even if it's blank ('').
1820
1831
1821 # Lines are NOT logged here. Handlers should process the line as
1832 # Lines are NOT logged here. Handlers should process the line as
1822 # needed, update the cache AND log it (so that the input cache array
1833 # needed, update the cache AND log it (so that the input cache array
1823 # stays synced).
1834 # stays synced).
1824
1835
1825 # This function is _very_ delicate, and since it's also the one which
1836 # This function is _very_ delicate, and since it's also the one which
1826 # determines IPython's response to user input, it must be as efficient
1837 # determines IPython's response to user input, it must be as efficient
1827 # as possible. For this reason it has _many_ returns in it, trying
1838 # as possible. For this reason it has _many_ returns in it, trying
1828 # always to exit as quickly as it can figure out what it needs to do.
1839 # always to exit as quickly as it can figure out what it needs to do.
1829
1840
1830 # This function is the main responsible for maintaining IPython's
1841 # This function is the main responsible for maintaining IPython's
1831 # behavior respectful of Python's semantics. So be _very_ careful if
1842 # behavior respectful of Python's semantics. So be _very_ careful if
1832 # making changes to anything here.
1843 # making changes to anything here.
1833
1844
1834 #.....................................................................
1845 #.....................................................................
1835 # Code begins
1846 # Code begins
1836
1847
1837 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1848 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1838
1849
1839 # save the line away in case we crash, so the post-mortem handler can
1850 # save the line away in case we crash, so the post-mortem handler can
1840 # record it
1851 # record it
1841 self._last_input_line = line
1852 self._last_input_line = line
1842
1853
1843 #print '***line: <%s>' % line # dbg
1854 #print '***line: <%s>' % line # dbg
1844
1855
1845 # the input history needs to track even empty lines
1856 # the input history needs to track even empty lines
1846 stripped = line.strip()
1857 stripped = line.strip()
1847
1858
1848 if not stripped:
1859 if not stripped:
1849 if not continue_prompt:
1860 if not continue_prompt:
1850 self.outputcache.prompt_count -= 1
1861 self.outputcache.prompt_count -= 1
1851 return self.handle_normal(line,continue_prompt)
1862 return self.handle_normal(line,continue_prompt)
1852 #return self.handle_normal('',continue_prompt)
1863 #return self.handle_normal('',continue_prompt)
1853
1864
1854 # print '***cont',continue_prompt # dbg
1865 # print '***cont',continue_prompt # dbg
1855 # special handlers are only allowed for single line statements
1866 # special handlers are only allowed for single line statements
1856 if continue_prompt and not self.rc.multi_line_specials:
1867 if continue_prompt and not self.rc.multi_line_specials:
1857 return self.handle_normal(line,continue_prompt)
1868 return self.handle_normal(line,continue_prompt)
1858
1869
1859
1870
1860 # For the rest, we need the structure of the input
1871 # For the rest, we need the structure of the input
1861 pre,iFun,theRest = self.split_user_input(line)
1872 pre,iFun,theRest = self.split_user_input(line)
1862
1873
1863 # See whether any pre-existing handler can take care of it
1874 # See whether any pre-existing handler can take care of it
1864
1875
1865 rewritten = self.hooks.input_prefilter(stripped)
1876 rewritten = self.hooks.input_prefilter(stripped)
1866 if rewritten != stripped: # ok, some prefilter did something
1877 if rewritten != stripped: # ok, some prefilter did something
1867 rewritten = pre + rewritten # add indentation
1878 rewritten = pre + rewritten # add indentation
1868 return self.handle_normal(rewritten)
1879 return self.handle_normal(rewritten)
1869
1880
1870
1881
1871
1882
1872
1883
1873 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1884 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1874
1885
1875 # First check for explicit escapes in the last/first character
1886 # First check for explicit escapes in the last/first character
1876 handler = None
1887 handler = None
1877 if line[-1] == self.ESC_HELP:
1888 if line[-1] == self.ESC_HELP:
1878 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1889 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1879 if handler is None:
1890 if handler is None:
1880 # look at the first character of iFun, NOT of line, so we skip
1891 # look at the first character of iFun, NOT of line, so we skip
1881 # leading whitespace in multiline input
1892 # leading whitespace in multiline input
1882 handler = self.esc_handlers.get(iFun[0:1])
1893 handler = self.esc_handlers.get(iFun[0:1])
1883 if handler is not None:
1894 if handler is not None:
1884 return handler(line,continue_prompt,pre,iFun,theRest)
1895 return handler(line,continue_prompt,pre,iFun,theRest)
1885 # Emacs ipython-mode tags certain input lines
1896 # Emacs ipython-mode tags certain input lines
1886 if line.endswith('# PYTHON-MODE'):
1897 if line.endswith('# PYTHON-MODE'):
1887 return self.handle_emacs(line,continue_prompt)
1898 return self.handle_emacs(line,continue_prompt)
1888
1899
1889 # Next, check if we can automatically execute this thing
1900 # Next, check if we can automatically execute this thing
1890
1901
1891 # Allow ! in multi-line statements if multi_line_specials is on:
1902 # Allow ! in multi-line statements if multi_line_specials is on:
1892 if continue_prompt and self.rc.multi_line_specials and \
1903 if continue_prompt and self.rc.multi_line_specials and \
1893 iFun.startswith(self.ESC_SHELL):
1904 iFun.startswith(self.ESC_SHELL):
1894 return self.handle_shell_escape(line,continue_prompt,
1905 return self.handle_shell_escape(line,continue_prompt,
1895 pre=pre,iFun=iFun,
1906 pre=pre,iFun=iFun,
1896 theRest=theRest)
1907 theRest=theRest)
1897
1908
1898 # Let's try to find if the input line is a magic fn
1909 # Let's try to find if the input line is a magic fn
1899 oinfo = None
1910 oinfo = None
1900 if hasattr(self,'magic_'+iFun):
1911 if hasattr(self,'magic_'+iFun):
1901 # WARNING: _ofind uses getattr(), so it can consume generators and
1912 # WARNING: _ofind uses getattr(), so it can consume generators and
1902 # cause other side effects.
1913 # cause other side effects.
1903 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1914 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1904 if oinfo['ismagic']:
1915 if oinfo['ismagic']:
1905 # Be careful not to call magics when a variable assignment is
1916 # Be careful not to call magics when a variable assignment is
1906 # being made (ls='hi', for example)
1917 # being made (ls='hi', for example)
1907 if self.rc.automagic and \
1918 if self.rc.automagic and \
1908 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1919 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1909 (self.rc.multi_line_specials or not continue_prompt):
1920 (self.rc.multi_line_specials or not continue_prompt):
1910 return self.handle_magic(line,continue_prompt,
1921 return self.handle_magic(line,continue_prompt,
1911 pre,iFun,theRest)
1922 pre,iFun,theRest)
1912 else:
1923 else:
1913 return self.handle_normal(line,continue_prompt)
1924 return self.handle_normal(line,continue_prompt)
1914
1925
1915 # If the rest of the line begins with an (in)equality, assginment or
1926 # If the rest of the line begins with an (in)equality, assginment or
1916 # function call, we should not call _ofind but simply execute it.
1927 # function call, we should not call _ofind but simply execute it.
1917 # This avoids spurious geattr() accesses on objects upon assignment.
1928 # This avoids spurious geattr() accesses on objects upon assignment.
1918 #
1929 #
1919 # It also allows users to assign to either alias or magic names true
1930 # It also allows users to assign to either alias or magic names true
1920 # python variables (the magic/alias systems always take second seat to
1931 # python variables (the magic/alias systems always take second seat to
1921 # true python code).
1932 # true python code).
1922 if theRest and theRest[0] in '!=()':
1933 if theRest and theRest[0] in '!=()':
1923 return self.handle_normal(line,continue_prompt)
1934 return self.handle_normal(line,continue_prompt)
1924
1935
1925 if oinfo is None:
1936 if oinfo is None:
1926 # let's try to ensure that _oinfo is ONLY called when autocall is
1937 # let's try to ensure that _oinfo is ONLY called when autocall is
1927 # on. Since it has inevitable potential side effects, at least
1938 # on. Since it has inevitable potential side effects, at least
1928 # having autocall off should be a guarantee to the user that no
1939 # having autocall off should be a guarantee to the user that no
1929 # weird things will happen.
1940 # weird things will happen.
1930
1941
1931 if self.rc.autocall:
1942 if self.rc.autocall:
1932 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1943 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1933 else:
1944 else:
1934 # in this case, all that's left is either an alias or
1945 # in this case, all that's left is either an alias or
1935 # processing the line normally.
1946 # processing the line normally.
1936 if iFun in self.alias_table:
1947 if iFun in self.alias_table:
1937 return self.handle_alias(line,continue_prompt,
1948 return self.handle_alias(line,continue_prompt,
1938 pre,iFun,theRest)
1949 pre,iFun,theRest)
1939
1950
1940 else:
1951 else:
1941 return self.handle_normal(line,continue_prompt)
1952 return self.handle_normal(line,continue_prompt)
1942
1953
1943 if not oinfo['found']:
1954 if not oinfo['found']:
1944 return self.handle_normal(line,continue_prompt)
1955 return self.handle_normal(line,continue_prompt)
1945 else:
1956 else:
1946 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1957 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1947 if oinfo['isalias']:
1958 if oinfo['isalias']:
1948 return self.handle_alias(line,continue_prompt,
1959 return self.handle_alias(line,continue_prompt,
1949 pre,iFun,theRest)
1960 pre,iFun,theRest)
1950
1961
1951 if (self.rc.autocall
1962 if (self.rc.autocall
1952 and
1963 and
1953 (
1964 (
1954 #only consider exclusion re if not "," or ";" autoquoting
1965 #only consider exclusion re if not "," or ";" autoquoting
1955 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
1966 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
1956 or pre == self.ESC_PAREN) or
1967 or pre == self.ESC_PAREN) or
1957 (not self.re_exclude_auto.match(theRest)))
1968 (not self.re_exclude_auto.match(theRest)))
1958 and
1969 and
1959 self.re_fun_name.match(iFun) and
1970 self.re_fun_name.match(iFun) and
1960 callable(oinfo['obj'])) :
1971 callable(oinfo['obj'])) :
1961 #print 'going auto' # dbg
1972 #print 'going auto' # dbg
1962 return self.handle_auto(line,continue_prompt,
1973 return self.handle_auto(line,continue_prompt,
1963 pre,iFun,theRest,oinfo['obj'])
1974 pre,iFun,theRest,oinfo['obj'])
1964 else:
1975 else:
1965 #print 'was callable?', callable(oinfo['obj']) # dbg
1976 #print 'was callable?', callable(oinfo['obj']) # dbg
1966 return self.handle_normal(line,continue_prompt)
1977 return self.handle_normal(line,continue_prompt)
1967
1978
1968 # If we get here, we have a normal Python line. Log and return.
1979 # If we get here, we have a normal Python line. Log and return.
1969 return self.handle_normal(line,continue_prompt)
1980 return self.handle_normal(line,continue_prompt)
1970
1981
1971 def _prefilter_dumb(self, line, continue_prompt):
1982 def _prefilter_dumb(self, line, continue_prompt):
1972 """simple prefilter function, for debugging"""
1983 """simple prefilter function, for debugging"""
1973 return self.handle_normal(line,continue_prompt)
1984 return self.handle_normal(line,continue_prompt)
1974
1985
1975 # Set the default prefilter() function (this can be user-overridden)
1986 # Set the default prefilter() function (this can be user-overridden)
1976 prefilter = _prefilter
1987 prefilter = _prefilter
1977
1988
1978 def handle_normal(self,line,continue_prompt=None,
1989 def handle_normal(self,line,continue_prompt=None,
1979 pre=None,iFun=None,theRest=None):
1990 pre=None,iFun=None,theRest=None):
1980 """Handle normal input lines. Use as a template for handlers."""
1991 """Handle normal input lines. Use as a template for handlers."""
1981
1992
1982 # With autoindent on, we need some way to exit the input loop, and I
1993 # With autoindent on, we need some way to exit the input loop, and I
1983 # don't want to force the user to have to backspace all the way to
1994 # don't want to force the user to have to backspace all the way to
1984 # clear the line. The rule will be in this case, that either two
1995 # clear the line. The rule will be in this case, that either two
1985 # lines of pure whitespace in a row, or a line of pure whitespace but
1996 # lines of pure whitespace in a row, or a line of pure whitespace but
1986 # of a size different to the indent level, will exit the input loop.
1997 # of a size different to the indent level, will exit the input loop.
1987
1998
1988 if (continue_prompt and self.autoindent and line.isspace() and
1999 if (continue_prompt and self.autoindent and line.isspace() and
1989 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2000 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1990 (self.buffer[-1]).isspace() )):
2001 (self.buffer[-1]).isspace() )):
1991 line = ''
2002 line = ''
1992
2003
1993 self.log(line,continue_prompt)
2004 self.log(line,continue_prompt)
1994 return line
2005 return line
1995
2006
1996 def handle_alias(self,line,continue_prompt=None,
2007 def handle_alias(self,line,continue_prompt=None,
1997 pre=None,iFun=None,theRest=None):
2008 pre=None,iFun=None,theRest=None):
1998 """Handle alias input lines. """
2009 """Handle alias input lines. """
1999
2010
2000 # pre is needed, because it carries the leading whitespace. Otherwise
2011 # pre is needed, because it carries the leading whitespace. Otherwise
2001 # aliases won't work in indented sections.
2012 # aliases won't work in indented sections.
2002 transformed = self.transform_alias(iFun, theRest)
2013 transformed = self.transform_alias(iFun, theRest)
2003 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2014 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2004 self.log(line_out,continue_prompt)
2015 self.log(line_out,continue_prompt)
2005 return line_out
2016 return line_out
2006
2017
2007 def handle_shell_escape(self, line, continue_prompt=None,
2018 def handle_shell_escape(self, line, continue_prompt=None,
2008 pre=None,iFun=None,theRest=None):
2019 pre=None,iFun=None,theRest=None):
2009 """Execute the line in a shell, empty return value"""
2020 """Execute the line in a shell, empty return value"""
2010
2021
2011 #print 'line in :', `line` # dbg
2022 #print 'line in :', `line` # dbg
2012 # Example of a special handler. Others follow a similar pattern.
2023 # Example of a special handler. Others follow a similar pattern.
2013 if line.lstrip().startswith('!!'):
2024 if line.lstrip().startswith('!!'):
2014 # rewrite iFun/theRest to properly hold the call to %sx and
2025 # rewrite iFun/theRest to properly hold the call to %sx and
2015 # the actual command to be executed, so handle_magic can work
2026 # the actual command to be executed, so handle_magic can work
2016 # correctly
2027 # correctly
2017 theRest = '%s %s' % (iFun[2:],theRest)
2028 theRest = '%s %s' % (iFun[2:],theRest)
2018 iFun = 'sx'
2029 iFun = 'sx'
2019 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2030 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2020 line.lstrip()[2:]),
2031 line.lstrip()[2:]),
2021 continue_prompt,pre,iFun,theRest)
2032 continue_prompt,pre,iFun,theRest)
2022 else:
2033 else:
2023 cmd=line.lstrip().lstrip('!')
2034 cmd=line.lstrip().lstrip('!')
2024 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2035 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2025 # update cache/log and return
2036 # update cache/log and return
2026 self.log(line_out,continue_prompt)
2037 self.log(line_out,continue_prompt)
2027 return line_out
2038 return line_out
2028
2039
2029 def handle_magic(self, line, continue_prompt=None,
2040 def handle_magic(self, line, continue_prompt=None,
2030 pre=None,iFun=None,theRest=None):
2041 pre=None,iFun=None,theRest=None):
2031 """Execute magic functions."""
2042 """Execute magic functions."""
2032
2043
2033
2044
2034 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2045 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2035 self.log(cmd,continue_prompt)
2046 self.log(cmd,continue_prompt)
2036 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2047 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2037 return cmd
2048 return cmd
2038
2049
2039 def handle_auto(self, line, continue_prompt=None,
2050 def handle_auto(self, line, continue_prompt=None,
2040 pre=None,iFun=None,theRest=None,obj=None):
2051 pre=None,iFun=None,theRest=None,obj=None):
2041 """Hande lines which can be auto-executed, quoting if requested."""
2052 """Hande lines which can be auto-executed, quoting if requested."""
2042
2053
2043 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2054 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2044
2055
2045 # This should only be active for single-line input!
2056 # This should only be active for single-line input!
2046 if continue_prompt:
2057 if continue_prompt:
2047 self.log(line,continue_prompt)
2058 self.log(line,continue_prompt)
2048 return line
2059 return line
2049
2060
2050 auto_rewrite = True
2061 auto_rewrite = True
2051
2062
2052 if pre == self.ESC_QUOTE:
2063 if pre == self.ESC_QUOTE:
2053 # Auto-quote splitting on whitespace
2064 # Auto-quote splitting on whitespace
2054 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2065 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2055 elif pre == self.ESC_QUOTE2:
2066 elif pre == self.ESC_QUOTE2:
2056 # Auto-quote whole string
2067 # Auto-quote whole string
2057 newcmd = '%s("%s")' % (iFun,theRest)
2068 newcmd = '%s("%s")' % (iFun,theRest)
2058 elif pre == self.ESC_PAREN:
2069 elif pre == self.ESC_PAREN:
2059 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2070 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2060 else:
2071 else:
2061 # Auto-paren.
2072 # Auto-paren.
2062 # We only apply it to argument-less calls if the autocall
2073 # We only apply it to argument-less calls if the autocall
2063 # parameter is set to 2. We only need to check that autocall is <
2074 # parameter is set to 2. We only need to check that autocall is <
2064 # 2, since this function isn't called unless it's at least 1.
2075 # 2, since this function isn't called unless it's at least 1.
2065 if not theRest and (self.rc.autocall < 2):
2076 if not theRest and (self.rc.autocall < 2):
2066 newcmd = '%s %s' % (iFun,theRest)
2077 newcmd = '%s %s' % (iFun,theRest)
2067 auto_rewrite = False
2078 auto_rewrite = False
2068 else:
2079 else:
2069 if theRest.startswith('['):
2080 if theRest.startswith('['):
2070 if hasattr(obj,'__getitem__'):
2081 if hasattr(obj,'__getitem__'):
2071 # Don't autocall in this case: item access for an object
2082 # Don't autocall in this case: item access for an object
2072 # which is BOTH callable and implements __getitem__.
2083 # which is BOTH callable and implements __getitem__.
2073 newcmd = '%s %s' % (iFun,theRest)
2084 newcmd = '%s %s' % (iFun,theRest)
2074 auto_rewrite = False
2085 auto_rewrite = False
2075 else:
2086 else:
2076 # if the object doesn't support [] access, go ahead and
2087 # if the object doesn't support [] access, go ahead and
2077 # autocall
2088 # autocall
2078 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2089 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2079 elif theRest.endswith(';'):
2090 elif theRest.endswith(';'):
2080 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2091 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2081 else:
2092 else:
2082 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2093 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2083
2094
2084 if auto_rewrite:
2095 if auto_rewrite:
2085 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2096 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2086 # log what is now valid Python, not the actual user input (without the
2097 # log what is now valid Python, not the actual user input (without the
2087 # final newline)
2098 # final newline)
2088 self.log(newcmd,continue_prompt)
2099 self.log(newcmd,continue_prompt)
2089 return newcmd
2100 return newcmd
2090
2101
2091 def handle_help(self, line, continue_prompt=None,
2102 def handle_help(self, line, continue_prompt=None,
2092 pre=None,iFun=None,theRest=None):
2103 pre=None,iFun=None,theRest=None):
2093 """Try to get some help for the object.
2104 """Try to get some help for the object.
2094
2105
2095 obj? or ?obj -> basic information.
2106 obj? or ?obj -> basic information.
2096 obj?? or ??obj -> more details.
2107 obj?? or ??obj -> more details.
2097 """
2108 """
2098
2109
2099 # We need to make sure that we don't process lines which would be
2110 # We need to make sure that we don't process lines which would be
2100 # otherwise valid python, such as "x=1 # what?"
2111 # otherwise valid python, such as "x=1 # what?"
2101 try:
2112 try:
2102 codeop.compile_command(line)
2113 codeop.compile_command(line)
2103 except SyntaxError:
2114 except SyntaxError:
2104 # We should only handle as help stuff which is NOT valid syntax
2115 # We should only handle as help stuff which is NOT valid syntax
2105 if line[0]==self.ESC_HELP:
2116 if line[0]==self.ESC_HELP:
2106 line = line[1:]
2117 line = line[1:]
2107 elif line[-1]==self.ESC_HELP:
2118 elif line[-1]==self.ESC_HELP:
2108 line = line[:-1]
2119 line = line[:-1]
2109 self.log('#?'+line)
2120 self.log('#?'+line)
2110 if line:
2121 if line:
2111 self.magic_pinfo(line)
2122 self.magic_pinfo(line)
2112 else:
2123 else:
2113 page(self.usage,screen_lines=self.rc.screen_length)
2124 page(self.usage,screen_lines=self.rc.screen_length)
2114 return '' # Empty string is needed here!
2125 return '' # Empty string is needed here!
2115 except:
2126 except:
2116 # Pass any other exceptions through to the normal handler
2127 # Pass any other exceptions through to the normal handler
2117 return self.handle_normal(line,continue_prompt)
2128 return self.handle_normal(line,continue_prompt)
2118 else:
2129 else:
2119 # If the code compiles ok, we should handle it normally
2130 # If the code compiles ok, we should handle it normally
2120 return self.handle_normal(line,continue_prompt)
2131 return self.handle_normal(line,continue_prompt)
2121
2132
2122 def getapi(self):
2133 def getapi(self):
2123 """ Get an IPApi object for this shell instance
2134 """ Get an IPApi object for this shell instance
2124
2135
2125 Getting an IPApi object is always preferable to accessing the shell
2136 Getting an IPApi object is always preferable to accessing the shell
2126 directly, but this holds true especially for extensions.
2137 directly, but this holds true especially for extensions.
2127
2138
2128 It should always be possible to implement an extension with IPApi
2139 It should always be possible to implement an extension with IPApi
2129 alone. If not, contact maintainer to request an addition.
2140 alone. If not, contact maintainer to request an addition.
2130
2141
2131 """
2142 """
2132 return self.api
2143 return self.api
2133
2144
2134 def handle_emacs(self,line,continue_prompt=None,
2145 def handle_emacs(self,line,continue_prompt=None,
2135 pre=None,iFun=None,theRest=None):
2146 pre=None,iFun=None,theRest=None):
2136 """Handle input lines marked by python-mode."""
2147 """Handle input lines marked by python-mode."""
2137
2148
2138 # Currently, nothing is done. Later more functionality can be added
2149 # Currently, nothing is done. Later more functionality can be added
2139 # here if needed.
2150 # here if needed.
2140
2151
2141 # The input cache shouldn't be updated
2152 # The input cache shouldn't be updated
2142
2153
2143 return line
2154 return line
2144
2155
2145 def mktempfile(self,data=None):
2156 def mktempfile(self,data=None):
2146 """Make a new tempfile and return its filename.
2157 """Make a new tempfile and return its filename.
2147
2158
2148 This makes a call to tempfile.mktemp, but it registers the created
2159 This makes a call to tempfile.mktemp, but it registers the created
2149 filename internally so ipython cleans it up at exit time.
2160 filename internally so ipython cleans it up at exit time.
2150
2161
2151 Optional inputs:
2162 Optional inputs:
2152
2163
2153 - data(None): if data is given, it gets written out to the temp file
2164 - data(None): if data is given, it gets written out to the temp file
2154 immediately, and the file is closed again."""
2165 immediately, and the file is closed again."""
2155
2166
2156 filename = tempfile.mktemp('.py','ipython_edit_')
2167 filename = tempfile.mktemp('.py','ipython_edit_')
2157 self.tempfiles.append(filename)
2168 self.tempfiles.append(filename)
2158
2169
2159 if data:
2170 if data:
2160 tmp_file = open(filename,'w')
2171 tmp_file = open(filename,'w')
2161 tmp_file.write(data)
2172 tmp_file.write(data)
2162 tmp_file.close()
2173 tmp_file.close()
2163 return filename
2174 return filename
2164
2175
2165 def write(self,data):
2176 def write(self,data):
2166 """Write a string to the default output"""
2177 """Write a string to the default output"""
2167 Term.cout.write(data)
2178 Term.cout.write(data)
2168
2179
2169 def write_err(self,data):
2180 def write_err(self,data):
2170 """Write a string to the default error output"""
2181 """Write a string to the default error output"""
2171 Term.cerr.write(data)
2182 Term.cerr.write(data)
2172
2183
2173 def exit(self):
2184 def exit(self):
2174 """Handle interactive exit.
2185 """Handle interactive exit.
2175
2186
2176 This method sets the exit_now attribute."""
2187 This method sets the exit_now attribute."""
2177
2188
2178 if self.rc.confirm_exit:
2189 if self.rc.confirm_exit:
2179 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2190 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2180 self.exit_now = True
2191 self.exit_now = True
2181 else:
2192 else:
2182 self.exit_now = True
2193 self.exit_now = True
2183 return self.exit_now
2194 return self.exit_now
2184
2195
2185 def safe_execfile(self,fname,*where,**kw):
2196 def safe_execfile(self,fname,*where,**kw):
2186 fname = os.path.expanduser(fname)
2197 fname = os.path.expanduser(fname)
2187
2198
2188 # find things also in current directory
2199 # find things also in current directory
2189 dname = os.path.dirname(fname)
2200 dname = os.path.dirname(fname)
2190 if not sys.path.count(dname):
2201 if not sys.path.count(dname):
2191 sys.path.append(dname)
2202 sys.path.append(dname)
2192
2203
2193 try:
2204 try:
2194 xfile = open(fname)
2205 xfile = open(fname)
2195 except:
2206 except:
2196 print >> Term.cerr, \
2207 print >> Term.cerr, \
2197 'Could not open file <%s> for safe execution.' % fname
2208 'Could not open file <%s> for safe execution.' % fname
2198 return None
2209 return None
2199
2210
2200 kw.setdefault('islog',0)
2211 kw.setdefault('islog',0)
2201 kw.setdefault('quiet',1)
2212 kw.setdefault('quiet',1)
2202 kw.setdefault('exit_ignore',0)
2213 kw.setdefault('exit_ignore',0)
2203 first = xfile.readline()
2214 first = xfile.readline()
2204 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2215 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2205 xfile.close()
2216 xfile.close()
2206 # line by line execution
2217 # line by line execution
2207 if first.startswith(loghead) or kw['islog']:
2218 if first.startswith(loghead) or kw['islog']:
2208 print 'Loading log file <%s> one line at a time...' % fname
2219 print 'Loading log file <%s> one line at a time...' % fname
2209 if kw['quiet']:
2220 if kw['quiet']:
2210 stdout_save = sys.stdout
2221 stdout_save = sys.stdout
2211 sys.stdout = StringIO.StringIO()
2222 sys.stdout = StringIO.StringIO()
2212 try:
2223 try:
2213 globs,locs = where[0:2]
2224 globs,locs = where[0:2]
2214 except:
2225 except:
2215 try:
2226 try:
2216 globs = locs = where[0]
2227 globs = locs = where[0]
2217 except:
2228 except:
2218 globs = locs = globals()
2229 globs = locs = globals()
2219 badblocks = []
2230 badblocks = []
2220
2231
2221 # we also need to identify indented blocks of code when replaying
2232 # we also need to identify indented blocks of code when replaying
2222 # logs and put them together before passing them to an exec
2233 # logs and put them together before passing them to an exec
2223 # statement. This takes a bit of regexp and look-ahead work in the
2234 # statement. This takes a bit of regexp and look-ahead work in the
2224 # file. It's easiest if we swallow the whole thing in memory
2235 # file. It's easiest if we swallow the whole thing in memory
2225 # first, and manually walk through the lines list moving the
2236 # first, and manually walk through the lines list moving the
2226 # counter ourselves.
2237 # counter ourselves.
2227 indent_re = re.compile('\s+\S')
2238 indent_re = re.compile('\s+\S')
2228 xfile = open(fname)
2239 xfile = open(fname)
2229 filelines = xfile.readlines()
2240 filelines = xfile.readlines()
2230 xfile.close()
2241 xfile.close()
2231 nlines = len(filelines)
2242 nlines = len(filelines)
2232 lnum = 0
2243 lnum = 0
2233 while lnum < nlines:
2244 while lnum < nlines:
2234 line = filelines[lnum]
2245 line = filelines[lnum]
2235 lnum += 1
2246 lnum += 1
2236 # don't re-insert logger status info into cache
2247 # don't re-insert logger status info into cache
2237 if line.startswith('#log#'):
2248 if line.startswith('#log#'):
2238 continue
2249 continue
2239 else:
2250 else:
2240 # build a block of code (maybe a single line) for execution
2251 # build a block of code (maybe a single line) for execution
2241 block = line
2252 block = line
2242 try:
2253 try:
2243 next = filelines[lnum] # lnum has already incremented
2254 next = filelines[lnum] # lnum has already incremented
2244 except:
2255 except:
2245 next = None
2256 next = None
2246 while next and indent_re.match(next):
2257 while next and indent_re.match(next):
2247 block += next
2258 block += next
2248 lnum += 1
2259 lnum += 1
2249 try:
2260 try:
2250 next = filelines[lnum]
2261 next = filelines[lnum]
2251 except:
2262 except:
2252 next = None
2263 next = None
2253 # now execute the block of one or more lines
2264 # now execute the block of one or more lines
2254 try:
2265 try:
2255 exec block in globs,locs
2266 exec block in globs,locs
2256 except SystemExit:
2267 except SystemExit:
2257 pass
2268 pass
2258 except:
2269 except:
2259 badblocks.append(block.rstrip())
2270 badblocks.append(block.rstrip())
2260 if kw['quiet']: # restore stdout
2271 if kw['quiet']: # restore stdout
2261 sys.stdout.close()
2272 sys.stdout.close()
2262 sys.stdout = stdout_save
2273 sys.stdout = stdout_save
2263 print 'Finished replaying log file <%s>' % fname
2274 print 'Finished replaying log file <%s>' % fname
2264 if badblocks:
2275 if badblocks:
2265 print >> sys.stderr, ('\nThe following lines/blocks in file '
2276 print >> sys.stderr, ('\nThe following lines/blocks in file '
2266 '<%s> reported errors:' % fname)
2277 '<%s> reported errors:' % fname)
2267
2278
2268 for badline in badblocks:
2279 for badline in badblocks:
2269 print >> sys.stderr, badline
2280 print >> sys.stderr, badline
2270 else: # regular file execution
2281 else: # regular file execution
2271 try:
2282 try:
2272 execfile(fname,*where)
2283 execfile(fname,*where)
2273 except SyntaxError:
2284 except SyntaxError:
2274 self.showsyntaxerror()
2285 self.showsyntaxerror()
2275 warn('Failure executing file: <%s>' % fname)
2286 warn('Failure executing file: <%s>' % fname)
2276 except SystemExit,status:
2287 except SystemExit,status:
2277 if not kw['exit_ignore']:
2288 if not kw['exit_ignore']:
2278 self.showtraceback()
2289 self.showtraceback()
2279 warn('Failure executing file: <%s>' % fname)
2290 warn('Failure executing file: <%s>' % fname)
2280 except:
2291 except:
2281 self.showtraceback()
2292 self.showtraceback()
2282 warn('Failure executing file: <%s>' % fname)
2293 warn('Failure executing file: <%s>' % fname)
2283
2294
2284 #************************* end of file <iplib.py> *****************************
2295 #************************* end of file <iplib.py> *****************************
@@ -1,5370 +1,5407 b''
1 2006-05-24 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/completer.py (Completer.attr_matches): add support for
4 PyCrust-style _getAttributeNames magic method. Patch contributed
5 by <mscott-AT-goldenspud.com>. Closes #50.
6
7 * IPython/iplib.py (InteractiveShell.__init__): remove the
8 deletion of exit/quit from __builtin__, which can break
9 third-party tools like the Zope debugging console. The
10 %exit/%quit magics remain. In general, it's probably a good idea
11 not to delete anything from __builtin__, since we never know what
12 that will break. In any case, python now (for 2.5) will support
13 'real' exit/quit, so this issue is moot. Closes #55.
14
15 * IPython/genutils.py (with_obj): rename the 'with' function to
16 'withobj' to avoid incompatibilities with Python 2.5, where 'with'
17 becomes a language keyword. Closes #53.
18
19 * IPython/FakeModule.py (FakeModule.__init__): add a proper
20 __file__ attribute to this so it fools more things into thinking
21 it is a real module. Closes #59.
22
23 * IPython/Magic.py (magic_edit): add -n option to open the editor
24 at a specific line number. After a patch by Stefan van der Walt.
25
26 2006-05-23 Fernando Perez <Fernando.Perez@colorado.edu>
27
28 * IPython/iplib.py (edit_syntax_error): fix crash when for some
29 reason the file could not be opened. After automatic crash
30 reports sent by James Graham <jgraham-AT-ast.cam.ac.uk> and
31 Charles Dolan <charlespatrickdolan-AT-yahoo.com>.
32 (_should_recompile): Don't fire editor if using %bg, since there
33 is no file in the first place. From the same report as above.
34 (raw_input): protect against faulty third-party prefilters. After
35 an automatic crash report sent by Dirk Laurie <dirk-AT-sun.ac.za>
36 while running under SAGE.
37
1 2006-05-23 Ville Vainio <vivainio@gmail.com>
38 2006-05-23 Ville Vainio <vivainio@gmail.com>
2
39
3 * ipapi.py: Stripped down ip.to_user_ns() to work only as
40 * ipapi.py: Stripped down ip.to_user_ns() to work only as
4 ip.to_user_ns("x1 y1"), which exposes vars x1 and y1. ipapi.get()
41 ip.to_user_ns("x1 y1"), which exposes vars x1 and y1. ipapi.get()
5 now returns None (again), unless dummy is specifically allowed by
42 now returns None (again), unless dummy is specifically allowed by
6 ipapi.get(allow_dummy=True).
43 ipapi.get(allow_dummy=True).
7
44
8 2006-05-18 Fernando Perez <Fernando.Perez@colorado.edu>
45 2006-05-18 Fernando Perez <Fernando.Perez@colorado.edu>
9
46
10 * IPython: remove all 2.2-compatibility objects and hacks from
47 * IPython: remove all 2.2-compatibility objects and hacks from
11 everywhere, since we only support 2.3 at this point. Docs
48 everywhere, since we only support 2.3 at this point. Docs
12 updated.
49 updated.
13
50
14 * IPython/ipapi.py (IPApi.__init__): Clean up of all getters.
51 * IPython/ipapi.py (IPApi.__init__): Clean up of all getters.
15 Anything requiring extra validation can be turned into a Python
52 Anything requiring extra validation can be turned into a Python
16 property in the future. I used a property for the db one b/c
53 property in the future. I used a property for the db one b/c
17 there was a nasty circularity problem with the initialization
54 there was a nasty circularity problem with the initialization
18 order, which right now I don't have time to clean up.
55 order, which right now I don't have time to clean up.
19
56
20 * IPython/Shell.py (MTInteractiveShell.runcode): Fix, I think,
57 * IPython/Shell.py (MTInteractiveShell.runcode): Fix, I think,
21 another locking bug reported by Jorgen. I'm not 100% sure though,
58 another locking bug reported by Jorgen. I'm not 100% sure though,
22 so more testing is needed...
59 so more testing is needed...
23
60
24 2006-05-17 Fernando Perez <Fernando.Perez@colorado.edu>
61 2006-05-17 Fernando Perez <Fernando.Perez@colorado.edu>
25
62
26 * IPython/ipapi.py (IPApi.to_user_ns): New function to inject
63 * IPython/ipapi.py (IPApi.to_user_ns): New function to inject
27 local variables from any routine in user code (typically executed
64 local variables from any routine in user code (typically executed
28 with %run) directly into the interactive namespace. Very useful
65 with %run) directly into the interactive namespace. Very useful
29 when doing complex debugging.
66 when doing complex debugging.
30 (IPythonNotRunning): Changed the default None object to a dummy
67 (IPythonNotRunning): Changed the default None object to a dummy
31 whose attributes can be queried as well as called without
68 whose attributes can be queried as well as called without
32 exploding, to ease writing code which works transparently both in
69 exploding, to ease writing code which works transparently both in
33 and out of ipython and uses some of this API.
70 and out of ipython and uses some of this API.
34
71
35 2006-05-16 Fernando Perez <Fernando.Perez@colorado.edu>
72 2006-05-16 Fernando Perez <Fernando.Perez@colorado.edu>
36
73
37 * IPython/hooks.py (result_display): Fix the fact that our display
74 * IPython/hooks.py (result_display): Fix the fact that our display
38 hook was using str() instead of repr(), as the default python
75 hook was using str() instead of repr(), as the default python
39 console does. This had gone unnoticed b/c it only happened if
76 console does. This had gone unnoticed b/c it only happened if
40 %Pprint was off, but the inconsistency was there.
77 %Pprint was off, but the inconsistency was there.
41
78
42 2006-05-15 Ville Vainio <vivainio@gmail.com>
79 2006-05-15 Ville Vainio <vivainio@gmail.com>
43
80
44 * Oinspect.py: Only show docstring for nonexisting/binary files
81 * Oinspect.py: Only show docstring for nonexisting/binary files
45 when doing object??, closing ticket #62
82 when doing object??, closing ticket #62
46
83
47 2006-05-13 Fernando Perez <Fernando.Perez@colorado.edu>
84 2006-05-13 Fernando Perez <Fernando.Perez@colorado.edu>
48
85
49 * IPython/Shell.py (MTInteractiveShell.runsource): Fix threading
86 * IPython/Shell.py (MTInteractiveShell.runsource): Fix threading
50 bug, closes http://www.scipy.net/roundup/ipython/issue55. A lock
87 bug, closes http://www.scipy.net/roundup/ipython/issue55. A lock
51 was being released in a routine which hadn't checked if it had
88 was being released in a routine which hadn't checked if it had
52 been the one to acquire it.
89 been the one to acquire it.
53
90
54 2006-05-07 Fernando Perez <Fernando.Perez@colorado.edu>
91 2006-05-07 Fernando Perez <Fernando.Perez@colorado.edu>
55
92
56 * IPython/Release.py (version): put out 0.7.2.rc1 for testing.
93 * IPython/Release.py (version): put out 0.7.2.rc1 for testing.
57
94
58 2006-04-11 Ville Vainio <vivainio@gmail.com>
95 2006-04-11 Ville Vainio <vivainio@gmail.com>
59
96
60 * iplib.py, ipmaker.py: .ipy extension now means "ipython batch file"
97 * iplib.py, ipmaker.py: .ipy extension now means "ipython batch file"
61 in command line. E.g. "ipython test.ipy" runs test.ipy with ipython
98 in command line. E.g. "ipython test.ipy" runs test.ipy with ipython
62 prefilters, allowing stuff like magics and aliases in the file.
99 prefilters, allowing stuff like magics and aliases in the file.
63
100
64 * Prompts.py, Extensions/clearcmd.py, ipy_system_conf.py: %clear magic
101 * Prompts.py, Extensions/clearcmd.py, ipy_system_conf.py: %clear magic
65 added. Supported now are "%clear in" and "%clear out" (clear input and
102 added. Supported now are "%clear in" and "%clear out" (clear input and
66 output history, respectively). Also fixed CachedOutput.flush to
103 output history, respectively). Also fixed CachedOutput.flush to
67 properly flush the output cache.
104 properly flush the output cache.
68
105
69 * Extensions/pspersistence.py: Fix %store to avoid "%store obj.attr"
106 * Extensions/pspersistence.py: Fix %store to avoid "%store obj.attr"
70 half-success (and fail explicitly).
107 half-success (and fail explicitly).
71
108
72 2006-03-28 Ville Vainio <vivainio@gmail.com>
109 2006-03-28 Ville Vainio <vivainio@gmail.com>
73
110
74 * iplib.py: Fix quoting of aliases so that only argless ones
111 * iplib.py: Fix quoting of aliases so that only argless ones
75 are quoted
112 are quoted
76
113
77 2006-03-28 Ville Vainio <vivainio@gmail.com>
114 2006-03-28 Ville Vainio <vivainio@gmail.com>
78
115
79 * iplib.py: Quote aliases with spaces in the name.
116 * iplib.py: Quote aliases with spaces in the name.
80 "c:\program files\blah\bin" is now legal alias target.
117 "c:\program files\blah\bin" is now legal alias target.
81
118
82 * ext_rehashdir.py: Space no longer allowed as arg
119 * ext_rehashdir.py: Space no longer allowed as arg
83 separator, since space is legal in path names.
120 separator, since space is legal in path names.
84
121
85 2006-03-16 Ville Vainio <vivainio@gmail.com>
122 2006-03-16 Ville Vainio <vivainio@gmail.com>
86
123
87 * upgrade_dir.py: Take path.py from Extensions, correcting
124 * upgrade_dir.py: Take path.py from Extensions, correcting
88 %upgrade magic
125 %upgrade magic
89
126
90 * ipmaker.py: Suggest using %upgrade if ipy_user_conf.py isn't found.
127 * ipmaker.py: Suggest using %upgrade if ipy_user_conf.py isn't found.
91
128
92 * hooks.py: Only enclose editor binary in quotes if legal and
129 * hooks.py: Only enclose editor binary in quotes if legal and
93 necessary (space in the name, and is an existing file). Fixes a bug
130 necessary (space in the name, and is an existing file). Fixes a bug
94 reported by Zachary Pincus.
131 reported by Zachary Pincus.
95
132
96 2006-03-13 Fernando Perez <Fernando.Perez@colorado.edu>
133 2006-03-13 Fernando Perez <Fernando.Perez@colorado.edu>
97
134
98 * Manual: thanks to a tip on proper color handling for Emacs, by
135 * Manual: thanks to a tip on proper color handling for Emacs, by
99 Eric J Haywiser <ejh1-AT-MIT.EDU>.
136 Eric J Haywiser <ejh1-AT-MIT.EDU>.
100
137
101 * ipython.el: close http://www.scipy.net/roundup/ipython/issue57
138 * ipython.el: close http://www.scipy.net/roundup/ipython/issue57
102 by applying the provided patch. Thanks to Liu Jin
139 by applying the provided patch. Thanks to Liu Jin
103 <m.liu.jin-AT-gmail.com> for the contribution. No problems under
140 <m.liu.jin-AT-gmail.com> for the contribution. No problems under
104 XEmacs/Linux, I'm trusting the submitter that it actually helps
141 XEmacs/Linux, I'm trusting the submitter that it actually helps
105 under win32/GNU Emacs. Will revisit if any problems are reported.
142 under win32/GNU Emacs. Will revisit if any problems are reported.
106
143
107 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
144 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
108
145
109 * IPython/Gnuplot2.py (_FileClass): update for current Gnuplot.py
146 * IPython/Gnuplot2.py (_FileClass): update for current Gnuplot.py
110 from SVN, thanks to a patch by Ryan Woodard <rywo@bas.ac.uk>.
147 from SVN, thanks to a patch by Ryan Woodard <rywo@bas.ac.uk>.
111
148
112 2006-03-12 Ville Vainio <vivainio@gmail.com>
149 2006-03-12 Ville Vainio <vivainio@gmail.com>
113
150
114 * Magic.py (magic_timeit): Added %timeit magic, contributed by
151 * Magic.py (magic_timeit): Added %timeit magic, contributed by
115 Torsten Marek.
152 Torsten Marek.
116
153
117 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
154 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
118
155
119 * IPython/Magic.py (magic_macro): fix so that the n1-n2 syntax for
156 * IPython/Magic.py (magic_macro): fix so that the n1-n2 syntax for
120 line ranges works again.
157 line ranges works again.
121
158
122 2006-03-11 Fernando Perez <Fernando.Perez@colorado.edu>
159 2006-03-11 Fernando Perez <Fernando.Perez@colorado.edu>
123
160
124 * IPython/iplib.py (showtraceback): add back sys.last_traceback
161 * IPython/iplib.py (showtraceback): add back sys.last_traceback
125 and friends, after a discussion with Zach Pincus on ipython-user.
162 and friends, after a discussion with Zach Pincus on ipython-user.
126 I'm not 100% sure, but after thinking aobut it quite a bit, it may
163 I'm not 100% sure, but after thinking aobut it quite a bit, it may
127 be OK. Testing with the multithreaded shells didn't reveal any
164 be OK. Testing with the multithreaded shells didn't reveal any
128 problems, but let's keep an eye out.
165 problems, but let's keep an eye out.
129
166
130 In the process, I fixed a few things which were calling
167 In the process, I fixed a few things which were calling
131 self.InteractiveTB() directly (like safe_execfile), which is a
168 self.InteractiveTB() directly (like safe_execfile), which is a
132 mistake: ALL exception reporting should be done by calling
169 mistake: ALL exception reporting should be done by calling
133 self.showtraceback(), which handles state and tab-completion and
170 self.showtraceback(), which handles state and tab-completion and
134 more.
171 more.
135
172
136 2006-03-01 Ville Vainio <vivainio@gmail.com>
173 2006-03-01 Ville Vainio <vivainio@gmail.com>
137
174
138 * Extensions/ipipe.py: Added Walter Doerwald's "ipipe" module.
175 * Extensions/ipipe.py: Added Walter Doerwald's "ipipe" module.
139 To use, do "from ipipe import *".
176 To use, do "from ipipe import *".
140
177
141 2006-02-24 Ville Vainio <vivainio@gmail.com>
178 2006-02-24 Ville Vainio <vivainio@gmail.com>
142
179
143 * Magic.py, upgrade_dir.py: %upgrade magic added. Does things more
180 * Magic.py, upgrade_dir.py: %upgrade magic added. Does things more
144 "cleanly" and safely than the older upgrade mechanism.
181 "cleanly" and safely than the older upgrade mechanism.
145
182
146 2006-02-21 Ville Vainio <vivainio@gmail.com>
183 2006-02-21 Ville Vainio <vivainio@gmail.com>
147
184
148 * Magic.py: %save works again.
185 * Magic.py: %save works again.
149
186
150 2006-02-15 Ville Vainio <vivainio@gmail.com>
187 2006-02-15 Ville Vainio <vivainio@gmail.com>
151
188
152 * Magic.py: %Pprint works again
189 * Magic.py: %Pprint works again
153
190
154 * Extensions/ipy_sane_defaults.py: Provide everything provided
191 * Extensions/ipy_sane_defaults.py: Provide everything provided
155 in default ipythonrc, to make it possible to have a completely empty
192 in default ipythonrc, to make it possible to have a completely empty
156 ipythonrc (and thus completely rc-file free configuration)
193 ipythonrc (and thus completely rc-file free configuration)
157
194
158
195
159 2006-02-11 Fernando Perez <Fernando.Perez@colorado.edu>
196 2006-02-11 Fernando Perez <Fernando.Perez@colorado.edu>
160
197
161 * IPython/hooks.py (editor): quote the call to the editor command,
198 * IPython/hooks.py (editor): quote the call to the editor command,
162 to allow commands with spaces in them. Problem noted by watching
199 to allow commands with spaces in them. Problem noted by watching
163 Ian Oswald's video about textpad under win32 at
200 Ian Oswald's video about textpad under win32 at
164 http://showmedo.com/videoListPage?listKey=PythonIPythonSeries
201 http://showmedo.com/videoListPage?listKey=PythonIPythonSeries
165
202
166 * IPython/UserConfig/ipythonrc: Replace @ signs with % when
203 * IPython/UserConfig/ipythonrc: Replace @ signs with % when
167 describing magics (we haven't used @ for a loong time).
204 describing magics (we haven't used @ for a loong time).
168
205
169 * IPython/ultraTB.py (VerboseTB.text.text_repr): Added patch
206 * IPython/ultraTB.py (VerboseTB.text.text_repr): Added patch
170 contributed by marienz to close
207 contributed by marienz to close
171 http://www.scipy.net/roundup/ipython/issue53.
208 http://www.scipy.net/roundup/ipython/issue53.
172
209
173 2006-02-10 Ville Vainio <vivainio@gmail.com>
210 2006-02-10 Ville Vainio <vivainio@gmail.com>
174
211
175 * genutils.py: getoutput now works in win32 too
212 * genutils.py: getoutput now works in win32 too
176
213
177 * completer.py: alias and magic completion only invoked
214 * completer.py: alias and magic completion only invoked
178 at the first "item" in the line, to avoid "cd %store"
215 at the first "item" in the line, to avoid "cd %store"
179 nonsense.
216 nonsense.
180
217
181 2006-02-09 Ville Vainio <vivainio@gmail.com>
218 2006-02-09 Ville Vainio <vivainio@gmail.com>
182
219
183 * test/*: Added a unit testing framework (finally).
220 * test/*: Added a unit testing framework (finally).
184 '%run runtests.py' to run test_*.
221 '%run runtests.py' to run test_*.
185
222
186 * ipapi.py: Exposed runlines and set_custom_exc
223 * ipapi.py: Exposed runlines and set_custom_exc
187
224
188 2006-02-07 Ville Vainio <vivainio@gmail.com>
225 2006-02-07 Ville Vainio <vivainio@gmail.com>
189
226
190 * iplib.py: don't split "f 1 2" to "f(1,2)" in autocall,
227 * iplib.py: don't split "f 1 2" to "f(1,2)" in autocall,
191 instead use "f(1 2)" as before.
228 instead use "f(1 2)" as before.
192
229
193 2006-02-05 Fernando Perez <Fernando.Perez@colorado.edu>
230 2006-02-05 Fernando Perez <Fernando.Perez@colorado.edu>
194
231
195 * IPython/demo.py (IPythonDemo): Add new classes to the demo
232 * IPython/demo.py (IPythonDemo): Add new classes to the demo
196 facilities, for demos processed by the IPython input filter
233 facilities, for demos processed by the IPython input filter
197 (IPythonDemo), and for running a script one-line-at-a-time as a
234 (IPythonDemo), and for running a script one-line-at-a-time as a
198 demo, both for pure Python (LineDemo) and for IPython-processed
235 demo, both for pure Python (LineDemo) and for IPython-processed
199 input (IPythonLineDemo). After a request by Dave Kohel, from the
236 input (IPythonLineDemo). After a request by Dave Kohel, from the
200 SAGE team.
237 SAGE team.
201 (Demo.edit): added and edit() method to the demo objects, to edit
238 (Demo.edit): added and edit() method to the demo objects, to edit
202 the in-memory copy of the last executed block.
239 the in-memory copy of the last executed block.
203
240
204 * IPython/Magic.py (magic_edit): add '-r' option for 'raw'
241 * IPython/Magic.py (magic_edit): add '-r' option for 'raw'
205 processing to %edit, %macro and %save. These commands can now be
242 processing to %edit, %macro and %save. These commands can now be
206 invoked on the unprocessed input as it was typed by the user
243 invoked on the unprocessed input as it was typed by the user
207 (without any prefilters applied). After requests by the SAGE team
244 (without any prefilters applied). After requests by the SAGE team
208 at SAGE days 2006: http://modular.ucsd.edu/sage/days1/schedule.html.
245 at SAGE days 2006: http://modular.ucsd.edu/sage/days1/schedule.html.
209
246
210 2006-02-01 Ville Vainio <vivainio@gmail.com>
247 2006-02-01 Ville Vainio <vivainio@gmail.com>
211
248
212 * setup.py, eggsetup.py: easy_install ipython==dev works
249 * setup.py, eggsetup.py: easy_install ipython==dev works
213 correctly now (on Linux)
250 correctly now (on Linux)
214
251
215 * ipy_user_conf,ipmaker: user config changes, removed spurious
252 * ipy_user_conf,ipmaker: user config changes, removed spurious
216 warnings
253 warnings
217
254
218 * iplib: if rc.banner is string, use it as is.
255 * iplib: if rc.banner is string, use it as is.
219
256
220 * Magic: %pycat accepts a string argument and pages it's contents.
257 * Magic: %pycat accepts a string argument and pages it's contents.
221
258
222
259
223 2006-01-30 Ville Vainio <vivainio@gmail.com>
260 2006-01-30 Ville Vainio <vivainio@gmail.com>
224
261
225 * pickleshare,pspersistence,ipapi,Magic: persistence overhaul.
262 * pickleshare,pspersistence,ipapi,Magic: persistence overhaul.
226 Now %store and bookmarks work through PickleShare, meaning that
263 Now %store and bookmarks work through PickleShare, meaning that
227 concurrent access is possible and all ipython sessions see the
264 concurrent access is possible and all ipython sessions see the
228 same database situation all the time, instead of snapshot of
265 same database situation all the time, instead of snapshot of
229 the situation when the session was started. Hence, %bookmark
266 the situation when the session was started. Hence, %bookmark
230 results are immediately accessible from othes sessions. The database
267 results are immediately accessible from othes sessions. The database
231 is also available for use by user extensions. See:
268 is also available for use by user extensions. See:
232 http://www.python.org/pypi/pickleshare
269 http://www.python.org/pypi/pickleshare
233
270
234 * hooks.py: Two new hooks, 'shutdown_hook' and 'late_startup_hook'.
271 * hooks.py: Two new hooks, 'shutdown_hook' and 'late_startup_hook'.
235
272
236 * aliases can now be %store'd
273 * aliases can now be %store'd
237
274
238 * path.py move to Extensions so that pickleshare does not need
275 * path.py move to Extensions so that pickleshare does not need
239 IPython-specific import. Extensions added to pythonpath right
276 IPython-specific import. Extensions added to pythonpath right
240 at __init__.
277 at __init__.
241
278
242 * iplib.py: ipalias deprecated/redundant; aliases are converted and
279 * iplib.py: ipalias deprecated/redundant; aliases are converted and
243 called with _ip.system and the pre-transformed command string.
280 called with _ip.system and the pre-transformed command string.
244
281
245 2006-01-29 Fernando Perez <Fernando.Perez@colorado.edu>
282 2006-01-29 Fernando Perez <Fernando.Perez@colorado.edu>
246
283
247 * IPython/iplib.py (interact): Fix that we were not catching
284 * IPython/iplib.py (interact): Fix that we were not catching
248 KeyboardInterrupt exceptions properly. I'm not quite sure why the
285 KeyboardInterrupt exceptions properly. I'm not quite sure why the
249 logic here had to change, but it's fixed now.
286 logic here had to change, but it's fixed now.
250
287
251 2006-01-29 Ville Vainio <vivainio@gmail.com>
288 2006-01-29 Ville Vainio <vivainio@gmail.com>
252
289
253 * iplib.py: Try to import pyreadline on Windows.
290 * iplib.py: Try to import pyreadline on Windows.
254
291
255 2006-01-27 Ville Vainio <vivainio@gmail.com>
292 2006-01-27 Ville Vainio <vivainio@gmail.com>
256
293
257 * iplib.py: Expose ipapi as _ip in builtin namespace.
294 * iplib.py: Expose ipapi as _ip in builtin namespace.
258 Makes ipmagic (-> _ip.magic), ipsystem (-> _ip.system)
295 Makes ipmagic (-> _ip.magic), ipsystem (-> _ip.system)
259 and ip_set_hook (-> _ip.set_hook) redundant. % and !
296 and ip_set_hook (-> _ip.set_hook) redundant. % and !
260 syntax now produce _ip.* variant of the commands.
297 syntax now produce _ip.* variant of the commands.
261
298
262 * "_ip.options().autoedit_syntax = 2" automatically throws
299 * "_ip.options().autoedit_syntax = 2" automatically throws
263 user to editor for syntax error correction without prompting.
300 user to editor for syntax error correction without prompting.
264
301
265 2006-01-27 Ville Vainio <vivainio@gmail.com>
302 2006-01-27 Ville Vainio <vivainio@gmail.com>
266
303
267 * ipmaker.py: Give "realistic" sys.argv for scripts (without
304 * ipmaker.py: Give "realistic" sys.argv for scripts (without
268 'ipython' at argv[0]) executed through command line.
305 'ipython' at argv[0]) executed through command line.
269 NOTE: this DEPRECATES calling ipython with multiple scripts
306 NOTE: this DEPRECATES calling ipython with multiple scripts
270 ("ipython a.py b.py c.py")
307 ("ipython a.py b.py c.py")
271
308
272 * iplib.py, hooks.py: Added configurable input prefilter,
309 * iplib.py, hooks.py: Added configurable input prefilter,
273 named 'input_prefilter'. See ext_rescapture.py for example
310 named 'input_prefilter'. See ext_rescapture.py for example
274 usage.
311 usage.
275
312
276 * ext_rescapture.py, Magic.py: Better system command output capture
313 * ext_rescapture.py, Magic.py: Better system command output capture
277 through 'var = !ls' (deprecates user-visible %sc). Same notation
314 through 'var = !ls' (deprecates user-visible %sc). Same notation
278 applies for magics, 'var = %alias' assigns alias list to var.
315 applies for magics, 'var = %alias' assigns alias list to var.
279
316
280 * ipapi.py: added meta() for accessing extension-usable data store.
317 * ipapi.py: added meta() for accessing extension-usable data store.
281
318
282 * iplib.py: added InteractiveShell.getapi(). New magics should be
319 * iplib.py: added InteractiveShell.getapi(). New magics should be
283 written doing self.getapi() instead of using the shell directly.
320 written doing self.getapi() instead of using the shell directly.
284
321
285 * Magic.py: %store now allows doing %store foo > ~/myfoo.txt and
322 * Magic.py: %store now allows doing %store foo > ~/myfoo.txt and
286 %store foo >> ~/myfoo.txt to store variables to files (in clean
323 %store foo >> ~/myfoo.txt to store variables to files (in clean
287 textual form, not a restorable pickle).
324 textual form, not a restorable pickle).
288
325
289 * ipmaker.py: now import ipy_profile_PROFILENAME automatically
326 * ipmaker.py: now import ipy_profile_PROFILENAME automatically
290
327
291 * usage.py, Magic.py: added %quickref
328 * usage.py, Magic.py: added %quickref
292
329
293 * iplib.py: ESC_PAREN fixes: /f 1 2 -> f(1,2), not f(1 2).
330 * iplib.py: ESC_PAREN fixes: /f 1 2 -> f(1,2), not f(1 2).
294
331
295 * GetoptErrors when invoking magics etc. with wrong args
332 * GetoptErrors when invoking magics etc. with wrong args
296 are now more helpful:
333 are now more helpful:
297 GetoptError: option -l not recognized (allowed: "qb" )
334 GetoptError: option -l not recognized (allowed: "qb" )
298
335
299 2006-01-25 Fernando Perez <Fernando.Perez@colorado.edu>
336 2006-01-25 Fernando Perez <Fernando.Perez@colorado.edu>
300
337
301 * IPython/demo.py (Demo.show): Flush stdout after each block, so
338 * IPython/demo.py (Demo.show): Flush stdout after each block, so
302 computationally intensive blocks don't appear to stall the demo.
339 computationally intensive blocks don't appear to stall the demo.
303
340
304 2006-01-24 Ville Vainio <vivainio@gmail.com>
341 2006-01-24 Ville Vainio <vivainio@gmail.com>
305
342
306 * iplib.py, hooks.py: 'result_display' hook can return a non-None
343 * iplib.py, hooks.py: 'result_display' hook can return a non-None
307 value to manipulate resulting history entry.
344 value to manipulate resulting history entry.
308
345
309 * ipapi.py: Moved TryNext here from hooks.py. Moved functions
346 * ipapi.py: Moved TryNext here from hooks.py. Moved functions
310 to instance methods of IPApi class, to make extending an embedded
347 to instance methods of IPApi class, to make extending an embedded
311 IPython feasible. See ext_rehashdir.py for example usage.
348 IPython feasible. See ext_rehashdir.py for example usage.
312
349
313 * Merged 1071-1076 from banches/0.7.1
350 * Merged 1071-1076 from banches/0.7.1
314
351
315
352
316 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
353 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
317
354
318 * tools/release (daystamp): Fix build tools to use the new
355 * tools/release (daystamp): Fix build tools to use the new
319 eggsetup.py script to build lightweight eggs.
356 eggsetup.py script to build lightweight eggs.
320
357
321 * Applied changesets 1062 and 1064 before 0.7.1 release.
358 * Applied changesets 1062 and 1064 before 0.7.1 release.
322
359
323 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
360 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
324 see the raw input history (without conversions like %ls ->
361 see the raw input history (without conversions like %ls ->
325 ipmagic("ls")). After a request from W. Stein, SAGE
362 ipmagic("ls")). After a request from W. Stein, SAGE
326 (http://modular.ucsd.edu/sage) developer. This information is
363 (http://modular.ucsd.edu/sage) developer. This information is
327 stored in the input_hist_raw attribute of the IPython instance, so
364 stored in the input_hist_raw attribute of the IPython instance, so
328 developers can access it if needed (it's an InputList instance).
365 developers can access it if needed (it's an InputList instance).
329
366
330 * Versionstring = 0.7.2.svn
367 * Versionstring = 0.7.2.svn
331
368
332 * eggsetup.py: A separate script for constructing eggs, creates
369 * eggsetup.py: A separate script for constructing eggs, creates
333 proper launch scripts even on Windows (an .exe file in
370 proper launch scripts even on Windows (an .exe file in
334 \python24\scripts).
371 \python24\scripts).
335
372
336 * ipapi.py: launch_new_instance, launch entry point needed for the
373 * ipapi.py: launch_new_instance, launch entry point needed for the
337 egg.
374 egg.
338
375
339 2006-01-23 Ville Vainio <vivainio@gmail.com>
376 2006-01-23 Ville Vainio <vivainio@gmail.com>
340
377
341 * Added %cpaste magic for pasting python code
378 * Added %cpaste magic for pasting python code
342
379
343 2006-01-22 Ville Vainio <vivainio@gmail.com>
380 2006-01-22 Ville Vainio <vivainio@gmail.com>
344
381
345 * Merge from branches/0.7.1 into trunk, revs 1052-1057
382 * Merge from branches/0.7.1 into trunk, revs 1052-1057
346
383
347 * Versionstring = 0.7.2.svn
384 * Versionstring = 0.7.2.svn
348
385
349 * eggsetup.py: A separate script for constructing eggs, creates
386 * eggsetup.py: A separate script for constructing eggs, creates
350 proper launch scripts even on Windows (an .exe file in
387 proper launch scripts even on Windows (an .exe file in
351 \python24\scripts).
388 \python24\scripts).
352
389
353 * ipapi.py: launch_new_instance, launch entry point needed for the
390 * ipapi.py: launch_new_instance, launch entry point needed for the
354 egg.
391 egg.
355
392
356 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
393 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
357
394
358 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
395 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
359 %pfile foo would print the file for foo even if it was a binary.
396 %pfile foo would print the file for foo even if it was a binary.
360 Now, extensions '.so' and '.dll' are skipped.
397 Now, extensions '.so' and '.dll' are skipped.
361
398
362 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
399 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
363 bug, where macros would fail in all threaded modes. I'm not 100%
400 bug, where macros would fail in all threaded modes. I'm not 100%
364 sure, so I'm going to put out an rc instead of making a release
401 sure, so I'm going to put out an rc instead of making a release
365 today, and wait for feedback for at least a few days.
402 today, and wait for feedback for at least a few days.
366
403
367 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
404 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
368 it...) the handling of pasting external code with autoindent on.
405 it...) the handling of pasting external code with autoindent on.
369 To get out of a multiline input, the rule will appear for most
406 To get out of a multiline input, the rule will appear for most
370 users unchanged: two blank lines or change the indent level
407 users unchanged: two blank lines or change the indent level
371 proposed by IPython. But there is a twist now: you can
408 proposed by IPython. But there is a twist now: you can
372 add/subtract only *one or two spaces*. If you add/subtract three
409 add/subtract only *one or two spaces*. If you add/subtract three
373 or more (unless you completely delete the line), IPython will
410 or more (unless you completely delete the line), IPython will
374 accept that line, and you'll need to enter a second one of pure
411 accept that line, and you'll need to enter a second one of pure
375 whitespace. I know it sounds complicated, but I can't find a
412 whitespace. I know it sounds complicated, but I can't find a
376 different solution that covers all the cases, with the right
413 different solution that covers all the cases, with the right
377 heuristics. Hopefully in actual use, nobody will really notice
414 heuristics. Hopefully in actual use, nobody will really notice
378 all these strange rules and things will 'just work'.
415 all these strange rules and things will 'just work'.
379
416
380 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
417 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
381
418
382 * IPython/iplib.py (interact): catch exceptions which can be
419 * IPython/iplib.py (interact): catch exceptions which can be
383 triggered asynchronously by signal handlers. Thanks to an
420 triggered asynchronously by signal handlers. Thanks to an
384 automatic crash report, submitted by Colin Kingsley
421 automatic crash report, submitted by Colin Kingsley
385 <tercel-AT-gentoo.org>.
422 <tercel-AT-gentoo.org>.
386
423
387 2006-01-20 Ville Vainio <vivainio@gmail.com>
424 2006-01-20 Ville Vainio <vivainio@gmail.com>
388
425
389 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
426 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
390 (%rehashdir, very useful, try it out) of how to extend ipython
427 (%rehashdir, very useful, try it out) of how to extend ipython
391 with new magics. Also added Extensions dir to pythonpath to make
428 with new magics. Also added Extensions dir to pythonpath to make
392 importing extensions easy.
429 importing extensions easy.
393
430
394 * %store now complains when trying to store interactively declared
431 * %store now complains when trying to store interactively declared
395 classes / instances of those classes.
432 classes / instances of those classes.
396
433
397 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
434 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
398 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
435 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
399 if they exist, and ipy_user_conf.py with some defaults is created for
436 if they exist, and ipy_user_conf.py with some defaults is created for
400 the user.
437 the user.
401
438
402 * Startup rehashing done by the config file, not InterpreterExec.
439 * Startup rehashing done by the config file, not InterpreterExec.
403 This means system commands are available even without selecting the
440 This means system commands are available even without selecting the
404 pysh profile. It's the sensible default after all.
441 pysh profile. It's the sensible default after all.
405
442
406 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
443 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
407
444
408 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
445 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
409 multiline code with autoindent on working. But I am really not
446 multiline code with autoindent on working. But I am really not
410 sure, so this needs more testing. Will commit a debug-enabled
447 sure, so this needs more testing. Will commit a debug-enabled
411 version for now, while I test it some more, so that Ville and
448 version for now, while I test it some more, so that Ville and
412 others may also catch any problems. Also made
449 others may also catch any problems. Also made
413 self.indent_current_str() a method, to ensure that there's no
450 self.indent_current_str() a method, to ensure that there's no
414 chance of the indent space count and the corresponding string
451 chance of the indent space count and the corresponding string
415 falling out of sync. All code needing the string should just call
452 falling out of sync. All code needing the string should just call
416 the method.
453 the method.
417
454
418 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
455 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
419
456
420 * IPython/Magic.py (magic_edit): fix check for when users don't
457 * IPython/Magic.py (magic_edit): fix check for when users don't
421 save their output files, the try/except was in the wrong section.
458 save their output files, the try/except was in the wrong section.
422
459
423 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
460 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
424
461
425 * IPython/Magic.py (magic_run): fix __file__ global missing from
462 * IPython/Magic.py (magic_run): fix __file__ global missing from
426 script's namespace when executed via %run. After a report by
463 script's namespace when executed via %run. After a report by
427 Vivian.
464 Vivian.
428
465
429 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
466 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
430 when using python 2.4. The parent constructor changed in 2.4, and
467 when using python 2.4. The parent constructor changed in 2.4, and
431 we need to track it directly (we can't call it, as it messes up
468 we need to track it directly (we can't call it, as it messes up
432 readline and tab-completion inside our pdb would stop working).
469 readline and tab-completion inside our pdb would stop working).
433 After a bug report by R. Bernstein <rocky-AT-panix.com>.
470 After a bug report by R. Bernstein <rocky-AT-panix.com>.
434
471
435 2006-01-16 Ville Vainio <vivainio@gmail.com>
472 2006-01-16 Ville Vainio <vivainio@gmail.com>
436
473
437 * Ipython/magic.py:Reverted back to old %edit functionality
474 * Ipython/magic.py:Reverted back to old %edit functionality
438 that returns file contents on exit.
475 that returns file contents on exit.
439
476
440 * IPython/path.py: Added Jason Orendorff's "path" module to
477 * IPython/path.py: Added Jason Orendorff's "path" module to
441 IPython tree, http://www.jorendorff.com/articles/python/path/.
478 IPython tree, http://www.jorendorff.com/articles/python/path/.
442 You can get path objects conveniently through %sc, and !!, e.g.:
479 You can get path objects conveniently through %sc, and !!, e.g.:
443 sc files=ls
480 sc files=ls
444 for p in files.paths: # or files.p
481 for p in files.paths: # or files.p
445 print p,p.mtime
482 print p,p.mtime
446
483
447 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
484 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
448 now work again without considering the exclusion regexp -
485 now work again without considering the exclusion regexp -
449 hence, things like ',foo my/path' turn to 'foo("my/path")'
486 hence, things like ',foo my/path' turn to 'foo("my/path")'
450 instead of syntax error.
487 instead of syntax error.
451
488
452
489
453 2006-01-14 Ville Vainio <vivainio@gmail.com>
490 2006-01-14 Ville Vainio <vivainio@gmail.com>
454
491
455 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
492 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
456 ipapi decorators for python 2.4 users, options() provides access to rc
493 ipapi decorators for python 2.4 users, options() provides access to rc
457 data.
494 data.
458
495
459 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
496 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
460 as path separators (even on Linux ;-). Space character after
497 as path separators (even on Linux ;-). Space character after
461 backslash (as yielded by tab completer) is still space;
498 backslash (as yielded by tab completer) is still space;
462 "%cd long\ name" works as expected.
499 "%cd long\ name" works as expected.
463
500
464 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
501 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
465 as "chain of command", with priority. API stays the same,
502 as "chain of command", with priority. API stays the same,
466 TryNext exception raised by a hook function signals that
503 TryNext exception raised by a hook function signals that
467 current hook failed and next hook should try handling it, as
504 current hook failed and next hook should try handling it, as
468 suggested by Walter DΓΆrwald <walter@livinglogic.de>. Walter also
505 suggested by Walter DΓΆrwald <walter@livinglogic.de>. Walter also
469 requested configurable display hook, which is now implemented.
506 requested configurable display hook, which is now implemented.
470
507
471 2006-01-13 Ville Vainio <vivainio@gmail.com>
508 2006-01-13 Ville Vainio <vivainio@gmail.com>
472
509
473 * IPython/platutils*.py: platform specific utility functions,
510 * IPython/platutils*.py: platform specific utility functions,
474 so far only set_term_title is implemented (change terminal
511 so far only set_term_title is implemented (change terminal
475 label in windowing systems). %cd now changes the title to
512 label in windowing systems). %cd now changes the title to
476 current dir.
513 current dir.
477
514
478 * IPython/Release.py: Added myself to "authors" list,
515 * IPython/Release.py: Added myself to "authors" list,
479 had to create new files.
516 had to create new files.
480
517
481 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
518 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
482 shell escape; not a known bug but had potential to be one in the
519 shell escape; not a known bug but had potential to be one in the
483 future.
520 future.
484
521
485 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
522 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
486 extension API for IPython! See the module for usage example. Fix
523 extension API for IPython! See the module for usage example. Fix
487 OInspect for docstring-less magic functions.
524 OInspect for docstring-less magic functions.
488
525
489
526
490 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
527 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
491
528
492 * IPython/iplib.py (raw_input): temporarily deactivate all
529 * IPython/iplib.py (raw_input): temporarily deactivate all
493 attempts at allowing pasting of code with autoindent on. It
530 attempts at allowing pasting of code with autoindent on. It
494 introduced bugs (reported by Prabhu) and I can't seem to find a
531 introduced bugs (reported by Prabhu) and I can't seem to find a
495 robust combination which works in all cases. Will have to revisit
532 robust combination which works in all cases. Will have to revisit
496 later.
533 later.
497
534
498 * IPython/genutils.py: remove isspace() function. We've dropped
535 * IPython/genutils.py: remove isspace() function. We've dropped
499 2.2 compatibility, so it's OK to use the string method.
536 2.2 compatibility, so it's OK to use the string method.
500
537
501 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
538 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
502
539
503 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
540 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
504 matching what NOT to autocall on, to include all python binary
541 matching what NOT to autocall on, to include all python binary
505 operators (including things like 'and', 'or', 'is' and 'in').
542 operators (including things like 'and', 'or', 'is' and 'in').
506 Prompted by a bug report on 'foo & bar', but I realized we had
543 Prompted by a bug report on 'foo & bar', but I realized we had
507 many more potential bug cases with other operators. The regexp is
544 many more potential bug cases with other operators. The regexp is
508 self.re_exclude_auto, it's fairly commented.
545 self.re_exclude_auto, it's fairly commented.
509
546
510 2006-01-12 Ville Vainio <vivainio@gmail.com>
547 2006-01-12 Ville Vainio <vivainio@gmail.com>
511
548
512 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
549 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
513 Prettified and hardened string/backslash quoting with ipsystem(),
550 Prettified and hardened string/backslash quoting with ipsystem(),
514 ipalias() and ipmagic(). Now even \ characters are passed to
551 ipalias() and ipmagic(). Now even \ characters are passed to
515 %magics, !shell escapes and aliases exactly as they are in the
552 %magics, !shell escapes and aliases exactly as they are in the
516 ipython command line. Should improve backslash experience,
553 ipython command line. Should improve backslash experience,
517 particularly in Windows (path delimiter for some commands that
554 particularly in Windows (path delimiter for some commands that
518 won't understand '/'), but Unix benefits as well (regexps). %cd
555 won't understand '/'), but Unix benefits as well (regexps). %cd
519 magic still doesn't support backslash path delimiters, though. Also
556 magic still doesn't support backslash path delimiters, though. Also
520 deleted all pretense of supporting multiline command strings in
557 deleted all pretense of supporting multiline command strings in
521 !system or %magic commands. Thanks to Jerry McRae for suggestions.
558 !system or %magic commands. Thanks to Jerry McRae for suggestions.
522
559
523 * doc/build_doc_instructions.txt added. Documentation on how to
560 * doc/build_doc_instructions.txt added. Documentation on how to
524 use doc/update_manual.py, added yesterday. Both files contributed
561 use doc/update_manual.py, added yesterday. Both files contributed
525 by JΓΆrgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
562 by JΓΆrgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
526 doc/*.sh for deprecation at a later date.
563 doc/*.sh for deprecation at a later date.
527
564
528 * /ipython.py Added ipython.py to root directory for
565 * /ipython.py Added ipython.py to root directory for
529 zero-installation (tar xzvf ipython.tgz; cd ipython; python
566 zero-installation (tar xzvf ipython.tgz; cd ipython; python
530 ipython.py) and development convenience (no need to kee doing
567 ipython.py) and development convenience (no need to kee doing
531 "setup.py install" between changes).
568 "setup.py install" between changes).
532
569
533 * Made ! and !! shell escapes work (again) in multiline expressions:
570 * Made ! and !! shell escapes work (again) in multiline expressions:
534 if 1:
571 if 1:
535 !ls
572 !ls
536 !!ls
573 !!ls
537
574
538 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
575 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
539
576
540 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
577 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
541 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
578 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
542 module in case-insensitive installation. Was causing crashes
579 module in case-insensitive installation. Was causing crashes
543 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
580 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
544
581
545 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
582 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
546 <marienz-AT-gentoo.org>, closes
583 <marienz-AT-gentoo.org>, closes
547 http://www.scipy.net/roundup/ipython/issue51.
584 http://www.scipy.net/roundup/ipython/issue51.
548
585
549 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
586 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
550
587
551 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
588 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
552 problem of excessive CPU usage under *nix and keyboard lag under
589 problem of excessive CPU usage under *nix and keyboard lag under
553 win32.
590 win32.
554
591
555 2006-01-10 *** Released version 0.7.0
592 2006-01-10 *** Released version 0.7.0
556
593
557 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
594 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
558
595
559 * IPython/Release.py (revision): tag version number to 0.7.0,
596 * IPython/Release.py (revision): tag version number to 0.7.0,
560 ready for release.
597 ready for release.
561
598
562 * IPython/Magic.py (magic_edit): Add print statement to %edit so
599 * IPython/Magic.py (magic_edit): Add print statement to %edit so
563 it informs the user of the name of the temp. file used. This can
600 it informs the user of the name of the temp. file used. This can
564 help if you decide later to reuse that same file, so you know
601 help if you decide later to reuse that same file, so you know
565 where to copy the info from.
602 where to copy the info from.
566
603
567 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
604 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
568
605
569 * setup_bdist_egg.py: little script to build an egg. Added
606 * setup_bdist_egg.py: little script to build an egg. Added
570 support in the release tools as well.
607 support in the release tools as well.
571
608
572 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
609 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
573
610
574 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
611 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
575 version selection (new -wxversion command line and ipythonrc
612 version selection (new -wxversion command line and ipythonrc
576 parameter). Patch contributed by Arnd Baecker
613 parameter). Patch contributed by Arnd Baecker
577 <arnd.baecker-AT-web.de>.
614 <arnd.baecker-AT-web.de>.
578
615
579 * IPython/iplib.py (embed_mainloop): fix tab-completion in
616 * IPython/iplib.py (embed_mainloop): fix tab-completion in
580 embedded instances, for variables defined at the interactive
617 embedded instances, for variables defined at the interactive
581 prompt of the embedded ipython. Reported by Arnd.
618 prompt of the embedded ipython. Reported by Arnd.
582
619
583 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
620 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
584 it can be used as a (stateful) toggle, or with a direct parameter.
621 it can be used as a (stateful) toggle, or with a direct parameter.
585
622
586 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
623 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
587 could be triggered in certain cases and cause the traceback
624 could be triggered in certain cases and cause the traceback
588 printer not to work.
625 printer not to work.
589
626
590 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
627 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
591
628
592 * IPython/iplib.py (_should_recompile): Small fix, closes
629 * IPython/iplib.py (_should_recompile): Small fix, closes
593 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
630 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
594
631
595 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
632 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
596
633
597 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
634 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
598 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
635 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
599 Moad for help with tracking it down.
636 Moad for help with tracking it down.
600
637
601 * IPython/iplib.py (handle_auto): fix autocall handling for
638 * IPython/iplib.py (handle_auto): fix autocall handling for
602 objects which support BOTH __getitem__ and __call__ (so that f [x]
639 objects which support BOTH __getitem__ and __call__ (so that f [x]
603 is left alone, instead of becoming f([x]) automatically).
640 is left alone, instead of becoming f([x]) automatically).
604
641
605 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
642 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
606 Ville's patch.
643 Ville's patch.
607
644
608 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
645 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
609
646
610 * IPython/iplib.py (handle_auto): changed autocall semantics to
647 * IPython/iplib.py (handle_auto): changed autocall semantics to
611 include 'smart' mode, where the autocall transformation is NOT
648 include 'smart' mode, where the autocall transformation is NOT
612 applied if there are no arguments on the line. This allows you to
649 applied if there are no arguments on the line. This allows you to
613 just type 'foo' if foo is a callable to see its internal form,
650 just type 'foo' if foo is a callable to see its internal form,
614 instead of having it called with no arguments (typically a
651 instead of having it called with no arguments (typically a
615 mistake). The old 'full' autocall still exists: for that, you
652 mistake). The old 'full' autocall still exists: for that, you
616 need to set the 'autocall' parameter to 2 in your ipythonrc file.
653 need to set the 'autocall' parameter to 2 in your ipythonrc file.
617
654
618 * IPython/completer.py (Completer.attr_matches): add
655 * IPython/completer.py (Completer.attr_matches): add
619 tab-completion support for Enthoughts' traits. After a report by
656 tab-completion support for Enthoughts' traits. After a report by
620 Arnd and a patch by Prabhu.
657 Arnd and a patch by Prabhu.
621
658
622 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
659 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
623
660
624 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
661 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
625 Schmolck's patch to fix inspect.getinnerframes().
662 Schmolck's patch to fix inspect.getinnerframes().
626
663
627 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
664 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
628 for embedded instances, regarding handling of namespaces and items
665 for embedded instances, regarding handling of namespaces and items
629 added to the __builtin__ one. Multiple embedded instances and
666 added to the __builtin__ one. Multiple embedded instances and
630 recursive embeddings should work better now (though I'm not sure
667 recursive embeddings should work better now (though I'm not sure
631 I've got all the corner cases fixed, that code is a bit of a brain
668 I've got all the corner cases fixed, that code is a bit of a brain
632 twister).
669 twister).
633
670
634 * IPython/Magic.py (magic_edit): added support to edit in-memory
671 * IPython/Magic.py (magic_edit): added support to edit in-memory
635 macros (automatically creates the necessary temp files). %edit
672 macros (automatically creates the necessary temp files). %edit
636 also doesn't return the file contents anymore, it's just noise.
673 also doesn't return the file contents anymore, it's just noise.
637
674
638 * IPython/completer.py (Completer.attr_matches): revert change to
675 * IPython/completer.py (Completer.attr_matches): revert change to
639 complete only on attributes listed in __all__. I realized it
676 complete only on attributes listed in __all__. I realized it
640 cripples the tab-completion system as a tool for exploring the
677 cripples the tab-completion system as a tool for exploring the
641 internals of unknown libraries (it renders any non-__all__
678 internals of unknown libraries (it renders any non-__all__
642 attribute off-limits). I got bit by this when trying to see
679 attribute off-limits). I got bit by this when trying to see
643 something inside the dis module.
680 something inside the dis module.
644
681
645 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
682 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
646
683
647 * IPython/iplib.py (InteractiveShell.__init__): add .meta
684 * IPython/iplib.py (InteractiveShell.__init__): add .meta
648 namespace for users and extension writers to hold data in. This
685 namespace for users and extension writers to hold data in. This
649 follows the discussion in
686 follows the discussion in
650 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
687 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
651
688
652 * IPython/completer.py (IPCompleter.complete): small patch to help
689 * IPython/completer.py (IPCompleter.complete): small patch to help
653 tab-completion under Emacs, after a suggestion by John Barnard
690 tab-completion under Emacs, after a suggestion by John Barnard
654 <barnarj-AT-ccf.org>.
691 <barnarj-AT-ccf.org>.
655
692
656 * IPython/Magic.py (Magic.extract_input_slices): added support for
693 * IPython/Magic.py (Magic.extract_input_slices): added support for
657 the slice notation in magics to use N-M to represent numbers N...M
694 the slice notation in magics to use N-M to represent numbers N...M
658 (closed endpoints). This is used by %macro and %save.
695 (closed endpoints). This is used by %macro and %save.
659
696
660 * IPython/completer.py (Completer.attr_matches): for modules which
697 * IPython/completer.py (Completer.attr_matches): for modules which
661 define __all__, complete only on those. After a patch by Jeffrey
698 define __all__, complete only on those. After a patch by Jeffrey
662 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
699 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
663 speed up this routine.
700 speed up this routine.
664
701
665 * IPython/Logger.py (Logger.log): fix a history handling bug. I
702 * IPython/Logger.py (Logger.log): fix a history handling bug. I
666 don't know if this is the end of it, but the behavior now is
703 don't know if this is the end of it, but the behavior now is
667 certainly much more correct. Note that coupled with macros,
704 certainly much more correct. Note that coupled with macros,
668 slightly surprising (at first) behavior may occur: a macro will in
705 slightly surprising (at first) behavior may occur: a macro will in
669 general expand to multiple lines of input, so upon exiting, the
706 general expand to multiple lines of input, so upon exiting, the
670 in/out counters will both be bumped by the corresponding amount
707 in/out counters will both be bumped by the corresponding amount
671 (as if the macro's contents had been typed interactively). Typing
708 (as if the macro's contents had been typed interactively). Typing
672 %hist will reveal the intermediate (silently processed) lines.
709 %hist will reveal the intermediate (silently processed) lines.
673
710
674 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
711 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
675 pickle to fail (%run was overwriting __main__ and not restoring
712 pickle to fail (%run was overwriting __main__ and not restoring
676 it, but pickle relies on __main__ to operate).
713 it, but pickle relies on __main__ to operate).
677
714
678 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
715 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
679 using properties, but forgot to make the main InteractiveShell
716 using properties, but forgot to make the main InteractiveShell
680 class a new-style class. Properties fail silently, and
717 class a new-style class. Properties fail silently, and
681 misteriously, with old-style class (getters work, but
718 misteriously, with old-style class (getters work, but
682 setters don't do anything).
719 setters don't do anything).
683
720
684 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
721 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
685
722
686 * IPython/Magic.py (magic_history): fix history reporting bug (I
723 * IPython/Magic.py (magic_history): fix history reporting bug (I
687 know some nasties are still there, I just can't seem to find a
724 know some nasties are still there, I just can't seem to find a
688 reproducible test case to track them down; the input history is
725 reproducible test case to track them down; the input history is
689 falling out of sync...)
726 falling out of sync...)
690
727
691 * IPython/iplib.py (handle_shell_escape): fix bug where both
728 * IPython/iplib.py (handle_shell_escape): fix bug where both
692 aliases and system accesses where broken for indented code (such
729 aliases and system accesses where broken for indented code (such
693 as loops).
730 as loops).
694
731
695 * IPython/genutils.py (shell): fix small but critical bug for
732 * IPython/genutils.py (shell): fix small but critical bug for
696 win32 system access.
733 win32 system access.
697
734
698 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
735 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
699
736
700 * IPython/iplib.py (showtraceback): remove use of the
737 * IPython/iplib.py (showtraceback): remove use of the
701 sys.last_{type/value/traceback} structures, which are non
738 sys.last_{type/value/traceback} structures, which are non
702 thread-safe.
739 thread-safe.
703 (_prefilter): change control flow to ensure that we NEVER
740 (_prefilter): change control flow to ensure that we NEVER
704 introspect objects when autocall is off. This will guarantee that
741 introspect objects when autocall is off. This will guarantee that
705 having an input line of the form 'x.y', where access to attribute
742 having an input line of the form 'x.y', where access to attribute
706 'y' has side effects, doesn't trigger the side effect TWICE. It
743 'y' has side effects, doesn't trigger the side effect TWICE. It
707 is important to note that, with autocall on, these side effects
744 is important to note that, with autocall on, these side effects
708 can still happen.
745 can still happen.
709 (ipsystem): new builtin, to complete the ip{magic/alias/system}
746 (ipsystem): new builtin, to complete the ip{magic/alias/system}
710 trio. IPython offers these three kinds of special calls which are
747 trio. IPython offers these three kinds of special calls which are
711 not python code, and it's a good thing to have their call method
748 not python code, and it's a good thing to have their call method
712 be accessible as pure python functions (not just special syntax at
749 be accessible as pure python functions (not just special syntax at
713 the command line). It gives us a better internal implementation
750 the command line). It gives us a better internal implementation
714 structure, as well as exposing these for user scripting more
751 structure, as well as exposing these for user scripting more
715 cleanly.
752 cleanly.
716
753
717 * IPython/macro.py (Macro.__init__): moved macros to a standalone
754 * IPython/macro.py (Macro.__init__): moved macros to a standalone
718 file. Now that they'll be more likely to be used with the
755 file. Now that they'll be more likely to be used with the
719 persistance system (%store), I want to make sure their module path
756 persistance system (%store), I want to make sure their module path
720 doesn't change in the future, so that we don't break things for
757 doesn't change in the future, so that we don't break things for
721 users' persisted data.
758 users' persisted data.
722
759
723 * IPython/iplib.py (autoindent_update): move indentation
760 * IPython/iplib.py (autoindent_update): move indentation
724 management into the _text_ processing loop, not the keyboard
761 management into the _text_ processing loop, not the keyboard
725 interactive one. This is necessary to correctly process non-typed
762 interactive one. This is necessary to correctly process non-typed
726 multiline input (such as macros).
763 multiline input (such as macros).
727
764
728 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
765 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
729 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
766 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
730 which was producing problems in the resulting manual.
767 which was producing problems in the resulting manual.
731 (magic_whos): improve reporting of instances (show their class,
768 (magic_whos): improve reporting of instances (show their class,
732 instead of simply printing 'instance' which isn't terribly
769 instead of simply printing 'instance' which isn't terribly
733 informative).
770 informative).
734
771
735 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
772 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
736 (minor mods) to support network shares under win32.
773 (minor mods) to support network shares under win32.
737
774
738 * IPython/winconsole.py (get_console_size): add new winconsole
775 * IPython/winconsole.py (get_console_size): add new winconsole
739 module and fixes to page_dumb() to improve its behavior under
776 module and fixes to page_dumb() to improve its behavior under
740 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
777 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
741
778
742 * IPython/Magic.py (Macro): simplified Macro class to just
779 * IPython/Magic.py (Macro): simplified Macro class to just
743 subclass list. We've had only 2.2 compatibility for a very long
780 subclass list. We've had only 2.2 compatibility for a very long
744 time, yet I was still avoiding subclassing the builtin types. No
781 time, yet I was still avoiding subclassing the builtin types. No
745 more (I'm also starting to use properties, though I won't shift to
782 more (I'm also starting to use properties, though I won't shift to
746 2.3-specific features quite yet).
783 2.3-specific features quite yet).
747 (magic_store): added Ville's patch for lightweight variable
784 (magic_store): added Ville's patch for lightweight variable
748 persistence, after a request on the user list by Matt Wilkie
785 persistence, after a request on the user list by Matt Wilkie
749 <maphew-AT-gmail.com>. The new %store magic's docstring has full
786 <maphew-AT-gmail.com>. The new %store magic's docstring has full
750 details.
787 details.
751
788
752 * IPython/iplib.py (InteractiveShell.post_config_initialization):
789 * IPython/iplib.py (InteractiveShell.post_config_initialization):
753 changed the default logfile name from 'ipython.log' to
790 changed the default logfile name from 'ipython.log' to
754 'ipython_log.py'. These logs are real python files, and now that
791 'ipython_log.py'. These logs are real python files, and now that
755 we have much better multiline support, people are more likely to
792 we have much better multiline support, people are more likely to
756 want to use them as such. Might as well name them correctly.
793 want to use them as such. Might as well name them correctly.
757
794
758 * IPython/Magic.py: substantial cleanup. While we can't stop
795 * IPython/Magic.py: substantial cleanup. While we can't stop
759 using magics as mixins, due to the existing customizations 'out
796 using magics as mixins, due to the existing customizations 'out
760 there' which rely on the mixin naming conventions, at least I
797 there' which rely on the mixin naming conventions, at least I
761 cleaned out all cross-class name usage. So once we are OK with
798 cleaned out all cross-class name usage. So once we are OK with
762 breaking compatibility, the two systems can be separated.
799 breaking compatibility, the two systems can be separated.
763
800
764 * IPython/Logger.py: major cleanup. This one is NOT a mixin
801 * IPython/Logger.py: major cleanup. This one is NOT a mixin
765 anymore, and the class is a fair bit less hideous as well. New
802 anymore, and the class is a fair bit less hideous as well. New
766 features were also introduced: timestamping of input, and logging
803 features were also introduced: timestamping of input, and logging
767 of output results. These are user-visible with the -t and -o
804 of output results. These are user-visible with the -t and -o
768 options to %logstart. Closes
805 options to %logstart. Closes
769 http://www.scipy.net/roundup/ipython/issue11 and a request by
806 http://www.scipy.net/roundup/ipython/issue11 and a request by
770 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
807 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
771
808
772 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
809 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
773
810
774 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
811 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
775 better hadnle backslashes in paths. See the thread 'More Windows
812 better hadnle backslashes in paths. See the thread 'More Windows
776 questions part 2 - \/ characters revisited' on the iypthon user
813 questions part 2 - \/ characters revisited' on the iypthon user
777 list:
814 list:
778 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
815 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
779
816
780 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
817 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
781
818
782 (InteractiveShell.__init__): change threaded shells to not use the
819 (InteractiveShell.__init__): change threaded shells to not use the
783 ipython crash handler. This was causing more problems than not,
820 ipython crash handler. This was causing more problems than not,
784 as exceptions in the main thread (GUI code, typically) would
821 as exceptions in the main thread (GUI code, typically) would
785 always show up as a 'crash', when they really weren't.
822 always show up as a 'crash', when they really weren't.
786
823
787 The colors and exception mode commands (%colors/%xmode) have been
824 The colors and exception mode commands (%colors/%xmode) have been
788 synchronized to also take this into account, so users can get
825 synchronized to also take this into account, so users can get
789 verbose exceptions for their threaded code as well. I also added
826 verbose exceptions for their threaded code as well. I also added
790 support for activating pdb inside this exception handler as well,
827 support for activating pdb inside this exception handler as well,
791 so now GUI authors can use IPython's enhanced pdb at runtime.
828 so now GUI authors can use IPython's enhanced pdb at runtime.
792
829
793 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
830 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
794 true by default, and add it to the shipped ipythonrc file. Since
831 true by default, and add it to the shipped ipythonrc file. Since
795 this asks the user before proceeding, I think it's OK to make it
832 this asks the user before proceeding, I think it's OK to make it
796 true by default.
833 true by default.
797
834
798 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
835 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
799 of the previous special-casing of input in the eval loop. I think
836 of the previous special-casing of input in the eval loop. I think
800 this is cleaner, as they really are commands and shouldn't have
837 this is cleaner, as they really are commands and shouldn't have
801 a special role in the middle of the core code.
838 a special role in the middle of the core code.
802
839
803 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
840 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
804
841
805 * IPython/iplib.py (edit_syntax_error): added support for
842 * IPython/iplib.py (edit_syntax_error): added support for
806 automatically reopening the editor if the file had a syntax error
843 automatically reopening the editor if the file had a syntax error
807 in it. Thanks to scottt who provided the patch at:
844 in it. Thanks to scottt who provided the patch at:
808 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
845 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
809 version committed).
846 version committed).
810
847
811 * IPython/iplib.py (handle_normal): add suport for multi-line
848 * IPython/iplib.py (handle_normal): add suport for multi-line
812 input with emtpy lines. This fixes
849 input with emtpy lines. This fixes
813 http://www.scipy.net/roundup/ipython/issue43 and a similar
850 http://www.scipy.net/roundup/ipython/issue43 and a similar
814 discussion on the user list.
851 discussion on the user list.
815
852
816 WARNING: a behavior change is necessarily introduced to support
853 WARNING: a behavior change is necessarily introduced to support
817 blank lines: now a single blank line with whitespace does NOT
854 blank lines: now a single blank line with whitespace does NOT
818 break the input loop, which means that when autoindent is on, by
855 break the input loop, which means that when autoindent is on, by
819 default hitting return on the next (indented) line does NOT exit.
856 default hitting return on the next (indented) line does NOT exit.
820
857
821 Instead, to exit a multiline input you can either have:
858 Instead, to exit a multiline input you can either have:
822
859
823 - TWO whitespace lines (just hit return again), or
860 - TWO whitespace lines (just hit return again), or
824 - a single whitespace line of a different length than provided
861 - a single whitespace line of a different length than provided
825 by the autoindent (add or remove a space).
862 by the autoindent (add or remove a space).
826
863
827 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
864 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
828 module to better organize all readline-related functionality.
865 module to better organize all readline-related functionality.
829 I've deleted FlexCompleter and put all completion clases here.
866 I've deleted FlexCompleter and put all completion clases here.
830
867
831 * IPython/iplib.py (raw_input): improve indentation management.
868 * IPython/iplib.py (raw_input): improve indentation management.
832 It is now possible to paste indented code with autoindent on, and
869 It is now possible to paste indented code with autoindent on, and
833 the code is interpreted correctly (though it still looks bad on
870 the code is interpreted correctly (though it still looks bad on
834 screen, due to the line-oriented nature of ipython).
871 screen, due to the line-oriented nature of ipython).
835 (MagicCompleter.complete): change behavior so that a TAB key on an
872 (MagicCompleter.complete): change behavior so that a TAB key on an
836 otherwise empty line actually inserts a tab, instead of completing
873 otherwise empty line actually inserts a tab, instead of completing
837 on the entire global namespace. This makes it easier to use the
874 on the entire global namespace. This makes it easier to use the
838 TAB key for indentation. After a request by Hans Meine
875 TAB key for indentation. After a request by Hans Meine
839 <hans_meine-AT-gmx.net>
876 <hans_meine-AT-gmx.net>
840 (_prefilter): add support so that typing plain 'exit' or 'quit'
877 (_prefilter): add support so that typing plain 'exit' or 'quit'
841 does a sensible thing. Originally I tried to deviate as little as
878 does a sensible thing. Originally I tried to deviate as little as
842 possible from the default python behavior, but even that one may
879 possible from the default python behavior, but even that one may
843 change in this direction (thread on python-dev to that effect).
880 change in this direction (thread on python-dev to that effect).
844 Regardless, ipython should do the right thing even if CPython's
881 Regardless, ipython should do the right thing even if CPython's
845 '>>>' prompt doesn't.
882 '>>>' prompt doesn't.
846 (InteractiveShell): removed subclassing code.InteractiveConsole
883 (InteractiveShell): removed subclassing code.InteractiveConsole
847 class. By now we'd overridden just about all of its methods: I've
884 class. By now we'd overridden just about all of its methods: I've
848 copied the remaining two over, and now ipython is a standalone
885 copied the remaining two over, and now ipython is a standalone
849 class. This will provide a clearer picture for the chainsaw
886 class. This will provide a clearer picture for the chainsaw
850 branch refactoring.
887 branch refactoring.
851
888
852 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
889 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
853
890
854 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
891 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
855 failures for objects which break when dir() is called on them.
892 failures for objects which break when dir() is called on them.
856
893
857 * IPython/FlexCompleter.py (Completer.__init__): Added support for
894 * IPython/FlexCompleter.py (Completer.__init__): Added support for
858 distinct local and global namespaces in the completer API. This
895 distinct local and global namespaces in the completer API. This
859 change allows us top properly handle completion with distinct
896 change allows us top properly handle completion with distinct
860 scopes, including in embedded instances (this had never really
897 scopes, including in embedded instances (this had never really
861 worked correctly).
898 worked correctly).
862
899
863 Note: this introduces a change in the constructor for
900 Note: this introduces a change in the constructor for
864 MagicCompleter, as a new global_namespace parameter is now the
901 MagicCompleter, as a new global_namespace parameter is now the
865 second argument (the others were bumped one position).
902 second argument (the others were bumped one position).
866
903
867 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
904 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
868
905
869 * IPython/iplib.py (embed_mainloop): fix tab-completion in
906 * IPython/iplib.py (embed_mainloop): fix tab-completion in
870 embedded instances (which can be done now thanks to Vivian's
907 embedded instances (which can be done now thanks to Vivian's
871 frame-handling fixes for pdb).
908 frame-handling fixes for pdb).
872 (InteractiveShell.__init__): Fix namespace handling problem in
909 (InteractiveShell.__init__): Fix namespace handling problem in
873 embedded instances. We were overwriting __main__ unconditionally,
910 embedded instances. We were overwriting __main__ unconditionally,
874 and this should only be done for 'full' (non-embedded) IPython;
911 and this should only be done for 'full' (non-embedded) IPython;
875 embedded instances must respect the caller's __main__. Thanks to
912 embedded instances must respect the caller's __main__. Thanks to
876 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
913 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
877
914
878 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
915 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
879
916
880 * setup.py: added download_url to setup(). This registers the
917 * setup.py: added download_url to setup(). This registers the
881 download address at PyPI, which is not only useful to humans
918 download address at PyPI, which is not only useful to humans
882 browsing the site, but is also picked up by setuptools (the Eggs
919 browsing the site, but is also picked up by setuptools (the Eggs
883 machinery). Thanks to Ville and R. Kern for the info/discussion
920 machinery). Thanks to Ville and R. Kern for the info/discussion
884 on this.
921 on this.
885
922
886 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
923 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
887
924
888 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
925 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
889 This brings a lot of nice functionality to the pdb mode, which now
926 This brings a lot of nice functionality to the pdb mode, which now
890 has tab-completion, syntax highlighting, and better stack handling
927 has tab-completion, syntax highlighting, and better stack handling
891 than before. Many thanks to Vivian De Smedt
928 than before. Many thanks to Vivian De Smedt
892 <vivian-AT-vdesmedt.com> for the original patches.
929 <vivian-AT-vdesmedt.com> for the original patches.
893
930
894 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
931 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
895
932
896 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
933 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
897 sequence to consistently accept the banner argument. The
934 sequence to consistently accept the banner argument. The
898 inconsistency was tripping SAGE, thanks to Gary Zablackis
935 inconsistency was tripping SAGE, thanks to Gary Zablackis
899 <gzabl-AT-yahoo.com> for the report.
936 <gzabl-AT-yahoo.com> for the report.
900
937
901 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
938 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
902
939
903 * IPython/iplib.py (InteractiveShell.post_config_initialization):
940 * IPython/iplib.py (InteractiveShell.post_config_initialization):
904 Fix bug where a naked 'alias' call in the ipythonrc file would
941 Fix bug where a naked 'alias' call in the ipythonrc file would
905 cause a crash. Bug reported by Jorgen Stenarson.
942 cause a crash. Bug reported by Jorgen Stenarson.
906
943
907 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
944 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
908
945
909 * IPython/ipmaker.py (make_IPython): cleanups which should improve
946 * IPython/ipmaker.py (make_IPython): cleanups which should improve
910 startup time.
947 startup time.
911
948
912 * IPython/iplib.py (runcode): my globals 'fix' for embedded
949 * IPython/iplib.py (runcode): my globals 'fix' for embedded
913 instances had introduced a bug with globals in normal code. Now
950 instances had introduced a bug with globals in normal code. Now
914 it's working in all cases.
951 it's working in all cases.
915
952
916 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
953 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
917 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
954 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
918 has been introduced to set the default case sensitivity of the
955 has been introduced to set the default case sensitivity of the
919 searches. Users can still select either mode at runtime on a
956 searches. Users can still select either mode at runtime on a
920 per-search basis.
957 per-search basis.
921
958
922 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
959 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
923
960
924 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
961 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
925 attributes in wildcard searches for subclasses. Modified version
962 attributes in wildcard searches for subclasses. Modified version
926 of a patch by Jorgen.
963 of a patch by Jorgen.
927
964
928 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
965 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
929
966
930 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
967 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
931 embedded instances. I added a user_global_ns attribute to the
968 embedded instances. I added a user_global_ns attribute to the
932 InteractiveShell class to handle this.
969 InteractiveShell class to handle this.
933
970
934 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
971 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
935
972
936 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
973 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
937 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
974 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
938 (reported under win32, but may happen also in other platforms).
975 (reported under win32, but may happen also in other platforms).
939 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
976 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
940
977
941 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
978 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
942
979
943 * IPython/Magic.py (magic_psearch): new support for wildcard
980 * IPython/Magic.py (magic_psearch): new support for wildcard
944 patterns. Now, typing ?a*b will list all names which begin with a
981 patterns. Now, typing ?a*b will list all names which begin with a
945 and end in b, for example. The %psearch magic has full
982 and end in b, for example. The %psearch magic has full
946 docstrings. Many thanks to JΓΆrgen Stenarson
983 docstrings. Many thanks to JΓΆrgen Stenarson
947 <jorgen.stenarson-AT-bostream.nu>, author of the patches
984 <jorgen.stenarson-AT-bostream.nu>, author of the patches
948 implementing this functionality.
985 implementing this functionality.
949
986
950 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
987 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
951
988
952 * Manual: fixed long-standing annoyance of double-dashes (as in
989 * Manual: fixed long-standing annoyance of double-dashes (as in
953 --prefix=~, for example) being stripped in the HTML version. This
990 --prefix=~, for example) being stripped in the HTML version. This
954 is a latex2html bug, but a workaround was provided. Many thanks
991 is a latex2html bug, but a workaround was provided. Many thanks
955 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
992 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
956 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
993 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
957 rolling. This seemingly small issue had tripped a number of users
994 rolling. This seemingly small issue had tripped a number of users
958 when first installing, so I'm glad to see it gone.
995 when first installing, so I'm glad to see it gone.
959
996
960 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
997 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
961
998
962 * IPython/Extensions/numeric_formats.py: fix missing import,
999 * IPython/Extensions/numeric_formats.py: fix missing import,
963 reported by Stephen Walton.
1000 reported by Stephen Walton.
964
1001
965 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
1002 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
966
1003
967 * IPython/demo.py: finish demo module, fully documented now.
1004 * IPython/demo.py: finish demo module, fully documented now.
968
1005
969 * IPython/genutils.py (file_read): simple little utility to read a
1006 * IPython/genutils.py (file_read): simple little utility to read a
970 file and ensure it's closed afterwards.
1007 file and ensure it's closed afterwards.
971
1008
972 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
1009 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
973
1010
974 * IPython/demo.py (Demo.__init__): added support for individually
1011 * IPython/demo.py (Demo.__init__): added support for individually
975 tagging blocks for automatic execution.
1012 tagging blocks for automatic execution.
976
1013
977 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
1014 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
978 syntax-highlighted python sources, requested by John.
1015 syntax-highlighted python sources, requested by John.
979
1016
980 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
1017 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
981
1018
982 * IPython/demo.py (Demo.again): fix bug where again() blocks after
1019 * IPython/demo.py (Demo.again): fix bug where again() blocks after
983 finishing.
1020 finishing.
984
1021
985 * IPython/genutils.py (shlex_split): moved from Magic to here,
1022 * IPython/genutils.py (shlex_split): moved from Magic to here,
986 where all 2.2 compatibility stuff lives. I needed it for demo.py.
1023 where all 2.2 compatibility stuff lives. I needed it for demo.py.
987
1024
988 * IPython/demo.py (Demo.__init__): added support for silent
1025 * IPython/demo.py (Demo.__init__): added support for silent
989 blocks, improved marks as regexps, docstrings written.
1026 blocks, improved marks as regexps, docstrings written.
990 (Demo.__init__): better docstring, added support for sys.argv.
1027 (Demo.__init__): better docstring, added support for sys.argv.
991
1028
992 * IPython/genutils.py (marquee): little utility used by the demo
1029 * IPython/genutils.py (marquee): little utility used by the demo
993 code, handy in general.
1030 code, handy in general.
994
1031
995 * IPython/demo.py (Demo.__init__): new class for interactive
1032 * IPython/demo.py (Demo.__init__): new class for interactive
996 demos. Not documented yet, I just wrote it in a hurry for
1033 demos. Not documented yet, I just wrote it in a hurry for
997 scipy'05. Will docstring later.
1034 scipy'05. Will docstring later.
998
1035
999 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
1036 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
1000
1037
1001 * IPython/Shell.py (sigint_handler): Drastic simplification which
1038 * IPython/Shell.py (sigint_handler): Drastic simplification which
1002 also seems to make Ctrl-C work correctly across threads! This is
1039 also seems to make Ctrl-C work correctly across threads! This is
1003 so simple, that I can't beleive I'd missed it before. Needs more
1040 so simple, that I can't beleive I'd missed it before. Needs more
1004 testing, though.
1041 testing, though.
1005 (KBINT): Never mind, revert changes. I'm sure I'd tried something
1042 (KBINT): Never mind, revert changes. I'm sure I'd tried something
1006 like this before...
1043 like this before...
1007
1044
1008 * IPython/genutils.py (get_home_dir): add protection against
1045 * IPython/genutils.py (get_home_dir): add protection against
1009 non-dirs in win32 registry.
1046 non-dirs in win32 registry.
1010
1047
1011 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
1048 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
1012 bug where dict was mutated while iterating (pysh crash).
1049 bug where dict was mutated while iterating (pysh crash).
1013
1050
1014 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
1051 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
1015
1052
1016 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
1053 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
1017 spurious newlines added by this routine. After a report by
1054 spurious newlines added by this routine. After a report by
1018 F. Mantegazza.
1055 F. Mantegazza.
1019
1056
1020 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
1057 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
1021
1058
1022 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
1059 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
1023 calls. These were a leftover from the GTK 1.x days, and can cause
1060 calls. These were a leftover from the GTK 1.x days, and can cause
1024 problems in certain cases (after a report by John Hunter).
1061 problems in certain cases (after a report by John Hunter).
1025
1062
1026 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
1063 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
1027 os.getcwd() fails at init time. Thanks to patch from David Remahl
1064 os.getcwd() fails at init time. Thanks to patch from David Remahl
1028 <chmod007-AT-mac.com>.
1065 <chmod007-AT-mac.com>.
1029 (InteractiveShell.__init__): prevent certain special magics from
1066 (InteractiveShell.__init__): prevent certain special magics from
1030 being shadowed by aliases. Closes
1067 being shadowed by aliases. Closes
1031 http://www.scipy.net/roundup/ipython/issue41.
1068 http://www.scipy.net/roundup/ipython/issue41.
1032
1069
1033 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
1070 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
1034
1071
1035 * IPython/iplib.py (InteractiveShell.complete): Added new
1072 * IPython/iplib.py (InteractiveShell.complete): Added new
1036 top-level completion method to expose the completion mechanism
1073 top-level completion method to expose the completion mechanism
1037 beyond readline-based environments.
1074 beyond readline-based environments.
1038
1075
1039 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
1076 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
1040
1077
1041 * tools/ipsvnc (svnversion): fix svnversion capture.
1078 * tools/ipsvnc (svnversion): fix svnversion capture.
1042
1079
1043 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
1080 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
1044 attribute to self, which was missing. Before, it was set by a
1081 attribute to self, which was missing. Before, it was set by a
1045 routine which in certain cases wasn't being called, so the
1082 routine which in certain cases wasn't being called, so the
1046 instance could end up missing the attribute. This caused a crash.
1083 instance could end up missing the attribute. This caused a crash.
1047 Closes http://www.scipy.net/roundup/ipython/issue40.
1084 Closes http://www.scipy.net/roundup/ipython/issue40.
1048
1085
1049 2005-08-16 Fernando Perez <fperez@colorado.edu>
1086 2005-08-16 Fernando Perez <fperez@colorado.edu>
1050
1087
1051 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
1088 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
1052 contains non-string attribute. Closes
1089 contains non-string attribute. Closes
1053 http://www.scipy.net/roundup/ipython/issue38.
1090 http://www.scipy.net/roundup/ipython/issue38.
1054
1091
1055 2005-08-14 Fernando Perez <fperez@colorado.edu>
1092 2005-08-14 Fernando Perez <fperez@colorado.edu>
1056
1093
1057 * tools/ipsvnc: Minor improvements, to add changeset info.
1094 * tools/ipsvnc: Minor improvements, to add changeset info.
1058
1095
1059 2005-08-12 Fernando Perez <fperez@colorado.edu>
1096 2005-08-12 Fernando Perez <fperez@colorado.edu>
1060
1097
1061 * IPython/iplib.py (runsource): remove self.code_to_run_src
1098 * IPython/iplib.py (runsource): remove self.code_to_run_src
1062 attribute. I realized this is nothing more than
1099 attribute. I realized this is nothing more than
1063 '\n'.join(self.buffer), and having the same data in two different
1100 '\n'.join(self.buffer), and having the same data in two different
1064 places is just asking for synchronization bugs. This may impact
1101 places is just asking for synchronization bugs. This may impact
1065 people who have custom exception handlers, so I need to warn
1102 people who have custom exception handlers, so I need to warn
1066 ipython-dev about it (F. Mantegazza may use them).
1103 ipython-dev about it (F. Mantegazza may use them).
1067
1104
1068 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
1105 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
1069
1106
1070 * IPython/genutils.py: fix 2.2 compatibility (generators)
1107 * IPython/genutils.py: fix 2.2 compatibility (generators)
1071
1108
1072 2005-07-18 Fernando Perez <fperez@colorado.edu>
1109 2005-07-18 Fernando Perez <fperez@colorado.edu>
1073
1110
1074 * IPython/genutils.py (get_home_dir): fix to help users with
1111 * IPython/genutils.py (get_home_dir): fix to help users with
1075 invalid $HOME under win32.
1112 invalid $HOME under win32.
1076
1113
1077 2005-07-17 Fernando Perez <fperez@colorado.edu>
1114 2005-07-17 Fernando Perez <fperez@colorado.edu>
1078
1115
1079 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
1116 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
1080 some old hacks and clean up a bit other routines; code should be
1117 some old hacks and clean up a bit other routines; code should be
1081 simpler and a bit faster.
1118 simpler and a bit faster.
1082
1119
1083 * IPython/iplib.py (interact): removed some last-resort attempts
1120 * IPython/iplib.py (interact): removed some last-resort attempts
1084 to survive broken stdout/stderr. That code was only making it
1121 to survive broken stdout/stderr. That code was only making it
1085 harder to abstract out the i/o (necessary for gui integration),
1122 harder to abstract out the i/o (necessary for gui integration),
1086 and the crashes it could prevent were extremely rare in practice
1123 and the crashes it could prevent were extremely rare in practice
1087 (besides being fully user-induced in a pretty violent manner).
1124 (besides being fully user-induced in a pretty violent manner).
1088
1125
1089 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
1126 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
1090 Nothing major yet, but the code is simpler to read; this should
1127 Nothing major yet, but the code is simpler to read; this should
1091 make it easier to do more serious modifications in the future.
1128 make it easier to do more serious modifications in the future.
1092
1129
1093 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
1130 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
1094 which broke in .15 (thanks to a report by Ville).
1131 which broke in .15 (thanks to a report by Ville).
1095
1132
1096 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
1133 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
1097 be quite correct, I know next to nothing about unicode). This
1134 be quite correct, I know next to nothing about unicode). This
1098 will allow unicode strings to be used in prompts, amongst other
1135 will allow unicode strings to be used in prompts, amongst other
1099 cases. It also will prevent ipython from crashing when unicode
1136 cases. It also will prevent ipython from crashing when unicode
1100 shows up unexpectedly in many places. If ascii encoding fails, we
1137 shows up unexpectedly in many places. If ascii encoding fails, we
1101 assume utf_8. Currently the encoding is not a user-visible
1138 assume utf_8. Currently the encoding is not a user-visible
1102 setting, though it could be made so if there is demand for it.
1139 setting, though it could be made so if there is demand for it.
1103
1140
1104 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
1141 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
1105
1142
1106 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
1143 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
1107
1144
1108 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
1145 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
1109
1146
1110 * IPython/genutils.py: Add 2.2 compatibility here, so all other
1147 * IPython/genutils.py: Add 2.2 compatibility here, so all other
1111 code can work transparently for 2.2/2.3.
1148 code can work transparently for 2.2/2.3.
1112
1149
1113 2005-07-16 Fernando Perez <fperez@colorado.edu>
1150 2005-07-16 Fernando Perez <fperez@colorado.edu>
1114
1151
1115 * IPython/ultraTB.py (ExceptionColors): Make a global variable
1152 * IPython/ultraTB.py (ExceptionColors): Make a global variable
1116 out of the color scheme table used for coloring exception
1153 out of the color scheme table used for coloring exception
1117 tracebacks. This allows user code to add new schemes at runtime.
1154 tracebacks. This allows user code to add new schemes at runtime.
1118 This is a minimally modified version of the patch at
1155 This is a minimally modified version of the patch at
1119 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
1156 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
1120 for the contribution.
1157 for the contribution.
1121
1158
1122 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
1159 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
1123 slightly modified version of the patch in
1160 slightly modified version of the patch in
1124 http://www.scipy.net/roundup/ipython/issue34, which also allows me
1161 http://www.scipy.net/roundup/ipython/issue34, which also allows me
1125 to remove the previous try/except solution (which was costlier).
1162 to remove the previous try/except solution (which was costlier).
1126 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
1163 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
1127
1164
1128 2005-06-08 Fernando Perez <fperez@colorado.edu>
1165 2005-06-08 Fernando Perez <fperez@colorado.edu>
1129
1166
1130 * IPython/iplib.py (write/write_err): Add methods to abstract all
1167 * IPython/iplib.py (write/write_err): Add methods to abstract all
1131 I/O a bit more.
1168 I/O a bit more.
1132
1169
1133 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
1170 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
1134 warning, reported by Aric Hagberg, fix by JD Hunter.
1171 warning, reported by Aric Hagberg, fix by JD Hunter.
1135
1172
1136 2005-06-02 *** Released version 0.6.15
1173 2005-06-02 *** Released version 0.6.15
1137
1174
1138 2005-06-01 Fernando Perez <fperez@colorado.edu>
1175 2005-06-01 Fernando Perez <fperez@colorado.edu>
1139
1176
1140 * IPython/iplib.py (MagicCompleter.file_matches): Fix
1177 * IPython/iplib.py (MagicCompleter.file_matches): Fix
1141 tab-completion of filenames within open-quoted strings. Note that
1178 tab-completion of filenames within open-quoted strings. Note that
1142 this requires that in ~/.ipython/ipythonrc, users change the
1179 this requires that in ~/.ipython/ipythonrc, users change the
1143 readline delimiters configuration to read:
1180 readline delimiters configuration to read:
1144
1181
1145 readline_remove_delims -/~
1182 readline_remove_delims -/~
1146
1183
1147
1184
1148 2005-05-31 *** Released version 0.6.14
1185 2005-05-31 *** Released version 0.6.14
1149
1186
1150 2005-05-29 Fernando Perez <fperez@colorado.edu>
1187 2005-05-29 Fernando Perez <fperez@colorado.edu>
1151
1188
1152 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
1189 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
1153 with files not on the filesystem. Reported by Eliyahu Sandler
1190 with files not on the filesystem. Reported by Eliyahu Sandler
1154 <eli@gondolin.net>
1191 <eli@gondolin.net>
1155
1192
1156 2005-05-22 Fernando Perez <fperez@colorado.edu>
1193 2005-05-22 Fernando Perez <fperez@colorado.edu>
1157
1194
1158 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
1195 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
1159 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
1196 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
1160
1197
1161 2005-05-19 Fernando Perez <fperez@colorado.edu>
1198 2005-05-19 Fernando Perez <fperez@colorado.edu>
1162
1199
1163 * IPython/iplib.py (safe_execfile): close a file which could be
1200 * IPython/iplib.py (safe_execfile): close a file which could be
1164 left open (causing problems in win32, which locks open files).
1201 left open (causing problems in win32, which locks open files).
1165 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
1202 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
1166
1203
1167 2005-05-18 Fernando Perez <fperez@colorado.edu>
1204 2005-05-18 Fernando Perez <fperez@colorado.edu>
1168
1205
1169 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
1206 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
1170 keyword arguments correctly to safe_execfile().
1207 keyword arguments correctly to safe_execfile().
1171
1208
1172 2005-05-13 Fernando Perez <fperez@colorado.edu>
1209 2005-05-13 Fernando Perez <fperez@colorado.edu>
1173
1210
1174 * ipython.1: Added info about Qt to manpage, and threads warning
1211 * ipython.1: Added info about Qt to manpage, and threads warning
1175 to usage page (invoked with --help).
1212 to usage page (invoked with --help).
1176
1213
1177 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
1214 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
1178 new matcher (it goes at the end of the priority list) to do
1215 new matcher (it goes at the end of the priority list) to do
1179 tab-completion on named function arguments. Submitted by George
1216 tab-completion on named function arguments. Submitted by George
1180 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
1217 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
1181 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
1218 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
1182 for more details.
1219 for more details.
1183
1220
1184 * IPython/Magic.py (magic_run): Added new -e flag to ignore
1221 * IPython/Magic.py (magic_run): Added new -e flag to ignore
1185 SystemExit exceptions in the script being run. Thanks to a report
1222 SystemExit exceptions in the script being run. Thanks to a report
1186 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
1223 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
1187 producing very annoying behavior when running unit tests.
1224 producing very annoying behavior when running unit tests.
1188
1225
1189 2005-05-12 Fernando Perez <fperez@colorado.edu>
1226 2005-05-12 Fernando Perez <fperez@colorado.edu>
1190
1227
1191 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
1228 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
1192 which I'd broken (again) due to a changed regexp. In the process,
1229 which I'd broken (again) due to a changed regexp. In the process,
1193 added ';' as an escape to auto-quote the whole line without
1230 added ';' as an escape to auto-quote the whole line without
1194 splitting its arguments. Thanks to a report by Jerry McRae
1231 splitting its arguments. Thanks to a report by Jerry McRae
1195 <qrs0xyc02-AT-sneakemail.com>.
1232 <qrs0xyc02-AT-sneakemail.com>.
1196
1233
1197 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
1234 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
1198 possible crashes caused by a TokenError. Reported by Ed Schofield
1235 possible crashes caused by a TokenError. Reported by Ed Schofield
1199 <schofield-AT-ftw.at>.
1236 <schofield-AT-ftw.at>.
1200
1237
1201 2005-05-06 Fernando Perez <fperez@colorado.edu>
1238 2005-05-06 Fernando Perez <fperez@colorado.edu>
1202
1239
1203 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
1240 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
1204
1241
1205 2005-04-29 Fernando Perez <fperez@colorado.edu>
1242 2005-04-29 Fernando Perez <fperez@colorado.edu>
1206
1243
1207 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
1244 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
1208 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
1245 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
1209 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
1246 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
1210 which provides support for Qt interactive usage (similar to the
1247 which provides support for Qt interactive usage (similar to the
1211 existing one for WX and GTK). This had been often requested.
1248 existing one for WX and GTK). This had been often requested.
1212
1249
1213 2005-04-14 *** Released version 0.6.13
1250 2005-04-14 *** Released version 0.6.13
1214
1251
1215 2005-04-08 Fernando Perez <fperez@colorado.edu>
1252 2005-04-08 Fernando Perez <fperez@colorado.edu>
1216
1253
1217 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
1254 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
1218 from _ofind, which gets called on almost every input line. Now,
1255 from _ofind, which gets called on almost every input line. Now,
1219 we only try to get docstrings if they are actually going to be
1256 we only try to get docstrings if they are actually going to be
1220 used (the overhead of fetching unnecessary docstrings can be
1257 used (the overhead of fetching unnecessary docstrings can be
1221 noticeable for certain objects, such as Pyro proxies).
1258 noticeable for certain objects, such as Pyro proxies).
1222
1259
1223 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
1260 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
1224 for completers. For some reason I had been passing them the state
1261 for completers. For some reason I had been passing them the state
1225 variable, which completers never actually need, and was in
1262 variable, which completers never actually need, and was in
1226 conflict with the rlcompleter API. Custom completers ONLY need to
1263 conflict with the rlcompleter API. Custom completers ONLY need to
1227 take the text parameter.
1264 take the text parameter.
1228
1265
1229 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
1266 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
1230 work correctly in pysh. I've also moved all the logic which used
1267 work correctly in pysh. I've also moved all the logic which used
1231 to be in pysh.py here, which will prevent problems with future
1268 to be in pysh.py here, which will prevent problems with future
1232 upgrades. However, this time I must warn users to update their
1269 upgrades. However, this time I must warn users to update their
1233 pysh profile to include the line
1270 pysh profile to include the line
1234
1271
1235 import_all IPython.Extensions.InterpreterExec
1272 import_all IPython.Extensions.InterpreterExec
1236
1273
1237 because otherwise things won't work for them. They MUST also
1274 because otherwise things won't work for them. They MUST also
1238 delete pysh.py and the line
1275 delete pysh.py and the line
1239
1276
1240 execfile pysh.py
1277 execfile pysh.py
1241
1278
1242 from their ipythonrc-pysh.
1279 from their ipythonrc-pysh.
1243
1280
1244 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
1281 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
1245 robust in the face of objects whose dir() returns non-strings
1282 robust in the face of objects whose dir() returns non-strings
1246 (which it shouldn't, but some broken libs like ITK do). Thanks to
1283 (which it shouldn't, but some broken libs like ITK do). Thanks to
1247 a patch by John Hunter (implemented differently, though). Also
1284 a patch by John Hunter (implemented differently, though). Also
1248 minor improvements by using .extend instead of + on lists.
1285 minor improvements by using .extend instead of + on lists.
1249
1286
1250 * pysh.py:
1287 * pysh.py:
1251
1288
1252 2005-04-06 Fernando Perez <fperez@colorado.edu>
1289 2005-04-06 Fernando Perez <fperez@colorado.edu>
1253
1290
1254 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
1291 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
1255 by default, so that all users benefit from it. Those who don't
1292 by default, so that all users benefit from it. Those who don't
1256 want it can still turn it off.
1293 want it can still turn it off.
1257
1294
1258 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
1295 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
1259 config file, I'd forgotten about this, so users were getting it
1296 config file, I'd forgotten about this, so users were getting it
1260 off by default.
1297 off by default.
1261
1298
1262 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
1299 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
1263 consistency. Now magics can be called in multiline statements,
1300 consistency. Now magics can be called in multiline statements,
1264 and python variables can be expanded in magic calls via $var.
1301 and python variables can be expanded in magic calls via $var.
1265 This makes the magic system behave just like aliases or !system
1302 This makes the magic system behave just like aliases or !system
1266 calls.
1303 calls.
1267
1304
1268 2005-03-28 Fernando Perez <fperez@colorado.edu>
1305 2005-03-28 Fernando Perez <fperez@colorado.edu>
1269
1306
1270 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
1307 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
1271 expensive string additions for building command. Add support for
1308 expensive string additions for building command. Add support for
1272 trailing ';' when autocall is used.
1309 trailing ';' when autocall is used.
1273
1310
1274 2005-03-26 Fernando Perez <fperez@colorado.edu>
1311 2005-03-26 Fernando Perez <fperez@colorado.edu>
1275
1312
1276 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
1313 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
1277 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
1314 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
1278 ipython.el robust against prompts with any number of spaces
1315 ipython.el robust against prompts with any number of spaces
1279 (including 0) after the ':' character.
1316 (including 0) after the ':' character.
1280
1317
1281 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
1318 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
1282 continuation prompt, which misled users to think the line was
1319 continuation prompt, which misled users to think the line was
1283 already indented. Closes debian Bug#300847, reported to me by
1320 already indented. Closes debian Bug#300847, reported to me by
1284 Norbert Tretkowski <tretkowski-AT-inittab.de>.
1321 Norbert Tretkowski <tretkowski-AT-inittab.de>.
1285
1322
1286 2005-03-23 Fernando Perez <fperez@colorado.edu>
1323 2005-03-23 Fernando Perez <fperez@colorado.edu>
1287
1324
1288 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
1325 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
1289 properly aligned if they have embedded newlines.
1326 properly aligned if they have embedded newlines.
1290
1327
1291 * IPython/iplib.py (runlines): Add a public method to expose
1328 * IPython/iplib.py (runlines): Add a public method to expose
1292 IPython's code execution machinery, so that users can run strings
1329 IPython's code execution machinery, so that users can run strings
1293 as if they had been typed at the prompt interactively.
1330 as if they had been typed at the prompt interactively.
1294 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
1331 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
1295 methods which can call the system shell, but with python variable
1332 methods which can call the system shell, but with python variable
1296 expansion. The three such methods are: __IPYTHON__.system,
1333 expansion. The three such methods are: __IPYTHON__.system,
1297 .getoutput and .getoutputerror. These need to be documented in a
1334 .getoutput and .getoutputerror. These need to be documented in a
1298 'public API' section (to be written) of the manual.
1335 'public API' section (to be written) of the manual.
1299
1336
1300 2005-03-20 Fernando Perez <fperez@colorado.edu>
1337 2005-03-20 Fernando Perez <fperez@colorado.edu>
1301
1338
1302 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
1339 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
1303 for custom exception handling. This is quite powerful, and it
1340 for custom exception handling. This is quite powerful, and it
1304 allows for user-installable exception handlers which can trap
1341 allows for user-installable exception handlers which can trap
1305 custom exceptions at runtime and treat them separately from
1342 custom exceptions at runtime and treat them separately from
1306 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
1343 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
1307 Mantegazza <mantegazza-AT-ill.fr>.
1344 Mantegazza <mantegazza-AT-ill.fr>.
1308 (InteractiveShell.set_custom_completer): public API function to
1345 (InteractiveShell.set_custom_completer): public API function to
1309 add new completers at runtime.
1346 add new completers at runtime.
1310
1347
1311 2005-03-19 Fernando Perez <fperez@colorado.edu>
1348 2005-03-19 Fernando Perez <fperez@colorado.edu>
1312
1349
1313 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1350 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1314 allow objects which provide their docstrings via non-standard
1351 allow objects which provide their docstrings via non-standard
1315 mechanisms (like Pyro proxies) to still be inspected by ipython's
1352 mechanisms (like Pyro proxies) to still be inspected by ipython's
1316 ? system.
1353 ? system.
1317
1354
1318 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1355 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1319 automatic capture system. I tried quite hard to make it work
1356 automatic capture system. I tried quite hard to make it work
1320 reliably, and simply failed. I tried many combinations with the
1357 reliably, and simply failed. I tried many combinations with the
1321 subprocess module, but eventually nothing worked in all needed
1358 subprocess module, but eventually nothing worked in all needed
1322 cases (not blocking stdin for the child, duplicating stdout
1359 cases (not blocking stdin for the child, duplicating stdout
1323 without blocking, etc). The new %sc/%sx still do capture to these
1360 without blocking, etc). The new %sc/%sx still do capture to these
1324 magical list/string objects which make shell use much more
1361 magical list/string objects which make shell use much more
1325 conveninent, so not all is lost.
1362 conveninent, so not all is lost.
1326
1363
1327 XXX - FIX MANUAL for the change above!
1364 XXX - FIX MANUAL for the change above!
1328
1365
1329 (runsource): I copied code.py's runsource() into ipython to modify
1366 (runsource): I copied code.py's runsource() into ipython to modify
1330 it a bit. Now the code object and source to be executed are
1367 it a bit. Now the code object and source to be executed are
1331 stored in ipython. This makes this info accessible to third-party
1368 stored in ipython. This makes this info accessible to third-party
1332 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
1369 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
1333 Mantegazza <mantegazza-AT-ill.fr>.
1370 Mantegazza <mantegazza-AT-ill.fr>.
1334
1371
1335 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1372 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1336 history-search via readline (like C-p/C-n). I'd wanted this for a
1373 history-search via readline (like C-p/C-n). I'd wanted this for a
1337 long time, but only recently found out how to do it. For users
1374 long time, but only recently found out how to do it. For users
1338 who already have their ipythonrc files made and want this, just
1375 who already have their ipythonrc files made and want this, just
1339 add:
1376 add:
1340
1377
1341 readline_parse_and_bind "\e[A": history-search-backward
1378 readline_parse_and_bind "\e[A": history-search-backward
1342 readline_parse_and_bind "\e[B": history-search-forward
1379 readline_parse_and_bind "\e[B": history-search-forward
1343
1380
1344 2005-03-18 Fernando Perez <fperez@colorado.edu>
1381 2005-03-18 Fernando Perez <fperez@colorado.edu>
1345
1382
1346 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1383 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1347 LSString and SList classes which allow transparent conversions
1384 LSString and SList classes which allow transparent conversions
1348 between list mode and whitespace-separated string.
1385 between list mode and whitespace-separated string.
1349 (magic_r): Fix recursion problem in %r.
1386 (magic_r): Fix recursion problem in %r.
1350
1387
1351 * IPython/genutils.py (LSString): New class to be used for
1388 * IPython/genutils.py (LSString): New class to be used for
1352 automatic storage of the results of all alias/system calls in _o
1389 automatic storage of the results of all alias/system calls in _o
1353 and _e (stdout/err). These provide a .l/.list attribute which
1390 and _e (stdout/err). These provide a .l/.list attribute which
1354 does automatic splitting on newlines. This means that for most
1391 does automatic splitting on newlines. This means that for most
1355 uses, you'll never need to do capturing of output with %sc/%sx
1392 uses, you'll never need to do capturing of output with %sc/%sx
1356 anymore, since ipython keeps this always done for you. Note that
1393 anymore, since ipython keeps this always done for you. Note that
1357 only the LAST results are stored, the _o/e variables are
1394 only the LAST results are stored, the _o/e variables are
1358 overwritten on each call. If you need to save their contents
1395 overwritten on each call. If you need to save their contents
1359 further, simply bind them to any other name.
1396 further, simply bind them to any other name.
1360
1397
1361 2005-03-17 Fernando Perez <fperez@colorado.edu>
1398 2005-03-17 Fernando Perez <fperez@colorado.edu>
1362
1399
1363 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1400 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1364 prompt namespace handling.
1401 prompt namespace handling.
1365
1402
1366 2005-03-16 Fernando Perez <fperez@colorado.edu>
1403 2005-03-16 Fernando Perez <fperez@colorado.edu>
1367
1404
1368 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1405 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1369 classic prompts to be '>>> ' (final space was missing, and it
1406 classic prompts to be '>>> ' (final space was missing, and it
1370 trips the emacs python mode).
1407 trips the emacs python mode).
1371 (BasePrompt.__str__): Added safe support for dynamic prompt
1408 (BasePrompt.__str__): Added safe support for dynamic prompt
1372 strings. Now you can set your prompt string to be '$x', and the
1409 strings. Now you can set your prompt string to be '$x', and the
1373 value of x will be printed from your interactive namespace. The
1410 value of x will be printed from your interactive namespace. The
1374 interpolation syntax includes the full Itpl support, so
1411 interpolation syntax includes the full Itpl support, so
1375 ${foo()+x+bar()} is a valid prompt string now, and the function
1412 ${foo()+x+bar()} is a valid prompt string now, and the function
1376 calls will be made at runtime.
1413 calls will be made at runtime.
1377
1414
1378 2005-03-15 Fernando Perez <fperez@colorado.edu>
1415 2005-03-15 Fernando Perez <fperez@colorado.edu>
1379
1416
1380 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1417 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1381 avoid name clashes in pylab. %hist still works, it just forwards
1418 avoid name clashes in pylab. %hist still works, it just forwards
1382 the call to %history.
1419 the call to %history.
1383
1420
1384 2005-03-02 *** Released version 0.6.12
1421 2005-03-02 *** Released version 0.6.12
1385
1422
1386 2005-03-02 Fernando Perez <fperez@colorado.edu>
1423 2005-03-02 Fernando Perez <fperez@colorado.edu>
1387
1424
1388 * IPython/iplib.py (handle_magic): log magic calls properly as
1425 * IPython/iplib.py (handle_magic): log magic calls properly as
1389 ipmagic() function calls.
1426 ipmagic() function calls.
1390
1427
1391 * IPython/Magic.py (magic_time): Improved %time to support
1428 * IPython/Magic.py (magic_time): Improved %time to support
1392 statements and provide wall-clock as well as CPU time.
1429 statements and provide wall-clock as well as CPU time.
1393
1430
1394 2005-02-27 Fernando Perez <fperez@colorado.edu>
1431 2005-02-27 Fernando Perez <fperez@colorado.edu>
1395
1432
1396 * IPython/hooks.py: New hooks module, to expose user-modifiable
1433 * IPython/hooks.py: New hooks module, to expose user-modifiable
1397 IPython functionality in a clean manner. For now only the editor
1434 IPython functionality in a clean manner. For now only the editor
1398 hook is actually written, and other thigns which I intend to turn
1435 hook is actually written, and other thigns which I intend to turn
1399 into proper hooks aren't yet there. The display and prefilter
1436 into proper hooks aren't yet there. The display and prefilter
1400 stuff, for example, should be hooks. But at least now the
1437 stuff, for example, should be hooks. But at least now the
1401 framework is in place, and the rest can be moved here with more
1438 framework is in place, and the rest can be moved here with more
1402 time later. IPython had had a .hooks variable for a long time for
1439 time later. IPython had had a .hooks variable for a long time for
1403 this purpose, but I'd never actually used it for anything.
1440 this purpose, but I'd never actually used it for anything.
1404
1441
1405 2005-02-26 Fernando Perez <fperez@colorado.edu>
1442 2005-02-26 Fernando Perez <fperez@colorado.edu>
1406
1443
1407 * IPython/ipmaker.py (make_IPython): make the default ipython
1444 * IPython/ipmaker.py (make_IPython): make the default ipython
1408 directory be called _ipython under win32, to follow more the
1445 directory be called _ipython under win32, to follow more the
1409 naming peculiarities of that platform (where buggy software like
1446 naming peculiarities of that platform (where buggy software like
1410 Visual Sourcesafe breaks with .named directories). Reported by
1447 Visual Sourcesafe breaks with .named directories). Reported by
1411 Ville Vainio.
1448 Ville Vainio.
1412
1449
1413 2005-02-23 Fernando Perez <fperez@colorado.edu>
1450 2005-02-23 Fernando Perez <fperez@colorado.edu>
1414
1451
1415 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1452 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1416 auto_aliases for win32 which were causing problems. Users can
1453 auto_aliases for win32 which were causing problems. Users can
1417 define the ones they personally like.
1454 define the ones they personally like.
1418
1455
1419 2005-02-21 Fernando Perez <fperez@colorado.edu>
1456 2005-02-21 Fernando Perez <fperez@colorado.edu>
1420
1457
1421 * IPython/Magic.py (magic_time): new magic to time execution of
1458 * IPython/Magic.py (magic_time): new magic to time execution of
1422 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1459 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1423
1460
1424 2005-02-19 Fernando Perez <fperez@colorado.edu>
1461 2005-02-19 Fernando Perez <fperez@colorado.edu>
1425
1462
1426 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1463 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1427 into keys (for prompts, for example).
1464 into keys (for prompts, for example).
1428
1465
1429 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1466 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1430 prompts in case users want them. This introduces a small behavior
1467 prompts in case users want them. This introduces a small behavior
1431 change: ipython does not automatically add a space to all prompts
1468 change: ipython does not automatically add a space to all prompts
1432 anymore. To get the old prompts with a space, users should add it
1469 anymore. To get the old prompts with a space, users should add it
1433 manually to their ipythonrc file, so for example prompt_in1 should
1470 manually to their ipythonrc file, so for example prompt_in1 should
1434 now read 'In [\#]: ' instead of 'In [\#]:'.
1471 now read 'In [\#]: ' instead of 'In [\#]:'.
1435 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1472 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1436 file) to control left-padding of secondary prompts.
1473 file) to control left-padding of secondary prompts.
1437
1474
1438 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1475 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1439 the profiler can't be imported. Fix for Debian, which removed
1476 the profiler can't be imported. Fix for Debian, which removed
1440 profile.py because of License issues. I applied a slightly
1477 profile.py because of License issues. I applied a slightly
1441 modified version of the original Debian patch at
1478 modified version of the original Debian patch at
1442 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1479 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1443
1480
1444 2005-02-17 Fernando Perez <fperez@colorado.edu>
1481 2005-02-17 Fernando Perez <fperez@colorado.edu>
1445
1482
1446 * IPython/genutils.py (native_line_ends): Fix bug which would
1483 * IPython/genutils.py (native_line_ends): Fix bug which would
1447 cause improper line-ends under win32 b/c I was not opening files
1484 cause improper line-ends under win32 b/c I was not opening files
1448 in binary mode. Bug report and fix thanks to Ville.
1485 in binary mode. Bug report and fix thanks to Ville.
1449
1486
1450 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1487 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1451 trying to catch spurious foo[1] autocalls. My fix actually broke
1488 trying to catch spurious foo[1] autocalls. My fix actually broke
1452 ',/' autoquote/call with explicit escape (bad regexp).
1489 ',/' autoquote/call with explicit escape (bad regexp).
1453
1490
1454 2005-02-15 *** Released version 0.6.11
1491 2005-02-15 *** Released version 0.6.11
1455
1492
1456 2005-02-14 Fernando Perez <fperez@colorado.edu>
1493 2005-02-14 Fernando Perez <fperez@colorado.edu>
1457
1494
1458 * IPython/background_jobs.py: New background job management
1495 * IPython/background_jobs.py: New background job management
1459 subsystem. This is implemented via a new set of classes, and
1496 subsystem. This is implemented via a new set of classes, and
1460 IPython now provides a builtin 'jobs' object for background job
1497 IPython now provides a builtin 'jobs' object for background job
1461 execution. A convenience %bg magic serves as a lightweight
1498 execution. A convenience %bg magic serves as a lightweight
1462 frontend for starting the more common type of calls. This was
1499 frontend for starting the more common type of calls. This was
1463 inspired by discussions with B. Granger and the BackgroundCommand
1500 inspired by discussions with B. Granger and the BackgroundCommand
1464 class described in the book Python Scripting for Computational
1501 class described in the book Python Scripting for Computational
1465 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1502 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1466 (although ultimately no code from this text was used, as IPython's
1503 (although ultimately no code from this text was used, as IPython's
1467 system is a separate implementation).
1504 system is a separate implementation).
1468
1505
1469 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1506 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1470 to control the completion of single/double underscore names
1507 to control the completion of single/double underscore names
1471 separately. As documented in the example ipytonrc file, the
1508 separately. As documented in the example ipytonrc file, the
1472 readline_omit__names variable can now be set to 2, to omit even
1509 readline_omit__names variable can now be set to 2, to omit even
1473 single underscore names. Thanks to a patch by Brian Wong
1510 single underscore names. Thanks to a patch by Brian Wong
1474 <BrianWong-AT-AirgoNetworks.Com>.
1511 <BrianWong-AT-AirgoNetworks.Com>.
1475 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1512 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1476 be autocalled as foo([1]) if foo were callable. A problem for
1513 be autocalled as foo([1]) if foo were callable. A problem for
1477 things which are both callable and implement __getitem__.
1514 things which are both callable and implement __getitem__.
1478 (init_readline): Fix autoindentation for win32. Thanks to a patch
1515 (init_readline): Fix autoindentation for win32. Thanks to a patch
1479 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1516 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1480
1517
1481 2005-02-12 Fernando Perez <fperez@colorado.edu>
1518 2005-02-12 Fernando Perez <fperez@colorado.edu>
1482
1519
1483 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1520 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1484 which I had written long ago to sort out user error messages which
1521 which I had written long ago to sort out user error messages which
1485 may occur during startup. This seemed like a good idea initially,
1522 may occur during startup. This seemed like a good idea initially,
1486 but it has proven a disaster in retrospect. I don't want to
1523 but it has proven a disaster in retrospect. I don't want to
1487 change much code for now, so my fix is to set the internal 'debug'
1524 change much code for now, so my fix is to set the internal 'debug'
1488 flag to true everywhere, whose only job was precisely to control
1525 flag to true everywhere, whose only job was precisely to control
1489 this subsystem. This closes issue 28 (as well as avoiding all
1526 this subsystem. This closes issue 28 (as well as avoiding all
1490 sorts of strange hangups which occur from time to time).
1527 sorts of strange hangups which occur from time to time).
1491
1528
1492 2005-02-07 Fernando Perez <fperez@colorado.edu>
1529 2005-02-07 Fernando Perez <fperez@colorado.edu>
1493
1530
1494 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1531 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1495 previous call produced a syntax error.
1532 previous call produced a syntax error.
1496
1533
1497 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1534 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1498 classes without constructor.
1535 classes without constructor.
1499
1536
1500 2005-02-06 Fernando Perez <fperez@colorado.edu>
1537 2005-02-06 Fernando Perez <fperez@colorado.edu>
1501
1538
1502 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1539 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1503 completions with the results of each matcher, so we return results
1540 completions with the results of each matcher, so we return results
1504 to the user from all namespaces. This breaks with ipython
1541 to the user from all namespaces. This breaks with ipython
1505 tradition, but I think it's a nicer behavior. Now you get all
1542 tradition, but I think it's a nicer behavior. Now you get all
1506 possible completions listed, from all possible namespaces (python,
1543 possible completions listed, from all possible namespaces (python,
1507 filesystem, magics...) After a request by John Hunter
1544 filesystem, magics...) After a request by John Hunter
1508 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1545 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1509
1546
1510 2005-02-05 Fernando Perez <fperez@colorado.edu>
1547 2005-02-05 Fernando Perez <fperez@colorado.edu>
1511
1548
1512 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1549 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1513 the call had quote characters in it (the quotes were stripped).
1550 the call had quote characters in it (the quotes were stripped).
1514
1551
1515 2005-01-31 Fernando Perez <fperez@colorado.edu>
1552 2005-01-31 Fernando Perez <fperez@colorado.edu>
1516
1553
1517 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1554 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1518 Itpl.itpl() to make the code more robust against psyco
1555 Itpl.itpl() to make the code more robust against psyco
1519 optimizations.
1556 optimizations.
1520
1557
1521 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1558 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1522 of causing an exception. Quicker, cleaner.
1559 of causing an exception. Quicker, cleaner.
1523
1560
1524 2005-01-28 Fernando Perez <fperez@colorado.edu>
1561 2005-01-28 Fernando Perez <fperez@colorado.edu>
1525
1562
1526 * scripts/ipython_win_post_install.py (install): hardcode
1563 * scripts/ipython_win_post_install.py (install): hardcode
1527 sys.prefix+'python.exe' as the executable path. It turns out that
1564 sys.prefix+'python.exe' as the executable path. It turns out that
1528 during the post-installation run, sys.executable resolves to the
1565 during the post-installation run, sys.executable resolves to the
1529 name of the binary installer! I should report this as a distutils
1566 name of the binary installer! I should report this as a distutils
1530 bug, I think. I updated the .10 release with this tiny fix, to
1567 bug, I think. I updated the .10 release with this tiny fix, to
1531 avoid annoying the lists further.
1568 avoid annoying the lists further.
1532
1569
1533 2005-01-27 *** Released version 0.6.10
1570 2005-01-27 *** Released version 0.6.10
1534
1571
1535 2005-01-27 Fernando Perez <fperez@colorado.edu>
1572 2005-01-27 Fernando Perez <fperez@colorado.edu>
1536
1573
1537 * IPython/numutils.py (norm): Added 'inf' as optional name for
1574 * IPython/numutils.py (norm): Added 'inf' as optional name for
1538 L-infinity norm, included references to mathworld.com for vector
1575 L-infinity norm, included references to mathworld.com for vector
1539 norm definitions.
1576 norm definitions.
1540 (amin/amax): added amin/amax for array min/max. Similar to what
1577 (amin/amax): added amin/amax for array min/max. Similar to what
1541 pylab ships with after the recent reorganization of names.
1578 pylab ships with after the recent reorganization of names.
1542 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1579 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1543
1580
1544 * ipython.el: committed Alex's recent fixes and improvements.
1581 * ipython.el: committed Alex's recent fixes and improvements.
1545 Tested with python-mode from CVS, and it looks excellent. Since
1582 Tested with python-mode from CVS, and it looks excellent. Since
1546 python-mode hasn't released anything in a while, I'm temporarily
1583 python-mode hasn't released anything in a while, I'm temporarily
1547 putting a copy of today's CVS (v 4.70) of python-mode in:
1584 putting a copy of today's CVS (v 4.70) of python-mode in:
1548 http://ipython.scipy.org/tmp/python-mode.el
1585 http://ipython.scipy.org/tmp/python-mode.el
1549
1586
1550 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1587 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1551 sys.executable for the executable name, instead of assuming it's
1588 sys.executable for the executable name, instead of assuming it's
1552 called 'python.exe' (the post-installer would have produced broken
1589 called 'python.exe' (the post-installer would have produced broken
1553 setups on systems with a differently named python binary).
1590 setups on systems with a differently named python binary).
1554
1591
1555 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1592 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1556 references to os.linesep, to make the code more
1593 references to os.linesep, to make the code more
1557 platform-independent. This is also part of the win32 coloring
1594 platform-independent. This is also part of the win32 coloring
1558 fixes.
1595 fixes.
1559
1596
1560 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1597 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1561 lines, which actually cause coloring bugs because the length of
1598 lines, which actually cause coloring bugs because the length of
1562 the line is very difficult to correctly compute with embedded
1599 the line is very difficult to correctly compute with embedded
1563 escapes. This was the source of all the coloring problems under
1600 escapes. This was the source of all the coloring problems under
1564 Win32. I think that _finally_, Win32 users have a properly
1601 Win32. I think that _finally_, Win32 users have a properly
1565 working ipython in all respects. This would never have happened
1602 working ipython in all respects. This would never have happened
1566 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1603 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1567
1604
1568 2005-01-26 *** Released version 0.6.9
1605 2005-01-26 *** Released version 0.6.9
1569
1606
1570 2005-01-25 Fernando Perez <fperez@colorado.edu>
1607 2005-01-25 Fernando Perez <fperez@colorado.edu>
1571
1608
1572 * setup.py: finally, we have a true Windows installer, thanks to
1609 * setup.py: finally, we have a true Windows installer, thanks to
1573 the excellent work of Viktor Ransmayr
1610 the excellent work of Viktor Ransmayr
1574 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1611 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1575 Windows users. The setup routine is quite a bit cleaner thanks to
1612 Windows users. The setup routine is quite a bit cleaner thanks to
1576 this, and the post-install script uses the proper functions to
1613 this, and the post-install script uses the proper functions to
1577 allow a clean de-installation using the standard Windows Control
1614 allow a clean de-installation using the standard Windows Control
1578 Panel.
1615 Panel.
1579
1616
1580 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1617 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1581 environment variable under all OSes (including win32) if
1618 environment variable under all OSes (including win32) if
1582 available. This will give consistency to win32 users who have set
1619 available. This will give consistency to win32 users who have set
1583 this variable for any reason. If os.environ['HOME'] fails, the
1620 this variable for any reason. If os.environ['HOME'] fails, the
1584 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1621 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1585
1622
1586 2005-01-24 Fernando Perez <fperez@colorado.edu>
1623 2005-01-24 Fernando Perez <fperez@colorado.edu>
1587
1624
1588 * IPython/numutils.py (empty_like): add empty_like(), similar to
1625 * IPython/numutils.py (empty_like): add empty_like(), similar to
1589 zeros_like() but taking advantage of the new empty() Numeric routine.
1626 zeros_like() but taking advantage of the new empty() Numeric routine.
1590
1627
1591 2005-01-23 *** Released version 0.6.8
1628 2005-01-23 *** Released version 0.6.8
1592
1629
1593 2005-01-22 Fernando Perez <fperez@colorado.edu>
1630 2005-01-22 Fernando Perez <fperez@colorado.edu>
1594
1631
1595 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1632 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1596 automatic show() calls. After discussing things with JDH, it
1633 automatic show() calls. After discussing things with JDH, it
1597 turns out there are too many corner cases where this can go wrong.
1634 turns out there are too many corner cases where this can go wrong.
1598 It's best not to try to be 'too smart', and simply have ipython
1635 It's best not to try to be 'too smart', and simply have ipython
1599 reproduce as much as possible the default behavior of a normal
1636 reproduce as much as possible the default behavior of a normal
1600 python shell.
1637 python shell.
1601
1638
1602 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1639 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1603 line-splitting regexp and _prefilter() to avoid calling getattr()
1640 line-splitting regexp and _prefilter() to avoid calling getattr()
1604 on assignments. This closes
1641 on assignments. This closes
1605 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1642 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1606 readline uses getattr(), so a simple <TAB> keypress is still
1643 readline uses getattr(), so a simple <TAB> keypress is still
1607 enough to trigger getattr() calls on an object.
1644 enough to trigger getattr() calls on an object.
1608
1645
1609 2005-01-21 Fernando Perez <fperez@colorado.edu>
1646 2005-01-21 Fernando Perez <fperez@colorado.edu>
1610
1647
1611 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1648 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1612 docstring under pylab so it doesn't mask the original.
1649 docstring under pylab so it doesn't mask the original.
1613
1650
1614 2005-01-21 *** Released version 0.6.7
1651 2005-01-21 *** Released version 0.6.7
1615
1652
1616 2005-01-21 Fernando Perez <fperez@colorado.edu>
1653 2005-01-21 Fernando Perez <fperez@colorado.edu>
1617
1654
1618 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1655 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1619 signal handling for win32 users in multithreaded mode.
1656 signal handling for win32 users in multithreaded mode.
1620
1657
1621 2005-01-17 Fernando Perez <fperez@colorado.edu>
1658 2005-01-17 Fernando Perez <fperez@colorado.edu>
1622
1659
1623 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1660 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1624 instances with no __init__. After a crash report by Norbert Nemec
1661 instances with no __init__. After a crash report by Norbert Nemec
1625 <Norbert-AT-nemec-online.de>.
1662 <Norbert-AT-nemec-online.de>.
1626
1663
1627 2005-01-14 Fernando Perez <fperez@colorado.edu>
1664 2005-01-14 Fernando Perez <fperez@colorado.edu>
1628
1665
1629 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1666 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1630 names for verbose exceptions, when multiple dotted names and the
1667 names for verbose exceptions, when multiple dotted names and the
1631 'parent' object were present on the same line.
1668 'parent' object were present on the same line.
1632
1669
1633 2005-01-11 Fernando Perez <fperez@colorado.edu>
1670 2005-01-11 Fernando Perez <fperez@colorado.edu>
1634
1671
1635 * IPython/genutils.py (flag_calls): new utility to trap and flag
1672 * IPython/genutils.py (flag_calls): new utility to trap and flag
1636 calls in functions. I need it to clean up matplotlib support.
1673 calls in functions. I need it to clean up matplotlib support.
1637 Also removed some deprecated code in genutils.
1674 Also removed some deprecated code in genutils.
1638
1675
1639 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1676 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1640 that matplotlib scripts called with %run, which don't call show()
1677 that matplotlib scripts called with %run, which don't call show()
1641 themselves, still have their plotting windows open.
1678 themselves, still have their plotting windows open.
1642
1679
1643 2005-01-05 Fernando Perez <fperez@colorado.edu>
1680 2005-01-05 Fernando Perez <fperez@colorado.edu>
1644
1681
1645 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1682 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1646 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1683 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1647
1684
1648 2004-12-19 Fernando Perez <fperez@colorado.edu>
1685 2004-12-19 Fernando Perez <fperez@colorado.edu>
1649
1686
1650 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1687 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1651 parent_runcode, which was an eyesore. The same result can be
1688 parent_runcode, which was an eyesore. The same result can be
1652 obtained with Python's regular superclass mechanisms.
1689 obtained with Python's regular superclass mechanisms.
1653
1690
1654 2004-12-17 Fernando Perez <fperez@colorado.edu>
1691 2004-12-17 Fernando Perez <fperez@colorado.edu>
1655
1692
1656 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1693 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1657 reported by Prabhu.
1694 reported by Prabhu.
1658 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1695 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1659 sys.stderr) instead of explicitly calling sys.stderr. This helps
1696 sys.stderr) instead of explicitly calling sys.stderr. This helps
1660 maintain our I/O abstractions clean, for future GUI embeddings.
1697 maintain our I/O abstractions clean, for future GUI embeddings.
1661
1698
1662 * IPython/genutils.py (info): added new utility for sys.stderr
1699 * IPython/genutils.py (info): added new utility for sys.stderr
1663 unified info message handling (thin wrapper around warn()).
1700 unified info message handling (thin wrapper around warn()).
1664
1701
1665 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1702 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1666 composite (dotted) names on verbose exceptions.
1703 composite (dotted) names on verbose exceptions.
1667 (VerboseTB.nullrepr): harden against another kind of errors which
1704 (VerboseTB.nullrepr): harden against another kind of errors which
1668 Python's inspect module can trigger, and which were crashing
1705 Python's inspect module can trigger, and which were crashing
1669 IPython. Thanks to a report by Marco Lombardi
1706 IPython. Thanks to a report by Marco Lombardi
1670 <mlombard-AT-ma010192.hq.eso.org>.
1707 <mlombard-AT-ma010192.hq.eso.org>.
1671
1708
1672 2004-12-13 *** Released version 0.6.6
1709 2004-12-13 *** Released version 0.6.6
1673
1710
1674 2004-12-12 Fernando Perez <fperez@colorado.edu>
1711 2004-12-12 Fernando Perez <fperez@colorado.edu>
1675
1712
1676 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1713 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1677 generated by pygtk upon initialization if it was built without
1714 generated by pygtk upon initialization if it was built without
1678 threads (for matplotlib users). After a crash reported by
1715 threads (for matplotlib users). After a crash reported by
1679 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1716 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1680
1717
1681 * IPython/ipmaker.py (make_IPython): fix small bug in the
1718 * IPython/ipmaker.py (make_IPython): fix small bug in the
1682 import_some parameter for multiple imports.
1719 import_some parameter for multiple imports.
1683
1720
1684 * IPython/iplib.py (ipmagic): simplified the interface of
1721 * IPython/iplib.py (ipmagic): simplified the interface of
1685 ipmagic() to take a single string argument, just as it would be
1722 ipmagic() to take a single string argument, just as it would be
1686 typed at the IPython cmd line.
1723 typed at the IPython cmd line.
1687 (ipalias): Added new ipalias() with an interface identical to
1724 (ipalias): Added new ipalias() with an interface identical to
1688 ipmagic(). This completes exposing a pure python interface to the
1725 ipmagic(). This completes exposing a pure python interface to the
1689 alias and magic system, which can be used in loops or more complex
1726 alias and magic system, which can be used in loops or more complex
1690 code where IPython's automatic line mangling is not active.
1727 code where IPython's automatic line mangling is not active.
1691
1728
1692 * IPython/genutils.py (timing): changed interface of timing to
1729 * IPython/genutils.py (timing): changed interface of timing to
1693 simply run code once, which is the most common case. timings()
1730 simply run code once, which is the most common case. timings()
1694 remains unchanged, for the cases where you want multiple runs.
1731 remains unchanged, for the cases where you want multiple runs.
1695
1732
1696 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1733 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1697 bug where Python2.2 crashes with exec'ing code which does not end
1734 bug where Python2.2 crashes with exec'ing code which does not end
1698 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1735 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1699 before.
1736 before.
1700
1737
1701 2004-12-10 Fernando Perez <fperez@colorado.edu>
1738 2004-12-10 Fernando Perez <fperez@colorado.edu>
1702
1739
1703 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1740 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1704 -t to -T, to accomodate the new -t flag in %run (the %run and
1741 -t to -T, to accomodate the new -t flag in %run (the %run and
1705 %prun options are kind of intermixed, and it's not easy to change
1742 %prun options are kind of intermixed, and it's not easy to change
1706 this with the limitations of python's getopt).
1743 this with the limitations of python's getopt).
1707
1744
1708 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1745 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1709 the execution of scripts. It's not as fine-tuned as timeit.py,
1746 the execution of scripts. It's not as fine-tuned as timeit.py,
1710 but it works from inside ipython (and under 2.2, which lacks
1747 but it works from inside ipython (and under 2.2, which lacks
1711 timeit.py). Optionally a number of runs > 1 can be given for
1748 timeit.py). Optionally a number of runs > 1 can be given for
1712 timing very short-running code.
1749 timing very short-running code.
1713
1750
1714 * IPython/genutils.py (uniq_stable): new routine which returns a
1751 * IPython/genutils.py (uniq_stable): new routine which returns a
1715 list of unique elements in any iterable, but in stable order of
1752 list of unique elements in any iterable, but in stable order of
1716 appearance. I needed this for the ultraTB fixes, and it's a handy
1753 appearance. I needed this for the ultraTB fixes, and it's a handy
1717 utility.
1754 utility.
1718
1755
1719 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1756 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1720 dotted names in Verbose exceptions. This had been broken since
1757 dotted names in Verbose exceptions. This had been broken since
1721 the very start, now x.y will properly be printed in a Verbose
1758 the very start, now x.y will properly be printed in a Verbose
1722 traceback, instead of x being shown and y appearing always as an
1759 traceback, instead of x being shown and y appearing always as an
1723 'undefined global'. Getting this to work was a bit tricky,
1760 'undefined global'. Getting this to work was a bit tricky,
1724 because by default python tokenizers are stateless. Saved by
1761 because by default python tokenizers are stateless. Saved by
1725 python's ability to easily add a bit of state to an arbitrary
1762 python's ability to easily add a bit of state to an arbitrary
1726 function (without needing to build a full-blown callable object).
1763 function (without needing to build a full-blown callable object).
1727
1764
1728 Also big cleanup of this code, which had horrendous runtime
1765 Also big cleanup of this code, which had horrendous runtime
1729 lookups of zillions of attributes for colorization. Moved all
1766 lookups of zillions of attributes for colorization. Moved all
1730 this code into a few templates, which make it cleaner and quicker.
1767 this code into a few templates, which make it cleaner and quicker.
1731
1768
1732 Printout quality was also improved for Verbose exceptions: one
1769 Printout quality was also improved for Verbose exceptions: one
1733 variable per line, and memory addresses are printed (this can be
1770 variable per line, and memory addresses are printed (this can be
1734 quite handy in nasty debugging situations, which is what Verbose
1771 quite handy in nasty debugging situations, which is what Verbose
1735 is for).
1772 is for).
1736
1773
1737 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1774 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1738 the command line as scripts to be loaded by embedded instances.
1775 the command line as scripts to be loaded by embedded instances.
1739 Doing so has the potential for an infinite recursion if there are
1776 Doing so has the potential for an infinite recursion if there are
1740 exceptions thrown in the process. This fixes a strange crash
1777 exceptions thrown in the process. This fixes a strange crash
1741 reported by Philippe MULLER <muller-AT-irit.fr>.
1778 reported by Philippe MULLER <muller-AT-irit.fr>.
1742
1779
1743 2004-12-09 Fernando Perez <fperez@colorado.edu>
1780 2004-12-09 Fernando Perez <fperez@colorado.edu>
1744
1781
1745 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1782 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1746 to reflect new names in matplotlib, which now expose the
1783 to reflect new names in matplotlib, which now expose the
1747 matlab-compatible interface via a pylab module instead of the
1784 matlab-compatible interface via a pylab module instead of the
1748 'matlab' name. The new code is backwards compatible, so users of
1785 'matlab' name. The new code is backwards compatible, so users of
1749 all matplotlib versions are OK. Patch by J. Hunter.
1786 all matplotlib versions are OK. Patch by J. Hunter.
1750
1787
1751 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1788 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1752 of __init__ docstrings for instances (class docstrings are already
1789 of __init__ docstrings for instances (class docstrings are already
1753 automatically printed). Instances with customized docstrings
1790 automatically printed). Instances with customized docstrings
1754 (indep. of the class) are also recognized and all 3 separate
1791 (indep. of the class) are also recognized and all 3 separate
1755 docstrings are printed (instance, class, constructor). After some
1792 docstrings are printed (instance, class, constructor). After some
1756 comments/suggestions by J. Hunter.
1793 comments/suggestions by J. Hunter.
1757
1794
1758 2004-12-05 Fernando Perez <fperez@colorado.edu>
1795 2004-12-05 Fernando Perez <fperez@colorado.edu>
1759
1796
1760 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1797 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1761 warnings when tab-completion fails and triggers an exception.
1798 warnings when tab-completion fails and triggers an exception.
1762
1799
1763 2004-12-03 Fernando Perez <fperez@colorado.edu>
1800 2004-12-03 Fernando Perez <fperez@colorado.edu>
1764
1801
1765 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1802 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1766 be triggered when using 'run -p'. An incorrect option flag was
1803 be triggered when using 'run -p'. An incorrect option flag was
1767 being set ('d' instead of 'D').
1804 being set ('d' instead of 'D').
1768 (manpage): fix missing escaped \- sign.
1805 (manpage): fix missing escaped \- sign.
1769
1806
1770 2004-11-30 *** Released version 0.6.5
1807 2004-11-30 *** Released version 0.6.5
1771
1808
1772 2004-11-30 Fernando Perez <fperez@colorado.edu>
1809 2004-11-30 Fernando Perez <fperez@colorado.edu>
1773
1810
1774 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1811 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1775 setting with -d option.
1812 setting with -d option.
1776
1813
1777 * setup.py (docfiles): Fix problem where the doc glob I was using
1814 * setup.py (docfiles): Fix problem where the doc glob I was using
1778 was COMPLETELY BROKEN. It was giving the right files by pure
1815 was COMPLETELY BROKEN. It was giving the right files by pure
1779 accident, but failed once I tried to include ipython.el. Note:
1816 accident, but failed once I tried to include ipython.el. Note:
1780 glob() does NOT allow you to do exclusion on multiple endings!
1817 glob() does NOT allow you to do exclusion on multiple endings!
1781
1818
1782 2004-11-29 Fernando Perez <fperez@colorado.edu>
1819 2004-11-29 Fernando Perez <fperez@colorado.edu>
1783
1820
1784 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1821 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1785 the manpage as the source. Better formatting & consistency.
1822 the manpage as the source. Better formatting & consistency.
1786
1823
1787 * IPython/Magic.py (magic_run): Added new -d option, to run
1824 * IPython/Magic.py (magic_run): Added new -d option, to run
1788 scripts under the control of the python pdb debugger. Note that
1825 scripts under the control of the python pdb debugger. Note that
1789 this required changing the %prun option -d to -D, to avoid a clash
1826 this required changing the %prun option -d to -D, to avoid a clash
1790 (since %run must pass options to %prun, and getopt is too dumb to
1827 (since %run must pass options to %prun, and getopt is too dumb to
1791 handle options with string values with embedded spaces). Thanks
1828 handle options with string values with embedded spaces). Thanks
1792 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1829 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1793 (magic_who_ls): added type matching to %who and %whos, so that one
1830 (magic_who_ls): added type matching to %who and %whos, so that one
1794 can filter their output to only include variables of certain
1831 can filter their output to only include variables of certain
1795 types. Another suggestion by Matthew.
1832 types. Another suggestion by Matthew.
1796 (magic_whos): Added memory summaries in kb and Mb for arrays.
1833 (magic_whos): Added memory summaries in kb and Mb for arrays.
1797 (magic_who): Improve formatting (break lines every 9 vars).
1834 (magic_who): Improve formatting (break lines every 9 vars).
1798
1835
1799 2004-11-28 Fernando Perez <fperez@colorado.edu>
1836 2004-11-28 Fernando Perez <fperez@colorado.edu>
1800
1837
1801 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1838 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1802 cache when empty lines were present.
1839 cache when empty lines were present.
1803
1840
1804 2004-11-24 Fernando Perez <fperez@colorado.edu>
1841 2004-11-24 Fernando Perez <fperez@colorado.edu>
1805
1842
1806 * IPython/usage.py (__doc__): document the re-activated threading
1843 * IPython/usage.py (__doc__): document the re-activated threading
1807 options for WX and GTK.
1844 options for WX and GTK.
1808
1845
1809 2004-11-23 Fernando Perez <fperez@colorado.edu>
1846 2004-11-23 Fernando Perez <fperez@colorado.edu>
1810
1847
1811 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1848 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1812 the -wthread and -gthread options, along with a new -tk one to try
1849 the -wthread and -gthread options, along with a new -tk one to try
1813 and coordinate Tk threading with wx/gtk. The tk support is very
1850 and coordinate Tk threading with wx/gtk. The tk support is very
1814 platform dependent, since it seems to require Tcl and Tk to be
1851 platform dependent, since it seems to require Tcl and Tk to be
1815 built with threads (Fedora1/2 appears NOT to have it, but in
1852 built with threads (Fedora1/2 appears NOT to have it, but in
1816 Prabhu's Debian boxes it works OK). But even with some Tk
1853 Prabhu's Debian boxes it works OK). But even with some Tk
1817 limitations, this is a great improvement.
1854 limitations, this is a great improvement.
1818
1855
1819 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1856 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1820 info in user prompts. Patch by Prabhu.
1857 info in user prompts. Patch by Prabhu.
1821
1858
1822 2004-11-18 Fernando Perez <fperez@colorado.edu>
1859 2004-11-18 Fernando Perez <fperez@colorado.edu>
1823
1860
1824 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1861 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1825 EOFErrors and bail, to avoid infinite loops if a non-terminating
1862 EOFErrors and bail, to avoid infinite loops if a non-terminating
1826 file is fed into ipython. Patch submitted in issue 19 by user,
1863 file is fed into ipython. Patch submitted in issue 19 by user,
1827 many thanks.
1864 many thanks.
1828
1865
1829 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1866 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1830 autoquote/parens in continuation prompts, which can cause lots of
1867 autoquote/parens in continuation prompts, which can cause lots of
1831 problems. Closes roundup issue 20.
1868 problems. Closes roundup issue 20.
1832
1869
1833 2004-11-17 Fernando Perez <fperez@colorado.edu>
1870 2004-11-17 Fernando Perez <fperez@colorado.edu>
1834
1871
1835 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1872 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1836 reported as debian bug #280505. I'm not sure my local changelog
1873 reported as debian bug #280505. I'm not sure my local changelog
1837 entry has the proper debian format (Jack?).
1874 entry has the proper debian format (Jack?).
1838
1875
1839 2004-11-08 *** Released version 0.6.4
1876 2004-11-08 *** Released version 0.6.4
1840
1877
1841 2004-11-08 Fernando Perez <fperez@colorado.edu>
1878 2004-11-08 Fernando Perez <fperez@colorado.edu>
1842
1879
1843 * IPython/iplib.py (init_readline): Fix exit message for Windows
1880 * IPython/iplib.py (init_readline): Fix exit message for Windows
1844 when readline is active. Thanks to a report by Eric Jones
1881 when readline is active. Thanks to a report by Eric Jones
1845 <eric-AT-enthought.com>.
1882 <eric-AT-enthought.com>.
1846
1883
1847 2004-11-07 Fernando Perez <fperez@colorado.edu>
1884 2004-11-07 Fernando Perez <fperez@colorado.edu>
1848
1885
1849 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1886 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1850 sometimes seen by win2k/cygwin users.
1887 sometimes seen by win2k/cygwin users.
1851
1888
1852 2004-11-06 Fernando Perez <fperez@colorado.edu>
1889 2004-11-06 Fernando Perez <fperez@colorado.edu>
1853
1890
1854 * IPython/iplib.py (interact): Change the handling of %Exit from
1891 * IPython/iplib.py (interact): Change the handling of %Exit from
1855 trying to propagate a SystemExit to an internal ipython flag.
1892 trying to propagate a SystemExit to an internal ipython flag.
1856 This is less elegant than using Python's exception mechanism, but
1893 This is less elegant than using Python's exception mechanism, but
1857 I can't get that to work reliably with threads, so under -pylab
1894 I can't get that to work reliably with threads, so under -pylab
1858 %Exit was hanging IPython. Cross-thread exception handling is
1895 %Exit was hanging IPython. Cross-thread exception handling is
1859 really a bitch. Thaks to a bug report by Stephen Walton
1896 really a bitch. Thaks to a bug report by Stephen Walton
1860 <stephen.walton-AT-csun.edu>.
1897 <stephen.walton-AT-csun.edu>.
1861
1898
1862 2004-11-04 Fernando Perez <fperez@colorado.edu>
1899 2004-11-04 Fernando Perez <fperez@colorado.edu>
1863
1900
1864 * IPython/iplib.py (raw_input_original): store a pointer to the
1901 * IPython/iplib.py (raw_input_original): store a pointer to the
1865 true raw_input to harden against code which can modify it
1902 true raw_input to harden against code which can modify it
1866 (wx.py.PyShell does this and would otherwise crash ipython).
1903 (wx.py.PyShell does this and would otherwise crash ipython).
1867 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1904 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1868
1905
1869 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1906 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1870 Ctrl-C problem, which does not mess up the input line.
1907 Ctrl-C problem, which does not mess up the input line.
1871
1908
1872 2004-11-03 Fernando Perez <fperez@colorado.edu>
1909 2004-11-03 Fernando Perez <fperez@colorado.edu>
1873
1910
1874 * IPython/Release.py: Changed licensing to BSD, in all files.
1911 * IPython/Release.py: Changed licensing to BSD, in all files.
1875 (name): lowercase name for tarball/RPM release.
1912 (name): lowercase name for tarball/RPM release.
1876
1913
1877 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1914 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1878 use throughout ipython.
1915 use throughout ipython.
1879
1916
1880 * IPython/Magic.py (Magic._ofind): Switch to using the new
1917 * IPython/Magic.py (Magic._ofind): Switch to using the new
1881 OInspect.getdoc() function.
1918 OInspect.getdoc() function.
1882
1919
1883 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1920 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1884 of the line currently being canceled via Ctrl-C. It's extremely
1921 of the line currently being canceled via Ctrl-C. It's extremely
1885 ugly, but I don't know how to do it better (the problem is one of
1922 ugly, but I don't know how to do it better (the problem is one of
1886 handling cross-thread exceptions).
1923 handling cross-thread exceptions).
1887
1924
1888 2004-10-28 Fernando Perez <fperez@colorado.edu>
1925 2004-10-28 Fernando Perez <fperez@colorado.edu>
1889
1926
1890 * IPython/Shell.py (signal_handler): add signal handlers to trap
1927 * IPython/Shell.py (signal_handler): add signal handlers to trap
1891 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1928 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1892 report by Francesc Alted.
1929 report by Francesc Alted.
1893
1930
1894 2004-10-21 Fernando Perez <fperez@colorado.edu>
1931 2004-10-21 Fernando Perez <fperez@colorado.edu>
1895
1932
1896 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1933 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1897 to % for pysh syntax extensions.
1934 to % for pysh syntax extensions.
1898
1935
1899 2004-10-09 Fernando Perez <fperez@colorado.edu>
1936 2004-10-09 Fernando Perez <fperez@colorado.edu>
1900
1937
1901 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1938 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1902 arrays to print a more useful summary, without calling str(arr).
1939 arrays to print a more useful summary, without calling str(arr).
1903 This avoids the problem of extremely lengthy computations which
1940 This avoids the problem of extremely lengthy computations which
1904 occur if arr is large, and appear to the user as a system lockup
1941 occur if arr is large, and appear to the user as a system lockup
1905 with 100% cpu activity. After a suggestion by Kristian Sandberg
1942 with 100% cpu activity. After a suggestion by Kristian Sandberg
1906 <Kristian.Sandberg@colorado.edu>.
1943 <Kristian.Sandberg@colorado.edu>.
1907 (Magic.__init__): fix bug in global magic escapes not being
1944 (Magic.__init__): fix bug in global magic escapes not being
1908 correctly set.
1945 correctly set.
1909
1946
1910 2004-10-08 Fernando Perez <fperez@colorado.edu>
1947 2004-10-08 Fernando Perez <fperez@colorado.edu>
1911
1948
1912 * IPython/Magic.py (__license__): change to absolute imports of
1949 * IPython/Magic.py (__license__): change to absolute imports of
1913 ipython's own internal packages, to start adapting to the absolute
1950 ipython's own internal packages, to start adapting to the absolute
1914 import requirement of PEP-328.
1951 import requirement of PEP-328.
1915
1952
1916 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1953 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1917 files, and standardize author/license marks through the Release
1954 files, and standardize author/license marks through the Release
1918 module instead of having per/file stuff (except for files with
1955 module instead of having per/file stuff (except for files with
1919 particular licenses, like the MIT/PSF-licensed codes).
1956 particular licenses, like the MIT/PSF-licensed codes).
1920
1957
1921 * IPython/Debugger.py: remove dead code for python 2.1
1958 * IPython/Debugger.py: remove dead code for python 2.1
1922
1959
1923 2004-10-04 Fernando Perez <fperez@colorado.edu>
1960 2004-10-04 Fernando Perez <fperez@colorado.edu>
1924
1961
1925 * IPython/iplib.py (ipmagic): New function for accessing magics
1962 * IPython/iplib.py (ipmagic): New function for accessing magics
1926 via a normal python function call.
1963 via a normal python function call.
1927
1964
1928 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1965 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1929 from '@' to '%', to accomodate the new @decorator syntax of python
1966 from '@' to '%', to accomodate the new @decorator syntax of python
1930 2.4.
1967 2.4.
1931
1968
1932 2004-09-29 Fernando Perez <fperez@colorado.edu>
1969 2004-09-29 Fernando Perez <fperez@colorado.edu>
1933
1970
1934 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1971 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1935 matplotlib.use to prevent running scripts which try to switch
1972 matplotlib.use to prevent running scripts which try to switch
1936 interactive backends from within ipython. This will just crash
1973 interactive backends from within ipython. This will just crash
1937 the python interpreter, so we can't allow it (but a detailed error
1974 the python interpreter, so we can't allow it (but a detailed error
1938 is given to the user).
1975 is given to the user).
1939
1976
1940 2004-09-28 Fernando Perez <fperez@colorado.edu>
1977 2004-09-28 Fernando Perez <fperez@colorado.edu>
1941
1978
1942 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1979 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1943 matplotlib-related fixes so that using @run with non-matplotlib
1980 matplotlib-related fixes so that using @run with non-matplotlib
1944 scripts doesn't pop up spurious plot windows. This requires
1981 scripts doesn't pop up spurious plot windows. This requires
1945 matplotlib >= 0.63, where I had to make some changes as well.
1982 matplotlib >= 0.63, where I had to make some changes as well.
1946
1983
1947 * IPython/ipmaker.py (make_IPython): update version requirement to
1984 * IPython/ipmaker.py (make_IPython): update version requirement to
1948 python 2.2.
1985 python 2.2.
1949
1986
1950 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1987 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1951 banner arg for embedded customization.
1988 banner arg for embedded customization.
1952
1989
1953 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1990 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1954 explicit uses of __IP as the IPython's instance name. Now things
1991 explicit uses of __IP as the IPython's instance name. Now things
1955 are properly handled via the shell.name value. The actual code
1992 are properly handled via the shell.name value. The actual code
1956 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1993 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1957 is much better than before. I'll clean things completely when the
1994 is much better than before. I'll clean things completely when the
1958 magic stuff gets a real overhaul.
1995 magic stuff gets a real overhaul.
1959
1996
1960 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1997 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1961 minor changes to debian dir.
1998 minor changes to debian dir.
1962
1999
1963 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
2000 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1964 pointer to the shell itself in the interactive namespace even when
2001 pointer to the shell itself in the interactive namespace even when
1965 a user-supplied dict is provided. This is needed for embedding
2002 a user-supplied dict is provided. This is needed for embedding
1966 purposes (found by tests with Michel Sanner).
2003 purposes (found by tests with Michel Sanner).
1967
2004
1968 2004-09-27 Fernando Perez <fperez@colorado.edu>
2005 2004-09-27 Fernando Perez <fperez@colorado.edu>
1969
2006
1970 * IPython/UserConfig/ipythonrc: remove []{} from
2007 * IPython/UserConfig/ipythonrc: remove []{} from
1971 readline_remove_delims, so that things like [modname.<TAB> do
2008 readline_remove_delims, so that things like [modname.<TAB> do
1972 proper completion. This disables [].TAB, but that's a less common
2009 proper completion. This disables [].TAB, but that's a less common
1973 case than module names in list comprehensions, for example.
2010 case than module names in list comprehensions, for example.
1974 Thanks to a report by Andrea Riciputi.
2011 Thanks to a report by Andrea Riciputi.
1975
2012
1976 2004-09-09 Fernando Perez <fperez@colorado.edu>
2013 2004-09-09 Fernando Perez <fperez@colorado.edu>
1977
2014
1978 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
2015 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1979 blocking problems in win32 and osx. Fix by John.
2016 blocking problems in win32 and osx. Fix by John.
1980
2017
1981 2004-09-08 Fernando Perez <fperez@colorado.edu>
2018 2004-09-08 Fernando Perez <fperez@colorado.edu>
1982
2019
1983 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
2020 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1984 for Win32 and OSX. Fix by John Hunter.
2021 for Win32 and OSX. Fix by John Hunter.
1985
2022
1986 2004-08-30 *** Released version 0.6.3
2023 2004-08-30 *** Released version 0.6.3
1987
2024
1988 2004-08-30 Fernando Perez <fperez@colorado.edu>
2025 2004-08-30 Fernando Perez <fperez@colorado.edu>
1989
2026
1990 * setup.py (isfile): Add manpages to list of dependent files to be
2027 * setup.py (isfile): Add manpages to list of dependent files to be
1991 updated.
2028 updated.
1992
2029
1993 2004-08-27 Fernando Perez <fperez@colorado.edu>
2030 2004-08-27 Fernando Perez <fperez@colorado.edu>
1994
2031
1995 * IPython/Shell.py (start): I've disabled -wthread and -gthread
2032 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1996 for now. They don't really work with standalone WX/GTK code
2033 for now. They don't really work with standalone WX/GTK code
1997 (though matplotlib IS working fine with both of those backends).
2034 (though matplotlib IS working fine with both of those backends).
1998 This will neeed much more testing. I disabled most things with
2035 This will neeed much more testing. I disabled most things with
1999 comments, so turning it back on later should be pretty easy.
2036 comments, so turning it back on later should be pretty easy.
2000
2037
2001 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
2038 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
2002 autocalling of expressions like r'foo', by modifying the line
2039 autocalling of expressions like r'foo', by modifying the line
2003 split regexp. Closes
2040 split regexp. Closes
2004 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
2041 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
2005 Riley <ipythonbugs-AT-sabi.net>.
2042 Riley <ipythonbugs-AT-sabi.net>.
2006 (InteractiveShell.mainloop): honor --nobanner with banner
2043 (InteractiveShell.mainloop): honor --nobanner with banner
2007 extensions.
2044 extensions.
2008
2045
2009 * IPython/Shell.py: Significant refactoring of all classes, so
2046 * IPython/Shell.py: Significant refactoring of all classes, so
2010 that we can really support ALL matplotlib backends and threading
2047 that we can really support ALL matplotlib backends and threading
2011 models (John spotted a bug with Tk which required this). Now we
2048 models (John spotted a bug with Tk which required this). Now we
2012 should support single-threaded, WX-threads and GTK-threads, both
2049 should support single-threaded, WX-threads and GTK-threads, both
2013 for generic code and for matplotlib.
2050 for generic code and for matplotlib.
2014
2051
2015 * IPython/ipmaker.py (__call__): Changed -mpthread option to
2052 * IPython/ipmaker.py (__call__): Changed -mpthread option to
2016 -pylab, to simplify things for users. Will also remove the pylab
2053 -pylab, to simplify things for users. Will also remove the pylab
2017 profile, since now all of matplotlib configuration is directly
2054 profile, since now all of matplotlib configuration is directly
2018 handled here. This also reduces startup time.
2055 handled here. This also reduces startup time.
2019
2056
2020 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
2057 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
2021 shell wasn't being correctly called. Also in IPShellWX.
2058 shell wasn't being correctly called. Also in IPShellWX.
2022
2059
2023 * IPython/iplib.py (InteractiveShell.__init__): Added option to
2060 * IPython/iplib.py (InteractiveShell.__init__): Added option to
2024 fine-tune banner.
2061 fine-tune banner.
2025
2062
2026 * IPython/numutils.py (spike): Deprecate these spike functions,
2063 * IPython/numutils.py (spike): Deprecate these spike functions,
2027 delete (long deprecated) gnuplot_exec handler.
2064 delete (long deprecated) gnuplot_exec handler.
2028
2065
2029 2004-08-26 Fernando Perez <fperez@colorado.edu>
2066 2004-08-26 Fernando Perez <fperez@colorado.edu>
2030
2067
2031 * ipython.1: Update for threading options, plus some others which
2068 * ipython.1: Update for threading options, plus some others which
2032 were missing.
2069 were missing.
2033
2070
2034 * IPython/ipmaker.py (__call__): Added -wthread option for
2071 * IPython/ipmaker.py (__call__): Added -wthread option for
2035 wxpython thread handling. Make sure threading options are only
2072 wxpython thread handling. Make sure threading options are only
2036 valid at the command line.
2073 valid at the command line.
2037
2074
2038 * scripts/ipython: moved shell selection into a factory function
2075 * scripts/ipython: moved shell selection into a factory function
2039 in Shell.py, to keep the starter script to a minimum.
2076 in Shell.py, to keep the starter script to a minimum.
2040
2077
2041 2004-08-25 Fernando Perez <fperez@colorado.edu>
2078 2004-08-25 Fernando Perez <fperez@colorado.edu>
2042
2079
2043 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
2080 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
2044 John. Along with some recent changes he made to matplotlib, the
2081 John. Along with some recent changes he made to matplotlib, the
2045 next versions of both systems should work very well together.
2082 next versions of both systems should work very well together.
2046
2083
2047 2004-08-24 Fernando Perez <fperez@colorado.edu>
2084 2004-08-24 Fernando Perez <fperez@colorado.edu>
2048
2085
2049 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
2086 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
2050 tried to switch the profiling to using hotshot, but I'm getting
2087 tried to switch the profiling to using hotshot, but I'm getting
2051 strange errors from prof.runctx() there. I may be misreading the
2088 strange errors from prof.runctx() there. I may be misreading the
2052 docs, but it looks weird. For now the profiling code will
2089 docs, but it looks weird. For now the profiling code will
2053 continue to use the standard profiler.
2090 continue to use the standard profiler.
2054
2091
2055 2004-08-23 Fernando Perez <fperez@colorado.edu>
2092 2004-08-23 Fernando Perez <fperez@colorado.edu>
2056
2093
2057 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
2094 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
2058 threaded shell, by John Hunter. It's not quite ready yet, but
2095 threaded shell, by John Hunter. It's not quite ready yet, but
2059 close.
2096 close.
2060
2097
2061 2004-08-22 Fernando Perez <fperez@colorado.edu>
2098 2004-08-22 Fernando Perez <fperez@colorado.edu>
2062
2099
2063 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
2100 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
2064 in Magic and ultraTB.
2101 in Magic and ultraTB.
2065
2102
2066 * ipython.1: document threading options in manpage.
2103 * ipython.1: document threading options in manpage.
2067
2104
2068 * scripts/ipython: Changed name of -thread option to -gthread,
2105 * scripts/ipython: Changed name of -thread option to -gthread,
2069 since this is GTK specific. I want to leave the door open for a
2106 since this is GTK specific. I want to leave the door open for a
2070 -wthread option for WX, which will most likely be necessary. This
2107 -wthread option for WX, which will most likely be necessary. This
2071 change affects usage and ipmaker as well.
2108 change affects usage and ipmaker as well.
2072
2109
2073 * IPython/Shell.py (matplotlib_shell): Add a factory function to
2110 * IPython/Shell.py (matplotlib_shell): Add a factory function to
2074 handle the matplotlib shell issues. Code by John Hunter
2111 handle the matplotlib shell issues. Code by John Hunter
2075 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2112 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2076 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
2113 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
2077 broken (and disabled for end users) for now, but it puts the
2114 broken (and disabled for end users) for now, but it puts the
2078 infrastructure in place.
2115 infrastructure in place.
2079
2116
2080 2004-08-21 Fernando Perez <fperez@colorado.edu>
2117 2004-08-21 Fernando Perez <fperez@colorado.edu>
2081
2118
2082 * ipythonrc-pylab: Add matplotlib support.
2119 * ipythonrc-pylab: Add matplotlib support.
2083
2120
2084 * matplotlib_config.py: new files for matplotlib support, part of
2121 * matplotlib_config.py: new files for matplotlib support, part of
2085 the pylab profile.
2122 the pylab profile.
2086
2123
2087 * IPython/usage.py (__doc__): documented the threading options.
2124 * IPython/usage.py (__doc__): documented the threading options.
2088
2125
2089 2004-08-20 Fernando Perez <fperez@colorado.edu>
2126 2004-08-20 Fernando Perez <fperez@colorado.edu>
2090
2127
2091 * ipython: Modified the main calling routine to handle the -thread
2128 * ipython: Modified the main calling routine to handle the -thread
2092 and -mpthread options. This needs to be done as a top-level hack,
2129 and -mpthread options. This needs to be done as a top-level hack,
2093 because it determines which class to instantiate for IPython
2130 because it determines which class to instantiate for IPython
2094 itself.
2131 itself.
2095
2132
2096 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
2133 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
2097 classes to support multithreaded GTK operation without blocking,
2134 classes to support multithreaded GTK operation without blocking,
2098 and matplotlib with all backends. This is a lot of still very
2135 and matplotlib with all backends. This is a lot of still very
2099 experimental code, and threads are tricky. So it may still have a
2136 experimental code, and threads are tricky. So it may still have a
2100 few rough edges... This code owes a lot to
2137 few rough edges... This code owes a lot to
2101 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
2138 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
2102 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
2139 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
2103 to John Hunter for all the matplotlib work.
2140 to John Hunter for all the matplotlib work.
2104
2141
2105 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
2142 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
2106 options for gtk thread and matplotlib support.
2143 options for gtk thread and matplotlib support.
2107
2144
2108 2004-08-16 Fernando Perez <fperez@colorado.edu>
2145 2004-08-16 Fernando Perez <fperez@colorado.edu>
2109
2146
2110 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
2147 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
2111 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
2148 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
2112 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
2149 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
2113
2150
2114 2004-08-11 Fernando Perez <fperez@colorado.edu>
2151 2004-08-11 Fernando Perez <fperez@colorado.edu>
2115
2152
2116 * setup.py (isfile): Fix build so documentation gets updated for
2153 * setup.py (isfile): Fix build so documentation gets updated for
2117 rpms (it was only done for .tgz builds).
2154 rpms (it was only done for .tgz builds).
2118
2155
2119 2004-08-10 Fernando Perez <fperez@colorado.edu>
2156 2004-08-10 Fernando Perez <fperez@colorado.edu>
2120
2157
2121 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
2158 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
2122
2159
2123 * iplib.py : Silence syntax error exceptions in tab-completion.
2160 * iplib.py : Silence syntax error exceptions in tab-completion.
2124
2161
2125 2004-08-05 Fernando Perez <fperez@colorado.edu>
2162 2004-08-05 Fernando Perez <fperez@colorado.edu>
2126
2163
2127 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
2164 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
2128 'color off' mark for continuation prompts. This was causing long
2165 'color off' mark for continuation prompts. This was causing long
2129 continuation lines to mis-wrap.
2166 continuation lines to mis-wrap.
2130
2167
2131 2004-08-01 Fernando Perez <fperez@colorado.edu>
2168 2004-08-01 Fernando Perez <fperez@colorado.edu>
2132
2169
2133 * IPython/ipmaker.py (make_IPython): Allow the shell class used
2170 * IPython/ipmaker.py (make_IPython): Allow the shell class used
2134 for building ipython to be a parameter. All this is necessary
2171 for building ipython to be a parameter. All this is necessary
2135 right now to have a multithreaded version, but this insane
2172 right now to have a multithreaded version, but this insane
2136 non-design will be cleaned up soon. For now, it's a hack that
2173 non-design will be cleaned up soon. For now, it's a hack that
2137 works.
2174 works.
2138
2175
2139 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
2176 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
2140 args in various places. No bugs so far, but it's a dangerous
2177 args in various places. No bugs so far, but it's a dangerous
2141 practice.
2178 practice.
2142
2179
2143 2004-07-31 Fernando Perez <fperez@colorado.edu>
2180 2004-07-31 Fernando Perez <fperez@colorado.edu>
2144
2181
2145 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
2182 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
2146 fix completion of files with dots in their names under most
2183 fix completion of files with dots in their names under most
2147 profiles (pysh was OK because the completion order is different).
2184 profiles (pysh was OK because the completion order is different).
2148
2185
2149 2004-07-27 Fernando Perez <fperez@colorado.edu>
2186 2004-07-27 Fernando Perez <fperez@colorado.edu>
2150
2187
2151 * IPython/iplib.py (InteractiveShell.__init__): build dict of
2188 * IPython/iplib.py (InteractiveShell.__init__): build dict of
2152 keywords manually, b/c the one in keyword.py was removed in python
2189 keywords manually, b/c the one in keyword.py was removed in python
2153 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
2190 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
2154 This is NOT a bug under python 2.3 and earlier.
2191 This is NOT a bug under python 2.3 and earlier.
2155
2192
2156 2004-07-26 Fernando Perez <fperez@colorado.edu>
2193 2004-07-26 Fernando Perez <fperez@colorado.edu>
2157
2194
2158 * IPython/ultraTB.py (VerboseTB.text): Add another
2195 * IPython/ultraTB.py (VerboseTB.text): Add another
2159 linecache.checkcache() call to try to prevent inspect.py from
2196 linecache.checkcache() call to try to prevent inspect.py from
2160 crashing under python 2.3. I think this fixes
2197 crashing under python 2.3. I think this fixes
2161 http://www.scipy.net/roundup/ipython/issue17.
2198 http://www.scipy.net/roundup/ipython/issue17.
2162
2199
2163 2004-07-26 *** Released version 0.6.2
2200 2004-07-26 *** Released version 0.6.2
2164
2201
2165 2004-07-26 Fernando Perez <fperez@colorado.edu>
2202 2004-07-26 Fernando Perez <fperez@colorado.edu>
2166
2203
2167 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
2204 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
2168 fail for any number.
2205 fail for any number.
2169 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
2206 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
2170 empty bookmarks.
2207 empty bookmarks.
2171
2208
2172 2004-07-26 *** Released version 0.6.1
2209 2004-07-26 *** Released version 0.6.1
2173
2210
2174 2004-07-26 Fernando Perez <fperez@colorado.edu>
2211 2004-07-26 Fernando Perez <fperez@colorado.edu>
2175
2212
2176 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
2213 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
2177
2214
2178 * IPython/iplib.py (protect_filename): Applied Ville's patch for
2215 * IPython/iplib.py (protect_filename): Applied Ville's patch for
2179 escaping '()[]{}' in filenames.
2216 escaping '()[]{}' in filenames.
2180
2217
2181 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
2218 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
2182 Python 2.2 users who lack a proper shlex.split.
2219 Python 2.2 users who lack a proper shlex.split.
2183
2220
2184 2004-07-19 Fernando Perez <fperez@colorado.edu>
2221 2004-07-19 Fernando Perez <fperez@colorado.edu>
2185
2222
2186 * IPython/iplib.py (InteractiveShell.init_readline): Add support
2223 * IPython/iplib.py (InteractiveShell.init_readline): Add support
2187 for reading readline's init file. I follow the normal chain:
2224 for reading readline's init file. I follow the normal chain:
2188 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
2225 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
2189 report by Mike Heeter. This closes
2226 report by Mike Heeter. This closes
2190 http://www.scipy.net/roundup/ipython/issue16.
2227 http://www.scipy.net/roundup/ipython/issue16.
2191
2228
2192 2004-07-18 Fernando Perez <fperez@colorado.edu>
2229 2004-07-18 Fernando Perez <fperez@colorado.edu>
2193
2230
2194 * IPython/iplib.py (__init__): Add better handling of '\' under
2231 * IPython/iplib.py (__init__): Add better handling of '\' under
2195 Win32 for filenames. After a patch by Ville.
2232 Win32 for filenames. After a patch by Ville.
2196
2233
2197 2004-07-17 Fernando Perez <fperez@colorado.edu>
2234 2004-07-17 Fernando Perez <fperez@colorado.edu>
2198
2235
2199 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2236 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2200 autocalling would be triggered for 'foo is bar' if foo is
2237 autocalling would be triggered for 'foo is bar' if foo is
2201 callable. I also cleaned up the autocall detection code to use a
2238 callable. I also cleaned up the autocall detection code to use a
2202 regexp, which is faster. Bug reported by Alexander Schmolck.
2239 regexp, which is faster. Bug reported by Alexander Schmolck.
2203
2240
2204 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
2241 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
2205 '?' in them would confuse the help system. Reported by Alex
2242 '?' in them would confuse the help system. Reported by Alex
2206 Schmolck.
2243 Schmolck.
2207
2244
2208 2004-07-16 Fernando Perez <fperez@colorado.edu>
2245 2004-07-16 Fernando Perez <fperez@colorado.edu>
2209
2246
2210 * IPython/GnuplotInteractive.py (__all__): added plot2.
2247 * IPython/GnuplotInteractive.py (__all__): added plot2.
2211
2248
2212 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
2249 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
2213 plotting dictionaries, lists or tuples of 1d arrays.
2250 plotting dictionaries, lists or tuples of 1d arrays.
2214
2251
2215 * IPython/Magic.py (Magic.magic_hist): small clenaups and
2252 * IPython/Magic.py (Magic.magic_hist): small clenaups and
2216 optimizations.
2253 optimizations.
2217
2254
2218 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
2255 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
2219 the information which was there from Janko's original IPP code:
2256 the information which was there from Janko's original IPP code:
2220
2257
2221 03.05.99 20:53 porto.ifm.uni-kiel.de
2258 03.05.99 20:53 porto.ifm.uni-kiel.de
2222 --Started changelog.
2259 --Started changelog.
2223 --make clear do what it say it does
2260 --make clear do what it say it does
2224 --added pretty output of lines from inputcache
2261 --added pretty output of lines from inputcache
2225 --Made Logger a mixin class, simplifies handling of switches
2262 --Made Logger a mixin class, simplifies handling of switches
2226 --Added own completer class. .string<TAB> expands to last history
2263 --Added own completer class. .string<TAB> expands to last history
2227 line which starts with string. The new expansion is also present
2264 line which starts with string. The new expansion is also present
2228 with Ctrl-r from the readline library. But this shows, who this
2265 with Ctrl-r from the readline library. But this shows, who this
2229 can be done for other cases.
2266 can be done for other cases.
2230 --Added convention that all shell functions should accept a
2267 --Added convention that all shell functions should accept a
2231 parameter_string This opens the door for different behaviour for
2268 parameter_string This opens the door for different behaviour for
2232 each function. @cd is a good example of this.
2269 each function. @cd is a good example of this.
2233
2270
2234 04.05.99 12:12 porto.ifm.uni-kiel.de
2271 04.05.99 12:12 porto.ifm.uni-kiel.de
2235 --added logfile rotation
2272 --added logfile rotation
2236 --added new mainloop method which freezes first the namespace
2273 --added new mainloop method which freezes first the namespace
2237
2274
2238 07.05.99 21:24 porto.ifm.uni-kiel.de
2275 07.05.99 21:24 porto.ifm.uni-kiel.de
2239 --added the docreader classes. Now there is a help system.
2276 --added the docreader classes. Now there is a help system.
2240 -This is only a first try. Currently it's not easy to put new
2277 -This is only a first try. Currently it's not easy to put new
2241 stuff in the indices. But this is the way to go. Info would be
2278 stuff in the indices. But this is the way to go. Info would be
2242 better, but HTML is every where and not everybody has an info
2279 better, but HTML is every where and not everybody has an info
2243 system installed and it's not so easy to change html-docs to info.
2280 system installed and it's not so easy to change html-docs to info.
2244 --added global logfile option
2281 --added global logfile option
2245 --there is now a hook for object inspection method pinfo needs to
2282 --there is now a hook for object inspection method pinfo needs to
2246 be provided for this. Can be reached by two '??'.
2283 be provided for this. Can be reached by two '??'.
2247
2284
2248 08.05.99 20:51 porto.ifm.uni-kiel.de
2285 08.05.99 20:51 porto.ifm.uni-kiel.de
2249 --added a README
2286 --added a README
2250 --bug in rc file. Something has changed so functions in the rc
2287 --bug in rc file. Something has changed so functions in the rc
2251 file need to reference the shell and not self. Not clear if it's a
2288 file need to reference the shell and not self. Not clear if it's a
2252 bug or feature.
2289 bug or feature.
2253 --changed rc file for new behavior
2290 --changed rc file for new behavior
2254
2291
2255 2004-07-15 Fernando Perez <fperez@colorado.edu>
2292 2004-07-15 Fernando Perez <fperez@colorado.edu>
2256
2293
2257 * IPython/Logger.py (Logger.log): fixed recent bug where the input
2294 * IPython/Logger.py (Logger.log): fixed recent bug where the input
2258 cache was falling out of sync in bizarre manners when multi-line
2295 cache was falling out of sync in bizarre manners when multi-line
2259 input was present. Minor optimizations and cleanup.
2296 input was present. Minor optimizations and cleanup.
2260
2297
2261 (Logger): Remove old Changelog info for cleanup. This is the
2298 (Logger): Remove old Changelog info for cleanup. This is the
2262 information which was there from Janko's original code:
2299 information which was there from Janko's original code:
2263
2300
2264 Changes to Logger: - made the default log filename a parameter
2301 Changes to Logger: - made the default log filename a parameter
2265
2302
2266 - put a check for lines beginning with !@? in log(). Needed
2303 - put a check for lines beginning with !@? in log(). Needed
2267 (even if the handlers properly log their lines) for mid-session
2304 (even if the handlers properly log their lines) for mid-session
2268 logging activation to work properly. Without this, lines logged
2305 logging activation to work properly. Without this, lines logged
2269 in mid session, which get read from the cache, would end up
2306 in mid session, which get read from the cache, would end up
2270 'bare' (with !@? in the open) in the log. Now they are caught
2307 'bare' (with !@? in the open) in the log. Now they are caught
2271 and prepended with a #.
2308 and prepended with a #.
2272
2309
2273 * IPython/iplib.py (InteractiveShell.init_readline): added check
2310 * IPython/iplib.py (InteractiveShell.init_readline): added check
2274 in case MagicCompleter fails to be defined, so we don't crash.
2311 in case MagicCompleter fails to be defined, so we don't crash.
2275
2312
2276 2004-07-13 Fernando Perez <fperez@colorado.edu>
2313 2004-07-13 Fernando Perez <fperez@colorado.edu>
2277
2314
2278 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
2315 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
2279 of EPS if the requested filename ends in '.eps'.
2316 of EPS if the requested filename ends in '.eps'.
2280
2317
2281 2004-07-04 Fernando Perez <fperez@colorado.edu>
2318 2004-07-04 Fernando Perez <fperez@colorado.edu>
2282
2319
2283 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
2320 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
2284 escaping of quotes when calling the shell.
2321 escaping of quotes when calling the shell.
2285
2322
2286 2004-07-02 Fernando Perez <fperez@colorado.edu>
2323 2004-07-02 Fernando Perez <fperez@colorado.edu>
2287
2324
2288 * IPython/Prompts.py (CachedOutput.update): Fix problem with
2325 * IPython/Prompts.py (CachedOutput.update): Fix problem with
2289 gettext not working because we were clobbering '_'. Fixes
2326 gettext not working because we were clobbering '_'. Fixes
2290 http://www.scipy.net/roundup/ipython/issue6.
2327 http://www.scipy.net/roundup/ipython/issue6.
2291
2328
2292 2004-07-01 Fernando Perez <fperez@colorado.edu>
2329 2004-07-01 Fernando Perez <fperez@colorado.edu>
2293
2330
2294 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
2331 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
2295 into @cd. Patch by Ville.
2332 into @cd. Patch by Ville.
2296
2333
2297 * IPython/iplib.py (InteractiveShell.post_config_initialization):
2334 * IPython/iplib.py (InteractiveShell.post_config_initialization):
2298 new function to store things after ipmaker runs. Patch by Ville.
2335 new function to store things after ipmaker runs. Patch by Ville.
2299 Eventually this will go away once ipmaker is removed and the class
2336 Eventually this will go away once ipmaker is removed and the class
2300 gets cleaned up, but for now it's ok. Key functionality here is
2337 gets cleaned up, but for now it's ok. Key functionality here is
2301 the addition of the persistent storage mechanism, a dict for
2338 the addition of the persistent storage mechanism, a dict for
2302 keeping data across sessions (for now just bookmarks, but more can
2339 keeping data across sessions (for now just bookmarks, but more can
2303 be implemented later).
2340 be implemented later).
2304
2341
2305 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2342 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2306 persistent across sections. Patch by Ville, I modified it
2343 persistent across sections. Patch by Ville, I modified it
2307 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2344 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2308 added a '-l' option to list all bookmarks.
2345 added a '-l' option to list all bookmarks.
2309
2346
2310 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2347 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2311 center for cleanup. Registered with atexit.register(). I moved
2348 center for cleanup. Registered with atexit.register(). I moved
2312 here the old exit_cleanup(). After a patch by Ville.
2349 here the old exit_cleanup(). After a patch by Ville.
2313
2350
2314 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2351 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2315 characters in the hacked shlex_split for python 2.2.
2352 characters in the hacked shlex_split for python 2.2.
2316
2353
2317 * IPython/iplib.py (file_matches): more fixes to filenames with
2354 * IPython/iplib.py (file_matches): more fixes to filenames with
2318 whitespace in them. It's not perfect, but limitations in python's
2355 whitespace in them. It's not perfect, but limitations in python's
2319 readline make it impossible to go further.
2356 readline make it impossible to go further.
2320
2357
2321 2004-06-29 Fernando Perez <fperez@colorado.edu>
2358 2004-06-29 Fernando Perez <fperez@colorado.edu>
2322
2359
2323 * IPython/iplib.py (file_matches): escape whitespace correctly in
2360 * IPython/iplib.py (file_matches): escape whitespace correctly in
2324 filename completions. Bug reported by Ville.
2361 filename completions. Bug reported by Ville.
2325
2362
2326 2004-06-28 Fernando Perez <fperez@colorado.edu>
2363 2004-06-28 Fernando Perez <fperez@colorado.edu>
2327
2364
2328 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2365 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2329 the history file will be called 'history-PROFNAME' (or just
2366 the history file will be called 'history-PROFNAME' (or just
2330 'history' if no profile is loaded). I was getting annoyed at
2367 'history' if no profile is loaded). I was getting annoyed at
2331 getting my Numerical work history clobbered by pysh sessions.
2368 getting my Numerical work history clobbered by pysh sessions.
2332
2369
2333 * IPython/iplib.py (InteractiveShell.__init__): Internal
2370 * IPython/iplib.py (InteractiveShell.__init__): Internal
2334 getoutputerror() function so that we can honor the system_verbose
2371 getoutputerror() function so that we can honor the system_verbose
2335 flag for _all_ system calls. I also added escaping of #
2372 flag for _all_ system calls. I also added escaping of #
2336 characters here to avoid confusing Itpl.
2373 characters here to avoid confusing Itpl.
2337
2374
2338 * IPython/Magic.py (shlex_split): removed call to shell in
2375 * IPython/Magic.py (shlex_split): removed call to shell in
2339 parse_options and replaced it with shlex.split(). The annoying
2376 parse_options and replaced it with shlex.split(). The annoying
2340 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2377 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2341 to backport it from 2.3, with several frail hacks (the shlex
2378 to backport it from 2.3, with several frail hacks (the shlex
2342 module is rather limited in 2.2). Thanks to a suggestion by Ville
2379 module is rather limited in 2.2). Thanks to a suggestion by Ville
2343 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2380 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2344 problem.
2381 problem.
2345
2382
2346 (Magic.magic_system_verbose): new toggle to print the actual
2383 (Magic.magic_system_verbose): new toggle to print the actual
2347 system calls made by ipython. Mainly for debugging purposes.
2384 system calls made by ipython. Mainly for debugging purposes.
2348
2385
2349 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2386 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2350 doesn't support persistence. Reported (and fix suggested) by
2387 doesn't support persistence. Reported (and fix suggested) by
2351 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2388 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2352
2389
2353 2004-06-26 Fernando Perez <fperez@colorado.edu>
2390 2004-06-26 Fernando Perez <fperez@colorado.edu>
2354
2391
2355 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2392 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2356 continue prompts.
2393 continue prompts.
2357
2394
2358 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2395 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2359 function (basically a big docstring) and a few more things here to
2396 function (basically a big docstring) and a few more things here to
2360 speedup startup. pysh.py is now very lightweight. We want because
2397 speedup startup. pysh.py is now very lightweight. We want because
2361 it gets execfile'd, while InterpreterExec gets imported, so
2398 it gets execfile'd, while InterpreterExec gets imported, so
2362 byte-compilation saves time.
2399 byte-compilation saves time.
2363
2400
2364 2004-06-25 Fernando Perez <fperez@colorado.edu>
2401 2004-06-25 Fernando Perez <fperez@colorado.edu>
2365
2402
2366 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2403 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2367 -NUM', which was recently broken.
2404 -NUM', which was recently broken.
2368
2405
2369 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2406 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2370 in multi-line input (but not !!, which doesn't make sense there).
2407 in multi-line input (but not !!, which doesn't make sense there).
2371
2408
2372 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2409 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2373 It's just too useful, and people can turn it off in the less
2410 It's just too useful, and people can turn it off in the less
2374 common cases where it's a problem.
2411 common cases where it's a problem.
2375
2412
2376 2004-06-24 Fernando Perez <fperez@colorado.edu>
2413 2004-06-24 Fernando Perez <fperez@colorado.edu>
2377
2414
2378 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2415 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2379 special syntaxes (like alias calling) is now allied in multi-line
2416 special syntaxes (like alias calling) is now allied in multi-line
2380 input. This is still _very_ experimental, but it's necessary for
2417 input. This is still _very_ experimental, but it's necessary for
2381 efficient shell usage combining python looping syntax with system
2418 efficient shell usage combining python looping syntax with system
2382 calls. For now it's restricted to aliases, I don't think it
2419 calls. For now it's restricted to aliases, I don't think it
2383 really even makes sense to have this for magics.
2420 really even makes sense to have this for magics.
2384
2421
2385 2004-06-23 Fernando Perez <fperez@colorado.edu>
2422 2004-06-23 Fernando Perez <fperez@colorado.edu>
2386
2423
2387 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2424 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2388 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2425 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2389
2426
2390 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2427 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2391 extensions under Windows (after code sent by Gary Bishop). The
2428 extensions under Windows (after code sent by Gary Bishop). The
2392 extensions considered 'executable' are stored in IPython's rc
2429 extensions considered 'executable' are stored in IPython's rc
2393 structure as win_exec_ext.
2430 structure as win_exec_ext.
2394
2431
2395 * IPython/genutils.py (shell): new function, like system() but
2432 * IPython/genutils.py (shell): new function, like system() but
2396 without return value. Very useful for interactive shell work.
2433 without return value. Very useful for interactive shell work.
2397
2434
2398 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2435 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2399 delete aliases.
2436 delete aliases.
2400
2437
2401 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2438 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2402 sure that the alias table doesn't contain python keywords.
2439 sure that the alias table doesn't contain python keywords.
2403
2440
2404 2004-06-21 Fernando Perez <fperez@colorado.edu>
2441 2004-06-21 Fernando Perez <fperez@colorado.edu>
2405
2442
2406 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2443 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2407 non-existent items are found in $PATH. Reported by Thorsten.
2444 non-existent items are found in $PATH. Reported by Thorsten.
2408
2445
2409 2004-06-20 Fernando Perez <fperez@colorado.edu>
2446 2004-06-20 Fernando Perez <fperez@colorado.edu>
2410
2447
2411 * IPython/iplib.py (complete): modified the completer so that the
2448 * IPython/iplib.py (complete): modified the completer so that the
2412 order of priorities can be easily changed at runtime.
2449 order of priorities can be easily changed at runtime.
2413
2450
2414 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2451 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2415 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2452 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2416
2453
2417 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2454 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2418 expand Python variables prepended with $ in all system calls. The
2455 expand Python variables prepended with $ in all system calls. The
2419 same was done to InteractiveShell.handle_shell_escape. Now all
2456 same was done to InteractiveShell.handle_shell_escape. Now all
2420 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2457 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2421 expansion of python variables and expressions according to the
2458 expansion of python variables and expressions according to the
2422 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2459 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2423
2460
2424 Though PEP-215 has been rejected, a similar (but simpler) one
2461 Though PEP-215 has been rejected, a similar (but simpler) one
2425 seems like it will go into Python 2.4, PEP-292 -
2462 seems like it will go into Python 2.4, PEP-292 -
2426 http://www.python.org/peps/pep-0292.html.
2463 http://www.python.org/peps/pep-0292.html.
2427
2464
2428 I'll keep the full syntax of PEP-215, since IPython has since the
2465 I'll keep the full syntax of PEP-215, since IPython has since the
2429 start used Ka-Ping Yee's reference implementation discussed there
2466 start used Ka-Ping Yee's reference implementation discussed there
2430 (Itpl), and I actually like the powerful semantics it offers.
2467 (Itpl), and I actually like the powerful semantics it offers.
2431
2468
2432 In order to access normal shell variables, the $ has to be escaped
2469 In order to access normal shell variables, the $ has to be escaped
2433 via an extra $. For example:
2470 via an extra $. For example:
2434
2471
2435 In [7]: PATH='a python variable'
2472 In [7]: PATH='a python variable'
2436
2473
2437 In [8]: !echo $PATH
2474 In [8]: !echo $PATH
2438 a python variable
2475 a python variable
2439
2476
2440 In [9]: !echo $$PATH
2477 In [9]: !echo $$PATH
2441 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2478 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2442
2479
2443 (Magic.parse_options): escape $ so the shell doesn't evaluate
2480 (Magic.parse_options): escape $ so the shell doesn't evaluate
2444 things prematurely.
2481 things prematurely.
2445
2482
2446 * IPython/iplib.py (InteractiveShell.call_alias): added the
2483 * IPython/iplib.py (InteractiveShell.call_alias): added the
2447 ability for aliases to expand python variables via $.
2484 ability for aliases to expand python variables via $.
2448
2485
2449 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2486 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2450 system, now there's a @rehash/@rehashx pair of magics. These work
2487 system, now there's a @rehash/@rehashx pair of magics. These work
2451 like the csh rehash command, and can be invoked at any time. They
2488 like the csh rehash command, and can be invoked at any time. They
2452 build a table of aliases to everything in the user's $PATH
2489 build a table of aliases to everything in the user's $PATH
2453 (@rehash uses everything, @rehashx is slower but only adds
2490 (@rehash uses everything, @rehashx is slower but only adds
2454 executable files). With this, the pysh.py-based shell profile can
2491 executable files). With this, the pysh.py-based shell profile can
2455 now simply call rehash upon startup, and full access to all
2492 now simply call rehash upon startup, and full access to all
2456 programs in the user's path is obtained.
2493 programs in the user's path is obtained.
2457
2494
2458 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2495 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2459 functionality is now fully in place. I removed the old dynamic
2496 functionality is now fully in place. I removed the old dynamic
2460 code generation based approach, in favor of a much lighter one
2497 code generation based approach, in favor of a much lighter one
2461 based on a simple dict. The advantage is that this allows me to
2498 based on a simple dict. The advantage is that this allows me to
2462 now have thousands of aliases with negligible cost (unthinkable
2499 now have thousands of aliases with negligible cost (unthinkable
2463 with the old system).
2500 with the old system).
2464
2501
2465 2004-06-19 Fernando Perez <fperez@colorado.edu>
2502 2004-06-19 Fernando Perez <fperez@colorado.edu>
2466
2503
2467 * IPython/iplib.py (__init__): extended MagicCompleter class to
2504 * IPython/iplib.py (__init__): extended MagicCompleter class to
2468 also complete (last in priority) on user aliases.
2505 also complete (last in priority) on user aliases.
2469
2506
2470 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2507 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2471 call to eval.
2508 call to eval.
2472 (ItplNS.__init__): Added a new class which functions like Itpl,
2509 (ItplNS.__init__): Added a new class which functions like Itpl,
2473 but allows configuring the namespace for the evaluation to occur
2510 but allows configuring the namespace for the evaluation to occur
2474 in.
2511 in.
2475
2512
2476 2004-06-18 Fernando Perez <fperez@colorado.edu>
2513 2004-06-18 Fernando Perez <fperez@colorado.edu>
2477
2514
2478 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2515 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2479 better message when 'exit' or 'quit' are typed (a common newbie
2516 better message when 'exit' or 'quit' are typed (a common newbie
2480 confusion).
2517 confusion).
2481
2518
2482 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2519 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2483 check for Windows users.
2520 check for Windows users.
2484
2521
2485 * IPython/iplib.py (InteractiveShell.user_setup): removed
2522 * IPython/iplib.py (InteractiveShell.user_setup): removed
2486 disabling of colors for Windows. I'll test at runtime and issue a
2523 disabling of colors for Windows. I'll test at runtime and issue a
2487 warning if Gary's readline isn't found, as to nudge users to
2524 warning if Gary's readline isn't found, as to nudge users to
2488 download it.
2525 download it.
2489
2526
2490 2004-06-16 Fernando Perez <fperez@colorado.edu>
2527 2004-06-16 Fernando Perez <fperez@colorado.edu>
2491
2528
2492 * IPython/genutils.py (Stream.__init__): changed to print errors
2529 * IPython/genutils.py (Stream.__init__): changed to print errors
2493 to sys.stderr. I had a circular dependency here. Now it's
2530 to sys.stderr. I had a circular dependency here. Now it's
2494 possible to run ipython as IDLE's shell (consider this pre-alpha,
2531 possible to run ipython as IDLE's shell (consider this pre-alpha,
2495 since true stdout things end up in the starting terminal instead
2532 since true stdout things end up in the starting terminal instead
2496 of IDLE's out).
2533 of IDLE's out).
2497
2534
2498 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2535 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2499 users who haven't # updated their prompt_in2 definitions. Remove
2536 users who haven't # updated their prompt_in2 definitions. Remove
2500 eventually.
2537 eventually.
2501 (multiple_replace): added credit to original ASPN recipe.
2538 (multiple_replace): added credit to original ASPN recipe.
2502
2539
2503 2004-06-15 Fernando Perez <fperez@colorado.edu>
2540 2004-06-15 Fernando Perez <fperez@colorado.edu>
2504
2541
2505 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2542 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2506 list of auto-defined aliases.
2543 list of auto-defined aliases.
2507
2544
2508 2004-06-13 Fernando Perez <fperez@colorado.edu>
2545 2004-06-13 Fernando Perez <fperez@colorado.edu>
2509
2546
2510 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2547 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2511 install was really requested (so setup.py can be used for other
2548 install was really requested (so setup.py can be used for other
2512 things under Windows).
2549 things under Windows).
2513
2550
2514 2004-06-10 Fernando Perez <fperez@colorado.edu>
2551 2004-06-10 Fernando Perez <fperez@colorado.edu>
2515
2552
2516 * IPython/Logger.py (Logger.create_log): Manually remove any old
2553 * IPython/Logger.py (Logger.create_log): Manually remove any old
2517 backup, since os.remove may fail under Windows. Fixes bug
2554 backup, since os.remove may fail under Windows. Fixes bug
2518 reported by Thorsten.
2555 reported by Thorsten.
2519
2556
2520 2004-06-09 Fernando Perez <fperez@colorado.edu>
2557 2004-06-09 Fernando Perez <fperez@colorado.edu>
2521
2558
2522 * examples/example-embed.py: fixed all references to %n (replaced
2559 * examples/example-embed.py: fixed all references to %n (replaced
2523 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2560 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2524 for all examples and the manual as well.
2561 for all examples and the manual as well.
2525
2562
2526 2004-06-08 Fernando Perez <fperez@colorado.edu>
2563 2004-06-08 Fernando Perez <fperez@colorado.edu>
2527
2564
2528 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2565 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2529 alignment and color management. All 3 prompt subsystems now
2566 alignment and color management. All 3 prompt subsystems now
2530 inherit from BasePrompt.
2567 inherit from BasePrompt.
2531
2568
2532 * tools/release: updates for windows installer build and tag rpms
2569 * tools/release: updates for windows installer build and tag rpms
2533 with python version (since paths are fixed).
2570 with python version (since paths are fixed).
2534
2571
2535 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2572 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2536 which will become eventually obsolete. Also fixed the default
2573 which will become eventually obsolete. Also fixed the default
2537 prompt_in2 to use \D, so at least new users start with the correct
2574 prompt_in2 to use \D, so at least new users start with the correct
2538 defaults.
2575 defaults.
2539 WARNING: Users with existing ipythonrc files will need to apply
2576 WARNING: Users with existing ipythonrc files will need to apply
2540 this fix manually!
2577 this fix manually!
2541
2578
2542 * setup.py: make windows installer (.exe). This is finally the
2579 * setup.py: make windows installer (.exe). This is finally the
2543 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2580 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2544 which I hadn't included because it required Python 2.3 (or recent
2581 which I hadn't included because it required Python 2.3 (or recent
2545 distutils).
2582 distutils).
2546
2583
2547 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2584 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2548 usage of new '\D' escape.
2585 usage of new '\D' escape.
2549
2586
2550 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2587 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2551 lacks os.getuid())
2588 lacks os.getuid())
2552 (CachedOutput.set_colors): Added the ability to turn coloring
2589 (CachedOutput.set_colors): Added the ability to turn coloring
2553 on/off with @colors even for manually defined prompt colors. It
2590 on/off with @colors even for manually defined prompt colors. It
2554 uses a nasty global, but it works safely and via the generic color
2591 uses a nasty global, but it works safely and via the generic color
2555 handling mechanism.
2592 handling mechanism.
2556 (Prompt2.__init__): Introduced new escape '\D' for continuation
2593 (Prompt2.__init__): Introduced new escape '\D' for continuation
2557 prompts. It represents the counter ('\#') as dots.
2594 prompts. It represents the counter ('\#') as dots.
2558 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2595 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2559 need to update their ipythonrc files and replace '%n' with '\D' in
2596 need to update their ipythonrc files and replace '%n' with '\D' in
2560 their prompt_in2 settings everywhere. Sorry, but there's
2597 their prompt_in2 settings everywhere. Sorry, but there's
2561 otherwise no clean way to get all prompts to properly align. The
2598 otherwise no clean way to get all prompts to properly align. The
2562 ipythonrc shipped with IPython has been updated.
2599 ipythonrc shipped with IPython has been updated.
2563
2600
2564 2004-06-07 Fernando Perez <fperez@colorado.edu>
2601 2004-06-07 Fernando Perez <fperez@colorado.edu>
2565
2602
2566 * setup.py (isfile): Pass local_icons option to latex2html, so the
2603 * setup.py (isfile): Pass local_icons option to latex2html, so the
2567 resulting HTML file is self-contained. Thanks to
2604 resulting HTML file is self-contained. Thanks to
2568 dryice-AT-liu.com.cn for the tip.
2605 dryice-AT-liu.com.cn for the tip.
2569
2606
2570 * pysh.py: I created a new profile 'shell', which implements a
2607 * pysh.py: I created a new profile 'shell', which implements a
2571 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2608 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2572 system shell, nor will it become one anytime soon. It's mainly
2609 system shell, nor will it become one anytime soon. It's mainly
2573 meant to illustrate the use of the new flexible bash-like prompts.
2610 meant to illustrate the use of the new flexible bash-like prompts.
2574 I guess it could be used by hardy souls for true shell management,
2611 I guess it could be used by hardy souls for true shell management,
2575 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2612 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2576 profile. This uses the InterpreterExec extension provided by
2613 profile. This uses the InterpreterExec extension provided by
2577 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2614 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2578
2615
2579 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2616 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2580 auto-align itself with the length of the previous input prompt
2617 auto-align itself with the length of the previous input prompt
2581 (taking into account the invisible color escapes).
2618 (taking into account the invisible color escapes).
2582 (CachedOutput.__init__): Large restructuring of this class. Now
2619 (CachedOutput.__init__): Large restructuring of this class. Now
2583 all three prompts (primary1, primary2, output) are proper objects,
2620 all three prompts (primary1, primary2, output) are proper objects,
2584 managed by the 'parent' CachedOutput class. The code is still a
2621 managed by the 'parent' CachedOutput class. The code is still a
2585 bit hackish (all prompts share state via a pointer to the cache),
2622 bit hackish (all prompts share state via a pointer to the cache),
2586 but it's overall far cleaner than before.
2623 but it's overall far cleaner than before.
2587
2624
2588 * IPython/genutils.py (getoutputerror): modified to add verbose,
2625 * IPython/genutils.py (getoutputerror): modified to add verbose,
2589 debug and header options. This makes the interface of all getout*
2626 debug and header options. This makes the interface of all getout*
2590 functions uniform.
2627 functions uniform.
2591 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2628 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2592
2629
2593 * IPython/Magic.py (Magic.default_option): added a function to
2630 * IPython/Magic.py (Magic.default_option): added a function to
2594 allow registering default options for any magic command. This
2631 allow registering default options for any magic command. This
2595 makes it easy to have profiles which customize the magics globally
2632 makes it easy to have profiles which customize the magics globally
2596 for a certain use. The values set through this function are
2633 for a certain use. The values set through this function are
2597 picked up by the parse_options() method, which all magics should
2634 picked up by the parse_options() method, which all magics should
2598 use to parse their options.
2635 use to parse their options.
2599
2636
2600 * IPython/genutils.py (warn): modified the warnings framework to
2637 * IPython/genutils.py (warn): modified the warnings framework to
2601 use the Term I/O class. I'm trying to slowly unify all of
2638 use the Term I/O class. I'm trying to slowly unify all of
2602 IPython's I/O operations to pass through Term.
2639 IPython's I/O operations to pass through Term.
2603
2640
2604 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2641 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2605 the secondary prompt to correctly match the length of the primary
2642 the secondary prompt to correctly match the length of the primary
2606 one for any prompt. Now multi-line code will properly line up
2643 one for any prompt. Now multi-line code will properly line up
2607 even for path dependent prompts, such as the new ones available
2644 even for path dependent prompts, such as the new ones available
2608 via the prompt_specials.
2645 via the prompt_specials.
2609
2646
2610 2004-06-06 Fernando Perez <fperez@colorado.edu>
2647 2004-06-06 Fernando Perez <fperez@colorado.edu>
2611
2648
2612 * IPython/Prompts.py (prompt_specials): Added the ability to have
2649 * IPython/Prompts.py (prompt_specials): Added the ability to have
2613 bash-like special sequences in the prompts, which get
2650 bash-like special sequences in the prompts, which get
2614 automatically expanded. Things like hostname, current working
2651 automatically expanded. Things like hostname, current working
2615 directory and username are implemented already, but it's easy to
2652 directory and username are implemented already, but it's easy to
2616 add more in the future. Thanks to a patch by W.J. van der Laan
2653 add more in the future. Thanks to a patch by W.J. van der Laan
2617 <gnufnork-AT-hetdigitalegat.nl>
2654 <gnufnork-AT-hetdigitalegat.nl>
2618 (prompt_specials): Added color support for prompt strings, so
2655 (prompt_specials): Added color support for prompt strings, so
2619 users can define arbitrary color setups for their prompts.
2656 users can define arbitrary color setups for their prompts.
2620
2657
2621 2004-06-05 Fernando Perez <fperez@colorado.edu>
2658 2004-06-05 Fernando Perez <fperez@colorado.edu>
2622
2659
2623 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2660 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2624 code to load Gary Bishop's readline and configure it
2661 code to load Gary Bishop's readline and configure it
2625 automatically. Thanks to Gary for help on this.
2662 automatically. Thanks to Gary for help on this.
2626
2663
2627 2004-06-01 Fernando Perez <fperez@colorado.edu>
2664 2004-06-01 Fernando Perez <fperez@colorado.edu>
2628
2665
2629 * IPython/Logger.py (Logger.create_log): fix bug for logging
2666 * IPython/Logger.py (Logger.create_log): fix bug for logging
2630 with no filename (previous fix was incomplete).
2667 with no filename (previous fix was incomplete).
2631
2668
2632 2004-05-25 Fernando Perez <fperez@colorado.edu>
2669 2004-05-25 Fernando Perez <fperez@colorado.edu>
2633
2670
2634 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2671 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2635 parens would get passed to the shell.
2672 parens would get passed to the shell.
2636
2673
2637 2004-05-20 Fernando Perez <fperez@colorado.edu>
2674 2004-05-20 Fernando Perez <fperez@colorado.edu>
2638
2675
2639 * IPython/Magic.py (Magic.magic_prun): changed default profile
2676 * IPython/Magic.py (Magic.magic_prun): changed default profile
2640 sort order to 'time' (the more common profiling need).
2677 sort order to 'time' (the more common profiling need).
2641
2678
2642 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2679 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2643 so that source code shown is guaranteed in sync with the file on
2680 so that source code shown is guaranteed in sync with the file on
2644 disk (also changed in psource). Similar fix to the one for
2681 disk (also changed in psource). Similar fix to the one for
2645 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2682 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2646 <yann.ledu-AT-noos.fr>.
2683 <yann.ledu-AT-noos.fr>.
2647
2684
2648 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2685 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2649 with a single option would not be correctly parsed. Closes
2686 with a single option would not be correctly parsed. Closes
2650 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2687 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2651 introduced in 0.6.0 (on 2004-05-06).
2688 introduced in 0.6.0 (on 2004-05-06).
2652
2689
2653 2004-05-13 *** Released version 0.6.0
2690 2004-05-13 *** Released version 0.6.0
2654
2691
2655 2004-05-13 Fernando Perez <fperez@colorado.edu>
2692 2004-05-13 Fernando Perez <fperez@colorado.edu>
2656
2693
2657 * debian/: Added debian/ directory to CVS, so that debian support
2694 * debian/: Added debian/ directory to CVS, so that debian support
2658 is publicly accessible. The debian package is maintained by Jack
2695 is publicly accessible. The debian package is maintained by Jack
2659 Moffit <jack-AT-xiph.org>.
2696 Moffit <jack-AT-xiph.org>.
2660
2697
2661 * Documentation: included the notes about an ipython-based system
2698 * Documentation: included the notes about an ipython-based system
2662 shell (the hypothetical 'pysh') into the new_design.pdf document,
2699 shell (the hypothetical 'pysh') into the new_design.pdf document,
2663 so that these ideas get distributed to users along with the
2700 so that these ideas get distributed to users along with the
2664 official documentation.
2701 official documentation.
2665
2702
2666 2004-05-10 Fernando Perez <fperez@colorado.edu>
2703 2004-05-10 Fernando Perez <fperez@colorado.edu>
2667
2704
2668 * IPython/Logger.py (Logger.create_log): fix recently introduced
2705 * IPython/Logger.py (Logger.create_log): fix recently introduced
2669 bug (misindented line) where logstart would fail when not given an
2706 bug (misindented line) where logstart would fail when not given an
2670 explicit filename.
2707 explicit filename.
2671
2708
2672 2004-05-09 Fernando Perez <fperez@colorado.edu>
2709 2004-05-09 Fernando Perez <fperez@colorado.edu>
2673
2710
2674 * IPython/Magic.py (Magic.parse_options): skip system call when
2711 * IPython/Magic.py (Magic.parse_options): skip system call when
2675 there are no options to look for. Faster, cleaner for the common
2712 there are no options to look for. Faster, cleaner for the common
2676 case.
2713 case.
2677
2714
2678 * Documentation: many updates to the manual: describing Windows
2715 * Documentation: many updates to the manual: describing Windows
2679 support better, Gnuplot updates, credits, misc small stuff. Also
2716 support better, Gnuplot updates, credits, misc small stuff. Also
2680 updated the new_design doc a bit.
2717 updated the new_design doc a bit.
2681
2718
2682 2004-05-06 *** Released version 0.6.0.rc1
2719 2004-05-06 *** Released version 0.6.0.rc1
2683
2720
2684 2004-05-06 Fernando Perez <fperez@colorado.edu>
2721 2004-05-06 Fernando Perez <fperez@colorado.edu>
2685
2722
2686 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2723 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2687 operations to use the vastly more efficient list/''.join() method.
2724 operations to use the vastly more efficient list/''.join() method.
2688 (FormattedTB.text): Fix
2725 (FormattedTB.text): Fix
2689 http://www.scipy.net/roundup/ipython/issue12 - exception source
2726 http://www.scipy.net/roundup/ipython/issue12 - exception source
2690 extract not updated after reload. Thanks to Mike Salib
2727 extract not updated after reload. Thanks to Mike Salib
2691 <msalib-AT-mit.edu> for pinning the source of the problem.
2728 <msalib-AT-mit.edu> for pinning the source of the problem.
2692 Fortunately, the solution works inside ipython and doesn't require
2729 Fortunately, the solution works inside ipython and doesn't require
2693 any changes to python proper.
2730 any changes to python proper.
2694
2731
2695 * IPython/Magic.py (Magic.parse_options): Improved to process the
2732 * IPython/Magic.py (Magic.parse_options): Improved to process the
2696 argument list as a true shell would (by actually using the
2733 argument list as a true shell would (by actually using the
2697 underlying system shell). This way, all @magics automatically get
2734 underlying system shell). This way, all @magics automatically get
2698 shell expansion for variables. Thanks to a comment by Alex
2735 shell expansion for variables. Thanks to a comment by Alex
2699 Schmolck.
2736 Schmolck.
2700
2737
2701 2004-04-04 Fernando Perez <fperez@colorado.edu>
2738 2004-04-04 Fernando Perez <fperez@colorado.edu>
2702
2739
2703 * IPython/iplib.py (InteractiveShell.interact): Added a special
2740 * IPython/iplib.py (InteractiveShell.interact): Added a special
2704 trap for a debugger quit exception, which is basically impossible
2741 trap for a debugger quit exception, which is basically impossible
2705 to handle by normal mechanisms, given what pdb does to the stack.
2742 to handle by normal mechanisms, given what pdb does to the stack.
2706 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2743 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2707
2744
2708 2004-04-03 Fernando Perez <fperez@colorado.edu>
2745 2004-04-03 Fernando Perez <fperez@colorado.edu>
2709
2746
2710 * IPython/genutils.py (Term): Standardized the names of the Term
2747 * IPython/genutils.py (Term): Standardized the names of the Term
2711 class streams to cin/cout/cerr, following C++ naming conventions
2748 class streams to cin/cout/cerr, following C++ naming conventions
2712 (I can't use in/out/err because 'in' is not a valid attribute
2749 (I can't use in/out/err because 'in' is not a valid attribute
2713 name).
2750 name).
2714
2751
2715 * IPython/iplib.py (InteractiveShell.interact): don't increment
2752 * IPython/iplib.py (InteractiveShell.interact): don't increment
2716 the prompt if there's no user input. By Daniel 'Dang' Griffith
2753 the prompt if there's no user input. By Daniel 'Dang' Griffith
2717 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2754 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2718 Francois Pinard.
2755 Francois Pinard.
2719
2756
2720 2004-04-02 Fernando Perez <fperez@colorado.edu>
2757 2004-04-02 Fernando Perez <fperez@colorado.edu>
2721
2758
2722 * IPython/genutils.py (Stream.__init__): Modified to survive at
2759 * IPython/genutils.py (Stream.__init__): Modified to survive at
2723 least importing in contexts where stdin/out/err aren't true file
2760 least importing in contexts where stdin/out/err aren't true file
2724 objects, such as PyCrust (they lack fileno() and mode). However,
2761 objects, such as PyCrust (they lack fileno() and mode). However,
2725 the recovery facilities which rely on these things existing will
2762 the recovery facilities which rely on these things existing will
2726 not work.
2763 not work.
2727
2764
2728 2004-04-01 Fernando Perez <fperez@colorado.edu>
2765 2004-04-01 Fernando Perez <fperez@colorado.edu>
2729
2766
2730 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2767 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2731 use the new getoutputerror() function, so it properly
2768 use the new getoutputerror() function, so it properly
2732 distinguishes stdout/err.
2769 distinguishes stdout/err.
2733
2770
2734 * IPython/genutils.py (getoutputerror): added a function to
2771 * IPython/genutils.py (getoutputerror): added a function to
2735 capture separately the standard output and error of a command.
2772 capture separately the standard output and error of a command.
2736 After a comment from dang on the mailing lists. This code is
2773 After a comment from dang on the mailing lists. This code is
2737 basically a modified version of commands.getstatusoutput(), from
2774 basically a modified version of commands.getstatusoutput(), from
2738 the standard library.
2775 the standard library.
2739
2776
2740 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2777 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2741 '!!' as a special syntax (shorthand) to access @sx.
2778 '!!' as a special syntax (shorthand) to access @sx.
2742
2779
2743 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2780 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2744 command and return its output as a list split on '\n'.
2781 command and return its output as a list split on '\n'.
2745
2782
2746 2004-03-31 Fernando Perez <fperez@colorado.edu>
2783 2004-03-31 Fernando Perez <fperez@colorado.edu>
2747
2784
2748 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2785 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2749 method to dictionaries used as FakeModule instances if they lack
2786 method to dictionaries used as FakeModule instances if they lack
2750 it. At least pydoc in python2.3 breaks for runtime-defined
2787 it. At least pydoc in python2.3 breaks for runtime-defined
2751 functions without this hack. At some point I need to _really_
2788 functions without this hack. At some point I need to _really_
2752 understand what FakeModule is doing, because it's a gross hack.
2789 understand what FakeModule is doing, because it's a gross hack.
2753 But it solves Arnd's problem for now...
2790 But it solves Arnd's problem for now...
2754
2791
2755 2004-02-27 Fernando Perez <fperez@colorado.edu>
2792 2004-02-27 Fernando Perez <fperez@colorado.edu>
2756
2793
2757 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2794 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2758 mode would behave erratically. Also increased the number of
2795 mode would behave erratically. Also increased the number of
2759 possible logs in rotate mod to 999. Thanks to Rod Holland
2796 possible logs in rotate mod to 999. Thanks to Rod Holland
2760 <rhh@StructureLABS.com> for the report and fixes.
2797 <rhh@StructureLABS.com> for the report and fixes.
2761
2798
2762 2004-02-26 Fernando Perez <fperez@colorado.edu>
2799 2004-02-26 Fernando Perez <fperez@colorado.edu>
2763
2800
2764 * IPython/genutils.py (page): Check that the curses module really
2801 * IPython/genutils.py (page): Check that the curses module really
2765 has the initscr attribute before trying to use it. For some
2802 has the initscr attribute before trying to use it. For some
2766 reason, the Solaris curses module is missing this. I think this
2803 reason, the Solaris curses module is missing this. I think this
2767 should be considered a Solaris python bug, but I'm not sure.
2804 should be considered a Solaris python bug, but I'm not sure.
2768
2805
2769 2004-01-17 Fernando Perez <fperez@colorado.edu>
2806 2004-01-17 Fernando Perez <fperez@colorado.edu>
2770
2807
2771 * IPython/genutils.py (Stream.__init__): Changes to try to make
2808 * IPython/genutils.py (Stream.__init__): Changes to try to make
2772 ipython robust against stdin/out/err being closed by the user.
2809 ipython robust against stdin/out/err being closed by the user.
2773 This is 'user error' (and blocks a normal python session, at least
2810 This is 'user error' (and blocks a normal python session, at least
2774 the stdout case). However, Ipython should be able to survive such
2811 the stdout case). However, Ipython should be able to survive such
2775 instances of abuse as gracefully as possible. To simplify the
2812 instances of abuse as gracefully as possible. To simplify the
2776 coding and maintain compatibility with Gary Bishop's Term
2813 coding and maintain compatibility with Gary Bishop's Term
2777 contributions, I've made use of classmethods for this. I think
2814 contributions, I've made use of classmethods for this. I think
2778 this introduces a dependency on python 2.2.
2815 this introduces a dependency on python 2.2.
2779
2816
2780 2004-01-13 Fernando Perez <fperez@colorado.edu>
2817 2004-01-13 Fernando Perez <fperez@colorado.edu>
2781
2818
2782 * IPython/numutils.py (exp_safe): simplified the code a bit and
2819 * IPython/numutils.py (exp_safe): simplified the code a bit and
2783 removed the need for importing the kinds module altogether.
2820 removed the need for importing the kinds module altogether.
2784
2821
2785 2004-01-06 Fernando Perez <fperez@colorado.edu>
2822 2004-01-06 Fernando Perez <fperez@colorado.edu>
2786
2823
2787 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2824 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2788 a magic function instead, after some community feedback. No
2825 a magic function instead, after some community feedback. No
2789 special syntax will exist for it, but its name is deliberately
2826 special syntax will exist for it, but its name is deliberately
2790 very short.
2827 very short.
2791
2828
2792 2003-12-20 Fernando Perez <fperez@colorado.edu>
2829 2003-12-20 Fernando Perez <fperez@colorado.edu>
2793
2830
2794 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2831 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2795 new functionality, to automagically assign the result of a shell
2832 new functionality, to automagically assign the result of a shell
2796 command to a variable. I'll solicit some community feedback on
2833 command to a variable. I'll solicit some community feedback on
2797 this before making it permanent.
2834 this before making it permanent.
2798
2835
2799 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2836 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2800 requested about callables for which inspect couldn't obtain a
2837 requested about callables for which inspect couldn't obtain a
2801 proper argspec. Thanks to a crash report sent by Etienne
2838 proper argspec. Thanks to a crash report sent by Etienne
2802 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2839 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2803
2840
2804 2003-12-09 Fernando Perez <fperez@colorado.edu>
2841 2003-12-09 Fernando Perez <fperez@colorado.edu>
2805
2842
2806 * IPython/genutils.py (page): patch for the pager to work across
2843 * IPython/genutils.py (page): patch for the pager to work across
2807 various versions of Windows. By Gary Bishop.
2844 various versions of Windows. By Gary Bishop.
2808
2845
2809 2003-12-04 Fernando Perez <fperez@colorado.edu>
2846 2003-12-04 Fernando Perez <fperez@colorado.edu>
2810
2847
2811 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2848 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2812 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2849 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2813 While I tested this and it looks ok, there may still be corner
2850 While I tested this and it looks ok, there may still be corner
2814 cases I've missed.
2851 cases I've missed.
2815
2852
2816 2003-12-01 Fernando Perez <fperez@colorado.edu>
2853 2003-12-01 Fernando Perez <fperez@colorado.edu>
2817
2854
2818 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2855 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2819 where a line like 'p,q=1,2' would fail because the automagic
2856 where a line like 'p,q=1,2' would fail because the automagic
2820 system would be triggered for @p.
2857 system would be triggered for @p.
2821
2858
2822 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2859 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2823 cleanups, code unmodified.
2860 cleanups, code unmodified.
2824
2861
2825 * IPython/genutils.py (Term): added a class for IPython to handle
2862 * IPython/genutils.py (Term): added a class for IPython to handle
2826 output. In most cases it will just be a proxy for stdout/err, but
2863 output. In most cases it will just be a proxy for stdout/err, but
2827 having this allows modifications to be made for some platforms,
2864 having this allows modifications to be made for some platforms,
2828 such as handling color escapes under Windows. All of this code
2865 such as handling color escapes under Windows. All of this code
2829 was contributed by Gary Bishop, with minor modifications by me.
2866 was contributed by Gary Bishop, with minor modifications by me.
2830 The actual changes affect many files.
2867 The actual changes affect many files.
2831
2868
2832 2003-11-30 Fernando Perez <fperez@colorado.edu>
2869 2003-11-30 Fernando Perez <fperez@colorado.edu>
2833
2870
2834 * IPython/iplib.py (file_matches): new completion code, courtesy
2871 * IPython/iplib.py (file_matches): new completion code, courtesy
2835 of Jeff Collins. This enables filename completion again under
2872 of Jeff Collins. This enables filename completion again under
2836 python 2.3, which disabled it at the C level.
2873 python 2.3, which disabled it at the C level.
2837
2874
2838 2003-11-11 Fernando Perez <fperez@colorado.edu>
2875 2003-11-11 Fernando Perez <fperez@colorado.edu>
2839
2876
2840 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2877 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2841 for Numeric.array(map(...)), but often convenient.
2878 for Numeric.array(map(...)), but often convenient.
2842
2879
2843 2003-11-05 Fernando Perez <fperez@colorado.edu>
2880 2003-11-05 Fernando Perez <fperez@colorado.edu>
2844
2881
2845 * IPython/numutils.py (frange): Changed a call from int() to
2882 * IPython/numutils.py (frange): Changed a call from int() to
2846 int(round()) to prevent a problem reported with arange() in the
2883 int(round()) to prevent a problem reported with arange() in the
2847 numpy list.
2884 numpy list.
2848
2885
2849 2003-10-06 Fernando Perez <fperez@colorado.edu>
2886 2003-10-06 Fernando Perez <fperez@colorado.edu>
2850
2887
2851 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2888 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2852 prevent crashes if sys lacks an argv attribute (it happens with
2889 prevent crashes if sys lacks an argv attribute (it happens with
2853 embedded interpreters which build a bare-bones sys module).
2890 embedded interpreters which build a bare-bones sys module).
2854 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2891 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2855
2892
2856 2003-09-24 Fernando Perez <fperez@colorado.edu>
2893 2003-09-24 Fernando Perez <fperez@colorado.edu>
2857
2894
2858 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2895 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2859 to protect against poorly written user objects where __getattr__
2896 to protect against poorly written user objects where __getattr__
2860 raises exceptions other than AttributeError. Thanks to a bug
2897 raises exceptions other than AttributeError. Thanks to a bug
2861 report by Oliver Sander <osander-AT-gmx.de>.
2898 report by Oliver Sander <osander-AT-gmx.de>.
2862
2899
2863 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2900 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2864 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2901 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2865
2902
2866 2003-09-09 Fernando Perez <fperez@colorado.edu>
2903 2003-09-09 Fernando Perez <fperez@colorado.edu>
2867
2904
2868 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2905 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2869 unpacking a list whith a callable as first element would
2906 unpacking a list whith a callable as first element would
2870 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2907 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2871 Collins.
2908 Collins.
2872
2909
2873 2003-08-25 *** Released version 0.5.0
2910 2003-08-25 *** Released version 0.5.0
2874
2911
2875 2003-08-22 Fernando Perez <fperez@colorado.edu>
2912 2003-08-22 Fernando Perez <fperez@colorado.edu>
2876
2913
2877 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2914 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2878 improperly defined user exceptions. Thanks to feedback from Mark
2915 improperly defined user exceptions. Thanks to feedback from Mark
2879 Russell <mrussell-AT-verio.net>.
2916 Russell <mrussell-AT-verio.net>.
2880
2917
2881 2003-08-20 Fernando Perez <fperez@colorado.edu>
2918 2003-08-20 Fernando Perez <fperez@colorado.edu>
2882
2919
2883 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2920 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2884 printing so that it would print multi-line string forms starting
2921 printing so that it would print multi-line string forms starting
2885 with a new line. This way the formatting is better respected for
2922 with a new line. This way the formatting is better respected for
2886 objects which work hard to make nice string forms.
2923 objects which work hard to make nice string forms.
2887
2924
2888 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2925 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2889 autocall would overtake data access for objects with both
2926 autocall would overtake data access for objects with both
2890 __getitem__ and __call__.
2927 __getitem__ and __call__.
2891
2928
2892 2003-08-19 *** Released version 0.5.0-rc1
2929 2003-08-19 *** Released version 0.5.0-rc1
2893
2930
2894 2003-08-19 Fernando Perez <fperez@colorado.edu>
2931 2003-08-19 Fernando Perez <fperez@colorado.edu>
2895
2932
2896 * IPython/deep_reload.py (load_tail): single tiny change here
2933 * IPython/deep_reload.py (load_tail): single tiny change here
2897 seems to fix the long-standing bug of dreload() failing to work
2934 seems to fix the long-standing bug of dreload() failing to work
2898 for dotted names. But this module is pretty tricky, so I may have
2935 for dotted names. But this module is pretty tricky, so I may have
2899 missed some subtlety. Needs more testing!.
2936 missed some subtlety. Needs more testing!.
2900
2937
2901 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2938 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2902 exceptions which have badly implemented __str__ methods.
2939 exceptions which have badly implemented __str__ methods.
2903 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2940 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2904 which I've been getting reports about from Python 2.3 users. I
2941 which I've been getting reports about from Python 2.3 users. I
2905 wish I had a simple test case to reproduce the problem, so I could
2942 wish I had a simple test case to reproduce the problem, so I could
2906 either write a cleaner workaround or file a bug report if
2943 either write a cleaner workaround or file a bug report if
2907 necessary.
2944 necessary.
2908
2945
2909 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2946 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2910 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2947 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2911 a bug report by Tjabo Kloppenburg.
2948 a bug report by Tjabo Kloppenburg.
2912
2949
2913 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2950 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2914 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2951 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2915 seems rather unstable. Thanks to a bug report by Tjabo
2952 seems rather unstable. Thanks to a bug report by Tjabo
2916 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2953 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2917
2954
2918 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2955 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2919 this out soon because of the critical fixes in the inner loop for
2956 this out soon because of the critical fixes in the inner loop for
2920 generators.
2957 generators.
2921
2958
2922 * IPython/Magic.py (Magic.getargspec): removed. This (and
2959 * IPython/Magic.py (Magic.getargspec): removed. This (and
2923 _get_def) have been obsoleted by OInspect for a long time, I
2960 _get_def) have been obsoleted by OInspect for a long time, I
2924 hadn't noticed that they were dead code.
2961 hadn't noticed that they were dead code.
2925 (Magic._ofind): restored _ofind functionality for a few literals
2962 (Magic._ofind): restored _ofind functionality for a few literals
2926 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2963 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2927 for things like "hello".capitalize?, since that would require a
2964 for things like "hello".capitalize?, since that would require a
2928 potentially dangerous eval() again.
2965 potentially dangerous eval() again.
2929
2966
2930 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2967 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2931 logic a bit more to clean up the escapes handling and minimize the
2968 logic a bit more to clean up the escapes handling and minimize the
2932 use of _ofind to only necessary cases. The interactive 'feel' of
2969 use of _ofind to only necessary cases. The interactive 'feel' of
2933 IPython should have improved quite a bit with the changes in
2970 IPython should have improved quite a bit with the changes in
2934 _prefilter and _ofind (besides being far safer than before).
2971 _prefilter and _ofind (besides being far safer than before).
2935
2972
2936 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2973 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2937 obscure, never reported). Edit would fail to find the object to
2974 obscure, never reported). Edit would fail to find the object to
2938 edit under some circumstances.
2975 edit under some circumstances.
2939 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2976 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2940 which were causing double-calling of generators. Those eval calls
2977 which were causing double-calling of generators. Those eval calls
2941 were _very_ dangerous, since code with side effects could be
2978 were _very_ dangerous, since code with side effects could be
2942 triggered. As they say, 'eval is evil'... These were the
2979 triggered. As they say, 'eval is evil'... These were the
2943 nastiest evals in IPython. Besides, _ofind is now far simpler,
2980 nastiest evals in IPython. Besides, _ofind is now far simpler,
2944 and it should also be quite a bit faster. Its use of inspect is
2981 and it should also be quite a bit faster. Its use of inspect is
2945 also safer, so perhaps some of the inspect-related crashes I've
2982 also safer, so perhaps some of the inspect-related crashes I've
2946 seen lately with Python 2.3 might be taken care of. That will
2983 seen lately with Python 2.3 might be taken care of. That will
2947 need more testing.
2984 need more testing.
2948
2985
2949 2003-08-17 Fernando Perez <fperez@colorado.edu>
2986 2003-08-17 Fernando Perez <fperez@colorado.edu>
2950
2987
2951 * IPython/iplib.py (InteractiveShell._prefilter): significant
2988 * IPython/iplib.py (InteractiveShell._prefilter): significant
2952 simplifications to the logic for handling user escapes. Faster
2989 simplifications to the logic for handling user escapes. Faster
2953 and simpler code.
2990 and simpler code.
2954
2991
2955 2003-08-14 Fernando Perez <fperez@colorado.edu>
2992 2003-08-14 Fernando Perez <fperez@colorado.edu>
2956
2993
2957 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2994 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2958 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2995 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2959 but it should be quite a bit faster. And the recursive version
2996 but it should be quite a bit faster. And the recursive version
2960 generated O(log N) intermediate storage for all rank>1 arrays,
2997 generated O(log N) intermediate storage for all rank>1 arrays,
2961 even if they were contiguous.
2998 even if they were contiguous.
2962 (l1norm): Added this function.
2999 (l1norm): Added this function.
2963 (norm): Added this function for arbitrary norms (including
3000 (norm): Added this function for arbitrary norms (including
2964 l-infinity). l1 and l2 are still special cases for convenience
3001 l-infinity). l1 and l2 are still special cases for convenience
2965 and speed.
3002 and speed.
2966
3003
2967 2003-08-03 Fernando Perez <fperez@colorado.edu>
3004 2003-08-03 Fernando Perez <fperez@colorado.edu>
2968
3005
2969 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
3006 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2970 exceptions, which now raise PendingDeprecationWarnings in Python
3007 exceptions, which now raise PendingDeprecationWarnings in Python
2971 2.3. There were some in Magic and some in Gnuplot2.
3008 2.3. There were some in Magic and some in Gnuplot2.
2972
3009
2973 2003-06-30 Fernando Perez <fperez@colorado.edu>
3010 2003-06-30 Fernando Perez <fperez@colorado.edu>
2974
3011
2975 * IPython/genutils.py (page): modified to call curses only for
3012 * IPython/genutils.py (page): modified to call curses only for
2976 terminals where TERM=='xterm'. After problems under many other
3013 terminals where TERM=='xterm'. After problems under many other
2977 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
3014 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2978
3015
2979 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
3016 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2980 would be triggered when readline was absent. This was just an old
3017 would be triggered when readline was absent. This was just an old
2981 debugging statement I'd forgotten to take out.
3018 debugging statement I'd forgotten to take out.
2982
3019
2983 2003-06-20 Fernando Perez <fperez@colorado.edu>
3020 2003-06-20 Fernando Perez <fperez@colorado.edu>
2984
3021
2985 * IPython/genutils.py (clock): modified to return only user time
3022 * IPython/genutils.py (clock): modified to return only user time
2986 (not counting system time), after a discussion on scipy. While
3023 (not counting system time), after a discussion on scipy. While
2987 system time may be a useful quantity occasionally, it may much
3024 system time may be a useful quantity occasionally, it may much
2988 more easily be skewed by occasional swapping or other similar
3025 more easily be skewed by occasional swapping or other similar
2989 activity.
3026 activity.
2990
3027
2991 2003-06-05 Fernando Perez <fperez@colorado.edu>
3028 2003-06-05 Fernando Perez <fperez@colorado.edu>
2992
3029
2993 * IPython/numutils.py (identity): new function, for building
3030 * IPython/numutils.py (identity): new function, for building
2994 arbitrary rank Kronecker deltas (mostly backwards compatible with
3031 arbitrary rank Kronecker deltas (mostly backwards compatible with
2995 Numeric.identity)
3032 Numeric.identity)
2996
3033
2997 2003-06-03 Fernando Perez <fperez@colorado.edu>
3034 2003-06-03 Fernando Perez <fperez@colorado.edu>
2998
3035
2999 * IPython/iplib.py (InteractiveShell.handle_magic): protect
3036 * IPython/iplib.py (InteractiveShell.handle_magic): protect
3000 arguments passed to magics with spaces, to allow trailing '\' to
3037 arguments passed to magics with spaces, to allow trailing '\' to
3001 work normally (mainly for Windows users).
3038 work normally (mainly for Windows users).
3002
3039
3003 2003-05-29 Fernando Perez <fperez@colorado.edu>
3040 2003-05-29 Fernando Perez <fperez@colorado.edu>
3004
3041
3005 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
3042 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
3006 instead of pydoc.help. This fixes a bizarre behavior where
3043 instead of pydoc.help. This fixes a bizarre behavior where
3007 printing '%s' % locals() would trigger the help system. Now
3044 printing '%s' % locals() would trigger the help system. Now
3008 ipython behaves like normal python does.
3045 ipython behaves like normal python does.
3009
3046
3010 Note that if one does 'from pydoc import help', the bizarre
3047 Note that if one does 'from pydoc import help', the bizarre
3011 behavior returns, but this will also happen in normal python, so
3048 behavior returns, but this will also happen in normal python, so
3012 it's not an ipython bug anymore (it has to do with how pydoc.help
3049 it's not an ipython bug anymore (it has to do with how pydoc.help
3013 is implemented).
3050 is implemented).
3014
3051
3015 2003-05-22 Fernando Perez <fperez@colorado.edu>
3052 2003-05-22 Fernando Perez <fperez@colorado.edu>
3016
3053
3017 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
3054 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
3018 return [] instead of None when nothing matches, also match to end
3055 return [] instead of None when nothing matches, also match to end
3019 of line. Patch by Gary Bishop.
3056 of line. Patch by Gary Bishop.
3020
3057
3021 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
3058 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
3022 protection as before, for files passed on the command line. This
3059 protection as before, for files passed on the command line. This
3023 prevents the CrashHandler from kicking in if user files call into
3060 prevents the CrashHandler from kicking in if user files call into
3024 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
3061 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
3025 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
3062 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
3026
3063
3027 2003-05-20 *** Released version 0.4.0
3064 2003-05-20 *** Released version 0.4.0
3028
3065
3029 2003-05-20 Fernando Perez <fperez@colorado.edu>
3066 2003-05-20 Fernando Perez <fperez@colorado.edu>
3030
3067
3031 * setup.py: added support for manpages. It's a bit hackish b/c of
3068 * setup.py: added support for manpages. It's a bit hackish b/c of
3032 a bug in the way the bdist_rpm distutils target handles gzipped
3069 a bug in the way the bdist_rpm distutils target handles gzipped
3033 manpages, but it works. After a patch by Jack.
3070 manpages, but it works. After a patch by Jack.
3034
3071
3035 2003-05-19 Fernando Perez <fperez@colorado.edu>
3072 2003-05-19 Fernando Perez <fperez@colorado.edu>
3036
3073
3037 * IPython/numutils.py: added a mockup of the kinds module, since
3074 * IPython/numutils.py: added a mockup of the kinds module, since
3038 it was recently removed from Numeric. This way, numutils will
3075 it was recently removed from Numeric. This way, numutils will
3039 work for all users even if they are missing kinds.
3076 work for all users even if they are missing kinds.
3040
3077
3041 * IPython/Magic.py (Magic._ofind): Harden against an inspect
3078 * IPython/Magic.py (Magic._ofind): Harden against an inspect
3042 failure, which can occur with SWIG-wrapped extensions. After a
3079 failure, which can occur with SWIG-wrapped extensions. After a
3043 crash report from Prabhu.
3080 crash report from Prabhu.
3044
3081
3045 2003-05-16 Fernando Perez <fperez@colorado.edu>
3082 2003-05-16 Fernando Perez <fperez@colorado.edu>
3046
3083
3047 * IPython/iplib.py (InteractiveShell.excepthook): New method to
3084 * IPython/iplib.py (InteractiveShell.excepthook): New method to
3048 protect ipython from user code which may call directly
3085 protect ipython from user code which may call directly
3049 sys.excepthook (this looks like an ipython crash to the user, even
3086 sys.excepthook (this looks like an ipython crash to the user, even
3050 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3087 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3051 This is especially important to help users of WxWindows, but may
3088 This is especially important to help users of WxWindows, but may
3052 also be useful in other cases.
3089 also be useful in other cases.
3053
3090
3054 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
3091 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
3055 an optional tb_offset to be specified, and to preserve exception
3092 an optional tb_offset to be specified, and to preserve exception
3056 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3093 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3057
3094
3058 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
3095 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
3059
3096
3060 2003-05-15 Fernando Perez <fperez@colorado.edu>
3097 2003-05-15 Fernando Perez <fperez@colorado.edu>
3061
3098
3062 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
3099 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
3063 installing for a new user under Windows.
3100 installing for a new user under Windows.
3064
3101
3065 2003-05-12 Fernando Perez <fperez@colorado.edu>
3102 2003-05-12 Fernando Perez <fperez@colorado.edu>
3066
3103
3067 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
3104 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
3068 handler for Emacs comint-based lines. Currently it doesn't do
3105 handler for Emacs comint-based lines. Currently it doesn't do
3069 much (but importantly, it doesn't update the history cache). In
3106 much (but importantly, it doesn't update the history cache). In
3070 the future it may be expanded if Alex needs more functionality
3107 the future it may be expanded if Alex needs more functionality
3071 there.
3108 there.
3072
3109
3073 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
3110 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
3074 info to crash reports.
3111 info to crash reports.
3075
3112
3076 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
3113 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
3077 just like Python's -c. Also fixed crash with invalid -color
3114 just like Python's -c. Also fixed crash with invalid -color
3078 option value at startup. Thanks to Will French
3115 option value at startup. Thanks to Will French
3079 <wfrench-AT-bestweb.net> for the bug report.
3116 <wfrench-AT-bestweb.net> for the bug report.
3080
3117
3081 2003-05-09 Fernando Perez <fperez@colorado.edu>
3118 2003-05-09 Fernando Perez <fperez@colorado.edu>
3082
3119
3083 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
3120 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
3084 to EvalDict (it's a mapping, after all) and simplified its code
3121 to EvalDict (it's a mapping, after all) and simplified its code
3085 quite a bit, after a nice discussion on c.l.py where Gustavo
3122 quite a bit, after a nice discussion on c.l.py where Gustavo
3086 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
3123 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
3087
3124
3088 2003-04-30 Fernando Perez <fperez@colorado.edu>
3125 2003-04-30 Fernando Perez <fperez@colorado.edu>
3089
3126
3090 * IPython/genutils.py (timings_out): modified it to reduce its
3127 * IPython/genutils.py (timings_out): modified it to reduce its
3091 overhead in the common reps==1 case.
3128 overhead in the common reps==1 case.
3092
3129
3093 2003-04-29 Fernando Perez <fperez@colorado.edu>
3130 2003-04-29 Fernando Perez <fperez@colorado.edu>
3094
3131
3095 * IPython/genutils.py (timings_out): Modified to use the resource
3132 * IPython/genutils.py (timings_out): Modified to use the resource
3096 module, which avoids the wraparound problems of time.clock().
3133 module, which avoids the wraparound problems of time.clock().
3097
3134
3098 2003-04-17 *** Released version 0.2.15pre4
3135 2003-04-17 *** Released version 0.2.15pre4
3099
3136
3100 2003-04-17 Fernando Perez <fperez@colorado.edu>
3137 2003-04-17 Fernando Perez <fperez@colorado.edu>
3101
3138
3102 * setup.py (scriptfiles): Split windows-specific stuff over to a
3139 * setup.py (scriptfiles): Split windows-specific stuff over to a
3103 separate file, in an attempt to have a Windows GUI installer.
3140 separate file, in an attempt to have a Windows GUI installer.
3104 That didn't work, but part of the groundwork is done.
3141 That didn't work, but part of the groundwork is done.
3105
3142
3106 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
3143 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
3107 indent/unindent with 4 spaces. Particularly useful in combination
3144 indent/unindent with 4 spaces. Particularly useful in combination
3108 with the new auto-indent option.
3145 with the new auto-indent option.
3109
3146
3110 2003-04-16 Fernando Perez <fperez@colorado.edu>
3147 2003-04-16 Fernando Perez <fperez@colorado.edu>
3111
3148
3112 * IPython/Magic.py: various replacements of self.rc for
3149 * IPython/Magic.py: various replacements of self.rc for
3113 self.shell.rc. A lot more remains to be done to fully disentangle
3150 self.shell.rc. A lot more remains to be done to fully disentangle
3114 this class from the main Shell class.
3151 this class from the main Shell class.
3115
3152
3116 * IPython/GnuplotRuntime.py: added checks for mouse support so
3153 * IPython/GnuplotRuntime.py: added checks for mouse support so
3117 that we don't try to enable it if the current gnuplot doesn't
3154 that we don't try to enable it if the current gnuplot doesn't
3118 really support it. Also added checks so that we don't try to
3155 really support it. Also added checks so that we don't try to
3119 enable persist under Windows (where Gnuplot doesn't recognize the
3156 enable persist under Windows (where Gnuplot doesn't recognize the
3120 option).
3157 option).
3121
3158
3122 * IPython/iplib.py (InteractiveShell.interact): Added optional
3159 * IPython/iplib.py (InteractiveShell.interact): Added optional
3123 auto-indenting code, after a patch by King C. Shu
3160 auto-indenting code, after a patch by King C. Shu
3124 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
3161 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
3125 get along well with pasting indented code. If I ever figure out
3162 get along well with pasting indented code. If I ever figure out
3126 how to make that part go well, it will become on by default.
3163 how to make that part go well, it will become on by default.
3127
3164
3128 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
3165 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
3129 crash ipython if there was an unmatched '%' in the user's prompt
3166 crash ipython if there was an unmatched '%' in the user's prompt
3130 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3167 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3131
3168
3132 * IPython/iplib.py (InteractiveShell.interact): removed the
3169 * IPython/iplib.py (InteractiveShell.interact): removed the
3133 ability to ask the user whether he wants to crash or not at the
3170 ability to ask the user whether he wants to crash or not at the
3134 'last line' exception handler. Calling functions at that point
3171 'last line' exception handler. Calling functions at that point
3135 changes the stack, and the error reports would have incorrect
3172 changes the stack, and the error reports would have incorrect
3136 tracebacks.
3173 tracebacks.
3137
3174
3138 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
3175 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
3139 pass through a peger a pretty-printed form of any object. After a
3176 pass through a peger a pretty-printed form of any object. After a
3140 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
3177 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
3141
3178
3142 2003-04-14 Fernando Perez <fperez@colorado.edu>
3179 2003-04-14 Fernando Perez <fperez@colorado.edu>
3143
3180
3144 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
3181 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
3145 all files in ~ would be modified at first install (instead of
3182 all files in ~ would be modified at first install (instead of
3146 ~/.ipython). This could be potentially disastrous, as the
3183 ~/.ipython). This could be potentially disastrous, as the
3147 modification (make line-endings native) could damage binary files.
3184 modification (make line-endings native) could damage binary files.
3148
3185
3149 2003-04-10 Fernando Perez <fperez@colorado.edu>
3186 2003-04-10 Fernando Perez <fperez@colorado.edu>
3150
3187
3151 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
3188 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
3152 handle only lines which are invalid python. This now means that
3189 handle only lines which are invalid python. This now means that
3153 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
3190 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
3154 for the bug report.
3191 for the bug report.
3155
3192
3156 2003-04-01 Fernando Perez <fperez@colorado.edu>
3193 2003-04-01 Fernando Perez <fperez@colorado.edu>
3157
3194
3158 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
3195 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
3159 where failing to set sys.last_traceback would crash pdb.pm().
3196 where failing to set sys.last_traceback would crash pdb.pm().
3160 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
3197 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
3161 report.
3198 report.
3162
3199
3163 2003-03-25 Fernando Perez <fperez@colorado.edu>
3200 2003-03-25 Fernando Perez <fperez@colorado.edu>
3164
3201
3165 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
3202 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
3166 before printing it (it had a lot of spurious blank lines at the
3203 before printing it (it had a lot of spurious blank lines at the
3167 end).
3204 end).
3168
3205
3169 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
3206 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
3170 output would be sent 21 times! Obviously people don't use this
3207 output would be sent 21 times! Obviously people don't use this
3171 too often, or I would have heard about it.
3208 too often, or I would have heard about it.
3172
3209
3173 2003-03-24 Fernando Perez <fperez@colorado.edu>
3210 2003-03-24 Fernando Perez <fperez@colorado.edu>
3174
3211
3175 * setup.py (scriptfiles): renamed the data_files parameter from
3212 * setup.py (scriptfiles): renamed the data_files parameter from
3176 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
3213 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
3177 for the patch.
3214 for the patch.
3178
3215
3179 2003-03-20 Fernando Perez <fperez@colorado.edu>
3216 2003-03-20 Fernando Perez <fperez@colorado.edu>
3180
3217
3181 * IPython/genutils.py (error): added error() and fatal()
3218 * IPython/genutils.py (error): added error() and fatal()
3182 functions.
3219 functions.
3183
3220
3184 2003-03-18 *** Released version 0.2.15pre3
3221 2003-03-18 *** Released version 0.2.15pre3
3185
3222
3186 2003-03-18 Fernando Perez <fperez@colorado.edu>
3223 2003-03-18 Fernando Perez <fperez@colorado.edu>
3187
3224
3188 * setupext/install_data_ext.py
3225 * setupext/install_data_ext.py
3189 (install_data_ext.initialize_options): Class contributed by Jack
3226 (install_data_ext.initialize_options): Class contributed by Jack
3190 Moffit for fixing the old distutils hack. He is sending this to
3227 Moffit for fixing the old distutils hack. He is sending this to
3191 the distutils folks so in the future we may not need it as a
3228 the distutils folks so in the future we may not need it as a
3192 private fix.
3229 private fix.
3193
3230
3194 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
3231 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
3195 changes for Debian packaging. See his patch for full details.
3232 changes for Debian packaging. See his patch for full details.
3196 The old distutils hack of making the ipythonrc* files carry a
3233 The old distutils hack of making the ipythonrc* files carry a
3197 bogus .py extension is gone, at last. Examples were moved to a
3234 bogus .py extension is gone, at last. Examples were moved to a
3198 separate subdir under doc/, and the separate executable scripts
3235 separate subdir under doc/, and the separate executable scripts
3199 now live in their own directory. Overall a great cleanup. The
3236 now live in their own directory. Overall a great cleanup. The
3200 manual was updated to use the new files, and setup.py has been
3237 manual was updated to use the new files, and setup.py has been
3201 fixed for this setup.
3238 fixed for this setup.
3202
3239
3203 * IPython/PyColorize.py (Parser.usage): made non-executable and
3240 * IPython/PyColorize.py (Parser.usage): made non-executable and
3204 created a pycolor wrapper around it to be included as a script.
3241 created a pycolor wrapper around it to be included as a script.
3205
3242
3206 2003-03-12 *** Released version 0.2.15pre2
3243 2003-03-12 *** Released version 0.2.15pre2
3207
3244
3208 2003-03-12 Fernando Perez <fperez@colorado.edu>
3245 2003-03-12 Fernando Perez <fperez@colorado.edu>
3209
3246
3210 * IPython/ColorANSI.py (make_color_table): Finally fixed the
3247 * IPython/ColorANSI.py (make_color_table): Finally fixed the
3211 long-standing problem with garbage characters in some terminals.
3248 long-standing problem with garbage characters in some terminals.
3212 The issue was really that the \001 and \002 escapes must _only_ be
3249 The issue was really that the \001 and \002 escapes must _only_ be
3213 passed to input prompts (which call readline), but _never_ to
3250 passed to input prompts (which call readline), but _never_ to
3214 normal text to be printed on screen. I changed ColorANSI to have
3251 normal text to be printed on screen. I changed ColorANSI to have
3215 two classes: TermColors and InputTermColors, each with the
3252 two classes: TermColors and InputTermColors, each with the
3216 appropriate escapes for input prompts or normal text. The code in
3253 appropriate escapes for input prompts or normal text. The code in
3217 Prompts.py got slightly more complicated, but this very old and
3254 Prompts.py got slightly more complicated, but this very old and
3218 annoying bug is finally fixed.
3255 annoying bug is finally fixed.
3219
3256
3220 All the credit for nailing down the real origin of this problem
3257 All the credit for nailing down the real origin of this problem
3221 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
3258 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
3222 *Many* thanks to him for spending quite a bit of effort on this.
3259 *Many* thanks to him for spending quite a bit of effort on this.
3223
3260
3224 2003-03-05 *** Released version 0.2.15pre1
3261 2003-03-05 *** Released version 0.2.15pre1
3225
3262
3226 2003-03-03 Fernando Perez <fperez@colorado.edu>
3263 2003-03-03 Fernando Perez <fperez@colorado.edu>
3227
3264
3228 * IPython/FakeModule.py: Moved the former _FakeModule to a
3265 * IPython/FakeModule.py: Moved the former _FakeModule to a
3229 separate file, because it's also needed by Magic (to fix a similar
3266 separate file, because it's also needed by Magic (to fix a similar
3230 pickle-related issue in @run).
3267 pickle-related issue in @run).
3231
3268
3232 2003-03-02 Fernando Perez <fperez@colorado.edu>
3269 2003-03-02 Fernando Perez <fperez@colorado.edu>
3233
3270
3234 * IPython/Magic.py (Magic.magic_autocall): new magic to control
3271 * IPython/Magic.py (Magic.magic_autocall): new magic to control
3235 the autocall option at runtime.
3272 the autocall option at runtime.
3236 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
3273 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
3237 across Magic.py to start separating Magic from InteractiveShell.
3274 across Magic.py to start separating Magic from InteractiveShell.
3238 (Magic._ofind): Fixed to return proper namespace for dotted
3275 (Magic._ofind): Fixed to return proper namespace for dotted
3239 names. Before, a dotted name would always return 'not currently
3276 names. Before, a dotted name would always return 'not currently
3240 defined', because it would find the 'parent'. s.x would be found,
3277 defined', because it would find the 'parent'. s.x would be found,
3241 but since 'x' isn't defined by itself, it would get confused.
3278 but since 'x' isn't defined by itself, it would get confused.
3242 (Magic.magic_run): Fixed pickling problems reported by Ralf
3279 (Magic.magic_run): Fixed pickling problems reported by Ralf
3243 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
3280 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
3244 that I'd used when Mike Heeter reported similar issues at the
3281 that I'd used when Mike Heeter reported similar issues at the
3245 top-level, but now for @run. It boils down to injecting the
3282 top-level, but now for @run. It boils down to injecting the
3246 namespace where code is being executed with something that looks
3283 namespace where code is being executed with something that looks
3247 enough like a module to fool pickle.dump(). Since a pickle stores
3284 enough like a module to fool pickle.dump(). Since a pickle stores
3248 a named reference to the importing module, we need this for
3285 a named reference to the importing module, we need this for
3249 pickles to save something sensible.
3286 pickles to save something sensible.
3250
3287
3251 * IPython/ipmaker.py (make_IPython): added an autocall option.
3288 * IPython/ipmaker.py (make_IPython): added an autocall option.
3252
3289
3253 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
3290 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
3254 the auto-eval code. Now autocalling is an option, and the code is
3291 the auto-eval code. Now autocalling is an option, and the code is
3255 also vastly safer. There is no more eval() involved at all.
3292 also vastly safer. There is no more eval() involved at all.
3256
3293
3257 2003-03-01 Fernando Perez <fperez@colorado.edu>
3294 2003-03-01 Fernando Perez <fperez@colorado.edu>
3258
3295
3259 * IPython/Magic.py (Magic._ofind): Changed interface to return a
3296 * IPython/Magic.py (Magic._ofind): Changed interface to return a
3260 dict with named keys instead of a tuple.
3297 dict with named keys instead of a tuple.
3261
3298
3262 * IPython: Started using CVS for IPython as of 0.2.15pre1.
3299 * IPython: Started using CVS for IPython as of 0.2.15pre1.
3263
3300
3264 * setup.py (make_shortcut): Fixed message about directories
3301 * setup.py (make_shortcut): Fixed message about directories
3265 created during Windows installation (the directories were ok, just
3302 created during Windows installation (the directories were ok, just
3266 the printed message was misleading). Thanks to Chris Liechti
3303 the printed message was misleading). Thanks to Chris Liechti
3267 <cliechti-AT-gmx.net> for the heads up.
3304 <cliechti-AT-gmx.net> for the heads up.
3268
3305
3269 2003-02-21 Fernando Perez <fperez@colorado.edu>
3306 2003-02-21 Fernando Perez <fperez@colorado.edu>
3270
3307
3271 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
3308 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
3272 of ValueError exception when checking for auto-execution. This
3309 of ValueError exception when checking for auto-execution. This
3273 one is raised by things like Numeric arrays arr.flat when the
3310 one is raised by things like Numeric arrays arr.flat when the
3274 array is non-contiguous.
3311 array is non-contiguous.
3275
3312
3276 2003-01-31 Fernando Perez <fperez@colorado.edu>
3313 2003-01-31 Fernando Perez <fperez@colorado.edu>
3277
3314
3278 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
3315 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
3279 not return any value at all (even though the command would get
3316 not return any value at all (even though the command would get
3280 executed).
3317 executed).
3281 (xsys): Flush stdout right after printing the command to ensure
3318 (xsys): Flush stdout right after printing the command to ensure
3282 proper ordering of commands and command output in the total
3319 proper ordering of commands and command output in the total
3283 output.
3320 output.
3284 (SystemExec/xsys/bq): Switched the names of xsys/bq and
3321 (SystemExec/xsys/bq): Switched the names of xsys/bq and
3285 system/getoutput as defaults. The old ones are kept for
3322 system/getoutput as defaults. The old ones are kept for
3286 compatibility reasons, so no code which uses this library needs
3323 compatibility reasons, so no code which uses this library needs
3287 changing.
3324 changing.
3288
3325
3289 2003-01-27 *** Released version 0.2.14
3326 2003-01-27 *** Released version 0.2.14
3290
3327
3291 2003-01-25 Fernando Perez <fperez@colorado.edu>
3328 2003-01-25 Fernando Perez <fperez@colorado.edu>
3292
3329
3293 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
3330 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
3294 functions defined in previous edit sessions could not be re-edited
3331 functions defined in previous edit sessions could not be re-edited
3295 (because the temp files were immediately removed). Now temp files
3332 (because the temp files were immediately removed). Now temp files
3296 are removed only at IPython's exit.
3333 are removed only at IPython's exit.
3297 (Magic.magic_run): Improved @run to perform shell-like expansions
3334 (Magic.magic_run): Improved @run to perform shell-like expansions
3298 on its arguments (~users and $VARS). With this, @run becomes more
3335 on its arguments (~users and $VARS). With this, @run becomes more
3299 like a normal command-line.
3336 like a normal command-line.
3300
3337
3301 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
3338 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
3302 bugs related to embedding and cleaned up that code. A fairly
3339 bugs related to embedding and cleaned up that code. A fairly
3303 important one was the impossibility to access the global namespace
3340 important one was the impossibility to access the global namespace
3304 through the embedded IPython (only local variables were visible).
3341 through the embedded IPython (only local variables were visible).
3305
3342
3306 2003-01-14 Fernando Perez <fperez@colorado.edu>
3343 2003-01-14 Fernando Perez <fperez@colorado.edu>
3307
3344
3308 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3345 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3309 auto-calling to be a bit more conservative. Now it doesn't get
3346 auto-calling to be a bit more conservative. Now it doesn't get
3310 triggered if any of '!=()<>' are in the rest of the input line, to
3347 triggered if any of '!=()<>' are in the rest of the input line, to
3311 allow comparing callables. Thanks to Alex for the heads up.
3348 allow comparing callables. Thanks to Alex for the heads up.
3312
3349
3313 2003-01-07 Fernando Perez <fperez@colorado.edu>
3350 2003-01-07 Fernando Perez <fperez@colorado.edu>
3314
3351
3315 * IPython/genutils.py (page): fixed estimation of the number of
3352 * IPython/genutils.py (page): fixed estimation of the number of
3316 lines in a string to be paged to simply count newlines. This
3353 lines in a string to be paged to simply count newlines. This
3317 prevents over-guessing due to embedded escape sequences. A better
3354 prevents over-guessing due to embedded escape sequences. A better
3318 long-term solution would involve stripping out the control chars
3355 long-term solution would involve stripping out the control chars
3319 for the count, but it's potentially so expensive I just don't
3356 for the count, but it's potentially so expensive I just don't
3320 think it's worth doing.
3357 think it's worth doing.
3321
3358
3322 2002-12-19 *** Released version 0.2.14pre50
3359 2002-12-19 *** Released version 0.2.14pre50
3323
3360
3324 2002-12-19 Fernando Perez <fperez@colorado.edu>
3361 2002-12-19 Fernando Perez <fperez@colorado.edu>
3325
3362
3326 * tools/release (version): Changed release scripts to inform
3363 * tools/release (version): Changed release scripts to inform
3327 Andrea and build a NEWS file with a list of recent changes.
3364 Andrea and build a NEWS file with a list of recent changes.
3328
3365
3329 * IPython/ColorANSI.py (__all__): changed terminal detection
3366 * IPython/ColorANSI.py (__all__): changed terminal detection
3330 code. Seems to work better for xterms without breaking
3367 code. Seems to work better for xterms without breaking
3331 konsole. Will need more testing to determine if WinXP and Mac OSX
3368 konsole. Will need more testing to determine if WinXP and Mac OSX
3332 also work ok.
3369 also work ok.
3333
3370
3334 2002-12-18 *** Released version 0.2.14pre49
3371 2002-12-18 *** Released version 0.2.14pre49
3335
3372
3336 2002-12-18 Fernando Perez <fperez@colorado.edu>
3373 2002-12-18 Fernando Perez <fperez@colorado.edu>
3337
3374
3338 * Docs: added new info about Mac OSX, from Andrea.
3375 * Docs: added new info about Mac OSX, from Andrea.
3339
3376
3340 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3377 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3341 allow direct plotting of python strings whose format is the same
3378 allow direct plotting of python strings whose format is the same
3342 of gnuplot data files.
3379 of gnuplot data files.
3343
3380
3344 2002-12-16 Fernando Perez <fperez@colorado.edu>
3381 2002-12-16 Fernando Perez <fperez@colorado.edu>
3345
3382
3346 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3383 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3347 value of exit question to be acknowledged.
3384 value of exit question to be acknowledged.
3348
3385
3349 2002-12-03 Fernando Perez <fperez@colorado.edu>
3386 2002-12-03 Fernando Perez <fperez@colorado.edu>
3350
3387
3351 * IPython/ipmaker.py: removed generators, which had been added
3388 * IPython/ipmaker.py: removed generators, which had been added
3352 by mistake in an earlier debugging run. This was causing trouble
3389 by mistake in an earlier debugging run. This was causing trouble
3353 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3390 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3354 for pointing this out.
3391 for pointing this out.
3355
3392
3356 2002-11-17 Fernando Perez <fperez@colorado.edu>
3393 2002-11-17 Fernando Perez <fperez@colorado.edu>
3357
3394
3358 * Manual: updated the Gnuplot section.
3395 * Manual: updated the Gnuplot section.
3359
3396
3360 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3397 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3361 a much better split of what goes in Runtime and what goes in
3398 a much better split of what goes in Runtime and what goes in
3362 Interactive.
3399 Interactive.
3363
3400
3364 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3401 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3365 being imported from iplib.
3402 being imported from iplib.
3366
3403
3367 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3404 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3368 for command-passing. Now the global Gnuplot instance is called
3405 for command-passing. Now the global Gnuplot instance is called
3369 'gp' instead of 'g', which was really a far too fragile and
3406 'gp' instead of 'g', which was really a far too fragile and
3370 common name.
3407 common name.
3371
3408
3372 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3409 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3373 bounding boxes generated by Gnuplot for square plots.
3410 bounding boxes generated by Gnuplot for square plots.
3374
3411
3375 * IPython/genutils.py (popkey): new function added. I should
3412 * IPython/genutils.py (popkey): new function added. I should
3376 suggest this on c.l.py as a dict method, it seems useful.
3413 suggest this on c.l.py as a dict method, it seems useful.
3377
3414
3378 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3415 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3379 to transparently handle PostScript generation. MUCH better than
3416 to transparently handle PostScript generation. MUCH better than
3380 the previous plot_eps/replot_eps (which I removed now). The code
3417 the previous plot_eps/replot_eps (which I removed now). The code
3381 is also fairly clean and well documented now (including
3418 is also fairly clean and well documented now (including
3382 docstrings).
3419 docstrings).
3383
3420
3384 2002-11-13 Fernando Perez <fperez@colorado.edu>
3421 2002-11-13 Fernando Perez <fperez@colorado.edu>
3385
3422
3386 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3423 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3387 (inconsistent with options).
3424 (inconsistent with options).
3388
3425
3389 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3426 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3390 manually disabled, I don't know why. Fixed it.
3427 manually disabled, I don't know why. Fixed it.
3391 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3428 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3392 eps output.
3429 eps output.
3393
3430
3394 2002-11-12 Fernando Perez <fperez@colorado.edu>
3431 2002-11-12 Fernando Perez <fperez@colorado.edu>
3395
3432
3396 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3433 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3397 don't propagate up to caller. Fixes crash reported by François
3434 don't propagate up to caller. Fixes crash reported by François
3398 Pinard.
3435 Pinard.
3399
3436
3400 2002-11-09 Fernando Perez <fperez@colorado.edu>
3437 2002-11-09 Fernando Perez <fperez@colorado.edu>
3401
3438
3402 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3439 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3403 history file for new users.
3440 history file for new users.
3404 (make_IPython): fixed bug where initial install would leave the
3441 (make_IPython): fixed bug where initial install would leave the
3405 user running in the .ipython dir.
3442 user running in the .ipython dir.
3406 (make_IPython): fixed bug where config dir .ipython would be
3443 (make_IPython): fixed bug where config dir .ipython would be
3407 created regardless of the given -ipythondir option. Thanks to Cory
3444 created regardless of the given -ipythondir option. Thanks to Cory
3408 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3445 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3409
3446
3410 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3447 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3411 type confirmations. Will need to use it in all of IPython's code
3448 type confirmations. Will need to use it in all of IPython's code
3412 consistently.
3449 consistently.
3413
3450
3414 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3451 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3415 context to print 31 lines instead of the default 5. This will make
3452 context to print 31 lines instead of the default 5. This will make
3416 the crash reports extremely detailed in case the problem is in
3453 the crash reports extremely detailed in case the problem is in
3417 libraries I don't have access to.
3454 libraries I don't have access to.
3418
3455
3419 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3456 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3420 line of defense' code to still crash, but giving users fair
3457 line of defense' code to still crash, but giving users fair
3421 warning. I don't want internal errors to go unreported: if there's
3458 warning. I don't want internal errors to go unreported: if there's
3422 an internal problem, IPython should crash and generate a full
3459 an internal problem, IPython should crash and generate a full
3423 report.
3460 report.
3424
3461
3425 2002-11-08 Fernando Perez <fperez@colorado.edu>
3462 2002-11-08 Fernando Perez <fperez@colorado.edu>
3426
3463
3427 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3464 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3428 otherwise uncaught exceptions which can appear if people set
3465 otherwise uncaught exceptions which can appear if people set
3429 sys.stdout to something badly broken. Thanks to a crash report
3466 sys.stdout to something badly broken. Thanks to a crash report
3430 from henni-AT-mail.brainbot.com.
3467 from henni-AT-mail.brainbot.com.
3431
3468
3432 2002-11-04 Fernando Perez <fperez@colorado.edu>
3469 2002-11-04 Fernando Perez <fperez@colorado.edu>
3433
3470
3434 * IPython/iplib.py (InteractiveShell.interact): added
3471 * IPython/iplib.py (InteractiveShell.interact): added
3435 __IPYTHON__active to the builtins. It's a flag which goes on when
3472 __IPYTHON__active to the builtins. It's a flag which goes on when
3436 the interaction starts and goes off again when it stops. This
3473 the interaction starts and goes off again when it stops. This
3437 allows embedding code to detect being inside IPython. Before this
3474 allows embedding code to detect being inside IPython. Before this
3438 was done via __IPYTHON__, but that only shows that an IPython
3475 was done via __IPYTHON__, but that only shows that an IPython
3439 instance has been created.
3476 instance has been created.
3440
3477
3441 * IPython/Magic.py (Magic.magic_env): I realized that in a
3478 * IPython/Magic.py (Magic.magic_env): I realized that in a
3442 UserDict, instance.data holds the data as a normal dict. So I
3479 UserDict, instance.data holds the data as a normal dict. So I
3443 modified @env to return os.environ.data instead of rebuilding a
3480 modified @env to return os.environ.data instead of rebuilding a
3444 dict by hand.
3481 dict by hand.
3445
3482
3446 2002-11-02 Fernando Perez <fperez@colorado.edu>
3483 2002-11-02 Fernando Perez <fperez@colorado.edu>
3447
3484
3448 * IPython/genutils.py (warn): changed so that level 1 prints no
3485 * IPython/genutils.py (warn): changed so that level 1 prints no
3449 header. Level 2 is now the default (with 'WARNING' header, as
3486 header. Level 2 is now the default (with 'WARNING' header, as
3450 before). I think I tracked all places where changes were needed in
3487 before). I think I tracked all places where changes were needed in
3451 IPython, but outside code using the old level numbering may have
3488 IPython, but outside code using the old level numbering may have
3452 broken.
3489 broken.
3453
3490
3454 * IPython/iplib.py (InteractiveShell.runcode): added this to
3491 * IPython/iplib.py (InteractiveShell.runcode): added this to
3455 handle the tracebacks in SystemExit traps correctly. The previous
3492 handle the tracebacks in SystemExit traps correctly. The previous
3456 code (through interact) was printing more of the stack than
3493 code (through interact) was printing more of the stack than
3457 necessary, showing IPython internal code to the user.
3494 necessary, showing IPython internal code to the user.
3458
3495
3459 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3496 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3460 default. Now that the default at the confirmation prompt is yes,
3497 default. Now that the default at the confirmation prompt is yes,
3461 it's not so intrusive. François' argument that ipython sessions
3498 it's not so intrusive. François' argument that ipython sessions
3462 tend to be complex enough not to lose them from an accidental C-d,
3499 tend to be complex enough not to lose them from an accidental C-d,
3463 is a valid one.
3500 is a valid one.
3464
3501
3465 * IPython/iplib.py (InteractiveShell.interact): added a
3502 * IPython/iplib.py (InteractiveShell.interact): added a
3466 showtraceback() call to the SystemExit trap, and modified the exit
3503 showtraceback() call to the SystemExit trap, and modified the exit
3467 confirmation to have yes as the default.
3504 confirmation to have yes as the default.
3468
3505
3469 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3506 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3470 this file. It's been gone from the code for a long time, this was
3507 this file. It's been gone from the code for a long time, this was
3471 simply leftover junk.
3508 simply leftover junk.
3472
3509
3473 2002-11-01 Fernando Perez <fperez@colorado.edu>
3510 2002-11-01 Fernando Perez <fperez@colorado.edu>
3474
3511
3475 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3512 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3476 added. If set, IPython now traps EOF and asks for
3513 added. If set, IPython now traps EOF and asks for
3477 confirmation. After a request by François Pinard.
3514 confirmation. After a request by François Pinard.
3478
3515
3479 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3516 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3480 of @abort, and with a new (better) mechanism for handling the
3517 of @abort, and with a new (better) mechanism for handling the
3481 exceptions.
3518 exceptions.
3482
3519
3483 2002-10-27 Fernando Perez <fperez@colorado.edu>
3520 2002-10-27 Fernando Perez <fperez@colorado.edu>
3484
3521
3485 * IPython/usage.py (__doc__): updated the --help information and
3522 * IPython/usage.py (__doc__): updated the --help information and
3486 the ipythonrc file to indicate that -log generates
3523 the ipythonrc file to indicate that -log generates
3487 ./ipython.log. Also fixed the corresponding info in @logstart.
3524 ./ipython.log. Also fixed the corresponding info in @logstart.
3488 This and several other fixes in the manuals thanks to reports by
3525 This and several other fixes in the manuals thanks to reports by
3489 François Pinard <pinard-AT-iro.umontreal.ca>.
3526 François Pinard <pinard-AT-iro.umontreal.ca>.
3490
3527
3491 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3528 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3492 refer to @logstart (instead of @log, which doesn't exist).
3529 refer to @logstart (instead of @log, which doesn't exist).
3493
3530
3494 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3531 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3495 AttributeError crash. Thanks to Christopher Armstrong
3532 AttributeError crash. Thanks to Christopher Armstrong
3496 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3533 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3497 introduced recently (in 0.2.14pre37) with the fix to the eval
3534 introduced recently (in 0.2.14pre37) with the fix to the eval
3498 problem mentioned below.
3535 problem mentioned below.
3499
3536
3500 2002-10-17 Fernando Perez <fperez@colorado.edu>
3537 2002-10-17 Fernando Perez <fperez@colorado.edu>
3501
3538
3502 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3539 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3503 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3540 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3504
3541
3505 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3542 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3506 this function to fix a problem reported by Alex Schmolck. He saw
3543 this function to fix a problem reported by Alex Schmolck. He saw
3507 it with list comprehensions and generators, which were getting
3544 it with list comprehensions and generators, which were getting
3508 called twice. The real problem was an 'eval' call in testing for
3545 called twice. The real problem was an 'eval' call in testing for
3509 automagic which was evaluating the input line silently.
3546 automagic which was evaluating the input line silently.
3510
3547
3511 This is a potentially very nasty bug, if the input has side
3548 This is a potentially very nasty bug, if the input has side
3512 effects which must not be repeated. The code is much cleaner now,
3549 effects which must not be repeated. The code is much cleaner now,
3513 without any blanket 'except' left and with a regexp test for
3550 without any blanket 'except' left and with a regexp test for
3514 actual function names.
3551 actual function names.
3515
3552
3516 But an eval remains, which I'm not fully comfortable with. I just
3553 But an eval remains, which I'm not fully comfortable with. I just
3517 don't know how to find out if an expression could be a callable in
3554 don't know how to find out if an expression could be a callable in
3518 the user's namespace without doing an eval on the string. However
3555 the user's namespace without doing an eval on the string. However
3519 that string is now much more strictly checked so that no code
3556 that string is now much more strictly checked so that no code
3520 slips by, so the eval should only happen for things that can
3557 slips by, so the eval should only happen for things that can
3521 really be only function/method names.
3558 really be only function/method names.
3522
3559
3523 2002-10-15 Fernando Perez <fperez@colorado.edu>
3560 2002-10-15 Fernando Perez <fperez@colorado.edu>
3524
3561
3525 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3562 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3526 OSX information to main manual, removed README_Mac_OSX file from
3563 OSX information to main manual, removed README_Mac_OSX file from
3527 distribution. Also updated credits for recent additions.
3564 distribution. Also updated credits for recent additions.
3528
3565
3529 2002-10-10 Fernando Perez <fperez@colorado.edu>
3566 2002-10-10 Fernando Perez <fperez@colorado.edu>
3530
3567
3531 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3568 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3532 terminal-related issues. Many thanks to Andrea Riciputi
3569 terminal-related issues. Many thanks to Andrea Riciputi
3533 <andrea.riciputi-AT-libero.it> for writing it.
3570 <andrea.riciputi-AT-libero.it> for writing it.
3534
3571
3535 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3572 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3536 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3573 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3537
3574
3538 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3575 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3539 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3576 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3540 <syver-en-AT-online.no> who both submitted patches for this problem.
3577 <syver-en-AT-online.no> who both submitted patches for this problem.
3541
3578
3542 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3579 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3543 global embedding to make sure that things don't overwrite user
3580 global embedding to make sure that things don't overwrite user
3544 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3581 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3545
3582
3546 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3583 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3547 compatibility. Thanks to Hayden Callow
3584 compatibility. Thanks to Hayden Callow
3548 <h.callow-AT-elec.canterbury.ac.nz>
3585 <h.callow-AT-elec.canterbury.ac.nz>
3549
3586
3550 2002-10-04 Fernando Perez <fperez@colorado.edu>
3587 2002-10-04 Fernando Perez <fperez@colorado.edu>
3551
3588
3552 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3589 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3553 Gnuplot.File objects.
3590 Gnuplot.File objects.
3554
3591
3555 2002-07-23 Fernando Perez <fperez@colorado.edu>
3592 2002-07-23 Fernando Perez <fperez@colorado.edu>
3556
3593
3557 * IPython/genutils.py (timing): Added timings() and timing() for
3594 * IPython/genutils.py (timing): Added timings() and timing() for
3558 quick access to the most commonly needed data, the execution
3595 quick access to the most commonly needed data, the execution
3559 times. Old timing() renamed to timings_out().
3596 times. Old timing() renamed to timings_out().
3560
3597
3561 2002-07-18 Fernando Perez <fperez@colorado.edu>
3598 2002-07-18 Fernando Perez <fperez@colorado.edu>
3562
3599
3563 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3600 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3564 bug with nested instances disrupting the parent's tab completion.
3601 bug with nested instances disrupting the parent's tab completion.
3565
3602
3566 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3603 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3567 all_completions code to begin the emacs integration.
3604 all_completions code to begin the emacs integration.
3568
3605
3569 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3606 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3570 argument to allow titling individual arrays when plotting.
3607 argument to allow titling individual arrays when plotting.
3571
3608
3572 2002-07-15 Fernando Perez <fperez@colorado.edu>
3609 2002-07-15 Fernando Perez <fperez@colorado.edu>
3573
3610
3574 * setup.py (make_shortcut): changed to retrieve the value of
3611 * setup.py (make_shortcut): changed to retrieve the value of
3575 'Program Files' directory from the registry (this value changes in
3612 'Program Files' directory from the registry (this value changes in
3576 non-english versions of Windows). Thanks to Thomas Fanslau
3613 non-english versions of Windows). Thanks to Thomas Fanslau
3577 <tfanslau-AT-gmx.de> for the report.
3614 <tfanslau-AT-gmx.de> for the report.
3578
3615
3579 2002-07-10 Fernando Perez <fperez@colorado.edu>
3616 2002-07-10 Fernando Perez <fperez@colorado.edu>
3580
3617
3581 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3618 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3582 a bug in pdb, which crashes if a line with only whitespace is
3619 a bug in pdb, which crashes if a line with only whitespace is
3583 entered. Bug report submitted to sourceforge.
3620 entered. Bug report submitted to sourceforge.
3584
3621
3585 2002-07-09 Fernando Perez <fperez@colorado.edu>
3622 2002-07-09 Fernando Perez <fperez@colorado.edu>
3586
3623
3587 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3624 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3588 reporting exceptions (it's a bug in inspect.py, I just set a
3625 reporting exceptions (it's a bug in inspect.py, I just set a
3589 workaround).
3626 workaround).
3590
3627
3591 2002-07-08 Fernando Perez <fperez@colorado.edu>
3628 2002-07-08 Fernando Perez <fperez@colorado.edu>
3592
3629
3593 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3630 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3594 __IPYTHON__ in __builtins__ to show up in user_ns.
3631 __IPYTHON__ in __builtins__ to show up in user_ns.
3595
3632
3596 2002-07-03 Fernando Perez <fperez@colorado.edu>
3633 2002-07-03 Fernando Perez <fperez@colorado.edu>
3597
3634
3598 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3635 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3599 name from @gp_set_instance to @gp_set_default.
3636 name from @gp_set_instance to @gp_set_default.
3600
3637
3601 * IPython/ipmaker.py (make_IPython): default editor value set to
3638 * IPython/ipmaker.py (make_IPython): default editor value set to
3602 '0' (a string), to match the rc file. Otherwise will crash when
3639 '0' (a string), to match the rc file. Otherwise will crash when
3603 .strip() is called on it.
3640 .strip() is called on it.
3604
3641
3605
3642
3606 2002-06-28 Fernando Perez <fperez@colorado.edu>
3643 2002-06-28 Fernando Perez <fperez@colorado.edu>
3607
3644
3608 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3645 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3609 of files in current directory when a file is executed via
3646 of files in current directory when a file is executed via
3610 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3647 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3611
3648
3612 * setup.py (manfiles): fix for rpm builds, submitted by RA
3649 * setup.py (manfiles): fix for rpm builds, submitted by RA
3613 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3650 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3614
3651
3615 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3652 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3616 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3653 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3617 string!). A. Schmolck caught this one.
3654 string!). A. Schmolck caught this one.
3618
3655
3619 2002-06-27 Fernando Perez <fperez@colorado.edu>
3656 2002-06-27 Fernando Perez <fperez@colorado.edu>
3620
3657
3621 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3658 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3622 defined files at the cmd line. __name__ wasn't being set to
3659 defined files at the cmd line. __name__ wasn't being set to
3623 __main__.
3660 __main__.
3624
3661
3625 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3662 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3626 regular lists and tuples besides Numeric arrays.
3663 regular lists and tuples besides Numeric arrays.
3627
3664
3628 * IPython/Prompts.py (CachedOutput.__call__): Added output
3665 * IPython/Prompts.py (CachedOutput.__call__): Added output
3629 supression for input ending with ';'. Similar to Mathematica and
3666 supression for input ending with ';'. Similar to Mathematica and
3630 Matlab. The _* vars and Out[] list are still updated, just like
3667 Matlab. The _* vars and Out[] list are still updated, just like
3631 Mathematica behaves.
3668 Mathematica behaves.
3632
3669
3633 2002-06-25 Fernando Perez <fperez@colorado.edu>
3670 2002-06-25 Fernando Perez <fperez@colorado.edu>
3634
3671
3635 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3672 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3636 .ini extensions for profiels under Windows.
3673 .ini extensions for profiels under Windows.
3637
3674
3638 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3675 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3639 string form. Fix contributed by Alexander Schmolck
3676 string form. Fix contributed by Alexander Schmolck
3640 <a.schmolck-AT-gmx.net>
3677 <a.schmolck-AT-gmx.net>
3641
3678
3642 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3679 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3643 pre-configured Gnuplot instance.
3680 pre-configured Gnuplot instance.
3644
3681
3645 2002-06-21 Fernando Perez <fperez@colorado.edu>
3682 2002-06-21 Fernando Perez <fperez@colorado.edu>
3646
3683
3647 * IPython/numutils.py (exp_safe): new function, works around the
3684 * IPython/numutils.py (exp_safe): new function, works around the
3648 underflow problems in Numeric.
3685 underflow problems in Numeric.
3649 (log2): New fn. Safe log in base 2: returns exact integer answer
3686 (log2): New fn. Safe log in base 2: returns exact integer answer
3650 for exact integer powers of 2.
3687 for exact integer powers of 2.
3651
3688
3652 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3689 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3653 properly.
3690 properly.
3654
3691
3655 2002-06-20 Fernando Perez <fperez@colorado.edu>
3692 2002-06-20 Fernando Perez <fperez@colorado.edu>
3656
3693
3657 * IPython/genutils.py (timing): new function like
3694 * IPython/genutils.py (timing): new function like
3658 Mathematica's. Similar to time_test, but returns more info.
3695 Mathematica's. Similar to time_test, but returns more info.
3659
3696
3660 2002-06-18 Fernando Perez <fperez@colorado.edu>
3697 2002-06-18 Fernando Perez <fperez@colorado.edu>
3661
3698
3662 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3699 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3663 according to Mike Heeter's suggestions.
3700 according to Mike Heeter's suggestions.
3664
3701
3665 2002-06-16 Fernando Perez <fperez@colorado.edu>
3702 2002-06-16 Fernando Perez <fperez@colorado.edu>
3666
3703
3667 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3704 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3668 system. GnuplotMagic is gone as a user-directory option. New files
3705 system. GnuplotMagic is gone as a user-directory option. New files
3669 make it easier to use all the gnuplot stuff both from external
3706 make it easier to use all the gnuplot stuff both from external
3670 programs as well as from IPython. Had to rewrite part of
3707 programs as well as from IPython. Had to rewrite part of
3671 hardcopy() b/c of a strange bug: often the ps files simply don't
3708 hardcopy() b/c of a strange bug: often the ps files simply don't
3672 get created, and require a repeat of the command (often several
3709 get created, and require a repeat of the command (often several
3673 times).
3710 times).
3674
3711
3675 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3712 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3676 resolve output channel at call time, so that if sys.stderr has
3713 resolve output channel at call time, so that if sys.stderr has
3677 been redirected by user this gets honored.
3714 been redirected by user this gets honored.
3678
3715
3679 2002-06-13 Fernando Perez <fperez@colorado.edu>
3716 2002-06-13 Fernando Perez <fperez@colorado.edu>
3680
3717
3681 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3718 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3682 IPShell. Kept a copy with the old names to avoid breaking people's
3719 IPShell. Kept a copy with the old names to avoid breaking people's
3683 embedded code.
3720 embedded code.
3684
3721
3685 * IPython/ipython: simplified it to the bare minimum after
3722 * IPython/ipython: simplified it to the bare minimum after
3686 Holger's suggestions. Added info about how to use it in
3723 Holger's suggestions. Added info about how to use it in
3687 PYTHONSTARTUP.
3724 PYTHONSTARTUP.
3688
3725
3689 * IPython/Shell.py (IPythonShell): changed the options passing
3726 * IPython/Shell.py (IPythonShell): changed the options passing
3690 from a string with funky %s replacements to a straight list. Maybe
3727 from a string with funky %s replacements to a straight list. Maybe
3691 a bit more typing, but it follows sys.argv conventions, so there's
3728 a bit more typing, but it follows sys.argv conventions, so there's
3692 less special-casing to remember.
3729 less special-casing to remember.
3693
3730
3694 2002-06-12 Fernando Perez <fperez@colorado.edu>
3731 2002-06-12 Fernando Perez <fperez@colorado.edu>
3695
3732
3696 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3733 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3697 command. Thanks to a suggestion by Mike Heeter.
3734 command. Thanks to a suggestion by Mike Heeter.
3698 (Magic.magic_pfile): added behavior to look at filenames if given
3735 (Magic.magic_pfile): added behavior to look at filenames if given
3699 arg is not a defined object.
3736 arg is not a defined object.
3700 (Magic.magic_save): New @save function to save code snippets. Also
3737 (Magic.magic_save): New @save function to save code snippets. Also
3701 a Mike Heeter idea.
3738 a Mike Heeter idea.
3702
3739
3703 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3740 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3704 plot() and replot(). Much more convenient now, especially for
3741 plot() and replot(). Much more convenient now, especially for
3705 interactive use.
3742 interactive use.
3706
3743
3707 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3744 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3708 filenames.
3745 filenames.
3709
3746
3710 2002-06-02 Fernando Perez <fperez@colorado.edu>
3747 2002-06-02 Fernando Perez <fperez@colorado.edu>
3711
3748
3712 * IPython/Struct.py (Struct.__init__): modified to admit
3749 * IPython/Struct.py (Struct.__init__): modified to admit
3713 initialization via another struct.
3750 initialization via another struct.
3714
3751
3715 * IPython/genutils.py (SystemExec.__init__): New stateful
3752 * IPython/genutils.py (SystemExec.__init__): New stateful
3716 interface to xsys and bq. Useful for writing system scripts.
3753 interface to xsys and bq. Useful for writing system scripts.
3717
3754
3718 2002-05-30 Fernando Perez <fperez@colorado.edu>
3755 2002-05-30 Fernando Perez <fperez@colorado.edu>
3719
3756
3720 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3757 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3721 documents. This will make the user download smaller (it's getting
3758 documents. This will make the user download smaller (it's getting
3722 too big).
3759 too big).
3723
3760
3724 2002-05-29 Fernando Perez <fperez@colorado.edu>
3761 2002-05-29 Fernando Perez <fperez@colorado.edu>
3725
3762
3726 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3763 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3727 fix problems with shelve and pickle. Seems to work, but I don't
3764 fix problems with shelve and pickle. Seems to work, but I don't
3728 know if corner cases break it. Thanks to Mike Heeter
3765 know if corner cases break it. Thanks to Mike Heeter
3729 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3766 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3730
3767
3731 2002-05-24 Fernando Perez <fperez@colorado.edu>
3768 2002-05-24 Fernando Perez <fperez@colorado.edu>
3732
3769
3733 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3770 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3734 macros having broken.
3771 macros having broken.
3735
3772
3736 2002-05-21 Fernando Perez <fperez@colorado.edu>
3773 2002-05-21 Fernando Perez <fperez@colorado.edu>
3737
3774
3738 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3775 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3739 introduced logging bug: all history before logging started was
3776 introduced logging bug: all history before logging started was
3740 being written one character per line! This came from the redesign
3777 being written one character per line! This came from the redesign
3741 of the input history as a special list which slices to strings,
3778 of the input history as a special list which slices to strings,
3742 not to lists.
3779 not to lists.
3743
3780
3744 2002-05-20 Fernando Perez <fperez@colorado.edu>
3781 2002-05-20 Fernando Perez <fperez@colorado.edu>
3745
3782
3746 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3783 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3747 be an attribute of all classes in this module. The design of these
3784 be an attribute of all classes in this module. The design of these
3748 classes needs some serious overhauling.
3785 classes needs some serious overhauling.
3749
3786
3750 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3787 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3751 which was ignoring '_' in option names.
3788 which was ignoring '_' in option names.
3752
3789
3753 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3790 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3754 'Verbose_novars' to 'Context' and made it the new default. It's a
3791 'Verbose_novars' to 'Context' and made it the new default. It's a
3755 bit more readable and also safer than verbose.
3792 bit more readable and also safer than verbose.
3756
3793
3757 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3794 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3758 triple-quoted strings.
3795 triple-quoted strings.
3759
3796
3760 * IPython/OInspect.py (__all__): new module exposing the object
3797 * IPython/OInspect.py (__all__): new module exposing the object
3761 introspection facilities. Now the corresponding magics are dummy
3798 introspection facilities. Now the corresponding magics are dummy
3762 wrappers around this. Having this module will make it much easier
3799 wrappers around this. Having this module will make it much easier
3763 to put these functions into our modified pdb.
3800 to put these functions into our modified pdb.
3764 This new object inspector system uses the new colorizing module,
3801 This new object inspector system uses the new colorizing module,
3765 so source code and other things are nicely syntax highlighted.
3802 so source code and other things are nicely syntax highlighted.
3766
3803
3767 2002-05-18 Fernando Perez <fperez@colorado.edu>
3804 2002-05-18 Fernando Perez <fperez@colorado.edu>
3768
3805
3769 * IPython/ColorANSI.py: Split the coloring tools into a separate
3806 * IPython/ColorANSI.py: Split the coloring tools into a separate
3770 module so I can use them in other code easier (they were part of
3807 module so I can use them in other code easier (they were part of
3771 ultraTB).
3808 ultraTB).
3772
3809
3773 2002-05-17 Fernando Perez <fperez@colorado.edu>
3810 2002-05-17 Fernando Perez <fperez@colorado.edu>
3774
3811
3775 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3812 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3776 fixed it to set the global 'g' also to the called instance, as
3813 fixed it to set the global 'g' also to the called instance, as
3777 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3814 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3778 user's 'g' variables).
3815 user's 'g' variables).
3779
3816
3780 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3817 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3781 global variables (aliases to _ih,_oh) so that users which expect
3818 global variables (aliases to _ih,_oh) so that users which expect
3782 In[5] or Out[7] to work aren't unpleasantly surprised.
3819 In[5] or Out[7] to work aren't unpleasantly surprised.
3783 (InputList.__getslice__): new class to allow executing slices of
3820 (InputList.__getslice__): new class to allow executing slices of
3784 input history directly. Very simple class, complements the use of
3821 input history directly. Very simple class, complements the use of
3785 macros.
3822 macros.
3786
3823
3787 2002-05-16 Fernando Perez <fperez@colorado.edu>
3824 2002-05-16 Fernando Perez <fperez@colorado.edu>
3788
3825
3789 * setup.py (docdirbase): make doc directory be just doc/IPython
3826 * setup.py (docdirbase): make doc directory be just doc/IPython
3790 without version numbers, it will reduce clutter for users.
3827 without version numbers, it will reduce clutter for users.
3791
3828
3792 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3829 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3793 execfile call to prevent possible memory leak. See for details:
3830 execfile call to prevent possible memory leak. See for details:
3794 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3831 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3795
3832
3796 2002-05-15 Fernando Perez <fperez@colorado.edu>
3833 2002-05-15 Fernando Perez <fperez@colorado.edu>
3797
3834
3798 * IPython/Magic.py (Magic.magic_psource): made the object
3835 * IPython/Magic.py (Magic.magic_psource): made the object
3799 introspection names be more standard: pdoc, pdef, pfile and
3836 introspection names be more standard: pdoc, pdef, pfile and
3800 psource. They all print/page their output, and it makes
3837 psource. They all print/page their output, and it makes
3801 remembering them easier. Kept old names for compatibility as
3838 remembering them easier. Kept old names for compatibility as
3802 aliases.
3839 aliases.
3803
3840
3804 2002-05-14 Fernando Perez <fperez@colorado.edu>
3841 2002-05-14 Fernando Perez <fperez@colorado.edu>
3805
3842
3806 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3843 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3807 what the mouse problem was. The trick is to use gnuplot with temp
3844 what the mouse problem was. The trick is to use gnuplot with temp
3808 files and NOT with pipes (for data communication), because having
3845 files and NOT with pipes (for data communication), because having
3809 both pipes and the mouse on is bad news.
3846 both pipes and the mouse on is bad news.
3810
3847
3811 2002-05-13 Fernando Perez <fperez@colorado.edu>
3848 2002-05-13 Fernando Perez <fperez@colorado.edu>
3812
3849
3813 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3850 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3814 bug. Information would be reported about builtins even when
3851 bug. Information would be reported about builtins even when
3815 user-defined functions overrode them.
3852 user-defined functions overrode them.
3816
3853
3817 2002-05-11 Fernando Perez <fperez@colorado.edu>
3854 2002-05-11 Fernando Perez <fperez@colorado.edu>
3818
3855
3819 * IPython/__init__.py (__all__): removed FlexCompleter from
3856 * IPython/__init__.py (__all__): removed FlexCompleter from
3820 __all__ so that things don't fail in platforms without readline.
3857 __all__ so that things don't fail in platforms without readline.
3821
3858
3822 2002-05-10 Fernando Perez <fperez@colorado.edu>
3859 2002-05-10 Fernando Perez <fperez@colorado.edu>
3823
3860
3824 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3861 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3825 it requires Numeric, effectively making Numeric a dependency for
3862 it requires Numeric, effectively making Numeric a dependency for
3826 IPython.
3863 IPython.
3827
3864
3828 * Released 0.2.13
3865 * Released 0.2.13
3829
3866
3830 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3867 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3831 profiler interface. Now all the major options from the profiler
3868 profiler interface. Now all the major options from the profiler
3832 module are directly supported in IPython, both for single
3869 module are directly supported in IPython, both for single
3833 expressions (@prun) and for full programs (@run -p).
3870 expressions (@prun) and for full programs (@run -p).
3834
3871
3835 2002-05-09 Fernando Perez <fperez@colorado.edu>
3872 2002-05-09 Fernando Perez <fperez@colorado.edu>
3836
3873
3837 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3874 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3838 magic properly formatted for screen.
3875 magic properly formatted for screen.
3839
3876
3840 * setup.py (make_shortcut): Changed things to put pdf version in
3877 * setup.py (make_shortcut): Changed things to put pdf version in
3841 doc/ instead of doc/manual (had to change lyxport a bit).
3878 doc/ instead of doc/manual (had to change lyxport a bit).
3842
3879
3843 * IPython/Magic.py (Profile.string_stats): made profile runs go
3880 * IPython/Magic.py (Profile.string_stats): made profile runs go
3844 through pager (they are long and a pager allows searching, saving,
3881 through pager (they are long and a pager allows searching, saving,
3845 etc.)
3882 etc.)
3846
3883
3847 2002-05-08 Fernando Perez <fperez@colorado.edu>
3884 2002-05-08 Fernando Perez <fperez@colorado.edu>
3848
3885
3849 * Released 0.2.12
3886 * Released 0.2.12
3850
3887
3851 2002-05-06 Fernando Perez <fperez@colorado.edu>
3888 2002-05-06 Fernando Perez <fperez@colorado.edu>
3852
3889
3853 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3890 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3854 introduced); 'hist n1 n2' was broken.
3891 introduced); 'hist n1 n2' was broken.
3855 (Magic.magic_pdb): added optional on/off arguments to @pdb
3892 (Magic.magic_pdb): added optional on/off arguments to @pdb
3856 (Magic.magic_run): added option -i to @run, which executes code in
3893 (Magic.magic_run): added option -i to @run, which executes code in
3857 the IPython namespace instead of a clean one. Also added @irun as
3894 the IPython namespace instead of a clean one. Also added @irun as
3858 an alias to @run -i.
3895 an alias to @run -i.
3859
3896
3860 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3897 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3861 fixed (it didn't really do anything, the namespaces were wrong).
3898 fixed (it didn't really do anything, the namespaces were wrong).
3862
3899
3863 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3900 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3864
3901
3865 * IPython/__init__.py (__all__): Fixed package namespace, now
3902 * IPython/__init__.py (__all__): Fixed package namespace, now
3866 'import IPython' does give access to IPython.<all> as
3903 'import IPython' does give access to IPython.<all> as
3867 expected. Also renamed __release__ to Release.
3904 expected. Also renamed __release__ to Release.
3868
3905
3869 * IPython/Debugger.py (__license__): created new Pdb class which
3906 * IPython/Debugger.py (__license__): created new Pdb class which
3870 functions like a drop-in for the normal pdb.Pdb but does NOT
3907 functions like a drop-in for the normal pdb.Pdb but does NOT
3871 import readline by default. This way it doesn't muck up IPython's
3908 import readline by default. This way it doesn't muck up IPython's
3872 readline handling, and now tab-completion finally works in the
3909 readline handling, and now tab-completion finally works in the
3873 debugger -- sort of. It completes things globally visible, but the
3910 debugger -- sort of. It completes things globally visible, but the
3874 completer doesn't track the stack as pdb walks it. That's a bit
3911 completer doesn't track the stack as pdb walks it. That's a bit
3875 tricky, and I'll have to implement it later.
3912 tricky, and I'll have to implement it later.
3876
3913
3877 2002-05-05 Fernando Perez <fperez@colorado.edu>
3914 2002-05-05 Fernando Perez <fperez@colorado.edu>
3878
3915
3879 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3916 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3880 magic docstrings when printed via ? (explicit \'s were being
3917 magic docstrings when printed via ? (explicit \'s were being
3881 printed).
3918 printed).
3882
3919
3883 * IPython/ipmaker.py (make_IPython): fixed namespace
3920 * IPython/ipmaker.py (make_IPython): fixed namespace
3884 identification bug. Now variables loaded via logs or command-line
3921 identification bug. Now variables loaded via logs or command-line
3885 files are recognized in the interactive namespace by @who.
3922 files are recognized in the interactive namespace by @who.
3886
3923
3887 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3924 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3888 log replay system stemming from the string form of Structs.
3925 log replay system stemming from the string form of Structs.
3889
3926
3890 * IPython/Magic.py (Macro.__init__): improved macros to properly
3927 * IPython/Magic.py (Macro.__init__): improved macros to properly
3891 handle magic commands in them.
3928 handle magic commands in them.
3892 (Magic.magic_logstart): usernames are now expanded so 'logstart
3929 (Magic.magic_logstart): usernames are now expanded so 'logstart
3893 ~/mylog' now works.
3930 ~/mylog' now works.
3894
3931
3895 * IPython/iplib.py (complete): fixed bug where paths starting with
3932 * IPython/iplib.py (complete): fixed bug where paths starting with
3896 '/' would be completed as magic names.
3933 '/' would be completed as magic names.
3897
3934
3898 2002-05-04 Fernando Perez <fperez@colorado.edu>
3935 2002-05-04 Fernando Perez <fperez@colorado.edu>
3899
3936
3900 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3937 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3901 allow running full programs under the profiler's control.
3938 allow running full programs under the profiler's control.
3902
3939
3903 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3940 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3904 mode to report exceptions verbosely but without formatting
3941 mode to report exceptions verbosely but without formatting
3905 variables. This addresses the issue of ipython 'freezing' (it's
3942 variables. This addresses the issue of ipython 'freezing' (it's
3906 not frozen, but caught in an expensive formatting loop) when huge
3943 not frozen, but caught in an expensive formatting loop) when huge
3907 variables are in the context of an exception.
3944 variables are in the context of an exception.
3908 (VerboseTB.text): Added '--->' markers at line where exception was
3945 (VerboseTB.text): Added '--->' markers at line where exception was
3909 triggered. Much clearer to read, especially in NoColor modes.
3946 triggered. Much clearer to read, especially in NoColor modes.
3910
3947
3911 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3948 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3912 implemented in reverse when changing to the new parse_options().
3949 implemented in reverse when changing to the new parse_options().
3913
3950
3914 2002-05-03 Fernando Perez <fperez@colorado.edu>
3951 2002-05-03 Fernando Perez <fperez@colorado.edu>
3915
3952
3916 * IPython/Magic.py (Magic.parse_options): new function so that
3953 * IPython/Magic.py (Magic.parse_options): new function so that
3917 magics can parse options easier.
3954 magics can parse options easier.
3918 (Magic.magic_prun): new function similar to profile.run(),
3955 (Magic.magic_prun): new function similar to profile.run(),
3919 suggested by Chris Hart.
3956 suggested by Chris Hart.
3920 (Magic.magic_cd): fixed behavior so that it only changes if
3957 (Magic.magic_cd): fixed behavior so that it only changes if
3921 directory actually is in history.
3958 directory actually is in history.
3922
3959
3923 * IPython/usage.py (__doc__): added information about potential
3960 * IPython/usage.py (__doc__): added information about potential
3924 slowness of Verbose exception mode when there are huge data
3961 slowness of Verbose exception mode when there are huge data
3925 structures to be formatted (thanks to Archie Paulson).
3962 structures to be formatted (thanks to Archie Paulson).
3926
3963
3927 * IPython/ipmaker.py (make_IPython): Changed default logging
3964 * IPython/ipmaker.py (make_IPython): Changed default logging
3928 (when simply called with -log) to use curr_dir/ipython.log in
3965 (when simply called with -log) to use curr_dir/ipython.log in
3929 rotate mode. Fixed crash which was occuring with -log before
3966 rotate mode. Fixed crash which was occuring with -log before
3930 (thanks to Jim Boyle).
3967 (thanks to Jim Boyle).
3931
3968
3932 2002-05-01 Fernando Perez <fperez@colorado.edu>
3969 2002-05-01 Fernando Perez <fperez@colorado.edu>
3933
3970
3934 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3971 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3935 was nasty -- though somewhat of a corner case).
3972 was nasty -- though somewhat of a corner case).
3936
3973
3937 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3974 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3938 text (was a bug).
3975 text (was a bug).
3939
3976
3940 2002-04-30 Fernando Perez <fperez@colorado.edu>
3977 2002-04-30 Fernando Perez <fperez@colorado.edu>
3941
3978
3942 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3979 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3943 a print after ^D or ^C from the user so that the In[] prompt
3980 a print after ^D or ^C from the user so that the In[] prompt
3944 doesn't over-run the gnuplot one.
3981 doesn't over-run the gnuplot one.
3945
3982
3946 2002-04-29 Fernando Perez <fperez@colorado.edu>
3983 2002-04-29 Fernando Perez <fperez@colorado.edu>
3947
3984
3948 * Released 0.2.10
3985 * Released 0.2.10
3949
3986
3950 * IPython/__release__.py (version): get date dynamically.
3987 * IPython/__release__.py (version): get date dynamically.
3951
3988
3952 * Misc. documentation updates thanks to Arnd's comments. Also ran
3989 * Misc. documentation updates thanks to Arnd's comments. Also ran
3953 a full spellcheck on the manual (hadn't been done in a while).
3990 a full spellcheck on the manual (hadn't been done in a while).
3954
3991
3955 2002-04-27 Fernando Perez <fperez@colorado.edu>
3992 2002-04-27 Fernando Perez <fperez@colorado.edu>
3956
3993
3957 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3994 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3958 starting a log in mid-session would reset the input history list.
3995 starting a log in mid-session would reset the input history list.
3959
3996
3960 2002-04-26 Fernando Perez <fperez@colorado.edu>
3997 2002-04-26 Fernando Perez <fperez@colorado.edu>
3961
3998
3962 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3999 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3963 all files were being included in an update. Now anything in
4000 all files were being included in an update. Now anything in
3964 UserConfig that matches [A-Za-z]*.py will go (this excludes
4001 UserConfig that matches [A-Za-z]*.py will go (this excludes
3965 __init__.py)
4002 __init__.py)
3966
4003
3967 2002-04-25 Fernando Perez <fperez@colorado.edu>
4004 2002-04-25 Fernando Perez <fperez@colorado.edu>
3968
4005
3969 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
4006 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3970 to __builtins__ so that any form of embedded or imported code can
4007 to __builtins__ so that any form of embedded or imported code can
3971 test for being inside IPython.
4008 test for being inside IPython.
3972
4009
3973 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
4010 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3974 changed to GnuplotMagic because it's now an importable module,
4011 changed to GnuplotMagic because it's now an importable module,
3975 this makes the name follow that of the standard Gnuplot module.
4012 this makes the name follow that of the standard Gnuplot module.
3976 GnuplotMagic can now be loaded at any time in mid-session.
4013 GnuplotMagic can now be loaded at any time in mid-session.
3977
4014
3978 2002-04-24 Fernando Perez <fperez@colorado.edu>
4015 2002-04-24 Fernando Perez <fperez@colorado.edu>
3979
4016
3980 * IPython/numutils.py: removed SIUnits. It doesn't properly set
4017 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3981 the globals (IPython has its own namespace) and the
4018 the globals (IPython has its own namespace) and the
3982 PhysicalQuantity stuff is much better anyway.
4019 PhysicalQuantity stuff is much better anyway.
3983
4020
3984 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
4021 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3985 embedding example to standard user directory for
4022 embedding example to standard user directory for
3986 distribution. Also put it in the manual.
4023 distribution. Also put it in the manual.
3987
4024
3988 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
4025 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3989 instance as first argument (so it doesn't rely on some obscure
4026 instance as first argument (so it doesn't rely on some obscure
3990 hidden global).
4027 hidden global).
3991
4028
3992 * IPython/UserConfig/ipythonrc.py: put () back in accepted
4029 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3993 delimiters. While it prevents ().TAB from working, it allows
4030 delimiters. While it prevents ().TAB from working, it allows
3994 completions in open (... expressions. This is by far a more common
4031 completions in open (... expressions. This is by far a more common
3995 case.
4032 case.
3996
4033
3997 2002-04-23 Fernando Perez <fperez@colorado.edu>
4034 2002-04-23 Fernando Perez <fperez@colorado.edu>
3998
4035
3999 * IPython/Extensions/InterpreterPasteInput.py: new
4036 * IPython/Extensions/InterpreterPasteInput.py: new
4000 syntax-processing module for pasting lines with >>> or ... at the
4037 syntax-processing module for pasting lines with >>> or ... at the
4001 start.
4038 start.
4002
4039
4003 * IPython/Extensions/PhysicalQ_Interactive.py
4040 * IPython/Extensions/PhysicalQ_Interactive.py
4004 (PhysicalQuantityInteractive.__int__): fixed to work with either
4041 (PhysicalQuantityInteractive.__int__): fixed to work with either
4005 Numeric or math.
4042 Numeric or math.
4006
4043
4007 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
4044 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
4008 provided profiles. Now we have:
4045 provided profiles. Now we have:
4009 -math -> math module as * and cmath with its own namespace.
4046 -math -> math module as * and cmath with its own namespace.
4010 -numeric -> Numeric as *, plus gnuplot & grace
4047 -numeric -> Numeric as *, plus gnuplot & grace
4011 -physics -> same as before
4048 -physics -> same as before
4012
4049
4013 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
4050 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
4014 user-defined magics wouldn't be found by @magic if they were
4051 user-defined magics wouldn't be found by @magic if they were
4015 defined as class methods. Also cleaned up the namespace search
4052 defined as class methods. Also cleaned up the namespace search
4016 logic and the string building (to use %s instead of many repeated
4053 logic and the string building (to use %s instead of many repeated
4017 string adds).
4054 string adds).
4018
4055
4019 * IPython/UserConfig/example-magic.py (magic_foo): updated example
4056 * IPython/UserConfig/example-magic.py (magic_foo): updated example
4020 of user-defined magics to operate with class methods (cleaner, in
4057 of user-defined magics to operate with class methods (cleaner, in
4021 line with the gnuplot code).
4058 line with the gnuplot code).
4022
4059
4023 2002-04-22 Fernando Perez <fperez@colorado.edu>
4060 2002-04-22 Fernando Perez <fperez@colorado.edu>
4024
4061
4025 * setup.py: updated dependency list so that manual is updated when
4062 * setup.py: updated dependency list so that manual is updated when
4026 all included files change.
4063 all included files change.
4027
4064
4028 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
4065 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
4029 the delimiter removal option (the fix is ugly right now).
4066 the delimiter removal option (the fix is ugly right now).
4030
4067
4031 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
4068 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
4032 all of the math profile (quicker loading, no conflict between
4069 all of the math profile (quicker loading, no conflict between
4033 g-9.8 and g-gnuplot).
4070 g-9.8 and g-gnuplot).
4034
4071
4035 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
4072 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
4036 name of post-mortem files to IPython_crash_report.txt.
4073 name of post-mortem files to IPython_crash_report.txt.
4037
4074
4038 * Cleanup/update of the docs. Added all the new readline info and
4075 * Cleanup/update of the docs. Added all the new readline info and
4039 formatted all lists as 'real lists'.
4076 formatted all lists as 'real lists'.
4040
4077
4041 * IPython/ipmaker.py (make_IPython): removed now-obsolete
4078 * IPython/ipmaker.py (make_IPython): removed now-obsolete
4042 tab-completion options, since the full readline parse_and_bind is
4079 tab-completion options, since the full readline parse_and_bind is
4043 now accessible.
4080 now accessible.
4044
4081
4045 * IPython/iplib.py (InteractiveShell.init_readline): Changed
4082 * IPython/iplib.py (InteractiveShell.init_readline): Changed
4046 handling of readline options. Now users can specify any string to
4083 handling of readline options. Now users can specify any string to
4047 be passed to parse_and_bind(), as well as the delimiters to be
4084 be passed to parse_and_bind(), as well as the delimiters to be
4048 removed.
4085 removed.
4049 (InteractiveShell.__init__): Added __name__ to the global
4086 (InteractiveShell.__init__): Added __name__ to the global
4050 namespace so that things like Itpl which rely on its existence
4087 namespace so that things like Itpl which rely on its existence
4051 don't crash.
4088 don't crash.
4052 (InteractiveShell._prefilter): Defined the default with a _ so
4089 (InteractiveShell._prefilter): Defined the default with a _ so
4053 that prefilter() is easier to override, while the default one
4090 that prefilter() is easier to override, while the default one
4054 remains available.
4091 remains available.
4055
4092
4056 2002-04-18 Fernando Perez <fperez@colorado.edu>
4093 2002-04-18 Fernando Perez <fperez@colorado.edu>
4057
4094
4058 * Added information about pdb in the docs.
4095 * Added information about pdb in the docs.
4059
4096
4060 2002-04-17 Fernando Perez <fperez@colorado.edu>
4097 2002-04-17 Fernando Perez <fperez@colorado.edu>
4061
4098
4062 * IPython/ipmaker.py (make_IPython): added rc_override option to
4099 * IPython/ipmaker.py (make_IPython): added rc_override option to
4063 allow passing config options at creation time which may override
4100 allow passing config options at creation time which may override
4064 anything set in the config files or command line. This is
4101 anything set in the config files or command line. This is
4065 particularly useful for configuring embedded instances.
4102 particularly useful for configuring embedded instances.
4066
4103
4067 2002-04-15 Fernando Perez <fperez@colorado.edu>
4104 2002-04-15 Fernando Perez <fperez@colorado.edu>
4068
4105
4069 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
4106 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
4070 crash embedded instances because of the input cache falling out of
4107 crash embedded instances because of the input cache falling out of
4071 sync with the output counter.
4108 sync with the output counter.
4072
4109
4073 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
4110 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
4074 mode which calls pdb after an uncaught exception in IPython itself.
4111 mode which calls pdb after an uncaught exception in IPython itself.
4075
4112
4076 2002-04-14 Fernando Perez <fperez@colorado.edu>
4113 2002-04-14 Fernando Perez <fperez@colorado.edu>
4077
4114
4078 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
4115 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
4079 readline, fix it back after each call.
4116 readline, fix it back after each call.
4080
4117
4081 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
4118 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
4082 method to force all access via __call__(), which guarantees that
4119 method to force all access via __call__(), which guarantees that
4083 traceback references are properly deleted.
4120 traceback references are properly deleted.
4084
4121
4085 * IPython/Prompts.py (CachedOutput._display): minor fixes to
4122 * IPython/Prompts.py (CachedOutput._display): minor fixes to
4086 improve printing when pprint is in use.
4123 improve printing when pprint is in use.
4087
4124
4088 2002-04-13 Fernando Perez <fperez@colorado.edu>
4125 2002-04-13 Fernando Perez <fperez@colorado.edu>
4089
4126
4090 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
4127 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
4091 exceptions aren't caught anymore. If the user triggers one, he
4128 exceptions aren't caught anymore. If the user triggers one, he
4092 should know why he's doing it and it should go all the way up,
4129 should know why he's doing it and it should go all the way up,
4093 just like any other exception. So now @abort will fully kill the
4130 just like any other exception. So now @abort will fully kill the
4094 embedded interpreter and the embedding code (unless that happens
4131 embedded interpreter and the embedding code (unless that happens
4095 to catch SystemExit).
4132 to catch SystemExit).
4096
4133
4097 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
4134 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
4098 and a debugger() method to invoke the interactive pdb debugger
4135 and a debugger() method to invoke the interactive pdb debugger
4099 after printing exception information. Also added the corresponding
4136 after printing exception information. Also added the corresponding
4100 -pdb option and @pdb magic to control this feature, and updated
4137 -pdb option and @pdb magic to control this feature, and updated
4101 the docs. After a suggestion from Christopher Hart
4138 the docs. After a suggestion from Christopher Hart
4102 (hart-AT-caltech.edu).
4139 (hart-AT-caltech.edu).
4103
4140
4104 2002-04-12 Fernando Perez <fperez@colorado.edu>
4141 2002-04-12 Fernando Perez <fperez@colorado.edu>
4105
4142
4106 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
4143 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
4107 the exception handlers defined by the user (not the CrashHandler)
4144 the exception handlers defined by the user (not the CrashHandler)
4108 so that user exceptions don't trigger an ipython bug report.
4145 so that user exceptions don't trigger an ipython bug report.
4109
4146
4110 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
4147 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
4111 configurable (it should have always been so).
4148 configurable (it should have always been so).
4112
4149
4113 2002-03-26 Fernando Perez <fperez@colorado.edu>
4150 2002-03-26 Fernando Perez <fperez@colorado.edu>
4114
4151
4115 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
4152 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
4116 and there to fix embedding namespace issues. This should all be
4153 and there to fix embedding namespace issues. This should all be
4117 done in a more elegant way.
4154 done in a more elegant way.
4118
4155
4119 2002-03-25 Fernando Perez <fperez@colorado.edu>
4156 2002-03-25 Fernando Perez <fperez@colorado.edu>
4120
4157
4121 * IPython/genutils.py (get_home_dir): Try to make it work under
4158 * IPython/genutils.py (get_home_dir): Try to make it work under
4122 win9x also.
4159 win9x also.
4123
4160
4124 2002-03-20 Fernando Perez <fperez@colorado.edu>
4161 2002-03-20 Fernando Perez <fperez@colorado.edu>
4125
4162
4126 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
4163 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
4127 sys.displayhook untouched upon __init__.
4164 sys.displayhook untouched upon __init__.
4128
4165
4129 2002-03-19 Fernando Perez <fperez@colorado.edu>
4166 2002-03-19 Fernando Perez <fperez@colorado.edu>
4130
4167
4131 * Released 0.2.9 (for embedding bug, basically).
4168 * Released 0.2.9 (for embedding bug, basically).
4132
4169
4133 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
4170 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
4134 exceptions so that enclosing shell's state can be restored.
4171 exceptions so that enclosing shell's state can be restored.
4135
4172
4136 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
4173 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
4137 naming conventions in the .ipython/ dir.
4174 naming conventions in the .ipython/ dir.
4138
4175
4139 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
4176 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
4140 from delimiters list so filenames with - in them get expanded.
4177 from delimiters list so filenames with - in them get expanded.
4141
4178
4142 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
4179 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
4143 sys.displayhook not being properly restored after an embedded call.
4180 sys.displayhook not being properly restored after an embedded call.
4144
4181
4145 2002-03-18 Fernando Perez <fperez@colorado.edu>
4182 2002-03-18 Fernando Perez <fperez@colorado.edu>
4146
4183
4147 * Released 0.2.8
4184 * Released 0.2.8
4148
4185
4149 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
4186 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
4150 some files weren't being included in a -upgrade.
4187 some files weren't being included in a -upgrade.
4151 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
4188 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
4152 on' so that the first tab completes.
4189 on' so that the first tab completes.
4153 (InteractiveShell.handle_magic): fixed bug with spaces around
4190 (InteractiveShell.handle_magic): fixed bug with spaces around
4154 quotes breaking many magic commands.
4191 quotes breaking many magic commands.
4155
4192
4156 * setup.py: added note about ignoring the syntax error messages at
4193 * setup.py: added note about ignoring the syntax error messages at
4157 installation.
4194 installation.
4158
4195
4159 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
4196 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
4160 streamlining the gnuplot interface, now there's only one magic @gp.
4197 streamlining the gnuplot interface, now there's only one magic @gp.
4161
4198
4162 2002-03-17 Fernando Perez <fperez@colorado.edu>
4199 2002-03-17 Fernando Perez <fperez@colorado.edu>
4163
4200
4164 * IPython/UserConfig/magic_gnuplot.py: new name for the
4201 * IPython/UserConfig/magic_gnuplot.py: new name for the
4165 example-magic_pm.py file. Much enhanced system, now with a shell
4202 example-magic_pm.py file. Much enhanced system, now with a shell
4166 for communicating directly with gnuplot, one command at a time.
4203 for communicating directly with gnuplot, one command at a time.
4167
4204
4168 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
4205 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
4169 setting __name__=='__main__'.
4206 setting __name__=='__main__'.
4170
4207
4171 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
4208 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
4172 mini-shell for accessing gnuplot from inside ipython. Should
4209 mini-shell for accessing gnuplot from inside ipython. Should
4173 extend it later for grace access too. Inspired by Arnd's
4210 extend it later for grace access too. Inspired by Arnd's
4174 suggestion.
4211 suggestion.
4175
4212
4176 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
4213 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
4177 calling magic functions with () in their arguments. Thanks to Arnd
4214 calling magic functions with () in their arguments. Thanks to Arnd
4178 Baecker for pointing this to me.
4215 Baecker for pointing this to me.
4179
4216
4180 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
4217 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
4181 infinitely for integer or complex arrays (only worked with floats).
4218 infinitely for integer or complex arrays (only worked with floats).
4182
4219
4183 2002-03-16 Fernando Perez <fperez@colorado.edu>
4220 2002-03-16 Fernando Perez <fperez@colorado.edu>
4184
4221
4185 * setup.py: Merged setup and setup_windows into a single script
4222 * setup.py: Merged setup and setup_windows into a single script
4186 which properly handles things for windows users.
4223 which properly handles things for windows users.
4187
4224
4188 2002-03-15 Fernando Perez <fperez@colorado.edu>
4225 2002-03-15 Fernando Perez <fperez@colorado.edu>
4189
4226
4190 * Big change to the manual: now the magics are all automatically
4227 * Big change to the manual: now the magics are all automatically
4191 documented. This information is generated from their docstrings
4228 documented. This information is generated from their docstrings
4192 and put in a latex file included by the manual lyx file. This way
4229 and put in a latex file included by the manual lyx file. This way
4193 we get always up to date information for the magics. The manual
4230 we get always up to date information for the magics. The manual
4194 now also has proper version information, also auto-synced.
4231 now also has proper version information, also auto-synced.
4195
4232
4196 For this to work, an undocumented --magic_docstrings option was added.
4233 For this to work, an undocumented --magic_docstrings option was added.
4197
4234
4198 2002-03-13 Fernando Perez <fperez@colorado.edu>
4235 2002-03-13 Fernando Perez <fperez@colorado.edu>
4199
4236
4200 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
4237 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
4201 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
4238 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
4202
4239
4203 2002-03-12 Fernando Perez <fperez@colorado.edu>
4240 2002-03-12 Fernando Perez <fperez@colorado.edu>
4204
4241
4205 * IPython/ultraTB.py (TermColors): changed color escapes again to
4242 * IPython/ultraTB.py (TermColors): changed color escapes again to
4206 fix the (old, reintroduced) line-wrapping bug. Basically, if
4243 fix the (old, reintroduced) line-wrapping bug. Basically, if
4207 \001..\002 aren't given in the color escapes, lines get wrapped
4244 \001..\002 aren't given in the color escapes, lines get wrapped
4208 weirdly. But giving those screws up old xterms and emacs terms. So
4245 weirdly. But giving those screws up old xterms and emacs terms. So
4209 I added some logic for emacs terms to be ok, but I can't identify old
4246 I added some logic for emacs terms to be ok, but I can't identify old
4210 xterms separately ($TERM=='xterm' for many terminals, like konsole).
4247 xterms separately ($TERM=='xterm' for many terminals, like konsole).
4211
4248
4212 2002-03-10 Fernando Perez <fperez@colorado.edu>
4249 2002-03-10 Fernando Perez <fperez@colorado.edu>
4213
4250
4214 * IPython/usage.py (__doc__): Various documentation cleanups and
4251 * IPython/usage.py (__doc__): Various documentation cleanups and
4215 updates, both in usage docstrings and in the manual.
4252 updates, both in usage docstrings and in the manual.
4216
4253
4217 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
4254 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
4218 handling of caching. Set minimum acceptabe value for having a
4255 handling of caching. Set minimum acceptabe value for having a
4219 cache at 20 values.
4256 cache at 20 values.
4220
4257
4221 * IPython/iplib.py (InteractiveShell.user_setup): moved the
4258 * IPython/iplib.py (InteractiveShell.user_setup): moved the
4222 install_first_time function to a method, renamed it and added an
4259 install_first_time function to a method, renamed it and added an
4223 'upgrade' mode. Now people can update their config directory with
4260 'upgrade' mode. Now people can update their config directory with
4224 a simple command line switch (-upgrade, also new).
4261 a simple command line switch (-upgrade, also new).
4225
4262
4226 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
4263 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
4227 @file (convenient for automagic users under Python >= 2.2).
4264 @file (convenient for automagic users under Python >= 2.2).
4228 Removed @files (it seemed more like a plural than an abbrev. of
4265 Removed @files (it seemed more like a plural than an abbrev. of
4229 'file show').
4266 'file show').
4230
4267
4231 * IPython/iplib.py (install_first_time): Fixed crash if there were
4268 * IPython/iplib.py (install_first_time): Fixed crash if there were
4232 backup files ('~') in .ipython/ install directory.
4269 backup files ('~') in .ipython/ install directory.
4233
4270
4234 * IPython/ipmaker.py (make_IPython): fixes for new prompt
4271 * IPython/ipmaker.py (make_IPython): fixes for new prompt
4235 system. Things look fine, but these changes are fairly
4272 system. Things look fine, but these changes are fairly
4236 intrusive. Test them for a few days.
4273 intrusive. Test them for a few days.
4237
4274
4238 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
4275 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
4239 the prompts system. Now all in/out prompt strings are user
4276 the prompts system. Now all in/out prompt strings are user
4240 controllable. This is particularly useful for embedding, as one
4277 controllable. This is particularly useful for embedding, as one
4241 can tag embedded instances with particular prompts.
4278 can tag embedded instances with particular prompts.
4242
4279
4243 Also removed global use of sys.ps1/2, which now allows nested
4280 Also removed global use of sys.ps1/2, which now allows nested
4244 embeddings without any problems. Added command-line options for
4281 embeddings without any problems. Added command-line options for
4245 the prompt strings.
4282 the prompt strings.
4246
4283
4247 2002-03-08 Fernando Perez <fperez@colorado.edu>
4284 2002-03-08 Fernando Perez <fperez@colorado.edu>
4248
4285
4249 * IPython/UserConfig/example-embed-short.py (ipshell): added
4286 * IPython/UserConfig/example-embed-short.py (ipshell): added
4250 example file with the bare minimum code for embedding.
4287 example file with the bare minimum code for embedding.
4251
4288
4252 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
4289 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
4253 functionality for the embeddable shell to be activated/deactivated
4290 functionality for the embeddable shell to be activated/deactivated
4254 either globally or at each call.
4291 either globally or at each call.
4255
4292
4256 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
4293 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
4257 rewriting the prompt with '--->' for auto-inputs with proper
4294 rewriting the prompt with '--->' for auto-inputs with proper
4258 coloring. Now the previous UGLY hack in handle_auto() is gone, and
4295 coloring. Now the previous UGLY hack in handle_auto() is gone, and
4259 this is handled by the prompts class itself, as it should.
4296 this is handled by the prompts class itself, as it should.
4260
4297
4261 2002-03-05 Fernando Perez <fperez@colorado.edu>
4298 2002-03-05 Fernando Perez <fperez@colorado.edu>
4262
4299
4263 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
4300 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
4264 @logstart to avoid name clashes with the math log function.
4301 @logstart to avoid name clashes with the math log function.
4265
4302
4266 * Big updates to X/Emacs section of the manual.
4303 * Big updates to X/Emacs section of the manual.
4267
4304
4268 * Removed ipython_emacs. Milan explained to me how to pass
4305 * Removed ipython_emacs. Milan explained to me how to pass
4269 arguments to ipython through Emacs. Some day I'm going to end up
4306 arguments to ipython through Emacs. Some day I'm going to end up
4270 learning some lisp...
4307 learning some lisp...
4271
4308
4272 2002-03-04 Fernando Perez <fperez@colorado.edu>
4309 2002-03-04 Fernando Perez <fperez@colorado.edu>
4273
4310
4274 * IPython/ipython_emacs: Created script to be used as the
4311 * IPython/ipython_emacs: Created script to be used as the
4275 py-python-command Emacs variable so we can pass IPython
4312 py-python-command Emacs variable so we can pass IPython
4276 parameters. I can't figure out how to tell Emacs directly to pass
4313 parameters. I can't figure out how to tell Emacs directly to pass
4277 parameters to IPython, so a dummy shell script will do it.
4314 parameters to IPython, so a dummy shell script will do it.
4278
4315
4279 Other enhancements made for things to work better under Emacs'
4316 Other enhancements made for things to work better under Emacs'
4280 various types of terminals. Many thanks to Milan Zamazal
4317 various types of terminals. Many thanks to Milan Zamazal
4281 <pdm-AT-zamazal.org> for all the suggestions and pointers.
4318 <pdm-AT-zamazal.org> for all the suggestions and pointers.
4282
4319
4283 2002-03-01 Fernando Perez <fperez@colorado.edu>
4320 2002-03-01 Fernando Perez <fperez@colorado.edu>
4284
4321
4285 * IPython/ipmaker.py (make_IPython): added a --readline! option so
4322 * IPython/ipmaker.py (make_IPython): added a --readline! option so
4286 that loading of readline is now optional. This gives better
4323 that loading of readline is now optional. This gives better
4287 control to emacs users.
4324 control to emacs users.
4288
4325
4289 * IPython/ultraTB.py (__date__): Modified color escape sequences
4326 * IPython/ultraTB.py (__date__): Modified color escape sequences
4290 and now things work fine under xterm and in Emacs' term buffers
4327 and now things work fine under xterm and in Emacs' term buffers
4291 (though not shell ones). Well, in emacs you get colors, but all
4328 (though not shell ones). Well, in emacs you get colors, but all
4292 seem to be 'light' colors (no difference between dark and light
4329 seem to be 'light' colors (no difference between dark and light
4293 ones). But the garbage chars are gone, and also in xterms. It
4330 ones). But the garbage chars are gone, and also in xterms. It
4294 seems that now I'm using 'cleaner' ansi sequences.
4331 seems that now I'm using 'cleaner' ansi sequences.
4295
4332
4296 2002-02-21 Fernando Perez <fperez@colorado.edu>
4333 2002-02-21 Fernando Perez <fperez@colorado.edu>
4297
4334
4298 * Released 0.2.7 (mainly to publish the scoping fix).
4335 * Released 0.2.7 (mainly to publish the scoping fix).
4299
4336
4300 * IPython/Logger.py (Logger.logstate): added. A corresponding
4337 * IPython/Logger.py (Logger.logstate): added. A corresponding
4301 @logstate magic was created.
4338 @logstate magic was created.
4302
4339
4303 * IPython/Magic.py: fixed nested scoping problem under Python
4340 * IPython/Magic.py: fixed nested scoping problem under Python
4304 2.1.x (automagic wasn't working).
4341 2.1.x (automagic wasn't working).
4305
4342
4306 2002-02-20 Fernando Perez <fperez@colorado.edu>
4343 2002-02-20 Fernando Perez <fperez@colorado.edu>
4307
4344
4308 * Released 0.2.6.
4345 * Released 0.2.6.
4309
4346
4310 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4347 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4311 option so that logs can come out without any headers at all.
4348 option so that logs can come out without any headers at all.
4312
4349
4313 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4350 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4314 SciPy.
4351 SciPy.
4315
4352
4316 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4353 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4317 that embedded IPython calls don't require vars() to be explicitly
4354 that embedded IPython calls don't require vars() to be explicitly
4318 passed. Now they are extracted from the caller's frame (code
4355 passed. Now they are extracted from the caller's frame (code
4319 snatched from Eric Jones' weave). Added better documentation to
4356 snatched from Eric Jones' weave). Added better documentation to
4320 the section on embedding and the example file.
4357 the section on embedding and the example file.
4321
4358
4322 * IPython/genutils.py (page): Changed so that under emacs, it just
4359 * IPython/genutils.py (page): Changed so that under emacs, it just
4323 prints the string. You can then page up and down in the emacs
4360 prints the string. You can then page up and down in the emacs
4324 buffer itself. This is how the builtin help() works.
4361 buffer itself. This is how the builtin help() works.
4325
4362
4326 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4363 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4327 macro scoping: macros need to be executed in the user's namespace
4364 macro scoping: macros need to be executed in the user's namespace
4328 to work as if they had been typed by the user.
4365 to work as if they had been typed by the user.
4329
4366
4330 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4367 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4331 execute automatically (no need to type 'exec...'). They then
4368 execute automatically (no need to type 'exec...'). They then
4332 behave like 'true macros'. The printing system was also modified
4369 behave like 'true macros'. The printing system was also modified
4333 for this to work.
4370 for this to work.
4334
4371
4335 2002-02-19 Fernando Perez <fperez@colorado.edu>
4372 2002-02-19 Fernando Perez <fperez@colorado.edu>
4336
4373
4337 * IPython/genutils.py (page_file): new function for paging files
4374 * IPython/genutils.py (page_file): new function for paging files
4338 in an OS-independent way. Also necessary for file viewing to work
4375 in an OS-independent way. Also necessary for file viewing to work
4339 well inside Emacs buffers.
4376 well inside Emacs buffers.
4340 (page): Added checks for being in an emacs buffer.
4377 (page): Added checks for being in an emacs buffer.
4341 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4378 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4342 same bug in iplib.
4379 same bug in iplib.
4343
4380
4344 2002-02-18 Fernando Perez <fperez@colorado.edu>
4381 2002-02-18 Fernando Perez <fperez@colorado.edu>
4345
4382
4346 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4383 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4347 of readline so that IPython can work inside an Emacs buffer.
4384 of readline so that IPython can work inside an Emacs buffer.
4348
4385
4349 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4386 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4350 method signatures (they weren't really bugs, but it looks cleaner
4387 method signatures (they weren't really bugs, but it looks cleaner
4351 and keeps PyChecker happy).
4388 and keeps PyChecker happy).
4352
4389
4353 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4390 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4354 for implementing various user-defined hooks. Currently only
4391 for implementing various user-defined hooks. Currently only
4355 display is done.
4392 display is done.
4356
4393
4357 * IPython/Prompts.py (CachedOutput._display): changed display
4394 * IPython/Prompts.py (CachedOutput._display): changed display
4358 functions so that they can be dynamically changed by users easily.
4395 functions so that they can be dynamically changed by users easily.
4359
4396
4360 * IPython/Extensions/numeric_formats.py (num_display): added an
4397 * IPython/Extensions/numeric_formats.py (num_display): added an
4361 extension for printing NumPy arrays in flexible manners. It
4398 extension for printing NumPy arrays in flexible manners. It
4362 doesn't do anything yet, but all the structure is in
4399 doesn't do anything yet, but all the structure is in
4363 place. Ultimately the plan is to implement output format control
4400 place. Ultimately the plan is to implement output format control
4364 like in Octave.
4401 like in Octave.
4365
4402
4366 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4403 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4367 methods are found at run-time by all the automatic machinery.
4404 methods are found at run-time by all the automatic machinery.
4368
4405
4369 2002-02-17 Fernando Perez <fperez@colorado.edu>
4406 2002-02-17 Fernando Perez <fperez@colorado.edu>
4370
4407
4371 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4408 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4372 whole file a little.
4409 whole file a little.
4373
4410
4374 * ToDo: closed this document. Now there's a new_design.lyx
4411 * ToDo: closed this document. Now there's a new_design.lyx
4375 document for all new ideas. Added making a pdf of it for the
4412 document for all new ideas. Added making a pdf of it for the
4376 end-user distro.
4413 end-user distro.
4377
4414
4378 * IPython/Logger.py (Logger.switch_log): Created this to replace
4415 * IPython/Logger.py (Logger.switch_log): Created this to replace
4379 logon() and logoff(). It also fixes a nasty crash reported by
4416 logon() and logoff(). It also fixes a nasty crash reported by
4380 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4417 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4381
4418
4382 * IPython/iplib.py (complete): got auto-completion to work with
4419 * IPython/iplib.py (complete): got auto-completion to work with
4383 automagic (I had wanted this for a long time).
4420 automagic (I had wanted this for a long time).
4384
4421
4385 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4422 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4386 to @file, since file() is now a builtin and clashes with automagic
4423 to @file, since file() is now a builtin and clashes with automagic
4387 for @file.
4424 for @file.
4388
4425
4389 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4426 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4390 of this was previously in iplib, which had grown to more than 2000
4427 of this was previously in iplib, which had grown to more than 2000
4391 lines, way too long. No new functionality, but it makes managing
4428 lines, way too long. No new functionality, but it makes managing
4392 the code a bit easier.
4429 the code a bit easier.
4393
4430
4394 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4431 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4395 information to crash reports.
4432 information to crash reports.
4396
4433
4397 2002-02-12 Fernando Perez <fperez@colorado.edu>
4434 2002-02-12 Fernando Perez <fperez@colorado.edu>
4398
4435
4399 * Released 0.2.5.
4436 * Released 0.2.5.
4400
4437
4401 2002-02-11 Fernando Perez <fperez@colorado.edu>
4438 2002-02-11 Fernando Perez <fperez@colorado.edu>
4402
4439
4403 * Wrote a relatively complete Windows installer. It puts
4440 * Wrote a relatively complete Windows installer. It puts
4404 everything in place, creates Start Menu entries and fixes the
4441 everything in place, creates Start Menu entries and fixes the
4405 color issues. Nothing fancy, but it works.
4442 color issues. Nothing fancy, but it works.
4406
4443
4407 2002-02-10 Fernando Perez <fperez@colorado.edu>
4444 2002-02-10 Fernando Perez <fperez@colorado.edu>
4408
4445
4409 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4446 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4410 os.path.expanduser() call so that we can type @run ~/myfile.py and
4447 os.path.expanduser() call so that we can type @run ~/myfile.py and
4411 have thigs work as expected.
4448 have thigs work as expected.
4412
4449
4413 * IPython/genutils.py (page): fixed exception handling so things
4450 * IPython/genutils.py (page): fixed exception handling so things
4414 work both in Unix and Windows correctly. Quitting a pager triggers
4451 work both in Unix and Windows correctly. Quitting a pager triggers
4415 an IOError/broken pipe in Unix, and in windows not finding a pager
4452 an IOError/broken pipe in Unix, and in windows not finding a pager
4416 is also an IOError, so I had to actually look at the return value
4453 is also an IOError, so I had to actually look at the return value
4417 of the exception, not just the exception itself. Should be ok now.
4454 of the exception, not just the exception itself. Should be ok now.
4418
4455
4419 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4456 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4420 modified to allow case-insensitive color scheme changes.
4457 modified to allow case-insensitive color scheme changes.
4421
4458
4422 2002-02-09 Fernando Perez <fperez@colorado.edu>
4459 2002-02-09 Fernando Perez <fperez@colorado.edu>
4423
4460
4424 * IPython/genutils.py (native_line_ends): new function to leave
4461 * IPython/genutils.py (native_line_ends): new function to leave
4425 user config files with os-native line-endings.
4462 user config files with os-native line-endings.
4426
4463
4427 * README and manual updates.
4464 * README and manual updates.
4428
4465
4429 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4466 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4430 instead of StringType to catch Unicode strings.
4467 instead of StringType to catch Unicode strings.
4431
4468
4432 * IPython/genutils.py (filefind): fixed bug for paths with
4469 * IPython/genutils.py (filefind): fixed bug for paths with
4433 embedded spaces (very common in Windows).
4470 embedded spaces (very common in Windows).
4434
4471
4435 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4472 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4436 files under Windows, so that they get automatically associated
4473 files under Windows, so that they get automatically associated
4437 with a text editor. Windows makes it a pain to handle
4474 with a text editor. Windows makes it a pain to handle
4438 extension-less files.
4475 extension-less files.
4439
4476
4440 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4477 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4441 warning about readline only occur for Posix. In Windows there's no
4478 warning about readline only occur for Posix. In Windows there's no
4442 way to get readline, so why bother with the warning.
4479 way to get readline, so why bother with the warning.
4443
4480
4444 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4481 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4445 for __str__ instead of dir(self), since dir() changed in 2.2.
4482 for __str__ instead of dir(self), since dir() changed in 2.2.
4446
4483
4447 * Ported to Windows! Tested on XP, I suspect it should work fine
4484 * Ported to Windows! Tested on XP, I suspect it should work fine
4448 on NT/2000, but I don't think it will work on 98 et al. That
4485 on NT/2000, but I don't think it will work on 98 et al. That
4449 series of Windows is such a piece of junk anyway that I won't try
4486 series of Windows is such a piece of junk anyway that I won't try
4450 porting it there. The XP port was straightforward, showed a few
4487 porting it there. The XP port was straightforward, showed a few
4451 bugs here and there (fixed all), in particular some string
4488 bugs here and there (fixed all), in particular some string
4452 handling stuff which required considering Unicode strings (which
4489 handling stuff which required considering Unicode strings (which
4453 Windows uses). This is good, but hasn't been too tested :) No
4490 Windows uses). This is good, but hasn't been too tested :) No
4454 fancy installer yet, I'll put a note in the manual so people at
4491 fancy installer yet, I'll put a note in the manual so people at
4455 least make manually a shortcut.
4492 least make manually a shortcut.
4456
4493
4457 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4494 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4458 into a single one, "colors". This now controls both prompt and
4495 into a single one, "colors". This now controls both prompt and
4459 exception color schemes, and can be changed both at startup
4496 exception color schemes, and can be changed both at startup
4460 (either via command-line switches or via ipythonrc files) and at
4497 (either via command-line switches or via ipythonrc files) and at
4461 runtime, with @colors.
4498 runtime, with @colors.
4462 (Magic.magic_run): renamed @prun to @run and removed the old
4499 (Magic.magic_run): renamed @prun to @run and removed the old
4463 @run. The two were too similar to warrant keeping both.
4500 @run. The two were too similar to warrant keeping both.
4464
4501
4465 2002-02-03 Fernando Perez <fperez@colorado.edu>
4502 2002-02-03 Fernando Perez <fperez@colorado.edu>
4466
4503
4467 * IPython/iplib.py (install_first_time): Added comment on how to
4504 * IPython/iplib.py (install_first_time): Added comment on how to
4468 configure the color options for first-time users. Put a <return>
4505 configure the color options for first-time users. Put a <return>
4469 request at the end so that small-terminal users get a chance to
4506 request at the end so that small-terminal users get a chance to
4470 read the startup info.
4507 read the startup info.
4471
4508
4472 2002-01-23 Fernando Perez <fperez@colorado.edu>
4509 2002-01-23 Fernando Perez <fperez@colorado.edu>
4473
4510
4474 * IPython/iplib.py (CachedOutput.update): Changed output memory
4511 * IPython/iplib.py (CachedOutput.update): Changed output memory
4475 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4512 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4476 input history we still use _i. Did this b/c these variable are
4513 input history we still use _i. Did this b/c these variable are
4477 very commonly used in interactive work, so the less we need to
4514 very commonly used in interactive work, so the less we need to
4478 type the better off we are.
4515 type the better off we are.
4479 (Magic.magic_prun): updated @prun to better handle the namespaces
4516 (Magic.magic_prun): updated @prun to better handle the namespaces
4480 the file will run in, including a fix for __name__ not being set
4517 the file will run in, including a fix for __name__ not being set
4481 before.
4518 before.
4482
4519
4483 2002-01-20 Fernando Perez <fperez@colorado.edu>
4520 2002-01-20 Fernando Perez <fperez@colorado.edu>
4484
4521
4485 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4522 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4486 extra garbage for Python 2.2. Need to look more carefully into
4523 extra garbage for Python 2.2. Need to look more carefully into
4487 this later.
4524 this later.
4488
4525
4489 2002-01-19 Fernando Perez <fperez@colorado.edu>
4526 2002-01-19 Fernando Perez <fperez@colorado.edu>
4490
4527
4491 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4528 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4492 display SyntaxError exceptions properly formatted when they occur
4529 display SyntaxError exceptions properly formatted when they occur
4493 (they can be triggered by imported code).
4530 (they can be triggered by imported code).
4494
4531
4495 2002-01-18 Fernando Perez <fperez@colorado.edu>
4532 2002-01-18 Fernando Perez <fperez@colorado.edu>
4496
4533
4497 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4534 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4498 SyntaxError exceptions are reported nicely formatted, instead of
4535 SyntaxError exceptions are reported nicely formatted, instead of
4499 spitting out only offset information as before.
4536 spitting out only offset information as before.
4500 (Magic.magic_prun): Added the @prun function for executing
4537 (Magic.magic_prun): Added the @prun function for executing
4501 programs with command line args inside IPython.
4538 programs with command line args inside IPython.
4502
4539
4503 2002-01-16 Fernando Perez <fperez@colorado.edu>
4540 2002-01-16 Fernando Perez <fperez@colorado.edu>
4504
4541
4505 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4542 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4506 to *not* include the last item given in a range. This brings their
4543 to *not* include the last item given in a range. This brings their
4507 behavior in line with Python's slicing:
4544 behavior in line with Python's slicing:
4508 a[n1:n2] -> a[n1]...a[n2-1]
4545 a[n1:n2] -> a[n1]...a[n2-1]
4509 It may be a bit less convenient, but I prefer to stick to Python's
4546 It may be a bit less convenient, but I prefer to stick to Python's
4510 conventions *everywhere*, so users never have to wonder.
4547 conventions *everywhere*, so users never have to wonder.
4511 (Magic.magic_macro): Added @macro function to ease the creation of
4548 (Magic.magic_macro): Added @macro function to ease the creation of
4512 macros.
4549 macros.
4513
4550
4514 2002-01-05 Fernando Perez <fperez@colorado.edu>
4551 2002-01-05 Fernando Perez <fperez@colorado.edu>
4515
4552
4516 * Released 0.2.4.
4553 * Released 0.2.4.
4517
4554
4518 * IPython/iplib.py (Magic.magic_pdef):
4555 * IPython/iplib.py (Magic.magic_pdef):
4519 (InteractiveShell.safe_execfile): report magic lines and error
4556 (InteractiveShell.safe_execfile): report magic lines and error
4520 lines without line numbers so one can easily copy/paste them for
4557 lines without line numbers so one can easily copy/paste them for
4521 re-execution.
4558 re-execution.
4522
4559
4523 * Updated manual with recent changes.
4560 * Updated manual with recent changes.
4524
4561
4525 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4562 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4526 docstring printing when class? is called. Very handy for knowing
4563 docstring printing when class? is called. Very handy for knowing
4527 how to create class instances (as long as __init__ is well
4564 how to create class instances (as long as __init__ is well
4528 documented, of course :)
4565 documented, of course :)
4529 (Magic.magic_doc): print both class and constructor docstrings.
4566 (Magic.magic_doc): print both class and constructor docstrings.
4530 (Magic.magic_pdef): give constructor info if passed a class and
4567 (Magic.magic_pdef): give constructor info if passed a class and
4531 __call__ info for callable object instances.
4568 __call__ info for callable object instances.
4532
4569
4533 2002-01-04 Fernando Perez <fperez@colorado.edu>
4570 2002-01-04 Fernando Perez <fperez@colorado.edu>
4534
4571
4535 * Made deep_reload() off by default. It doesn't always work
4572 * Made deep_reload() off by default. It doesn't always work
4536 exactly as intended, so it's probably safer to have it off. It's
4573 exactly as intended, so it's probably safer to have it off. It's
4537 still available as dreload() anyway, so nothing is lost.
4574 still available as dreload() anyway, so nothing is lost.
4538
4575
4539 2002-01-02 Fernando Perez <fperez@colorado.edu>
4576 2002-01-02 Fernando Perez <fperez@colorado.edu>
4540
4577
4541 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4578 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4542 so I wanted an updated release).
4579 so I wanted an updated release).
4543
4580
4544 2001-12-27 Fernando Perez <fperez@colorado.edu>
4581 2001-12-27 Fernando Perez <fperez@colorado.edu>
4545
4582
4546 * IPython/iplib.py (InteractiveShell.interact): Added the original
4583 * IPython/iplib.py (InteractiveShell.interact): Added the original
4547 code from 'code.py' for this module in order to change the
4584 code from 'code.py' for this module in order to change the
4548 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4585 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4549 the history cache would break when the user hit Ctrl-C, and
4586 the history cache would break when the user hit Ctrl-C, and
4550 interact() offers no way to add any hooks to it.
4587 interact() offers no way to add any hooks to it.
4551
4588
4552 2001-12-23 Fernando Perez <fperez@colorado.edu>
4589 2001-12-23 Fernando Perez <fperez@colorado.edu>
4553
4590
4554 * setup.py: added check for 'MANIFEST' before trying to remove
4591 * setup.py: added check for 'MANIFEST' before trying to remove
4555 it. Thanks to Sean Reifschneider.
4592 it. Thanks to Sean Reifschneider.
4556
4593
4557 2001-12-22 Fernando Perez <fperez@colorado.edu>
4594 2001-12-22 Fernando Perez <fperez@colorado.edu>
4558
4595
4559 * Released 0.2.2.
4596 * Released 0.2.2.
4560
4597
4561 * Finished (reasonably) writing the manual. Later will add the
4598 * Finished (reasonably) writing the manual. Later will add the
4562 python-standard navigation stylesheets, but for the time being
4599 python-standard navigation stylesheets, but for the time being
4563 it's fairly complete. Distribution will include html and pdf
4600 it's fairly complete. Distribution will include html and pdf
4564 versions.
4601 versions.
4565
4602
4566 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4603 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4567 (MayaVi author).
4604 (MayaVi author).
4568
4605
4569 2001-12-21 Fernando Perez <fperez@colorado.edu>
4606 2001-12-21 Fernando Perez <fperez@colorado.edu>
4570
4607
4571 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4608 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4572 good public release, I think (with the manual and the distutils
4609 good public release, I think (with the manual and the distutils
4573 installer). The manual can use some work, but that can go
4610 installer). The manual can use some work, but that can go
4574 slowly. Otherwise I think it's quite nice for end users. Next
4611 slowly. Otherwise I think it's quite nice for end users. Next
4575 summer, rewrite the guts of it...
4612 summer, rewrite the guts of it...
4576
4613
4577 * Changed format of ipythonrc files to use whitespace as the
4614 * Changed format of ipythonrc files to use whitespace as the
4578 separator instead of an explicit '='. Cleaner.
4615 separator instead of an explicit '='. Cleaner.
4579
4616
4580 2001-12-20 Fernando Perez <fperez@colorado.edu>
4617 2001-12-20 Fernando Perez <fperez@colorado.edu>
4581
4618
4582 * Started a manual in LyX. For now it's just a quick merge of the
4619 * Started a manual in LyX. For now it's just a quick merge of the
4583 various internal docstrings and READMEs. Later it may grow into a
4620 various internal docstrings and READMEs. Later it may grow into a
4584 nice, full-blown manual.
4621 nice, full-blown manual.
4585
4622
4586 * Set up a distutils based installer. Installation should now be
4623 * Set up a distutils based installer. Installation should now be
4587 trivially simple for end-users.
4624 trivially simple for end-users.
4588
4625
4589 2001-12-11 Fernando Perez <fperez@colorado.edu>
4626 2001-12-11 Fernando Perez <fperez@colorado.edu>
4590
4627
4591 * Released 0.2.0. First public release, announced it at
4628 * Released 0.2.0. First public release, announced it at
4592 comp.lang.python. From now on, just bugfixes...
4629 comp.lang.python. From now on, just bugfixes...
4593
4630
4594 * Went through all the files, set copyright/license notices and
4631 * Went through all the files, set copyright/license notices and
4595 cleaned up things. Ready for release.
4632 cleaned up things. Ready for release.
4596
4633
4597 2001-12-10 Fernando Perez <fperez@colorado.edu>
4634 2001-12-10 Fernando Perez <fperez@colorado.edu>
4598
4635
4599 * Changed the first-time installer not to use tarfiles. It's more
4636 * Changed the first-time installer not to use tarfiles. It's more
4600 robust now and less unix-dependent. Also makes it easier for
4637 robust now and less unix-dependent. Also makes it easier for
4601 people to later upgrade versions.
4638 people to later upgrade versions.
4602
4639
4603 * Changed @exit to @abort to reflect the fact that it's pretty
4640 * Changed @exit to @abort to reflect the fact that it's pretty
4604 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4641 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4605 becomes significant only when IPyhton is embedded: in that case,
4642 becomes significant only when IPyhton is embedded: in that case,
4606 C-D closes IPython only, but @abort kills the enclosing program
4643 C-D closes IPython only, but @abort kills the enclosing program
4607 too (unless it had called IPython inside a try catching
4644 too (unless it had called IPython inside a try catching
4608 SystemExit).
4645 SystemExit).
4609
4646
4610 * Created Shell module which exposes the actuall IPython Shell
4647 * Created Shell module which exposes the actuall IPython Shell
4611 classes, currently the normal and the embeddable one. This at
4648 classes, currently the normal and the embeddable one. This at
4612 least offers a stable interface we won't need to change when
4649 least offers a stable interface we won't need to change when
4613 (later) the internals are rewritten. That rewrite will be confined
4650 (later) the internals are rewritten. That rewrite will be confined
4614 to iplib and ipmaker, but the Shell interface should remain as is.
4651 to iplib and ipmaker, but the Shell interface should remain as is.
4615
4652
4616 * Added embed module which offers an embeddable IPShell object,
4653 * Added embed module which offers an embeddable IPShell object,
4617 useful to fire up IPython *inside* a running program. Great for
4654 useful to fire up IPython *inside* a running program. Great for
4618 debugging or dynamical data analysis.
4655 debugging or dynamical data analysis.
4619
4656
4620 2001-12-08 Fernando Perez <fperez@colorado.edu>
4657 2001-12-08 Fernando Perez <fperez@colorado.edu>
4621
4658
4622 * Fixed small bug preventing seeing info from methods of defined
4659 * Fixed small bug preventing seeing info from methods of defined
4623 objects (incorrect namespace in _ofind()).
4660 objects (incorrect namespace in _ofind()).
4624
4661
4625 * Documentation cleanup. Moved the main usage docstrings to a
4662 * Documentation cleanup. Moved the main usage docstrings to a
4626 separate file, usage.py (cleaner to maintain, and hopefully in the
4663 separate file, usage.py (cleaner to maintain, and hopefully in the
4627 future some perlpod-like way of producing interactive, man and
4664 future some perlpod-like way of producing interactive, man and
4628 html docs out of it will be found).
4665 html docs out of it will be found).
4629
4666
4630 * Added @profile to see your profile at any time.
4667 * Added @profile to see your profile at any time.
4631
4668
4632 * Added @p as an alias for 'print'. It's especially convenient if
4669 * Added @p as an alias for 'print'. It's especially convenient if
4633 using automagic ('p x' prints x).
4670 using automagic ('p x' prints x).
4634
4671
4635 * Small cleanups and fixes after a pychecker run.
4672 * Small cleanups and fixes after a pychecker run.
4636
4673
4637 * Changed the @cd command to handle @cd - and @cd -<n> for
4674 * Changed the @cd command to handle @cd - and @cd -<n> for
4638 visiting any directory in _dh.
4675 visiting any directory in _dh.
4639
4676
4640 * Introduced _dh, a history of visited directories. @dhist prints
4677 * Introduced _dh, a history of visited directories. @dhist prints
4641 it out with numbers.
4678 it out with numbers.
4642
4679
4643 2001-12-07 Fernando Perez <fperez@colorado.edu>
4680 2001-12-07 Fernando Perez <fperez@colorado.edu>
4644
4681
4645 * Released 0.1.22
4682 * Released 0.1.22
4646
4683
4647 * Made initialization a bit more robust against invalid color
4684 * Made initialization a bit more robust against invalid color
4648 options in user input (exit, not traceback-crash).
4685 options in user input (exit, not traceback-crash).
4649
4686
4650 * Changed the bug crash reporter to write the report only in the
4687 * Changed the bug crash reporter to write the report only in the
4651 user's .ipython directory. That way IPython won't litter people's
4688 user's .ipython directory. That way IPython won't litter people's
4652 hard disks with crash files all over the place. Also print on
4689 hard disks with crash files all over the place. Also print on
4653 screen the necessary mail command.
4690 screen the necessary mail command.
4654
4691
4655 * With the new ultraTB, implemented LightBG color scheme for light
4692 * With the new ultraTB, implemented LightBG color scheme for light
4656 background terminals. A lot of people like white backgrounds, so I
4693 background terminals. A lot of people like white backgrounds, so I
4657 guess we should at least give them something readable.
4694 guess we should at least give them something readable.
4658
4695
4659 2001-12-06 Fernando Perez <fperez@colorado.edu>
4696 2001-12-06 Fernando Perez <fperez@colorado.edu>
4660
4697
4661 * Modified the structure of ultraTB. Now there's a proper class
4698 * Modified the structure of ultraTB. Now there's a proper class
4662 for tables of color schemes which allow adding schemes easily and
4699 for tables of color schemes which allow adding schemes easily and
4663 switching the active scheme without creating a new instance every
4700 switching the active scheme without creating a new instance every
4664 time (which was ridiculous). The syntax for creating new schemes
4701 time (which was ridiculous). The syntax for creating new schemes
4665 is also cleaner. I think ultraTB is finally done, with a clean
4702 is also cleaner. I think ultraTB is finally done, with a clean
4666 class structure. Names are also much cleaner (now there's proper
4703 class structure. Names are also much cleaner (now there's proper
4667 color tables, no need for every variable to also have 'color' in
4704 color tables, no need for every variable to also have 'color' in
4668 its name).
4705 its name).
4669
4706
4670 * Broke down genutils into separate files. Now genutils only
4707 * Broke down genutils into separate files. Now genutils only
4671 contains utility functions, and classes have been moved to their
4708 contains utility functions, and classes have been moved to their
4672 own files (they had enough independent functionality to warrant
4709 own files (they had enough independent functionality to warrant
4673 it): ConfigLoader, OutputTrap, Struct.
4710 it): ConfigLoader, OutputTrap, Struct.
4674
4711
4675 2001-12-05 Fernando Perez <fperez@colorado.edu>
4712 2001-12-05 Fernando Perez <fperez@colorado.edu>
4676
4713
4677 * IPython turns 21! Released version 0.1.21, as a candidate for
4714 * IPython turns 21! Released version 0.1.21, as a candidate for
4678 public consumption. If all goes well, release in a few days.
4715 public consumption. If all goes well, release in a few days.
4679
4716
4680 * Fixed path bug (files in Extensions/ directory wouldn't be found
4717 * Fixed path bug (files in Extensions/ directory wouldn't be found
4681 unless IPython/ was explicitly in sys.path).
4718 unless IPython/ was explicitly in sys.path).
4682
4719
4683 * Extended the FlexCompleter class as MagicCompleter to allow
4720 * Extended the FlexCompleter class as MagicCompleter to allow
4684 completion of @-starting lines.
4721 completion of @-starting lines.
4685
4722
4686 * Created __release__.py file as a central repository for release
4723 * Created __release__.py file as a central repository for release
4687 info that other files can read from.
4724 info that other files can read from.
4688
4725
4689 * Fixed small bug in logging: when logging was turned on in
4726 * Fixed small bug in logging: when logging was turned on in
4690 mid-session, old lines with special meanings (!@?) were being
4727 mid-session, old lines with special meanings (!@?) were being
4691 logged without the prepended comment, which is necessary since
4728 logged without the prepended comment, which is necessary since
4692 they are not truly valid python syntax. This should make session
4729 they are not truly valid python syntax. This should make session
4693 restores produce less errors.
4730 restores produce less errors.
4694
4731
4695 * The namespace cleanup forced me to make a FlexCompleter class
4732 * The namespace cleanup forced me to make a FlexCompleter class
4696 which is nothing but a ripoff of rlcompleter, but with selectable
4733 which is nothing but a ripoff of rlcompleter, but with selectable
4697 namespace (rlcompleter only works in __main__.__dict__). I'll try
4734 namespace (rlcompleter only works in __main__.__dict__). I'll try
4698 to submit a note to the authors to see if this change can be
4735 to submit a note to the authors to see if this change can be
4699 incorporated in future rlcompleter releases (Dec.6: done)
4736 incorporated in future rlcompleter releases (Dec.6: done)
4700
4737
4701 * More fixes to namespace handling. It was a mess! Now all
4738 * More fixes to namespace handling. It was a mess! Now all
4702 explicit references to __main__.__dict__ are gone (except when
4739 explicit references to __main__.__dict__ are gone (except when
4703 really needed) and everything is handled through the namespace
4740 really needed) and everything is handled through the namespace
4704 dicts in the IPython instance. We seem to be getting somewhere
4741 dicts in the IPython instance. We seem to be getting somewhere
4705 with this, finally...
4742 with this, finally...
4706
4743
4707 * Small documentation updates.
4744 * Small documentation updates.
4708
4745
4709 * Created the Extensions directory under IPython (with an
4746 * Created the Extensions directory under IPython (with an
4710 __init__.py). Put the PhysicalQ stuff there. This directory should
4747 __init__.py). Put the PhysicalQ stuff there. This directory should
4711 be used for all special-purpose extensions.
4748 be used for all special-purpose extensions.
4712
4749
4713 * File renaming:
4750 * File renaming:
4714 ipythonlib --> ipmaker
4751 ipythonlib --> ipmaker
4715 ipplib --> iplib
4752 ipplib --> iplib
4716 This makes a bit more sense in terms of what these files actually do.
4753 This makes a bit more sense in terms of what these files actually do.
4717
4754
4718 * Moved all the classes and functions in ipythonlib to ipplib, so
4755 * Moved all the classes and functions in ipythonlib to ipplib, so
4719 now ipythonlib only has make_IPython(). This will ease up its
4756 now ipythonlib only has make_IPython(). This will ease up its
4720 splitting in smaller functional chunks later.
4757 splitting in smaller functional chunks later.
4721
4758
4722 * Cleaned up (done, I think) output of @whos. Better column
4759 * Cleaned up (done, I think) output of @whos. Better column
4723 formatting, and now shows str(var) for as much as it can, which is
4760 formatting, and now shows str(var) for as much as it can, which is
4724 typically what one gets with a 'print var'.
4761 typically what one gets with a 'print var'.
4725
4762
4726 2001-12-04 Fernando Perez <fperez@colorado.edu>
4763 2001-12-04 Fernando Perez <fperez@colorado.edu>
4727
4764
4728 * Fixed namespace problems. Now builtin/IPyhton/user names get
4765 * Fixed namespace problems. Now builtin/IPyhton/user names get
4729 properly reported in their namespace. Internal namespace handling
4766 properly reported in their namespace. Internal namespace handling
4730 is finally getting decent (not perfect yet, but much better than
4767 is finally getting decent (not perfect yet, but much better than
4731 the ad-hoc mess we had).
4768 the ad-hoc mess we had).
4732
4769
4733 * Removed -exit option. If people just want to run a python
4770 * Removed -exit option. If people just want to run a python
4734 script, that's what the normal interpreter is for. Less
4771 script, that's what the normal interpreter is for. Less
4735 unnecessary options, less chances for bugs.
4772 unnecessary options, less chances for bugs.
4736
4773
4737 * Added a crash handler which generates a complete post-mortem if
4774 * Added a crash handler which generates a complete post-mortem if
4738 IPython crashes. This will help a lot in tracking bugs down the
4775 IPython crashes. This will help a lot in tracking bugs down the
4739 road.
4776 road.
4740
4777
4741 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4778 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4742 which were boud to functions being reassigned would bypass the
4779 which were boud to functions being reassigned would bypass the
4743 logger, breaking the sync of _il with the prompt counter. This
4780 logger, breaking the sync of _il with the prompt counter. This
4744 would then crash IPython later when a new line was logged.
4781 would then crash IPython later when a new line was logged.
4745
4782
4746 2001-12-02 Fernando Perez <fperez@colorado.edu>
4783 2001-12-02 Fernando Perez <fperez@colorado.edu>
4747
4784
4748 * Made IPython a package. This means people don't have to clutter
4785 * Made IPython a package. This means people don't have to clutter
4749 their sys.path with yet another directory. Changed the INSTALL
4786 their sys.path with yet another directory. Changed the INSTALL
4750 file accordingly.
4787 file accordingly.
4751
4788
4752 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4789 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4753 sorts its output (so @who shows it sorted) and @whos formats the
4790 sorts its output (so @who shows it sorted) and @whos formats the
4754 table according to the width of the first column. Nicer, easier to
4791 table according to the width of the first column. Nicer, easier to
4755 read. Todo: write a generic table_format() which takes a list of
4792 read. Todo: write a generic table_format() which takes a list of
4756 lists and prints it nicely formatted, with optional row/column
4793 lists and prints it nicely formatted, with optional row/column
4757 separators and proper padding and justification.
4794 separators and proper padding and justification.
4758
4795
4759 * Released 0.1.20
4796 * Released 0.1.20
4760
4797
4761 * Fixed bug in @log which would reverse the inputcache list (a
4798 * Fixed bug in @log which would reverse the inputcache list (a
4762 copy operation was missing).
4799 copy operation was missing).
4763
4800
4764 * Code cleanup. @config was changed to use page(). Better, since
4801 * Code cleanup. @config was changed to use page(). Better, since
4765 its output is always quite long.
4802 its output is always quite long.
4766
4803
4767 * Itpl is back as a dependency. I was having too many problems
4804 * Itpl is back as a dependency. I was having too many problems
4768 getting the parametric aliases to work reliably, and it's just
4805 getting the parametric aliases to work reliably, and it's just
4769 easier to code weird string operations with it than playing %()s
4806 easier to code weird string operations with it than playing %()s
4770 games. It's only ~6k, so I don't think it's too big a deal.
4807 games. It's only ~6k, so I don't think it's too big a deal.
4771
4808
4772 * Found (and fixed) a very nasty bug with history. !lines weren't
4809 * Found (and fixed) a very nasty bug with history. !lines weren't
4773 getting cached, and the out of sync caches would crash
4810 getting cached, and the out of sync caches would crash
4774 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4811 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4775 division of labor a bit better. Bug fixed, cleaner structure.
4812 division of labor a bit better. Bug fixed, cleaner structure.
4776
4813
4777 2001-12-01 Fernando Perez <fperez@colorado.edu>
4814 2001-12-01 Fernando Perez <fperez@colorado.edu>
4778
4815
4779 * Released 0.1.19
4816 * Released 0.1.19
4780
4817
4781 * Added option -n to @hist to prevent line number printing. Much
4818 * Added option -n to @hist to prevent line number printing. Much
4782 easier to copy/paste code this way.
4819 easier to copy/paste code this way.
4783
4820
4784 * Created global _il to hold the input list. Allows easy
4821 * Created global _il to hold the input list. Allows easy
4785 re-execution of blocks of code by slicing it (inspired by Janko's
4822 re-execution of blocks of code by slicing it (inspired by Janko's
4786 comment on 'macros').
4823 comment on 'macros').
4787
4824
4788 * Small fixes and doc updates.
4825 * Small fixes and doc updates.
4789
4826
4790 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4827 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4791 much too fragile with automagic. Handles properly multi-line
4828 much too fragile with automagic. Handles properly multi-line
4792 statements and takes parameters.
4829 statements and takes parameters.
4793
4830
4794 2001-11-30 Fernando Perez <fperez@colorado.edu>
4831 2001-11-30 Fernando Perez <fperez@colorado.edu>
4795
4832
4796 * Version 0.1.18 released.
4833 * Version 0.1.18 released.
4797
4834
4798 * Fixed nasty namespace bug in initial module imports.
4835 * Fixed nasty namespace bug in initial module imports.
4799
4836
4800 * Added copyright/license notes to all code files (except
4837 * Added copyright/license notes to all code files (except
4801 DPyGetOpt). For the time being, LGPL. That could change.
4838 DPyGetOpt). For the time being, LGPL. That could change.
4802
4839
4803 * Rewrote a much nicer README, updated INSTALL, cleaned up
4840 * Rewrote a much nicer README, updated INSTALL, cleaned up
4804 ipythonrc-* samples.
4841 ipythonrc-* samples.
4805
4842
4806 * Overall code/documentation cleanup. Basically ready for
4843 * Overall code/documentation cleanup. Basically ready for
4807 release. Only remaining thing: licence decision (LGPL?).
4844 release. Only remaining thing: licence decision (LGPL?).
4808
4845
4809 * Converted load_config to a class, ConfigLoader. Now recursion
4846 * Converted load_config to a class, ConfigLoader. Now recursion
4810 control is better organized. Doesn't include the same file twice.
4847 control is better organized. Doesn't include the same file twice.
4811
4848
4812 2001-11-29 Fernando Perez <fperez@colorado.edu>
4849 2001-11-29 Fernando Perez <fperez@colorado.edu>
4813
4850
4814 * Got input history working. Changed output history variables from
4851 * Got input history working. Changed output history variables from
4815 _p to _o so that _i is for input and _o for output. Just cleaner
4852 _p to _o so that _i is for input and _o for output. Just cleaner
4816 convention.
4853 convention.
4817
4854
4818 * Implemented parametric aliases. This pretty much allows the
4855 * Implemented parametric aliases. This pretty much allows the
4819 alias system to offer full-blown shell convenience, I think.
4856 alias system to offer full-blown shell convenience, I think.
4820
4857
4821 * Version 0.1.17 released, 0.1.18 opened.
4858 * Version 0.1.17 released, 0.1.18 opened.
4822
4859
4823 * dot_ipython/ipythonrc (alias): added documentation.
4860 * dot_ipython/ipythonrc (alias): added documentation.
4824 (xcolor): Fixed small bug (xcolors -> xcolor)
4861 (xcolor): Fixed small bug (xcolors -> xcolor)
4825
4862
4826 * Changed the alias system. Now alias is a magic command to define
4863 * Changed the alias system. Now alias is a magic command to define
4827 aliases just like the shell. Rationale: the builtin magics should
4864 aliases just like the shell. Rationale: the builtin magics should
4828 be there for things deeply connected to IPython's
4865 be there for things deeply connected to IPython's
4829 architecture. And this is a much lighter system for what I think
4866 architecture. And this is a much lighter system for what I think
4830 is the really important feature: allowing users to define quickly
4867 is the really important feature: allowing users to define quickly
4831 magics that will do shell things for them, so they can customize
4868 magics that will do shell things for them, so they can customize
4832 IPython easily to match their work habits. If someone is really
4869 IPython easily to match their work habits. If someone is really
4833 desperate to have another name for a builtin alias, they can
4870 desperate to have another name for a builtin alias, they can
4834 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4871 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4835 works.
4872 works.
4836
4873
4837 2001-11-28 Fernando Perez <fperez@colorado.edu>
4874 2001-11-28 Fernando Perez <fperez@colorado.edu>
4838
4875
4839 * Changed @file so that it opens the source file at the proper
4876 * Changed @file so that it opens the source file at the proper
4840 line. Since it uses less, if your EDITOR environment is
4877 line. Since it uses less, if your EDITOR environment is
4841 configured, typing v will immediately open your editor of choice
4878 configured, typing v will immediately open your editor of choice
4842 right at the line where the object is defined. Not as quick as
4879 right at the line where the object is defined. Not as quick as
4843 having a direct @edit command, but for all intents and purposes it
4880 having a direct @edit command, but for all intents and purposes it
4844 works. And I don't have to worry about writing @edit to deal with
4881 works. And I don't have to worry about writing @edit to deal with
4845 all the editors, less does that.
4882 all the editors, less does that.
4846
4883
4847 * Version 0.1.16 released, 0.1.17 opened.
4884 * Version 0.1.16 released, 0.1.17 opened.
4848
4885
4849 * Fixed some nasty bugs in the page/page_dumb combo that could
4886 * Fixed some nasty bugs in the page/page_dumb combo that could
4850 crash IPython.
4887 crash IPython.
4851
4888
4852 2001-11-27 Fernando Perez <fperez@colorado.edu>
4889 2001-11-27 Fernando Perez <fperez@colorado.edu>
4853
4890
4854 * Version 0.1.15 released, 0.1.16 opened.
4891 * Version 0.1.15 released, 0.1.16 opened.
4855
4892
4856 * Finally got ? and ?? to work for undefined things: now it's
4893 * Finally got ? and ?? to work for undefined things: now it's
4857 possible to type {}.get? and get information about the get method
4894 possible to type {}.get? and get information about the get method
4858 of dicts, or os.path? even if only os is defined (so technically
4895 of dicts, or os.path? even if only os is defined (so technically
4859 os.path isn't). Works at any level. For example, after import os,
4896 os.path isn't). Works at any level. For example, after import os,
4860 os?, os.path?, os.path.abspath? all work. This is great, took some
4897 os?, os.path?, os.path.abspath? all work. This is great, took some
4861 work in _ofind.
4898 work in _ofind.
4862
4899
4863 * Fixed more bugs with logging. The sanest way to do it was to add
4900 * Fixed more bugs with logging. The sanest way to do it was to add
4864 to @log a 'mode' parameter. Killed two in one shot (this mode
4901 to @log a 'mode' parameter. Killed two in one shot (this mode
4865 option was a request of Janko's). I think it's finally clean
4902 option was a request of Janko's). I think it's finally clean
4866 (famous last words).
4903 (famous last words).
4867
4904
4868 * Added a page_dumb() pager which does a decent job of paging on
4905 * Added a page_dumb() pager which does a decent job of paging on
4869 screen, if better things (like less) aren't available. One less
4906 screen, if better things (like less) aren't available. One less
4870 unix dependency (someday maybe somebody will port this to
4907 unix dependency (someday maybe somebody will port this to
4871 windows).
4908 windows).
4872
4909
4873 * Fixed problem in magic_log: would lock of logging out if log
4910 * Fixed problem in magic_log: would lock of logging out if log
4874 creation failed (because it would still think it had succeeded).
4911 creation failed (because it would still think it had succeeded).
4875
4912
4876 * Improved the page() function using curses to auto-detect screen
4913 * Improved the page() function using curses to auto-detect screen
4877 size. Now it can make a much better decision on whether to print
4914 size. Now it can make a much better decision on whether to print
4878 or page a string. Option screen_length was modified: a value 0
4915 or page a string. Option screen_length was modified: a value 0
4879 means auto-detect, and that's the default now.
4916 means auto-detect, and that's the default now.
4880
4917
4881 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4918 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4882 go out. I'll test it for a few days, then talk to Janko about
4919 go out. I'll test it for a few days, then talk to Janko about
4883 licences and announce it.
4920 licences and announce it.
4884
4921
4885 * Fixed the length of the auto-generated ---> prompt which appears
4922 * Fixed the length of the auto-generated ---> prompt which appears
4886 for auto-parens and auto-quotes. Getting this right isn't trivial,
4923 for auto-parens and auto-quotes. Getting this right isn't trivial,
4887 with all the color escapes, different prompt types and optional
4924 with all the color escapes, different prompt types and optional
4888 separators. But it seems to be working in all the combinations.
4925 separators. But it seems to be working in all the combinations.
4889
4926
4890 2001-11-26 Fernando Perez <fperez@colorado.edu>
4927 2001-11-26 Fernando Perez <fperez@colorado.edu>
4891
4928
4892 * Wrote a regexp filter to get option types from the option names
4929 * Wrote a regexp filter to get option types from the option names
4893 string. This eliminates the need to manually keep two duplicate
4930 string. This eliminates the need to manually keep two duplicate
4894 lists.
4931 lists.
4895
4932
4896 * Removed the unneeded check_option_names. Now options are handled
4933 * Removed the unneeded check_option_names. Now options are handled
4897 in a much saner manner and it's easy to visually check that things
4934 in a much saner manner and it's easy to visually check that things
4898 are ok.
4935 are ok.
4899
4936
4900 * Updated version numbers on all files I modified to carry a
4937 * Updated version numbers on all files I modified to carry a
4901 notice so Janko and Nathan have clear version markers.
4938 notice so Janko and Nathan have clear version markers.
4902
4939
4903 * Updated docstring for ultraTB with my changes. I should send
4940 * Updated docstring for ultraTB with my changes. I should send
4904 this to Nathan.
4941 this to Nathan.
4905
4942
4906 * Lots of small fixes. Ran everything through pychecker again.
4943 * Lots of small fixes. Ran everything through pychecker again.
4907
4944
4908 * Made loading of deep_reload an cmd line option. If it's not too
4945 * Made loading of deep_reload an cmd line option. If it's not too
4909 kosher, now people can just disable it. With -nodeep_reload it's
4946 kosher, now people can just disable it. With -nodeep_reload it's
4910 still available as dreload(), it just won't overwrite reload().
4947 still available as dreload(), it just won't overwrite reload().
4911
4948
4912 * Moved many options to the no| form (-opt and -noopt
4949 * Moved many options to the no| form (-opt and -noopt
4913 accepted). Cleaner.
4950 accepted). Cleaner.
4914
4951
4915 * Changed magic_log so that if called with no parameters, it uses
4952 * Changed magic_log so that if called with no parameters, it uses
4916 'rotate' mode. That way auto-generated logs aren't automatically
4953 'rotate' mode. That way auto-generated logs aren't automatically
4917 over-written. For normal logs, now a backup is made if it exists
4954 over-written. For normal logs, now a backup is made if it exists
4918 (only 1 level of backups). A new 'backup' mode was added to the
4955 (only 1 level of backups). A new 'backup' mode was added to the
4919 Logger class to support this. This was a request by Janko.
4956 Logger class to support this. This was a request by Janko.
4920
4957
4921 * Added @logoff/@logon to stop/restart an active log.
4958 * Added @logoff/@logon to stop/restart an active log.
4922
4959
4923 * Fixed a lot of bugs in log saving/replay. It was pretty
4960 * Fixed a lot of bugs in log saving/replay. It was pretty
4924 broken. Now special lines (!@,/) appear properly in the command
4961 broken. Now special lines (!@,/) appear properly in the command
4925 history after a log replay.
4962 history after a log replay.
4926
4963
4927 * Tried and failed to implement full session saving via pickle. My
4964 * Tried and failed to implement full session saving via pickle. My
4928 idea was to pickle __main__.__dict__, but modules can't be
4965 idea was to pickle __main__.__dict__, but modules can't be
4929 pickled. This would be a better alternative to replaying logs, but
4966 pickled. This would be a better alternative to replaying logs, but
4930 seems quite tricky to get to work. Changed -session to be called
4967 seems quite tricky to get to work. Changed -session to be called
4931 -logplay, which more accurately reflects what it does. And if we
4968 -logplay, which more accurately reflects what it does. And if we
4932 ever get real session saving working, -session is now available.
4969 ever get real session saving working, -session is now available.
4933
4970
4934 * Implemented color schemes for prompts also. As for tracebacks,
4971 * Implemented color schemes for prompts also. As for tracebacks,
4935 currently only NoColor and Linux are supported. But now the
4972 currently only NoColor and Linux are supported. But now the
4936 infrastructure is in place, based on a generic ColorScheme
4973 infrastructure is in place, based on a generic ColorScheme
4937 class. So writing and activating new schemes both for the prompts
4974 class. So writing and activating new schemes both for the prompts
4938 and the tracebacks should be straightforward.
4975 and the tracebacks should be straightforward.
4939
4976
4940 * Version 0.1.13 released, 0.1.14 opened.
4977 * Version 0.1.13 released, 0.1.14 opened.
4941
4978
4942 * Changed handling of options for output cache. Now counter is
4979 * Changed handling of options for output cache. Now counter is
4943 hardwired starting at 1 and one specifies the maximum number of
4980 hardwired starting at 1 and one specifies the maximum number of
4944 entries *in the outcache* (not the max prompt counter). This is
4981 entries *in the outcache* (not the max prompt counter). This is
4945 much better, since many statements won't increase the cache
4982 much better, since many statements won't increase the cache
4946 count. It also eliminated some confusing options, now there's only
4983 count. It also eliminated some confusing options, now there's only
4947 one: cache_size.
4984 one: cache_size.
4948
4985
4949 * Added 'alias' magic function and magic_alias option in the
4986 * Added 'alias' magic function and magic_alias option in the
4950 ipythonrc file. Now the user can easily define whatever names he
4987 ipythonrc file. Now the user can easily define whatever names he
4951 wants for the magic functions without having to play weird
4988 wants for the magic functions without having to play weird
4952 namespace games. This gives IPython a real shell-like feel.
4989 namespace games. This gives IPython a real shell-like feel.
4953
4990
4954 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4991 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4955 @ or not).
4992 @ or not).
4956
4993
4957 This was one of the last remaining 'visible' bugs (that I know
4994 This was one of the last remaining 'visible' bugs (that I know
4958 of). I think if I can clean up the session loading so it works
4995 of). I think if I can clean up the session loading so it works
4959 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4996 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4960 about licensing).
4997 about licensing).
4961
4998
4962 2001-11-25 Fernando Perez <fperez@colorado.edu>
4999 2001-11-25 Fernando Perez <fperez@colorado.edu>
4963
5000
4964 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
5001 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4965 there's a cleaner distinction between what ? and ?? show.
5002 there's a cleaner distinction between what ? and ?? show.
4966
5003
4967 * Added screen_length option. Now the user can define his own
5004 * Added screen_length option. Now the user can define his own
4968 screen size for page() operations.
5005 screen size for page() operations.
4969
5006
4970 * Implemented magic shell-like functions with automatic code
5007 * Implemented magic shell-like functions with automatic code
4971 generation. Now adding another function is just a matter of adding
5008 generation. Now adding another function is just a matter of adding
4972 an entry to a dict, and the function is dynamically generated at
5009 an entry to a dict, and the function is dynamically generated at
4973 run-time. Python has some really cool features!
5010 run-time. Python has some really cool features!
4974
5011
4975 * Renamed many options to cleanup conventions a little. Now all
5012 * Renamed many options to cleanup conventions a little. Now all
4976 are lowercase, and only underscores where needed. Also in the code
5013 are lowercase, and only underscores where needed. Also in the code
4977 option name tables are clearer.
5014 option name tables are clearer.
4978
5015
4979 * Changed prompts a little. Now input is 'In [n]:' instead of
5016 * Changed prompts a little. Now input is 'In [n]:' instead of
4980 'In[n]:='. This allows it the numbers to be aligned with the
5017 'In[n]:='. This allows it the numbers to be aligned with the
4981 Out[n] numbers, and removes usage of ':=' which doesn't exist in
5018 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4982 Python (it was a Mathematica thing). The '...' continuation prompt
5019 Python (it was a Mathematica thing). The '...' continuation prompt
4983 was also changed a little to align better.
5020 was also changed a little to align better.
4984
5021
4985 * Fixed bug when flushing output cache. Not all _p<n> variables
5022 * Fixed bug when flushing output cache. Not all _p<n> variables
4986 exist, so their deletion needs to be wrapped in a try:
5023 exist, so their deletion needs to be wrapped in a try:
4987
5024
4988 * Figured out how to properly use inspect.formatargspec() (it
5025 * Figured out how to properly use inspect.formatargspec() (it
4989 requires the args preceded by *). So I removed all the code from
5026 requires the args preceded by *). So I removed all the code from
4990 _get_pdef in Magic, which was just replicating that.
5027 _get_pdef in Magic, which was just replicating that.
4991
5028
4992 * Added test to prefilter to allow redefining magic function names
5029 * Added test to prefilter to allow redefining magic function names
4993 as variables. This is ok, since the @ form is always available,
5030 as variables. This is ok, since the @ form is always available,
4994 but whe should allow the user to define a variable called 'ls' if
5031 but whe should allow the user to define a variable called 'ls' if
4995 he needs it.
5032 he needs it.
4996
5033
4997 * Moved the ToDo information from README into a separate ToDo.
5034 * Moved the ToDo information from README into a separate ToDo.
4998
5035
4999 * General code cleanup and small bugfixes. I think it's close to a
5036 * General code cleanup and small bugfixes. I think it's close to a
5000 state where it can be released, obviously with a big 'beta'
5037 state where it can be released, obviously with a big 'beta'
5001 warning on it.
5038 warning on it.
5002
5039
5003 * Got the magic function split to work. Now all magics are defined
5040 * Got the magic function split to work. Now all magics are defined
5004 in a separate class. It just organizes things a bit, and now
5041 in a separate class. It just organizes things a bit, and now
5005 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
5042 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
5006 was too long).
5043 was too long).
5007
5044
5008 * Changed @clear to @reset to avoid potential confusions with
5045 * Changed @clear to @reset to avoid potential confusions with
5009 the shell command clear. Also renamed @cl to @clear, which does
5046 the shell command clear. Also renamed @cl to @clear, which does
5010 exactly what people expect it to from their shell experience.
5047 exactly what people expect it to from their shell experience.
5011
5048
5012 Added a check to the @reset command (since it's so
5049 Added a check to the @reset command (since it's so
5013 destructive, it's probably a good idea to ask for confirmation).
5050 destructive, it's probably a good idea to ask for confirmation).
5014 But now reset only works for full namespace resetting. Since the
5051 But now reset only works for full namespace resetting. Since the
5015 del keyword is already there for deleting a few specific
5052 del keyword is already there for deleting a few specific
5016 variables, I don't see the point of having a redundant magic
5053 variables, I don't see the point of having a redundant magic
5017 function for the same task.
5054 function for the same task.
5018
5055
5019 2001-11-24 Fernando Perez <fperez@colorado.edu>
5056 2001-11-24 Fernando Perez <fperez@colorado.edu>
5020
5057
5021 * Updated the builtin docs (esp. the ? ones).
5058 * Updated the builtin docs (esp. the ? ones).
5022
5059
5023 * Ran all the code through pychecker. Not terribly impressed with
5060 * Ran all the code through pychecker. Not terribly impressed with
5024 it: lots of spurious warnings and didn't really find anything of
5061 it: lots of spurious warnings and didn't really find anything of
5025 substance (just a few modules being imported and not used).
5062 substance (just a few modules being imported and not used).
5026
5063
5027 * Implemented the new ultraTB functionality into IPython. New
5064 * Implemented the new ultraTB functionality into IPython. New
5028 option: xcolors. This chooses color scheme. xmode now only selects
5065 option: xcolors. This chooses color scheme. xmode now only selects
5029 between Plain and Verbose. Better orthogonality.
5066 between Plain and Verbose. Better orthogonality.
5030
5067
5031 * Large rewrite of ultraTB. Much cleaner now, with a separation of
5068 * Large rewrite of ultraTB. Much cleaner now, with a separation of
5032 mode and color scheme for the exception handlers. Now it's
5069 mode and color scheme for the exception handlers. Now it's
5033 possible to have the verbose traceback with no coloring.
5070 possible to have the verbose traceback with no coloring.
5034
5071
5035 2001-11-23 Fernando Perez <fperez@colorado.edu>
5072 2001-11-23 Fernando Perez <fperez@colorado.edu>
5036
5073
5037 * Version 0.1.12 released, 0.1.13 opened.
5074 * Version 0.1.12 released, 0.1.13 opened.
5038
5075
5039 * Removed option to set auto-quote and auto-paren escapes by
5076 * Removed option to set auto-quote and auto-paren escapes by
5040 user. The chances of breaking valid syntax are just too high. If
5077 user. The chances of breaking valid syntax are just too high. If
5041 someone *really* wants, they can always dig into the code.
5078 someone *really* wants, they can always dig into the code.
5042
5079
5043 * Made prompt separators configurable.
5080 * Made prompt separators configurable.
5044
5081
5045 2001-11-22 Fernando Perez <fperez@colorado.edu>
5082 2001-11-22 Fernando Perez <fperez@colorado.edu>
5046
5083
5047 * Small bugfixes in many places.
5084 * Small bugfixes in many places.
5048
5085
5049 * Removed the MyCompleter class from ipplib. It seemed redundant
5086 * Removed the MyCompleter class from ipplib. It seemed redundant
5050 with the C-p,C-n history search functionality. Less code to
5087 with the C-p,C-n history search functionality. Less code to
5051 maintain.
5088 maintain.
5052
5089
5053 * Moved all the original ipython.py code into ipythonlib.py. Right
5090 * Moved all the original ipython.py code into ipythonlib.py. Right
5054 now it's just one big dump into a function called make_IPython, so
5091 now it's just one big dump into a function called make_IPython, so
5055 no real modularity has been gained. But at least it makes the
5092 no real modularity has been gained. But at least it makes the
5056 wrapper script tiny, and since ipythonlib is a module, it gets
5093 wrapper script tiny, and since ipythonlib is a module, it gets
5057 compiled and startup is much faster.
5094 compiled and startup is much faster.
5058
5095
5059 This is a reasobably 'deep' change, so we should test it for a
5096 This is a reasobably 'deep' change, so we should test it for a
5060 while without messing too much more with the code.
5097 while without messing too much more with the code.
5061
5098
5062 2001-11-21 Fernando Perez <fperez@colorado.edu>
5099 2001-11-21 Fernando Perez <fperez@colorado.edu>
5063
5100
5064 * Version 0.1.11 released, 0.1.12 opened for further work.
5101 * Version 0.1.11 released, 0.1.12 opened for further work.
5065
5102
5066 * Removed dependency on Itpl. It was only needed in one place. It
5103 * Removed dependency on Itpl. It was only needed in one place. It
5067 would be nice if this became part of python, though. It makes life
5104 would be nice if this became part of python, though. It makes life
5068 *a lot* easier in some cases.
5105 *a lot* easier in some cases.
5069
5106
5070 * Simplified the prefilter code a bit. Now all handlers are
5107 * Simplified the prefilter code a bit. Now all handlers are
5071 expected to explicitly return a value (at least a blank string).
5108 expected to explicitly return a value (at least a blank string).
5072
5109
5073 * Heavy edits in ipplib. Removed the help system altogether. Now
5110 * Heavy edits in ipplib. Removed the help system altogether. Now
5074 obj?/?? is used for inspecting objects, a magic @doc prints
5111 obj?/?? is used for inspecting objects, a magic @doc prints
5075 docstrings, and full-blown Python help is accessed via the 'help'
5112 docstrings, and full-blown Python help is accessed via the 'help'
5076 keyword. This cleans up a lot of code (less to maintain) and does
5113 keyword. This cleans up a lot of code (less to maintain) and does
5077 the job. Since 'help' is now a standard Python component, might as
5114 the job. Since 'help' is now a standard Python component, might as
5078 well use it and remove duplicate functionality.
5115 well use it and remove duplicate functionality.
5079
5116
5080 Also removed the option to use ipplib as a standalone program. By
5117 Also removed the option to use ipplib as a standalone program. By
5081 now it's too dependent on other parts of IPython to function alone.
5118 now it's too dependent on other parts of IPython to function alone.
5082
5119
5083 * Fixed bug in genutils.pager. It would crash if the pager was
5120 * Fixed bug in genutils.pager. It would crash if the pager was
5084 exited immediately after opening (broken pipe).
5121 exited immediately after opening (broken pipe).
5085
5122
5086 * Trimmed down the VerboseTB reporting a little. The header is
5123 * Trimmed down the VerboseTB reporting a little. The header is
5087 much shorter now and the repeated exception arguments at the end
5124 much shorter now and the repeated exception arguments at the end
5088 have been removed. For interactive use the old header seemed a bit
5125 have been removed. For interactive use the old header seemed a bit
5089 excessive.
5126 excessive.
5090
5127
5091 * Fixed small bug in output of @whos for variables with multi-word
5128 * Fixed small bug in output of @whos for variables with multi-word
5092 types (only first word was displayed).
5129 types (only first word was displayed).
5093
5130
5094 2001-11-17 Fernando Perez <fperez@colorado.edu>
5131 2001-11-17 Fernando Perez <fperez@colorado.edu>
5095
5132
5096 * Version 0.1.10 released, 0.1.11 opened for further work.
5133 * Version 0.1.10 released, 0.1.11 opened for further work.
5097
5134
5098 * Modified dirs and friends. dirs now *returns* the stack (not
5135 * Modified dirs and friends. dirs now *returns* the stack (not
5099 prints), so one can manipulate it as a variable. Convenient to
5136 prints), so one can manipulate it as a variable. Convenient to
5100 travel along many directories.
5137 travel along many directories.
5101
5138
5102 * Fixed bug in magic_pdef: would only work with functions with
5139 * Fixed bug in magic_pdef: would only work with functions with
5103 arguments with default values.
5140 arguments with default values.
5104
5141
5105 2001-11-14 Fernando Perez <fperez@colorado.edu>
5142 2001-11-14 Fernando Perez <fperez@colorado.edu>
5106
5143
5107 * Added the PhysicsInput stuff to dot_ipython so it ships as an
5144 * Added the PhysicsInput stuff to dot_ipython so it ships as an
5108 example with IPython. Various other minor fixes and cleanups.
5145 example with IPython. Various other minor fixes and cleanups.
5109
5146
5110 * Version 0.1.9 released, 0.1.10 opened for further work.
5147 * Version 0.1.9 released, 0.1.10 opened for further work.
5111
5148
5112 * Added sys.path to the list of directories searched in the
5149 * Added sys.path to the list of directories searched in the
5113 execfile= option. It used to be the current directory and the
5150 execfile= option. It used to be the current directory and the
5114 user's IPYTHONDIR only.
5151 user's IPYTHONDIR only.
5115
5152
5116 2001-11-13 Fernando Perez <fperez@colorado.edu>
5153 2001-11-13 Fernando Perez <fperez@colorado.edu>
5117
5154
5118 * Reinstated the raw_input/prefilter separation that Janko had
5155 * Reinstated the raw_input/prefilter separation that Janko had
5119 initially. This gives a more convenient setup for extending the
5156 initially. This gives a more convenient setup for extending the
5120 pre-processor from the outside: raw_input always gets a string,
5157 pre-processor from the outside: raw_input always gets a string,
5121 and prefilter has to process it. We can then redefine prefilter
5158 and prefilter has to process it. We can then redefine prefilter
5122 from the outside and implement extensions for special
5159 from the outside and implement extensions for special
5123 purposes.
5160 purposes.
5124
5161
5125 Today I got one for inputting PhysicalQuantity objects
5162 Today I got one for inputting PhysicalQuantity objects
5126 (from Scientific) without needing any function calls at
5163 (from Scientific) without needing any function calls at
5127 all. Extremely convenient, and it's all done as a user-level
5164 all. Extremely convenient, and it's all done as a user-level
5128 extension (no IPython code was touched). Now instead of:
5165 extension (no IPython code was touched). Now instead of:
5129 a = PhysicalQuantity(4.2,'m/s**2')
5166 a = PhysicalQuantity(4.2,'m/s**2')
5130 one can simply say
5167 one can simply say
5131 a = 4.2 m/s**2
5168 a = 4.2 m/s**2
5132 or even
5169 or even
5133 a = 4.2 m/s^2
5170 a = 4.2 m/s^2
5134
5171
5135 I use this, but it's also a proof of concept: IPython really is
5172 I use this, but it's also a proof of concept: IPython really is
5136 fully user-extensible, even at the level of the parsing of the
5173 fully user-extensible, even at the level of the parsing of the
5137 command line. It's not trivial, but it's perfectly doable.
5174 command line. It's not trivial, but it's perfectly doable.
5138
5175
5139 * Added 'add_flip' method to inclusion conflict resolver. Fixes
5176 * Added 'add_flip' method to inclusion conflict resolver. Fixes
5140 the problem of modules being loaded in the inverse order in which
5177 the problem of modules being loaded in the inverse order in which
5141 they were defined in
5178 they were defined in
5142
5179
5143 * Version 0.1.8 released, 0.1.9 opened for further work.
5180 * Version 0.1.8 released, 0.1.9 opened for further work.
5144
5181
5145 * Added magics pdef, source and file. They respectively show the
5182 * Added magics pdef, source and file. They respectively show the
5146 definition line ('prototype' in C), source code and full python
5183 definition line ('prototype' in C), source code and full python
5147 file for any callable object. The object inspector oinfo uses
5184 file for any callable object. The object inspector oinfo uses
5148 these to show the same information.
5185 these to show the same information.
5149
5186
5150 * Version 0.1.7 released, 0.1.8 opened for further work.
5187 * Version 0.1.7 released, 0.1.8 opened for further work.
5151
5188
5152 * Separated all the magic functions into a class called Magic. The
5189 * Separated all the magic functions into a class called Magic. The
5153 InteractiveShell class was becoming too big for Xemacs to handle
5190 InteractiveShell class was becoming too big for Xemacs to handle
5154 (de-indenting a line would lock it up for 10 seconds while it
5191 (de-indenting a line would lock it up for 10 seconds while it
5155 backtracked on the whole class!)
5192 backtracked on the whole class!)
5156
5193
5157 FIXME: didn't work. It can be done, but right now namespaces are
5194 FIXME: didn't work. It can be done, but right now namespaces are
5158 all messed up. Do it later (reverted it for now, so at least
5195 all messed up. Do it later (reverted it for now, so at least
5159 everything works as before).
5196 everything works as before).
5160
5197
5161 * Got the object introspection system (magic_oinfo) working! I
5198 * Got the object introspection system (magic_oinfo) working! I
5162 think this is pretty much ready for release to Janko, so he can
5199 think this is pretty much ready for release to Janko, so he can
5163 test it for a while and then announce it. Pretty much 100% of what
5200 test it for a while and then announce it. Pretty much 100% of what
5164 I wanted for the 'phase 1' release is ready. Happy, tired.
5201 I wanted for the 'phase 1' release is ready. Happy, tired.
5165
5202
5166 2001-11-12 Fernando Perez <fperez@colorado.edu>
5203 2001-11-12 Fernando Perez <fperez@colorado.edu>
5167
5204
5168 * Version 0.1.6 released, 0.1.7 opened for further work.
5205 * Version 0.1.6 released, 0.1.7 opened for further work.
5169
5206
5170 * Fixed bug in printing: it used to test for truth before
5207 * Fixed bug in printing: it used to test for truth before
5171 printing, so 0 wouldn't print. Now checks for None.
5208 printing, so 0 wouldn't print. Now checks for None.
5172
5209
5173 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
5210 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
5174 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
5211 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
5175 reaches by hand into the outputcache. Think of a better way to do
5212 reaches by hand into the outputcache. Think of a better way to do
5176 this later.
5213 this later.
5177
5214
5178 * Various small fixes thanks to Nathan's comments.
5215 * Various small fixes thanks to Nathan's comments.
5179
5216
5180 * Changed magic_pprint to magic_Pprint. This way it doesn't
5217 * Changed magic_pprint to magic_Pprint. This way it doesn't
5181 collide with pprint() and the name is consistent with the command
5218 collide with pprint() and the name is consistent with the command
5182 line option.
5219 line option.
5183
5220
5184 * Changed prompt counter behavior to be fully like
5221 * Changed prompt counter behavior to be fully like
5185 Mathematica's. That is, even input that doesn't return a result
5222 Mathematica's. That is, even input that doesn't return a result
5186 raises the prompt counter. The old behavior was kind of confusing
5223 raises the prompt counter. The old behavior was kind of confusing
5187 (getting the same prompt number several times if the operation
5224 (getting the same prompt number several times if the operation
5188 didn't return a result).
5225 didn't return a result).
5189
5226
5190 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
5227 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
5191
5228
5192 * Fixed -Classic mode (wasn't working anymore).
5229 * Fixed -Classic mode (wasn't working anymore).
5193
5230
5194 * Added colored prompts using Nathan's new code. Colors are
5231 * Added colored prompts using Nathan's new code. Colors are
5195 currently hardwired, they can be user-configurable. For
5232 currently hardwired, they can be user-configurable. For
5196 developers, they can be chosen in file ipythonlib.py, at the
5233 developers, they can be chosen in file ipythonlib.py, at the
5197 beginning of the CachedOutput class def.
5234 beginning of the CachedOutput class def.
5198
5235
5199 2001-11-11 Fernando Perez <fperez@colorado.edu>
5236 2001-11-11 Fernando Perez <fperez@colorado.edu>
5200
5237
5201 * Version 0.1.5 released, 0.1.6 opened for further work.
5238 * Version 0.1.5 released, 0.1.6 opened for further work.
5202
5239
5203 * Changed magic_env to *return* the environment as a dict (not to
5240 * Changed magic_env to *return* the environment as a dict (not to
5204 print it). This way it prints, but it can also be processed.
5241 print it). This way it prints, but it can also be processed.
5205
5242
5206 * Added Verbose exception reporting to interactive
5243 * Added Verbose exception reporting to interactive
5207 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
5244 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
5208 traceback. Had to make some changes to the ultraTB file. This is
5245 traceback. Had to make some changes to the ultraTB file. This is
5209 probably the last 'big' thing in my mental todo list. This ties
5246 probably the last 'big' thing in my mental todo list. This ties
5210 in with the next entry:
5247 in with the next entry:
5211
5248
5212 * Changed -Xi and -Xf to a single -xmode option. Now all the user
5249 * Changed -Xi and -Xf to a single -xmode option. Now all the user
5213 has to specify is Plain, Color or Verbose for all exception
5250 has to specify is Plain, Color or Verbose for all exception
5214 handling.
5251 handling.
5215
5252
5216 * Removed ShellServices option. All this can really be done via
5253 * Removed ShellServices option. All this can really be done via
5217 the magic system. It's easier to extend, cleaner and has automatic
5254 the magic system. It's easier to extend, cleaner and has automatic
5218 namespace protection and documentation.
5255 namespace protection and documentation.
5219
5256
5220 2001-11-09 Fernando Perez <fperez@colorado.edu>
5257 2001-11-09 Fernando Perez <fperez@colorado.edu>
5221
5258
5222 * Fixed bug in output cache flushing (missing parameter to
5259 * Fixed bug in output cache flushing (missing parameter to
5223 __init__). Other small bugs fixed (found using pychecker).
5260 __init__). Other small bugs fixed (found using pychecker).
5224
5261
5225 * Version 0.1.4 opened for bugfixing.
5262 * Version 0.1.4 opened for bugfixing.
5226
5263
5227 2001-11-07 Fernando Perez <fperez@colorado.edu>
5264 2001-11-07 Fernando Perez <fperez@colorado.edu>
5228
5265
5229 * Version 0.1.3 released, mainly because of the raw_input bug.
5266 * Version 0.1.3 released, mainly because of the raw_input bug.
5230
5267
5231 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
5268 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
5232 and when testing for whether things were callable, a call could
5269 and when testing for whether things were callable, a call could
5233 actually be made to certain functions. They would get called again
5270 actually be made to certain functions. They would get called again
5234 once 'really' executed, with a resulting double call. A disaster
5271 once 'really' executed, with a resulting double call. A disaster
5235 in many cases (list.reverse() would never work!).
5272 in many cases (list.reverse() would never work!).
5236
5273
5237 * Removed prefilter() function, moved its code to raw_input (which
5274 * Removed prefilter() function, moved its code to raw_input (which
5238 after all was just a near-empty caller for prefilter). This saves
5275 after all was just a near-empty caller for prefilter). This saves
5239 a function call on every prompt, and simplifies the class a tiny bit.
5276 a function call on every prompt, and simplifies the class a tiny bit.
5240
5277
5241 * Fix _ip to __ip name in magic example file.
5278 * Fix _ip to __ip name in magic example file.
5242
5279
5243 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
5280 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
5244 work with non-gnu versions of tar.
5281 work with non-gnu versions of tar.
5245
5282
5246 2001-11-06 Fernando Perez <fperez@colorado.edu>
5283 2001-11-06 Fernando Perez <fperez@colorado.edu>
5247
5284
5248 * Version 0.1.2. Just to keep track of the recent changes.
5285 * Version 0.1.2. Just to keep track of the recent changes.
5249
5286
5250 * Fixed nasty bug in output prompt routine. It used to check 'if
5287 * Fixed nasty bug in output prompt routine. It used to check 'if
5251 arg != None...'. Problem is, this fails if arg implements a
5288 arg != None...'. Problem is, this fails if arg implements a
5252 special comparison (__cmp__) which disallows comparing to
5289 special comparison (__cmp__) which disallows comparing to
5253 None. Found it when trying to use the PhysicalQuantity module from
5290 None. Found it when trying to use the PhysicalQuantity module from
5254 ScientificPython.
5291 ScientificPython.
5255
5292
5256 2001-11-05 Fernando Perez <fperez@colorado.edu>
5293 2001-11-05 Fernando Perez <fperez@colorado.edu>
5257
5294
5258 * Also added dirs. Now the pushd/popd/dirs family functions
5295 * Also added dirs. Now the pushd/popd/dirs family functions
5259 basically like the shell, with the added convenience of going home
5296 basically like the shell, with the added convenience of going home
5260 when called with no args.
5297 when called with no args.
5261
5298
5262 * pushd/popd slightly modified to mimic shell behavior more
5299 * pushd/popd slightly modified to mimic shell behavior more
5263 closely.
5300 closely.
5264
5301
5265 * Added env,pushd,popd from ShellServices as magic functions. I
5302 * Added env,pushd,popd from ShellServices as magic functions. I
5266 think the cleanest will be to port all desired functions from
5303 think the cleanest will be to port all desired functions from
5267 ShellServices as magics and remove ShellServices altogether. This
5304 ShellServices as magics and remove ShellServices altogether. This
5268 will provide a single, clean way of adding functionality
5305 will provide a single, clean way of adding functionality
5269 (shell-type or otherwise) to IP.
5306 (shell-type or otherwise) to IP.
5270
5307
5271 2001-11-04 Fernando Perez <fperez@colorado.edu>
5308 2001-11-04 Fernando Perez <fperez@colorado.edu>
5272
5309
5273 * Added .ipython/ directory to sys.path. This way users can keep
5310 * Added .ipython/ directory to sys.path. This way users can keep
5274 customizations there and access them via import.
5311 customizations there and access them via import.
5275
5312
5276 2001-11-03 Fernando Perez <fperez@colorado.edu>
5313 2001-11-03 Fernando Perez <fperez@colorado.edu>
5277
5314
5278 * Opened version 0.1.1 for new changes.
5315 * Opened version 0.1.1 for new changes.
5279
5316
5280 * Changed version number to 0.1.0: first 'public' release, sent to
5317 * Changed version number to 0.1.0: first 'public' release, sent to
5281 Nathan and Janko.
5318 Nathan and Janko.
5282
5319
5283 * Lots of small fixes and tweaks.
5320 * Lots of small fixes and tweaks.
5284
5321
5285 * Minor changes to whos format. Now strings are shown, snipped if
5322 * Minor changes to whos format. Now strings are shown, snipped if
5286 too long.
5323 too long.
5287
5324
5288 * Changed ShellServices to work on __main__ so they show up in @who
5325 * Changed ShellServices to work on __main__ so they show up in @who
5289
5326
5290 * Help also works with ? at the end of a line:
5327 * Help also works with ? at the end of a line:
5291 ?sin and sin?
5328 ?sin and sin?
5292 both produce the same effect. This is nice, as often I use the
5329 both produce the same effect. This is nice, as often I use the
5293 tab-complete to find the name of a method, but I used to then have
5330 tab-complete to find the name of a method, but I used to then have
5294 to go to the beginning of the line to put a ? if I wanted more
5331 to go to the beginning of the line to put a ? if I wanted more
5295 info. Now I can just add the ? and hit return. Convenient.
5332 info. Now I can just add the ? and hit return. Convenient.
5296
5333
5297 2001-11-02 Fernando Perez <fperez@colorado.edu>
5334 2001-11-02 Fernando Perez <fperez@colorado.edu>
5298
5335
5299 * Python version check (>=2.1) added.
5336 * Python version check (>=2.1) added.
5300
5337
5301 * Added LazyPython documentation. At this point the docs are quite
5338 * Added LazyPython documentation. At this point the docs are quite
5302 a mess. A cleanup is in order.
5339 a mess. A cleanup is in order.
5303
5340
5304 * Auto-installer created. For some bizarre reason, the zipfiles
5341 * Auto-installer created. For some bizarre reason, the zipfiles
5305 module isn't working on my system. So I made a tar version
5342 module isn't working on my system. So I made a tar version
5306 (hopefully the command line options in various systems won't kill
5343 (hopefully the command line options in various systems won't kill
5307 me).
5344 me).
5308
5345
5309 * Fixes to Struct in genutils. Now all dictionary-like methods are
5346 * Fixes to Struct in genutils. Now all dictionary-like methods are
5310 protected (reasonably).
5347 protected (reasonably).
5311
5348
5312 * Added pager function to genutils and changed ? to print usage
5349 * Added pager function to genutils and changed ? to print usage
5313 note through it (it was too long).
5350 note through it (it was too long).
5314
5351
5315 * Added the LazyPython functionality. Works great! I changed the
5352 * Added the LazyPython functionality. Works great! I changed the
5316 auto-quote escape to ';', it's on home row and next to '. But
5353 auto-quote escape to ';', it's on home row and next to '. But
5317 both auto-quote and auto-paren (still /) escapes are command-line
5354 both auto-quote and auto-paren (still /) escapes are command-line
5318 parameters.
5355 parameters.
5319
5356
5320
5357
5321 2001-11-01 Fernando Perez <fperez@colorado.edu>
5358 2001-11-01 Fernando Perez <fperez@colorado.edu>
5322
5359
5323 * Version changed to 0.0.7. Fairly large change: configuration now
5360 * Version changed to 0.0.7. Fairly large change: configuration now
5324 is all stored in a directory, by default .ipython. There, all
5361 is all stored in a directory, by default .ipython. There, all
5325 config files have normal looking names (not .names)
5362 config files have normal looking names (not .names)
5326
5363
5327 * Version 0.0.6 Released first to Lucas and Archie as a test
5364 * Version 0.0.6 Released first to Lucas and Archie as a test
5328 run. Since it's the first 'semi-public' release, change version to
5365 run. Since it's the first 'semi-public' release, change version to
5329 > 0.0.6 for any changes now.
5366 > 0.0.6 for any changes now.
5330
5367
5331 * Stuff I had put in the ipplib.py changelog:
5368 * Stuff I had put in the ipplib.py changelog:
5332
5369
5333 Changes to InteractiveShell:
5370 Changes to InteractiveShell:
5334
5371
5335 - Made the usage message a parameter.
5372 - Made the usage message a parameter.
5336
5373
5337 - Require the name of the shell variable to be given. It's a bit
5374 - Require the name of the shell variable to be given. It's a bit
5338 of a hack, but allows the name 'shell' not to be hardwire in the
5375 of a hack, but allows the name 'shell' not to be hardwire in the
5339 magic (@) handler, which is problematic b/c it requires
5376 magic (@) handler, which is problematic b/c it requires
5340 polluting the global namespace with 'shell'. This in turn is
5377 polluting the global namespace with 'shell'. This in turn is
5341 fragile: if a user redefines a variable called shell, things
5378 fragile: if a user redefines a variable called shell, things
5342 break.
5379 break.
5343
5380
5344 - magic @: all functions available through @ need to be defined
5381 - magic @: all functions available through @ need to be defined
5345 as magic_<name>, even though they can be called simply as
5382 as magic_<name>, even though they can be called simply as
5346 @<name>. This allows the special command @magic to gather
5383 @<name>. This allows the special command @magic to gather
5347 information automatically about all existing magic functions,
5384 information automatically about all existing magic functions,
5348 even if they are run-time user extensions, by parsing the shell
5385 even if they are run-time user extensions, by parsing the shell
5349 instance __dict__ looking for special magic_ names.
5386 instance __dict__ looking for special magic_ names.
5350
5387
5351 - mainloop: added *two* local namespace parameters. This allows
5388 - mainloop: added *two* local namespace parameters. This allows
5352 the class to differentiate between parameters which were there
5389 the class to differentiate between parameters which were there
5353 before and after command line initialization was processed. This
5390 before and after command line initialization was processed. This
5354 way, later @who can show things loaded at startup by the
5391 way, later @who can show things loaded at startup by the
5355 user. This trick was necessary to make session saving/reloading
5392 user. This trick was necessary to make session saving/reloading
5356 really work: ideally after saving/exiting/reloading a session,
5393 really work: ideally after saving/exiting/reloading a session,
5357 *everythin* should look the same, including the output of @who. I
5394 *everythin* should look the same, including the output of @who. I
5358 was only able to make this work with this double namespace
5395 was only able to make this work with this double namespace
5359 trick.
5396 trick.
5360
5397
5361 - added a header to the logfile which allows (almost) full
5398 - added a header to the logfile which allows (almost) full
5362 session restoring.
5399 session restoring.
5363
5400
5364 - prepend lines beginning with @ or !, with a and log
5401 - prepend lines beginning with @ or !, with a and log
5365 them. Why? !lines: may be useful to know what you did @lines:
5402 them. Why? !lines: may be useful to know what you did @lines:
5366 they may affect session state. So when restoring a session, at
5403 they may affect session state. So when restoring a session, at
5367 least inform the user of their presence. I couldn't quite get
5404 least inform the user of their presence. I couldn't quite get
5368 them to properly re-execute, but at least the user is warned.
5405 them to properly re-execute, but at least the user is warned.
5369
5406
5370 * Started ChangeLog.
5407 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now