##// END OF EJS Templates
Pdb calling, pickle (under certain circumstances, connected with %run) and...
fperez -
Show More
@@ -1,221 +1,228 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Logger class for IPython's logging facilities.
3 Logger class for IPython's logging facilities.
4
4
5 $Id: Logger.py 974 2005-12-29 19:48:33Z fperez $
5 $Id: Logger.py 984 2005-12-31 08:40:31Z fperez $
6 """
6 """
7
7
8 #*****************************************************************************
8 #*****************************************************************************
9 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
9 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
10 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 #****************************************************************************
16 #****************************************************************************
17 # Modules and globals
17 # Modules and globals
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>\n%s <%s>' % \
20 __author__ = '%s <%s>\n%s <%s>' % \
21 ( Release.authors['Janko'] + Release.authors['Fernando'] )
21 ( Release.authors['Janko'] + Release.authors['Fernando'] )
22 __license__ = Release.license
22 __license__ = Release.license
23
23
24 # Python standard modules
24 # Python standard modules
25 import glob
25 import glob
26 import os
26 import os
27 import time
27 import time
28
28
29 #****************************************************************************
29 #****************************************************************************
30 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
30 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
31 # ipython and does input cache management. Finish cleanup later...
31 # ipython and does input cache management. Finish cleanup later...
32
32
33 class Logger(object):
33 class Logger(object):
34 """A Logfile class with different policies for file creation"""
34 """A Logfile class with different policies for file creation"""
35
35
36 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
36 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
37
37
38 self._i00,self._i,self._ii,self._iii = '','','',''
38 self._i00,self._i,self._ii,self._iii = '','','',''
39
39
40 # this is the full ipython instance, we need some attributes from it
40 # this is the full ipython instance, we need some attributes from it
41 # which won't exist until later. What a mess, clean up later...
41 # which won't exist until later. What a mess, clean up later...
42 self.shell = shell
42 self.shell = shell
43
43
44 self.logfname = logfname
44 self.logfname = logfname
45 self.loghead = loghead
45 self.loghead = loghead
46 self.logmode = logmode
46 self.logmode = logmode
47 self.logfile = None
47 self.logfile = None
48
48
49 # whether to also log output
49 # whether to also log output
50 self.log_output = False
50 self.log_output = False
51
51
52 # whether to put timestamps before each log entry
52 # whether to put timestamps before each log entry
53 self.timestamp = False
53 self.timestamp = False
54
54
55 # activity control flags
55 # activity control flags
56 self.log_active = False
56 self.log_active = False
57
57
58 # logmode is a validated property
58 # logmode is a validated property
59 def _set_mode(self,mode):
59 def _set_mode(self,mode):
60 if mode not in ['append','backup','global','over','rotate']:
60 if mode not in ['append','backup','global','over','rotate']:
61 raise ValueError,'invalid log mode %s given' % mode
61 raise ValueError,'invalid log mode %s given' % mode
62 self._logmode = mode
62 self._logmode = mode
63
63
64 def _get_mode(self):
64 def _get_mode(self):
65 return self._logmode
65 return self._logmode
66
66
67 logmode = property(_get_mode,_set_mode)
67 logmode = property(_get_mode,_set_mode)
68
68
69 def logstart(self,logfname=None,loghead=None,logmode=None,
69 def logstart(self,logfname=None,loghead=None,logmode=None,
70 log_output=False,timestamp=False):
70 log_output=False,timestamp=False):
71 """Generate a new log-file with a default header.
71 """Generate a new log-file with a default header.
72
72
73 Raises RuntimeError if the log has already been started"""
73 Raises RuntimeError if the log has already been started"""
74
74
75 if self.logfile is not None:
75 if self.logfile is not None:
76 raise RuntimeError('Log file is already active: %s' %
76 raise RuntimeError('Log file is already active: %s' %
77 self.logfname)
77 self.logfname)
78
78
79 self.log_active = True
79 self.log_active = True
80
80
81 # The three parameters can override constructor defaults
81 # The three parameters can override constructor defaults
82 if logfname: self.logfname = logfname
82 if logfname: self.logfname = logfname
83 if loghead: self.loghead = loghead
83 if loghead: self.loghead = loghead
84 if logmode: self.logmode = logmode
84 if logmode: self.logmode = logmode
85 self.timestamp = timestamp
85 self.timestamp = timestamp
86 self.log_output = log_output
86 self.log_output = log_output
87
87
88 # init depending on the log mode requested
88 # init depending on the log mode requested
89 isfile = os.path.isfile
89 isfile = os.path.isfile
90 logmode = self.logmode
90 logmode = self.logmode
91
91
92 if logmode == 'append':
92 if logmode == 'append':
93 self.logfile = open(self.logfname,'a')
93 self.logfile = open(self.logfname,'a')
94
94
95 elif logmode == 'backup':
95 elif logmode == 'backup':
96 if isfile(self.logfname):
96 if isfile(self.logfname):
97 backup_logname = self.logfname+'~'
97 backup_logname = self.logfname+'~'
98 # Manually remove any old backup, since os.rename may fail
98 # Manually remove any old backup, since os.rename may fail
99 # under Windows.
99 # under Windows.
100 if isfile(backup_logname):
100 if isfile(backup_logname):
101 os.remove(backup_logname)
101 os.remove(backup_logname)
102 os.rename(self.logfname,backup_logname)
102 os.rename(self.logfname,backup_logname)
103 self.logfile = open(self.logfname,'w')
103 self.logfile = open(self.logfname,'w')
104
104
105 elif logmode == 'global':
105 elif logmode == 'global':
106 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
106 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
107 self.logfile = open(self.logfname, 'a')
107 self.logfile = open(self.logfname, 'a')
108
108
109 elif logmode == 'over':
109 elif logmode == 'over':
110 if isfile(self.logfname):
110 if isfile(self.logfname):
111 os.remove(self.logfname)
111 os.remove(self.logfname)
112 self.logfile = open(self.logfname,'w')
112 self.logfile = open(self.logfname,'w')
113
113
114 elif logmode == 'rotate':
114 elif logmode == 'rotate':
115 if isfile(self.logfname):
115 if isfile(self.logfname):
116 if isfile(self.logfname+'.001~'):
116 if isfile(self.logfname+'.001~'):
117 old = glob.glob(self.logfname+'.*~')
117 old = glob.glob(self.logfname+'.*~')
118 old.sort()
118 old.sort()
119 old.reverse()
119 old.reverse()
120 for f in old:
120 for f in old:
121 root, ext = os.path.splitext(f)
121 root, ext = os.path.splitext(f)
122 num = int(ext[1:-1])+1
122 num = int(ext[1:-1])+1
123 os.rename(f, root+'.'+`num`.zfill(3)+'~')
123 os.rename(f, root+'.'+`num`.zfill(3)+'~')
124 os.rename(self.logfname, self.logfname+'.001~')
124 os.rename(self.logfname, self.logfname+'.001~')
125 self.logfile = open(self.logfname,'w')
125 self.logfile = open(self.logfname,'w')
126
126
127 if logmode != 'append':
127 if logmode != 'append':
128 self.logfile.write(self.loghead)
128 self.logfile.write(self.loghead)
129
129
130 self.logfile.flush()
130 self.logfile.flush()
131
131
132 def switch_log(self,val):
132 def switch_log(self,val):
133 """Switch logging on/off. val should be ONLY a boolean."""
133 """Switch logging on/off. val should be ONLY a boolean."""
134
134
135 if val not in [False,True,0,1]:
135 if val not in [False,True,0,1]:
136 raise ValueError, \
136 raise ValueError, \
137 'Call switch_log ONLY with a boolean argument, not with:',val
137 'Call switch_log ONLY with a boolean argument, not with:',val
138
138
139 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
139 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
140
140
141 if self.logfile is None:
141 if self.logfile is None:
142 print """
142 print """
143 Logging hasn't been started yet (use logstart for that).
143 Logging hasn't been started yet (use logstart for that).
144
144
145 %logon/%logoff are for temporarily starting and stopping logging for a logfile
145 %logon/%logoff are for temporarily starting and stopping logging for a logfile
146 which already exists. But you must first start the logging process with
146 which already exists. But you must first start the logging process with
147 %logstart (optionally giving a logfile name)."""
147 %logstart (optionally giving a logfile name)."""
148
148
149 else:
149 else:
150 if self.log_active == val:
150 if self.log_active == val:
151 print 'Logging is already',label[val]
151 print 'Logging is already',label[val]
152 else:
152 else:
153 print 'Switching logging',label[val]
153 print 'Switching logging',label[val]
154 self.log_active = not self.log_active
154 self.log_active = not self.log_active
155 self.log_active_out = self.log_active
155 self.log_active_out = self.log_active
156
156
157 def logstate(self):
157 def logstate(self):
158 """Print a status message about the logger."""
158 """Print a status message about the logger."""
159 if self.logfile is None:
159 if self.logfile is None:
160 print 'Logging has not been activated.'
160 print 'Logging has not been activated.'
161 else:
161 else:
162 state = self.log_active and 'active' or 'temporarily suspended'
162 state = self.log_active and 'active' or 'temporarily suspended'
163 print 'Filename :',self.logfname
163 print 'Filename :',self.logfname
164 print 'Mode :',self.logmode
164 print 'Mode :',self.logmode
165 print 'Output logging :',self.log_output
165 print 'Output logging :',self.log_output
166 print 'Timestamping :',self.timestamp
166 print 'Timestamping :',self.timestamp
167 print 'State :',state
167 print 'State :',state
168
168
169 def log(self, line,continuation=None):
169 def log(self, line,continuation=None):
170 """Write the line to a log and create input cache variables _i*."""
170 """Write the line to a log and create input cache variables _i*."""
171
171
172 # update the auto _i tables
172 # update the auto _i tables
173 #print '***logging line',line # dbg
173 #print '***logging line',line # dbg
174 #print '***cache_count', self.shell.outputcache.prompt_count # dbg
174 #print '***cache_count', self.shell.outputcache.prompt_count # dbg
175 input_hist = self.shell.user_ns['_ih']
175 input_hist = self.shell.user_ns['_ih']
176 if not continuation and line:
176 if not continuation and line:
177 self._iii = self._ii
177 self._iii = self._ii
178 self._ii = self._i
178 self._ii = self._i
179 self._i = self._i00
179 self._i = self._i00
180 # put back the final \n of every input line
180 # put back the final \n of every input line
181 self._i00 = line+'\n'
181 self._i00 = line+'\n'
182 #print 'Logging input:<%s>' % line # dbg
182 #print 'Logging input:<%s>' % line # dbg
183 input_hist.append(self._i00)
183 input_hist.append(self._i00)
184 #print '---[%s]' % (len(input_hist)-1,) # dbg
184
185
185 # hackish access to top-level namespace to create _i1,_i2... dynamically
186 # hackish access to top-level namespace to create _i1,_i2... dynamically
186 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
187 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
187 if self.shell.outputcache.do_full_cache:
188 if self.shell.outputcache.do_full_cache:
188 in_num = self.shell.outputcache.prompt_count
189 in_num = self.shell.outputcache.prompt_count
189 # add blank lines if the input cache fell out of sync. This can
190 # add blank lines if the input cache fell out of sync. This can
190 # happen for embedded instances which get killed via C-D and then
191 # happen for embedded instances which get killed via C-D and then
191 # get resumed.
192 # get resumed.
192 while in_num >= len(input_hist):
193 while in_num >= len(input_hist):
193 input_hist.append('\n')
194 input_hist.append('\n')
195 # but if the opposite is true (a macro can produce multiple inputs
196 # with no output display called), then bring the output counter in
197 # sync:
198 last_num = len(input_hist)-1
199 if in_num != last_num:
200 in_num = self.shell.outputcache.prompt_count = last_num
194 new_i = '_i%s' % in_num
201 new_i = '_i%s' % in_num
195 if continuation:
202 if continuation:
196 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line)
203 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line)
197 input_hist[in_num] = self._i00
204 input_hist[in_num] = self._i00
198 to_main[new_i] = self._i00
205 to_main[new_i] = self._i00
199 self.shell.user_ns.update(to_main)
206 self.shell.user_ns.update(to_main)
200 self.log_write(line)
207 self.log_write(line)
201
208
202 def log_write(self,data,kind='input'):
209 def log_write(self,data,kind='input'):
203 """Write data to the log file, if active"""
210 """Write data to the log file, if active"""
204
211
205 if self.log_active and data:
212 if self.log_active and data:
206 write = self.logfile.write
213 write = self.logfile.write
207 if kind=='input':
214 if kind=='input':
208 if self.timestamp:
215 if self.timestamp:
209 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
216 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
210 time.localtime()))
217 time.localtime()))
211 write('%s\n' % data)
218 write('%s\n' % data)
212 elif kind=='output' and self.log_output:
219 elif kind=='output' and self.log_output:
213 odata = '\n'.join(['#[Out]# %s' % s
220 odata = '\n'.join(['#[Out]# %s' % s
214 for s in data.split('\n')])
221 for s in data.split('\n')])
215 write('%s\n' % odata)
222 write('%s\n' % odata)
216 self.logfile.flush()
223 self.logfile.flush()
217
224
218 def close_log(self):
225 def close_log(self):
219 self.logfile.close()
226 self.logfile.close()
220 self.logfile = None
227 self.logfile = None
221 self.logfname = ''
228 self.logfname = ''
@@ -1,2672 +1,2677 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 975 2005-12-29 23:50:22Z fperez $"""
4 $Id: Magic.py 984 2005-12-31 08:40:31Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 from cStringIO import StringIO
34 from cStringIO import StringIO
35 from getopt import getopt
35 from getopt import getopt
36 from pprint import pprint, pformat
36 from pprint import pprint, pformat
37
37
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # Homebrewed
44 # Homebrewed
45 from IPython import Debugger, OInspect, wildcard
45 from IPython import Debugger, OInspect, wildcard
46 from IPython.FakeModule import FakeModule
46 from IPython.FakeModule import FakeModule
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.PyColorize import Parser
48 from IPython.PyColorize import Parser
49 from IPython.Struct import Struct
49 from IPython.Struct import Struct
50 from IPython.macro import Macro
50 from IPython.macro import Macro
51 from IPython.genutils import *
51 from IPython.genutils import *
52
52
53 #***************************************************************************
53 #***************************************************************************
54 # Utility functions
54 # Utility functions
55 def on_off(tag):
55 def on_off(tag):
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 return ['OFF','ON'][tag]
57 return ['OFF','ON'][tag]
58
58
59
59
60 #***************************************************************************
60 #***************************************************************************
61 # Main class implementing Magic functionality
61 # Main class implementing Magic functionality
62 class Magic:
62 class Magic:
63 """Magic functions for InteractiveShell.
63 """Magic functions for InteractiveShell.
64
64
65 Shell functions which can be reached as %function_name. All magic
65 Shell functions which can be reached as %function_name. All magic
66 functions should accept a string, which they can parse for their own
66 functions should accept a string, which they can parse for their own
67 needs. This can make some functions easier to type, eg `%cd ../`
67 needs. This can make some functions easier to type, eg `%cd ../`
68 vs. `%cd("../")`
68 vs. `%cd("../")`
69
69
70 ALL definitions MUST begin with the prefix magic_. The user won't need it
70 ALL definitions MUST begin with the prefix magic_. The user won't need it
71 at the command line, but it is is needed in the definition. """
71 at the command line, but it is is needed in the definition. """
72
72
73 # class globals
73 # class globals
74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
75 'Automagic is ON, % prefix NOT needed for magic functions.']
75 'Automagic is ON, % prefix NOT needed for magic functions.']
76
76
77 #......................................................................
77 #......................................................................
78 # some utility functions
78 # some utility functions
79
79
80 def __init__(self,shell):
80 def __init__(self,shell):
81
81
82 self.options_table = {}
82 self.options_table = {}
83 if profile is None:
83 if profile is None:
84 self.magic_prun = self.profile_missing_notice
84 self.magic_prun = self.profile_missing_notice
85 self.shell = shell
85 self.shell = shell
86
86
87 def profile_missing_notice(self, *args, **kwargs):
87 def profile_missing_notice(self, *args, **kwargs):
88 error("""\
88 error("""\
89 The profile module could not be found. If you are a Debian user,
89 The profile module could not be found. If you are a Debian user,
90 it has been removed from the standard Debian package because of its non-free
90 it has been removed from the standard Debian package because of its non-free
91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
92
92
93 def default_option(self,fn,optstr):
93 def default_option(self,fn,optstr):
94 """Make an entry in the options_table for fn, with value optstr"""
94 """Make an entry in the options_table for fn, with value optstr"""
95
95
96 if fn not in self.lsmagic():
96 if fn not in self.lsmagic():
97 error("%s is not a magic function" % fn)
97 error("%s is not a magic function" % fn)
98 self.options_table[fn] = optstr
98 self.options_table[fn] = optstr
99
99
100 def lsmagic(self):
100 def lsmagic(self):
101 """Return a list of currently available magic functions.
101 """Return a list of currently available magic functions.
102
102
103 Gives a list of the bare names after mangling (['ls','cd', ...], not
103 Gives a list of the bare names after mangling (['ls','cd', ...], not
104 ['magic_ls','magic_cd',...]"""
104 ['magic_ls','magic_cd',...]"""
105
105
106 # FIXME. This needs a cleanup, in the way the magics list is built.
106 # FIXME. This needs a cleanup, in the way the magics list is built.
107
107
108 # magics in class definition
108 # magics in class definition
109 class_magic = lambda fn: fn.startswith('magic_') and \
109 class_magic = lambda fn: fn.startswith('magic_') and \
110 callable(Magic.__dict__[fn])
110 callable(Magic.__dict__[fn])
111 # in instance namespace (run-time user additions)
111 # in instance namespace (run-time user additions)
112 inst_magic = lambda fn: fn.startswith('magic_') and \
112 inst_magic = lambda fn: fn.startswith('magic_') and \
113 callable(self.__dict__[fn])
113 callable(self.__dict__[fn])
114 # and bound magics by user (so they can access self):
114 # and bound magics by user (so they can access self):
115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
116 callable(self.__class__.__dict__[fn])
116 callable(self.__class__.__dict__[fn])
117 magics = filter(class_magic,Magic.__dict__.keys()) + \
117 magics = filter(class_magic,Magic.__dict__.keys()) + \
118 filter(inst_magic,self.__dict__.keys()) + \
118 filter(inst_magic,self.__dict__.keys()) + \
119 filter(inst_bound_magic,self.__class__.__dict__.keys())
119 filter(inst_bound_magic,self.__class__.__dict__.keys())
120 out = []
120 out = []
121 for fn in magics:
121 for fn in magics:
122 out.append(fn.replace('magic_','',1))
122 out.append(fn.replace('magic_','',1))
123 out.sort()
123 out.sort()
124 return out
124 return out
125
125
126 def extract_input_slices(self,slices):
126 def extract_input_slices(self,slices):
127 """Return as a string a set of input history slices.
127 """Return as a string a set of input history slices.
128
128
129 The set of slices is given as a list of strings (like ['1','4:8','9'],
129 The set of slices is given as a list of strings (like ['1','4:8','9'],
130 since this function is for use by magic functions which get their
130 since this function is for use by magic functions which get their
131 arguments as strings."""
131 arguments as strings."""
132
132
133 cmds = []
133 cmds = []
134 for chunk in slices:
134 for chunk in slices:
135 if ':' in chunk:
135 if ':' in chunk:
136 ini,fin = map(int,chunk.split(':'))
136 ini,fin = map(int,chunk.split(':'))
137 else:
137 else:
138 ini = int(chunk)
138 ini = int(chunk)
139 fin = ini+1
139 fin = ini+1
140 cmds.append(self.shell.input_hist[ini:fin])
140 cmds.append(self.shell.input_hist[ini:fin])
141 return cmds
141 return cmds
142
142
143 def _ofind(self,oname):
143 def _ofind(self,oname):
144 """Find an object in the available namespaces.
144 """Find an object in the available namespaces.
145
145
146 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
146 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
147
147
148 Has special code to detect magic functions.
148 Has special code to detect magic functions.
149 """
149 """
150
150
151 oname = oname.strip()
151 oname = oname.strip()
152
152
153 # Namespaces to search in:
153 # Namespaces to search in:
154 user_ns = self.shell.user_ns
154 user_ns = self.shell.user_ns
155 internal_ns = self.shell.internal_ns
155 internal_ns = self.shell.internal_ns
156 builtin_ns = __builtin__.__dict__
156 builtin_ns = __builtin__.__dict__
157 alias_ns = self.shell.alias_table
157 alias_ns = self.shell.alias_table
158
158
159 # Put them in a list. The order is important so that we find things in
159 # Put them in a list. The order is important so that we find things in
160 # the same order that Python finds them.
160 # the same order that Python finds them.
161 namespaces = [ ('Interactive',user_ns),
161 namespaces = [ ('Interactive',user_ns),
162 ('IPython internal',internal_ns),
162 ('IPython internal',internal_ns),
163 ('Python builtin',builtin_ns),
163 ('Python builtin',builtin_ns),
164 ('Alias',alias_ns),
164 ('Alias',alias_ns),
165 ]
165 ]
166
166
167 # initialize results to 'null'
167 # initialize results to 'null'
168 found = 0; obj = None; ospace = None; ds = None;
168 found = 0; obj = None; ospace = None; ds = None;
169 ismagic = 0; isalias = 0
169 ismagic = 0; isalias = 0
170
170
171 # Look for the given name by splitting it in parts. If the head is
171 # Look for the given name by splitting it in parts. If the head is
172 # found, then we look for all the remaining parts as members, and only
172 # found, then we look for all the remaining parts as members, and only
173 # declare success if we can find them all.
173 # declare success if we can find them all.
174 oname_parts = oname.split('.')
174 oname_parts = oname.split('.')
175 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
175 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
176 for nsname,ns in namespaces:
176 for nsname,ns in namespaces:
177 try:
177 try:
178 obj = ns[oname_head]
178 obj = ns[oname_head]
179 except KeyError:
179 except KeyError:
180 continue
180 continue
181 else:
181 else:
182 for part in oname_rest:
182 for part in oname_rest:
183 try:
183 try:
184 obj = getattr(obj,part)
184 obj = getattr(obj,part)
185 except:
185 except:
186 # Blanket except b/c some badly implemented objects
186 # Blanket except b/c some badly implemented objects
187 # allow __getattr__ to raise exceptions other than
187 # allow __getattr__ to raise exceptions other than
188 # AttributeError, which then crashes IPython.
188 # AttributeError, which then crashes IPython.
189 break
189 break
190 else:
190 else:
191 # If we finish the for loop (no break), we got all members
191 # If we finish the for loop (no break), we got all members
192 found = 1
192 found = 1
193 ospace = nsname
193 ospace = nsname
194 if ns == alias_ns:
194 if ns == alias_ns:
195 isalias = 1
195 isalias = 1
196 break # namespace loop
196 break # namespace loop
197
197
198 # Try to see if it's magic
198 # Try to see if it's magic
199 if not found:
199 if not found:
200 if oname.startswith(self.shell.ESC_MAGIC):
200 if oname.startswith(self.shell.ESC_MAGIC):
201 oname = oname[1:]
201 oname = oname[1:]
202 obj = getattr(self,'magic_'+oname,None)
202 obj = getattr(self,'magic_'+oname,None)
203 if obj is not None:
203 if obj is not None:
204 found = 1
204 found = 1
205 ospace = 'IPython internal'
205 ospace = 'IPython internal'
206 ismagic = 1
206 ismagic = 1
207
207
208 # Last try: special-case some literals like '', [], {}, etc:
208 # Last try: special-case some literals like '', [], {}, etc:
209 if not found and oname_head in ["''",'""','[]','{}','()']:
209 if not found and oname_head in ["''",'""','[]','{}','()']:
210 obj = eval(oname_head)
210 obj = eval(oname_head)
211 found = 1
211 found = 1
212 ospace = 'Interactive'
212 ospace = 'Interactive'
213
213
214 return {'found':found, 'obj':obj, 'namespace':ospace,
214 return {'found':found, 'obj':obj, 'namespace':ospace,
215 'ismagic':ismagic, 'isalias':isalias}
215 'ismagic':ismagic, 'isalias':isalias}
216
216
217 def arg_err(self,func):
217 def arg_err(self,func):
218 """Print docstring if incorrect arguments were passed"""
218 """Print docstring if incorrect arguments were passed"""
219 print 'Error in arguments:'
219 print 'Error in arguments:'
220 print OInspect.getdoc(func)
220 print OInspect.getdoc(func)
221
221
222 def format_latex(self,strng):
222 def format_latex(self,strng):
223 """Format a string for latex inclusion."""
223 """Format a string for latex inclusion."""
224
224
225 # Characters that need to be escaped for latex:
225 # Characters that need to be escaped for latex:
226 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
226 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
227 # Magic command names as headers:
227 # Magic command names as headers:
228 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
228 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
229 re.MULTILINE)
229 re.MULTILINE)
230 # Magic commands
230 # Magic commands
231 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
231 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
232 re.MULTILINE)
232 re.MULTILINE)
233 # Paragraph continue
233 # Paragraph continue
234 par_re = re.compile(r'\\$',re.MULTILINE)
234 par_re = re.compile(r'\\$',re.MULTILINE)
235
235
236 # The "\n" symbol
236 # The "\n" symbol
237 newline_re = re.compile(r'\\n')
237 newline_re = re.compile(r'\\n')
238
238
239 # Now build the string for output:
239 # Now build the string for output:
240 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
240 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
241 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
241 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
242 strng = par_re.sub(r'\\\\',strng)
242 strng = par_re.sub(r'\\\\',strng)
243 strng = escape_re.sub(r'\\\1',strng)
243 strng = escape_re.sub(r'\\\1',strng)
244 strng = newline_re.sub(r'\\textbackslash{}n',strng)
244 strng = newline_re.sub(r'\\textbackslash{}n',strng)
245 return strng
245 return strng
246
246
247 def format_screen(self,strng):
247 def format_screen(self,strng):
248 """Format a string for screen printing.
248 """Format a string for screen printing.
249
249
250 This removes some latex-type format codes."""
250 This removes some latex-type format codes."""
251 # Paragraph continue
251 # Paragraph continue
252 par_re = re.compile(r'\\$',re.MULTILINE)
252 par_re = re.compile(r'\\$',re.MULTILINE)
253 strng = par_re.sub('',strng)
253 strng = par_re.sub('',strng)
254 return strng
254 return strng
255
255
256 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
256 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
257 """Parse options passed to an argument string.
257 """Parse options passed to an argument string.
258
258
259 The interface is similar to that of getopt(), but it returns back a
259 The interface is similar to that of getopt(), but it returns back a
260 Struct with the options as keys and the stripped argument string still
260 Struct with the options as keys and the stripped argument string still
261 as a string.
261 as a string.
262
262
263 arg_str is quoted as a true sys.argv vector by using shlex.split.
263 arg_str is quoted as a true sys.argv vector by using shlex.split.
264 This allows us to easily expand variables, glob files, quote
264 This allows us to easily expand variables, glob files, quote
265 arguments, etc.
265 arguments, etc.
266
266
267 Options:
267 Options:
268 -mode: default 'string'. If given as 'list', the argument string is
268 -mode: default 'string'. If given as 'list', the argument string is
269 returned as a list (split on whitespace) instead of a string.
269 returned as a list (split on whitespace) instead of a string.
270
270
271 -list_all: put all option values in lists. Normally only options
271 -list_all: put all option values in lists. Normally only options
272 appearing more than once are put in a list."""
272 appearing more than once are put in a list."""
273
273
274 # inject default options at the beginning of the input line
274 # inject default options at the beginning of the input line
275 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
275 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
276 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
276 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
277
277
278 mode = kw.get('mode','string')
278 mode = kw.get('mode','string')
279 if mode not in ['string','list']:
279 if mode not in ['string','list']:
280 raise ValueError,'incorrect mode given: %s' % mode
280 raise ValueError,'incorrect mode given: %s' % mode
281 # Get options
281 # Get options
282 list_all = kw.get('list_all',0)
282 list_all = kw.get('list_all',0)
283
283
284 # Check if we have more than one argument to warrant extra processing:
284 # Check if we have more than one argument to warrant extra processing:
285 odict = {} # Dictionary with options
285 odict = {} # Dictionary with options
286 args = arg_str.split()
286 args = arg_str.split()
287 if len(args) >= 1:
287 if len(args) >= 1:
288 # If the list of inputs only has 0 or 1 thing in it, there's no
288 # If the list of inputs only has 0 or 1 thing in it, there's no
289 # need to look for options
289 # need to look for options
290 argv = shlex_split(arg_str)
290 argv = shlex_split(arg_str)
291 # Do regular option processing
291 # Do regular option processing
292 opts,args = getopt(argv,opt_str,*long_opts)
292 opts,args = getopt(argv,opt_str,*long_opts)
293 for o,a in opts:
293 for o,a in opts:
294 if o.startswith('--'):
294 if o.startswith('--'):
295 o = o[2:]
295 o = o[2:]
296 else:
296 else:
297 o = o[1:]
297 o = o[1:]
298 try:
298 try:
299 odict[o].append(a)
299 odict[o].append(a)
300 except AttributeError:
300 except AttributeError:
301 odict[o] = [odict[o],a]
301 odict[o] = [odict[o],a]
302 except KeyError:
302 except KeyError:
303 if list_all:
303 if list_all:
304 odict[o] = [a]
304 odict[o] = [a]
305 else:
305 else:
306 odict[o] = a
306 odict[o] = a
307
307
308 # Prepare opts,args for return
308 # Prepare opts,args for return
309 opts = Struct(odict)
309 opts = Struct(odict)
310 if mode == 'string':
310 if mode == 'string':
311 args = ' '.join(args)
311 args = ' '.join(args)
312
312
313 return opts,args
313 return opts,args
314
314
315 #......................................................................
315 #......................................................................
316 # And now the actual magic functions
316 # And now the actual magic functions
317
317
318 # Functions for IPython shell work (vars,funcs, config, etc)
318 # Functions for IPython shell work (vars,funcs, config, etc)
319 def magic_lsmagic(self, parameter_s = ''):
319 def magic_lsmagic(self, parameter_s = ''):
320 """List currently available magic functions."""
320 """List currently available magic functions."""
321 mesc = self.shell.ESC_MAGIC
321 mesc = self.shell.ESC_MAGIC
322 print 'Available magic functions:\n'+mesc+\
322 print 'Available magic functions:\n'+mesc+\
323 (' '+mesc).join(self.lsmagic())
323 (' '+mesc).join(self.lsmagic())
324 print '\n' + Magic.auto_status[self.shell.rc.automagic]
324 print '\n' + Magic.auto_status[self.shell.rc.automagic]
325 return None
325 return None
326
326
327 def magic_magic(self, parameter_s = ''):
327 def magic_magic(self, parameter_s = ''):
328 """Print information about the magic function system."""
328 """Print information about the magic function system."""
329
329
330 mode = ''
330 mode = ''
331 try:
331 try:
332 if parameter_s.split()[0] == '-latex':
332 if parameter_s.split()[0] == '-latex':
333 mode = 'latex'
333 mode = 'latex'
334 except:
334 except:
335 pass
335 pass
336
336
337 magic_docs = []
337 magic_docs = []
338 for fname in self.lsmagic():
338 for fname in self.lsmagic():
339 mname = 'magic_' + fname
339 mname = 'magic_' + fname
340 for space in (Magic,self,self.__class__):
340 for space in (Magic,self,self.__class__):
341 try:
341 try:
342 fn = space.__dict__[mname]
342 fn = space.__dict__[mname]
343 except KeyError:
343 except KeyError:
344 pass
344 pass
345 else:
345 else:
346 break
346 break
347 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
347 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
348 fname,fn.__doc__))
348 fname,fn.__doc__))
349 magic_docs = ''.join(magic_docs)
349 magic_docs = ''.join(magic_docs)
350
350
351 if mode == 'latex':
351 if mode == 'latex':
352 print self.format_latex(magic_docs)
352 print self.format_latex(magic_docs)
353 return
353 return
354 else:
354 else:
355 magic_docs = self.format_screen(magic_docs)
355 magic_docs = self.format_screen(magic_docs)
356
356
357 outmsg = """
357 outmsg = """
358 IPython's 'magic' functions
358 IPython's 'magic' functions
359 ===========================
359 ===========================
360
360
361 The magic function system provides a series of functions which allow you to
361 The magic function system provides a series of functions which allow you to
362 control the behavior of IPython itself, plus a lot of system-type
362 control the behavior of IPython itself, plus a lot of system-type
363 features. All these functions are prefixed with a % character, but parameters
363 features. All these functions are prefixed with a % character, but parameters
364 are given without parentheses or quotes.
364 are given without parentheses or quotes.
365
365
366 NOTE: If you have 'automagic' enabled (via the command line option or with the
366 NOTE: If you have 'automagic' enabled (via the command line option or with the
367 %automagic function), you don't need to type in the % explicitly. By default,
367 %automagic function), you don't need to type in the % explicitly. By default,
368 IPython ships with automagic on, so you should only rarely need the % escape.
368 IPython ships with automagic on, so you should only rarely need the % escape.
369
369
370 Example: typing '%cd mydir' (without the quotes) changes you working directory
370 Example: typing '%cd mydir' (without the quotes) changes you working directory
371 to 'mydir', if it exists.
371 to 'mydir', if it exists.
372
372
373 You can define your own magic functions to extend the system. See the supplied
373 You can define your own magic functions to extend the system. See the supplied
374 ipythonrc and example-magic.py files for details (in your ipython
374 ipythonrc and example-magic.py files for details (in your ipython
375 configuration directory, typically $HOME/.ipython/).
375 configuration directory, typically $HOME/.ipython/).
376
376
377 You can also define your own aliased names for magic functions. In your
377 You can also define your own aliased names for magic functions. In your
378 ipythonrc file, placing a line like:
378 ipythonrc file, placing a line like:
379
379
380 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
380 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
381
381
382 will define %pf as a new name for %profile.
382 will define %pf as a new name for %profile.
383
383
384 You can also call magics in code using the ipmagic() function, which IPython
384 You can also call magics in code using the ipmagic() function, which IPython
385 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
385 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
386
386
387 For a list of the available magic functions, use %lsmagic. For a description
387 For a list of the available magic functions, use %lsmagic. For a description
388 of any of them, type %magic_name?, e.g. '%cd?'.
388 of any of them, type %magic_name?, e.g. '%cd?'.
389
389
390 Currently the magic system has the following functions:\n"""
390 Currently the magic system has the following functions:\n"""
391
391
392 mesc = self.shell.ESC_MAGIC
392 mesc = self.shell.ESC_MAGIC
393 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
393 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
394 "\n\n%s%s\n\n%s" % (outmsg,
394 "\n\n%s%s\n\n%s" % (outmsg,
395 magic_docs,mesc,mesc,
395 magic_docs,mesc,mesc,
396 (' '+mesc).join(self.lsmagic()),
396 (' '+mesc).join(self.lsmagic()),
397 Magic.auto_status[self.shell.rc.automagic] ) )
397 Magic.auto_status[self.shell.rc.automagic] ) )
398
398
399 page(outmsg,screen_lines=self.shell.rc.screen_length)
399 page(outmsg,screen_lines=self.shell.rc.screen_length)
400
400
401 def magic_automagic(self, parameter_s = ''):
401 def magic_automagic(self, parameter_s = ''):
402 """Make magic functions callable without having to type the initial %.
402 """Make magic functions callable without having to type the initial %.
403
403
404 Toggles on/off (when off, you must call it as %automagic, of
404 Toggles on/off (when off, you must call it as %automagic, of
405 course). Note that magic functions have lowest priority, so if there's
405 course). Note that magic functions have lowest priority, so if there's
406 a variable whose name collides with that of a magic fn, automagic
406 a variable whose name collides with that of a magic fn, automagic
407 won't work for that function (you get the variable instead). However,
407 won't work for that function (you get the variable instead). However,
408 if you delete the variable (del var), the previously shadowed magic
408 if you delete the variable (del var), the previously shadowed magic
409 function becomes visible to automagic again."""
409 function becomes visible to automagic again."""
410
410
411 rc = self.shell.rc
411 rc = self.shell.rc
412 rc.automagic = not rc.automagic
412 rc.automagic = not rc.automagic
413 print '\n' + Magic.auto_status[rc.automagic]
413 print '\n' + Magic.auto_status[rc.automagic]
414
414
415 def magic_autocall(self, parameter_s = ''):
415 def magic_autocall(self, parameter_s = ''):
416 """Make functions callable without having to type parentheses.
416 """Make functions callable without having to type parentheses.
417
417
418 This toggles the autocall command line option on and off."""
418 This toggles the autocall command line option on and off."""
419
419
420 rc = self.shell.rc
420 rc = self.shell.rc
421 rc.autocall = not rc.autocall
421 rc.autocall = not rc.autocall
422 print "Automatic calling is:",['OFF','ON'][rc.autocall]
422 print "Automatic calling is:",['OFF','ON'][rc.autocall]
423
423
424 def magic_autoindent(self, parameter_s = ''):
424 def magic_autoindent(self, parameter_s = ''):
425 """Toggle autoindent on/off (if available)."""
425 """Toggle autoindent on/off (if available)."""
426
426
427 self.shell.set_autoindent()
427 self.shell.set_autoindent()
428 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
428 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
429
429
430 def magic_system_verbose(self, parameter_s = ''):
430 def magic_system_verbose(self, parameter_s = ''):
431 """Toggle verbose printing of system calls on/off."""
431 """Toggle verbose printing of system calls on/off."""
432
432
433 self.shell.rc_set_toggle('system_verbose')
433 self.shell.rc_set_toggle('system_verbose')
434 print "System verbose printing is:",\
434 print "System verbose printing is:",\
435 ['OFF','ON'][self.shell.rc.system_verbose]
435 ['OFF','ON'][self.shell.rc.system_verbose]
436
436
437 def magic_history(self, parameter_s = ''):
437 def magic_history(self, parameter_s = ''):
438 """Print input history (_i<n> variables), with most recent last.
438 """Print input history (_i<n> variables), with most recent last.
439
439
440 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
440 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
441 %history [-n] n -> print at most n inputs\\
441 %history [-n] n -> print at most n inputs\\
442 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
442 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
443
443
444 Each input's number <n> is shown, and is accessible as the
444 Each input's number <n> is shown, and is accessible as the
445 automatically generated variable _i<n>. Multi-line statements are
445 automatically generated variable _i<n>. Multi-line statements are
446 printed starting at a new line for easy copy/paste.
446 printed starting at a new line for easy copy/paste.
447
447
448 If option -n is used, input numbers are not printed. This is useful if
448 If option -n is used, input numbers are not printed. This is useful if
449 you want to get a printout of many lines which can be directly pasted
449 you want to get a printout of many lines which can be directly pasted
450 into a text editor.
450 into a text editor.
451
451
452 This feature is only available if numbered prompts are in use."""
452 This feature is only available if numbered prompts are in use."""
453
453
454 if not self.shell.outputcache.do_full_cache:
454 shell = self.shell
455 if not shell.outputcache.do_full_cache:
455 print 'This feature is only available if numbered prompts are in use.'
456 print 'This feature is only available if numbered prompts are in use.'
456 return
457 return
457 opts,args = self.parse_options(parameter_s,'n',mode='list')
458 opts,args = self.parse_options(parameter_s,'n',mode='list')
458
459
460 input_hist = shell.input_hist
459 default_length = 40
461 default_length = 40
460 if len(args) == 0:
462 if len(args) == 0:
461 final = self.shell.outputcache.prompt_count
463 final = len(input_hist)
462 init = max(1,final-default_length)
464 init = max(1,final-default_length)
463 elif len(args) == 1:
465 elif len(args) == 1:
464 final = self.shell.outputcache.prompt_count
466 final = len(input_hist)
465 init = max(1,final-int(args[0]))
467 init = max(1,final-int(args[0]))
466 elif len(args) == 2:
468 elif len(args) == 2:
467 init,final = map(int,args)
469 init,final = map(int,args)
468 else:
470 else:
469 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
471 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
470 print self.magic_hist.__doc__
472 print self.magic_hist.__doc__
471 return
473 return
472 width = len(str(final))
474 width = len(str(final))
473 line_sep = ['','\n']
475 line_sep = ['','\n']
474 input_hist = self.shell.input_hist
475 print_nums = not opts.has_key('n')
476 print_nums = not opts.has_key('n')
476 for in_num in range(init,final):
477 for in_num in range(init,final):
477 inline = input_hist[in_num]
478 inline = input_hist[in_num]
478 multiline = inline.count('\n') > 1
479 multiline = int(inline.count('\n') > 1)
479 if print_nums:
480 if print_nums:
480 print str(in_num).ljust(width)+':'+ line_sep[multiline],
481 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
481 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
482 inline.startswith('#!'):
483 print inline[1:],
484 else:
485 print inline,
482 print inline,
486
483
487 def magic_hist(self, parameter_s=''):
484 def magic_hist(self, parameter_s=''):
488 """Alternate name for %history."""
485 """Alternate name for %history."""
489 return self.magic_history(parameter_s)
486 return self.magic_history(parameter_s)
490
487
491 def magic_p(self, parameter_s=''):
488 def magic_p(self, parameter_s=''):
492 """Just a short alias for Python's 'print'."""
489 """Just a short alias for Python's 'print'."""
493 exec 'print ' + parameter_s in self.shell.user_ns
490 exec 'print ' + parameter_s in self.shell.user_ns
494
491
495 def magic_r(self, parameter_s=''):
492 def magic_r(self, parameter_s=''):
496 """Repeat previous input.
493 """Repeat previous input.
497
494
498 If given an argument, repeats the previous command which starts with
495 If given an argument, repeats the previous command which starts with
499 the same string, otherwise it just repeats the previous input.
496 the same string, otherwise it just repeats the previous input.
500
497
501 Shell escaped commands (with ! as first character) are not recognized
498 Shell escaped commands (with ! as first character) are not recognized
502 by this system, only pure python code and magic commands.
499 by this system, only pure python code and magic commands.
503 """
500 """
504
501
505 start = parameter_s.strip()
502 start = parameter_s.strip()
506 esc_magic = self.shell.ESC_MAGIC
503 esc_magic = self.shell.ESC_MAGIC
507 # Identify magic commands even if automagic is on (which means
504 # Identify magic commands even if automagic is on (which means
508 # the in-memory version is different from that typed by the user).
505 # the in-memory version is different from that typed by the user).
509 if self.shell.rc.automagic:
506 if self.shell.rc.automagic:
510 start_magic = esc_magic+start
507 start_magic = esc_magic+start
511 else:
508 else:
512 start_magic = start
509 start_magic = start
513 # Look through the input history in reverse
510 # Look through the input history in reverse
514 for n in range(len(self.shell.input_hist)-2,0,-1):
511 for n in range(len(self.shell.input_hist)-2,0,-1):
515 input = self.shell.input_hist[n]
512 input = self.shell.input_hist[n]
516 # skip plain 'r' lines so we don't recurse to infinity
513 # skip plain 'r' lines so we don't recurse to infinity
517 if input != 'ipmagic("r")\n' and \
514 if input != 'ipmagic("r")\n' and \
518 (input.startswith(start) or input.startswith(start_magic)):
515 (input.startswith(start) or input.startswith(start_magic)):
519 #print 'match',`input` # dbg
516 #print 'match',`input` # dbg
520 print 'Executing:',input,
517 print 'Executing:',input,
521 self.shell.runlines(input)
518 self.shell.runlines(input)
522 return
519 return
523 print 'No previous input matching `%s` found.' % start
520 print 'No previous input matching `%s` found.' % start
524
521
525 def magic_page(self, parameter_s=''):
522 def magic_page(self, parameter_s=''):
526 """Pretty print the object and display it through a pager.
523 """Pretty print the object and display it through a pager.
527
524
528 If no parameter is given, use _ (last output)."""
525 If no parameter is given, use _ (last output)."""
529 # After a function contributed by Olivier Aubert, slightly modified.
526 # After a function contributed by Olivier Aubert, slightly modified.
530
527
531 oname = parameter_s and parameter_s or '_'
528 oname = parameter_s and parameter_s or '_'
532 info = self._ofind(oname)
529 info = self._ofind(oname)
533 if info['found']:
530 if info['found']:
534 page(pformat(info['obj']))
531 page(pformat(info['obj']))
535 else:
532 else:
536 print 'Object `%s` not found' % oname
533 print 'Object `%s` not found' % oname
537
534
538 def magic_profile(self, parameter_s=''):
535 def magic_profile(self, parameter_s=''):
539 """Print your currently active IPyhton profile."""
536 """Print your currently active IPyhton profile."""
540 if self.shell.rc.profile:
537 if self.shell.rc.profile:
541 printpl('Current IPython profile: $self.shell.rc.profile.')
538 printpl('Current IPython profile: $self.shell.rc.profile.')
542 else:
539 else:
543 print 'No profile active.'
540 print 'No profile active.'
544
541
545 def _inspect(self,meth,oname,**kw):
542 def _inspect(self,meth,oname,**kw):
546 """Generic interface to the inspector system.
543 """Generic interface to the inspector system.
547
544
548 This function is meant to be called by pdef, pdoc & friends."""
545 This function is meant to be called by pdef, pdoc & friends."""
549
546
550 oname = oname.strip()
547 oname = oname.strip()
551 info = Struct(self._ofind(oname))
548 info = Struct(self._ofind(oname))
552 if info.found:
549 if info.found:
553 pmethod = getattr(self.shell.inspector,meth)
550 pmethod = getattr(self.shell.inspector,meth)
554 formatter = info.ismagic and self.format_screen or None
551 formatter = info.ismagic and self.format_screen or None
555 if meth == 'pdoc':
552 if meth == 'pdoc':
556 pmethod(info.obj,oname,formatter)
553 pmethod(info.obj,oname,formatter)
557 elif meth == 'pinfo':
554 elif meth == 'pinfo':
558 pmethod(info.obj,oname,formatter,info,**kw)
555 pmethod(info.obj,oname,formatter,info,**kw)
559 else:
556 else:
560 pmethod(info.obj,oname)
557 pmethod(info.obj,oname)
561 else:
558 else:
562 print 'Object `%s` not found.' % oname
559 print 'Object `%s` not found.' % oname
563 return 'not found' # so callers can take other action
560 return 'not found' # so callers can take other action
564
561
565 def magic_pdef(self, parameter_s=''):
562 def magic_pdef(self, parameter_s=''):
566 """Print the definition header for any callable object.
563 """Print the definition header for any callable object.
567
564
568 If the object is a class, print the constructor information."""
565 If the object is a class, print the constructor information."""
569 self._inspect('pdef',parameter_s)
566 self._inspect('pdef',parameter_s)
570
567
571 def magic_pdoc(self, parameter_s=''):
568 def magic_pdoc(self, parameter_s=''):
572 """Print the docstring for an object.
569 """Print the docstring for an object.
573
570
574 If the given object is a class, it will print both the class and the
571 If the given object is a class, it will print both the class and the
575 constructor docstrings."""
572 constructor docstrings."""
576 self._inspect('pdoc',parameter_s)
573 self._inspect('pdoc',parameter_s)
577
574
578 def magic_psource(self, parameter_s=''):
575 def magic_psource(self, parameter_s=''):
579 """Print (or run through pager) the source code for an object."""
576 """Print (or run through pager) the source code for an object."""
580 self._inspect('psource',parameter_s)
577 self._inspect('psource',parameter_s)
581
578
582 def magic_pfile(self, parameter_s=''):
579 def magic_pfile(self, parameter_s=''):
583 """Print (or run through pager) the file where an object is defined.
580 """Print (or run through pager) the file where an object is defined.
584
581
585 The file opens at the line where the object definition begins. IPython
582 The file opens at the line where the object definition begins. IPython
586 will honor the environment variable PAGER if set, and otherwise will
583 will honor the environment variable PAGER if set, and otherwise will
587 do its best to print the file in a convenient form.
584 do its best to print the file in a convenient form.
588
585
589 If the given argument is not an object currently defined, IPython will
586 If the given argument is not an object currently defined, IPython will
590 try to interpret it as a filename (automatically adding a .py extension
587 try to interpret it as a filename (automatically adding a .py extension
591 if needed). You can thus use %pfile as a syntax highlighting code
588 if needed). You can thus use %pfile as a syntax highlighting code
592 viewer."""
589 viewer."""
593
590
594 # first interpret argument as an object name
591 # first interpret argument as an object name
595 out = self._inspect('pfile',parameter_s)
592 out = self._inspect('pfile',parameter_s)
596 # if not, try the input as a filename
593 # if not, try the input as a filename
597 if out == 'not found':
594 if out == 'not found':
598 try:
595 try:
599 filename = get_py_filename(parameter_s)
596 filename = get_py_filename(parameter_s)
600 except IOError,msg:
597 except IOError,msg:
601 print msg
598 print msg
602 return
599 return
603 page(self.shell.inspector.format(file(filename).read()))
600 page(self.shell.inspector.format(file(filename).read()))
604
601
605 def magic_pinfo(self, parameter_s=''):
602 def magic_pinfo(self, parameter_s=''):
606 """Provide detailed information about an object.
603 """Provide detailed information about an object.
607
604
608 '%pinfo object' is just a synonym for object? or ?object."""
605 '%pinfo object' is just a synonym for object? or ?object."""
609
606
610 #print 'pinfo par: <%s>' % parameter_s # dbg
607 #print 'pinfo par: <%s>' % parameter_s # dbg
611
608
612 # detail_level: 0 -> obj? , 1 -> obj??
609 # detail_level: 0 -> obj? , 1 -> obj??
613 detail_level = 0
610 detail_level = 0
614 # We need to detect if we got called as 'pinfo pinfo foo', which can
611 # We need to detect if we got called as 'pinfo pinfo foo', which can
615 # happen if the user types 'pinfo foo?' at the cmd line.
612 # happen if the user types 'pinfo foo?' at the cmd line.
616 pinfo,qmark1,oname,qmark2 = \
613 pinfo,qmark1,oname,qmark2 = \
617 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
614 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
618 if pinfo or qmark1 or qmark2:
615 if pinfo or qmark1 or qmark2:
619 detail_level = 1
616 detail_level = 1
620 if "*" in oname:
617 if "*" in oname:
621 self.magic_psearch(oname)
618 self.magic_psearch(oname)
622 else:
619 else:
623 self._inspect('pinfo',oname,detail_level=detail_level)
620 self._inspect('pinfo',oname,detail_level=detail_level)
624
621
625 def magic_psearch(self, parameter_s=''):
622 def magic_psearch(self, parameter_s=''):
626 """Search for object in namespaces by wildcard.
623 """Search for object in namespaces by wildcard.
627
624
628 %psearch [options] PATTERN [OBJECT TYPE]
625 %psearch [options] PATTERN [OBJECT TYPE]
629
626
630 Note: ? can be used as a synonym for %psearch, at the beginning or at
627 Note: ? can be used as a synonym for %psearch, at the beginning or at
631 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
628 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
632 rest of the command line must be unchanged (options come first), so
629 rest of the command line must be unchanged (options come first), so
633 for example the following forms are equivalent
630 for example the following forms are equivalent
634
631
635 %psearch -i a* function
632 %psearch -i a* function
636 -i a* function?
633 -i a* function?
637 ?-i a* function
634 ?-i a* function
638
635
639 Arguments:
636 Arguments:
640
637
641 PATTERN
638 PATTERN
642
639
643 where PATTERN is a string containing * as a wildcard similar to its
640 where PATTERN is a string containing * as a wildcard similar to its
644 use in a shell. The pattern is matched in all namespaces on the
641 use in a shell. The pattern is matched in all namespaces on the
645 search path. By default objects starting with a single _ are not
642 search path. By default objects starting with a single _ are not
646 matched, many IPython generated objects have a single
643 matched, many IPython generated objects have a single
647 underscore. The default is case insensitive matching. Matching is
644 underscore. The default is case insensitive matching. Matching is
648 also done on the attributes of objects and not only on the objects
645 also done on the attributes of objects and not only on the objects
649 in a module.
646 in a module.
650
647
651 [OBJECT TYPE]
648 [OBJECT TYPE]
652
649
653 Is the name of a python type from the types module. The name is
650 Is the name of a python type from the types module. The name is
654 given in lowercase without the ending type, ex. StringType is
651 given in lowercase without the ending type, ex. StringType is
655 written string. By adding a type here only objects matching the
652 written string. By adding a type here only objects matching the
656 given type are matched. Using all here makes the pattern match all
653 given type are matched. Using all here makes the pattern match all
657 types (this is the default).
654 types (this is the default).
658
655
659 Options:
656 Options:
660
657
661 -a: makes the pattern match even objects whose names start with a
658 -a: makes the pattern match even objects whose names start with a
662 single underscore. These names are normally ommitted from the
659 single underscore. These names are normally ommitted from the
663 search.
660 search.
664
661
665 -i/-c: make the pattern case insensitive/sensitive. If neither of
662 -i/-c: make the pattern case insensitive/sensitive. If neither of
666 these options is given, the default is read from your ipythonrc
663 these options is given, the default is read from your ipythonrc
667 file. The option name which sets this value is
664 file. The option name which sets this value is
668 'wildcards_case_sensitive'. If this option is not specified in your
665 'wildcards_case_sensitive'. If this option is not specified in your
669 ipythonrc file, IPython's internal default is to do a case sensitive
666 ipythonrc file, IPython's internal default is to do a case sensitive
670 search.
667 search.
671
668
672 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
669 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
673 specifiy can be searched in any of the following namespaces:
670 specifiy can be searched in any of the following namespaces:
674 'builtin', 'user', 'user_global','internal', 'alias', where
671 'builtin', 'user', 'user_global','internal', 'alias', where
675 'builtin' and 'user' are the search defaults. Note that you should
672 'builtin' and 'user' are the search defaults. Note that you should
676 not use quotes when specifying namespaces.
673 not use quotes when specifying namespaces.
677
674
678 'Builtin' contains the python module builtin, 'user' contains all
675 'Builtin' contains the python module builtin, 'user' contains all
679 user data, 'alias' only contain the shell aliases and no python
676 user data, 'alias' only contain the shell aliases and no python
680 objects, 'internal' contains objects used by IPython. The
677 objects, 'internal' contains objects used by IPython. The
681 'user_global' namespace is only used by embedded IPython instances,
678 'user_global' namespace is only used by embedded IPython instances,
682 and it contains module-level globals. You can add namespaces to the
679 and it contains module-level globals. You can add namespaces to the
683 search with -s or exclude them with -e (these options can be given
680 search with -s or exclude them with -e (these options can be given
684 more than once).
681 more than once).
685
682
686 Examples:
683 Examples:
687
684
688 %psearch a* -> objects beginning with an a
685 %psearch a* -> objects beginning with an a
689 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
686 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
690 %psearch a* function -> all functions beginning with an a
687 %psearch a* function -> all functions beginning with an a
691 %psearch re.e* -> objects beginning with an e in module re
688 %psearch re.e* -> objects beginning with an e in module re
692 %psearch r*.e* -> objects that start with e in modules starting in r
689 %psearch r*.e* -> objects that start with e in modules starting in r
693 %psearch r*.* string -> all strings in modules beginning with r
690 %psearch r*.* string -> all strings in modules beginning with r
694
691
695 Case sensitve search:
692 Case sensitve search:
696
693
697 %psearch -c a* list all object beginning with lower case a
694 %psearch -c a* list all object beginning with lower case a
698
695
699 Show objects beginning with a single _:
696 Show objects beginning with a single _:
700
697
701 %psearch -a _* list objects beginning with a single underscore"""
698 %psearch -a _* list objects beginning with a single underscore"""
702
699
703 # default namespaces to be searched
700 # default namespaces to be searched
704 def_search = ['user','builtin']
701 def_search = ['user','builtin']
705
702
706 # Process options/args
703 # Process options/args
707 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
704 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
708 opt = opts.get
705 opt = opts.get
709 shell = self.shell
706 shell = self.shell
710 psearch = shell.inspector.psearch
707 psearch = shell.inspector.psearch
711
708
712 # select case options
709 # select case options
713 if opts.has_key('i'):
710 if opts.has_key('i'):
714 ignore_case = True
711 ignore_case = True
715 elif opts.has_key('c'):
712 elif opts.has_key('c'):
716 ignore_case = False
713 ignore_case = False
717 else:
714 else:
718 ignore_case = not shell.rc.wildcards_case_sensitive
715 ignore_case = not shell.rc.wildcards_case_sensitive
719
716
720 # Build list of namespaces to search from user options
717 # Build list of namespaces to search from user options
721 def_search.extend(opt('s',[]))
718 def_search.extend(opt('s',[]))
722 ns_exclude = ns_exclude=opt('e',[])
719 ns_exclude = ns_exclude=opt('e',[])
723 ns_search = [nm for nm in def_search if nm not in ns_exclude]
720 ns_search = [nm for nm in def_search if nm not in ns_exclude]
724
721
725 # Call the actual search
722 # Call the actual search
726 try:
723 try:
727 psearch(args,shell.ns_table,ns_search,
724 psearch(args,shell.ns_table,ns_search,
728 show_all=opt('a'),ignore_case=ignore_case)
725 show_all=opt('a'),ignore_case=ignore_case)
729 except:
726 except:
730 shell.showtraceback()
727 shell.showtraceback()
731
728
732 def magic_who_ls(self, parameter_s=''):
729 def magic_who_ls(self, parameter_s=''):
733 """Return a sorted list of all interactive variables.
730 """Return a sorted list of all interactive variables.
734
731
735 If arguments are given, only variables of types matching these
732 If arguments are given, only variables of types matching these
736 arguments are returned."""
733 arguments are returned."""
737
734
738 user_ns = self.shell.user_ns
735 user_ns = self.shell.user_ns
739 out = []
736 out = []
740 typelist = parameter_s.split()
737 typelist = parameter_s.split()
741 for i in self.shell.user_ns.keys():
738 for i in self.shell.user_ns.keys():
742 if not (i.startswith('_') or i.startswith('_i')) \
739 if not (i.startswith('_') or i.startswith('_i')) \
743 and not (self.shell.internal_ns.has_key(i) or
740 and not (self.shell.internal_ns.has_key(i) or
744 self.shell.user_config_ns.has_key(i)):
741 self.shell.user_config_ns.has_key(i)):
745 if typelist:
742 if typelist:
746 if type(user_ns[i]).__name__ in typelist:
743 if type(user_ns[i]).__name__ in typelist:
747 out.append(i)
744 out.append(i)
748 else:
745 else:
749 out.append(i)
746 out.append(i)
750 out.sort()
747 out.sort()
751 return out
748 return out
752
749
753 def magic_who(self, parameter_s=''):
750 def magic_who(self, parameter_s=''):
754 """Print all interactive variables, with some minimal formatting.
751 """Print all interactive variables, with some minimal formatting.
755
752
756 If any arguments are given, only variables whose type matches one of
753 If any arguments are given, only variables whose type matches one of
757 these are printed. For example:
754 these are printed. For example:
758
755
759 %who function str
756 %who function str
760
757
761 will only list functions and strings, excluding all other types of
758 will only list functions and strings, excluding all other types of
762 variables. To find the proper type names, simply use type(var) at a
759 variables. To find the proper type names, simply use type(var) at a
763 command line to see how python prints type names. For example:
760 command line to see how python prints type names. For example:
764
761
765 In [1]: type('hello')\\
762 In [1]: type('hello')\\
766 Out[1]: <type 'str'>
763 Out[1]: <type 'str'>
767
764
768 indicates that the type name for strings is 'str'.
765 indicates that the type name for strings is 'str'.
769
766
770 %who always excludes executed names loaded through your configuration
767 %who always excludes executed names loaded through your configuration
771 file and things which are internal to IPython.
768 file and things which are internal to IPython.
772
769
773 This is deliberate, as typically you may load many modules and the
770 This is deliberate, as typically you may load many modules and the
774 purpose of %who is to show you only what you've manually defined."""
771 purpose of %who is to show you only what you've manually defined."""
775
772
776 varlist = self.magic_who_ls(parameter_s)
773 varlist = self.magic_who_ls(parameter_s)
777 if not varlist:
774 if not varlist:
778 print 'Interactive namespace is empty.'
775 print 'Interactive namespace is empty.'
779 return
776 return
780
777
781 # if we have variables, move on...
778 # if we have variables, move on...
782
779
783 # stupid flushing problem: when prompts have no separators, stdout is
780 # stupid flushing problem: when prompts have no separators, stdout is
784 # getting lost. I'm starting to think this is a python bug. I'm having
781 # getting lost. I'm starting to think this is a python bug. I'm having
785 # to force a flush with a print because even a sys.stdout.flush
782 # to force a flush with a print because even a sys.stdout.flush
786 # doesn't seem to do anything!
783 # doesn't seem to do anything!
787
784
788 count = 0
785 count = 0
789 for i in varlist:
786 for i in varlist:
790 print i+'\t',
787 print i+'\t',
791 count += 1
788 count += 1
792 if count > 8:
789 if count > 8:
793 count = 0
790 count = 0
794 print
791 print
795 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
792 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
796
793
797 print # well, this does force a flush at the expense of an extra \n
794 print # well, this does force a flush at the expense of an extra \n
798
795
799 def magic_whos(self, parameter_s=''):
796 def magic_whos(self, parameter_s=''):
800 """Like %who, but gives some extra information about each variable.
797 """Like %who, but gives some extra information about each variable.
801
798
802 The same type filtering of %who can be applied here.
799 The same type filtering of %who can be applied here.
803
800
804 For all variables, the type is printed. Additionally it prints:
801 For all variables, the type is printed. Additionally it prints:
805
802
806 - For {},[],(): their length.
803 - For {},[],(): their length.
807
804
808 - For Numeric arrays, a summary with shape, number of elements,
805 - For Numeric arrays, a summary with shape, number of elements,
809 typecode and size in memory.
806 typecode and size in memory.
810
807
811 - Everything else: a string representation, snipping their middle if
808 - Everything else: a string representation, snipping their middle if
812 too long."""
809 too long."""
813
810
814 varnames = self.magic_who_ls(parameter_s)
811 varnames = self.magic_who_ls(parameter_s)
815 if not varnames:
812 if not varnames:
816 print 'Interactive namespace is empty.'
813 print 'Interactive namespace is empty.'
817 return
814 return
818
815
819 # if we have variables, move on...
816 # if we have variables, move on...
820
817
821 # for these types, show len() instead of data:
818 # for these types, show len() instead of data:
822 seq_types = [types.DictType,types.ListType,types.TupleType]
819 seq_types = [types.DictType,types.ListType,types.TupleType]
823
820
824 # for Numeric arrays, display summary info
821 # for Numeric arrays, display summary info
825 try:
822 try:
826 import Numeric
823 import Numeric
827 except ImportError:
824 except ImportError:
828 array_type = None
825 array_type = None
829 else:
826 else:
830 array_type = Numeric.ArrayType.__name__
827 array_type = Numeric.ArrayType.__name__
831
828
832 # Find all variable names and types so we can figure out column sizes
829 # Find all variable names and types so we can figure out column sizes
833 get_vars = lambda i: self.shell.user_ns[i]
830 get_vars = lambda i: self.shell.user_ns[i]
834 type_name = lambda v: type(v).__name__
831 type_name = lambda v: type(v).__name__
835 varlist = map(get_vars,varnames)
832 varlist = map(get_vars,varnames)
836
833
837 typelist = []
834 typelist = []
838 for vv in varlist:
835 for vv in varlist:
839 tt = type_name(vv)
836 tt = type_name(vv)
840 if tt=='instance':
837 if tt=='instance':
841 typelist.append(str(vv.__class__))
838 typelist.append(str(vv.__class__))
842 else:
839 else:
843 typelist.append(tt)
840 typelist.append(tt)
844
841
845 # column labels and # of spaces as separator
842 # column labels and # of spaces as separator
846 varlabel = 'Variable'
843 varlabel = 'Variable'
847 typelabel = 'Type'
844 typelabel = 'Type'
848 datalabel = 'Data/Info'
845 datalabel = 'Data/Info'
849 colsep = 3
846 colsep = 3
850 # variable format strings
847 # variable format strings
851 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
848 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
852 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
849 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
853 aformat = "%s: %s elems, type `%s`, %s bytes"
850 aformat = "%s: %s elems, type `%s`, %s bytes"
854 # find the size of the columns to format the output nicely
851 # find the size of the columns to format the output nicely
855 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
852 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
856 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
853 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
857 # table header
854 # table header
858 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
855 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
859 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
856 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
860 # and the table itself
857 # and the table itself
861 kb = 1024
858 kb = 1024
862 Mb = 1048576 # kb**2
859 Mb = 1048576 # kb**2
863 for vname,var,vtype in zip(varnames,varlist,typelist):
860 for vname,var,vtype in zip(varnames,varlist,typelist):
864 print itpl(vformat),
861 print itpl(vformat),
865 if vtype in seq_types:
862 if vtype in seq_types:
866 print len(var)
863 print len(var)
867 elif vtype==array_type:
864 elif vtype==array_type:
868 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
865 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
869 vsize = Numeric.size(var)
866 vsize = Numeric.size(var)
870 vbytes = vsize*var.itemsize()
867 vbytes = vsize*var.itemsize()
871 if vbytes < 100000:
868 if vbytes < 100000:
872 print aformat % (vshape,vsize,var.typecode(),vbytes)
869 print aformat % (vshape,vsize,var.typecode(),vbytes)
873 else:
870 else:
874 print aformat % (vshape,vsize,var.typecode(),vbytes),
871 print aformat % (vshape,vsize,var.typecode(),vbytes),
875 if vbytes < Mb:
872 if vbytes < Mb:
876 print '(%s kb)' % (vbytes/kb,)
873 print '(%s kb)' % (vbytes/kb,)
877 else:
874 else:
878 print '(%s Mb)' % (vbytes/Mb,)
875 print '(%s Mb)' % (vbytes/Mb,)
879 else:
876 else:
880 vstr = str(var).replace('\n','\\n')
877 vstr = str(var).replace('\n','\\n')
881 if len(vstr) < 50:
878 if len(vstr) < 50:
882 print vstr
879 print vstr
883 else:
880 else:
884 printpl(vfmt_short)
881 printpl(vfmt_short)
885
882
886 def magic_reset(self, parameter_s=''):
883 def magic_reset(self, parameter_s=''):
887 """Resets the namespace by removing all names defined by the user.
884 """Resets the namespace by removing all names defined by the user.
888
885
889 Input/Output history are left around in case you need them."""
886 Input/Output history are left around in case you need them."""
890
887
891 ans = raw_input(
888 ans = raw_input(
892 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
889 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
893 if not ans.lower() == 'y':
890 if not ans.lower() == 'y':
894 print 'Nothing done.'
891 print 'Nothing done.'
895 return
892 return
896 user_ns = self.shell.user_ns
893 user_ns = self.shell.user_ns
897 for i in self.magic_who_ls():
894 for i in self.magic_who_ls():
898 del(user_ns[i])
895 del(user_ns[i])
899
896
900 def magic_config(self,parameter_s=''):
897 def magic_config(self,parameter_s=''):
901 """Show IPython's internal configuration."""
898 """Show IPython's internal configuration."""
902
899
903 page('Current configuration structure:\n'+
900 page('Current configuration structure:\n'+
904 pformat(self.shell.rc.dict()))
901 pformat(self.shell.rc.dict()))
905
902
906 def magic_logstart(self,parameter_s=''):
903 def magic_logstart(self,parameter_s=''):
907 """Start logging anywhere in a session.
904 """Start logging anywhere in a session.
908
905
909 %logstart [-o|-t] [log_name [log_mode]]
906 %logstart [-o|-t] [log_name [log_mode]]
910
907
911 If no name is given, it defaults to a file named 'ipython_log.py' in your
908 If no name is given, it defaults to a file named 'ipython_log.py' in your
912 current directory, in 'rotate' mode (see below).
909 current directory, in 'rotate' mode (see below).
913
910
914 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
911 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
915 history up to that point and then continues logging.
912 history up to that point and then continues logging.
916
913
917 %logstart takes a second optional parameter: logging mode. This can be one
914 %logstart takes a second optional parameter: logging mode. This can be one
918 of (note that the modes are given unquoted):\\
915 of (note that the modes are given unquoted):\\
919 append: well, that says it.\\
916 append: well, that says it.\\
920 backup: rename (if exists) to name~ and start name.\\
917 backup: rename (if exists) to name~ and start name.\\
921 global: single logfile in your home dir, appended to.\\
918 global: single logfile in your home dir, appended to.\\
922 over : overwrite existing log.\\
919 over : overwrite existing log.\\
923 rotate: create rotating logs name.1~, name.2~, etc.
920 rotate: create rotating logs name.1~, name.2~, etc.
924
921
925 Options:
922 Options:
926
923
927 -o: log also IPython's output. In this mode, all commands which
924 -o: log also IPython's output. In this mode, all commands which
928 generate an Out[NN] prompt are recorded to the logfile, right after
925 generate an Out[NN] prompt are recorded to the logfile, right after
929 their corresponding input line. The output lines are always
926 their corresponding input line. The output lines are always
930 prepended with a '#[Out]# ' marker, so that the log remains valid
927 prepended with a '#[Out]# ' marker, so that the log remains valid
931 Python code.
928 Python code.
932
929
933 Since this marker is always the same, filtering only the output from
930 Since this marker is always the same, filtering only the output from
934 a log is very easy, using for example a simple awk call:
931 a log is very easy, using for example a simple awk call:
935
932
936 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
933 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
937
934
938 -t: put timestamps before each input line logged (these are put in
935 -t: put timestamps before each input line logged (these are put in
939 comments)."""
936 comments)."""
940
937
941 opts,par = self.parse_options(parameter_s,'ot')
938 opts,par = self.parse_options(parameter_s,'ot')
942 log_output = 'o' in opts
939 log_output = 'o' in opts
943 timestamp = 't' in opts
940 timestamp = 't' in opts
944
941
945 rc = self.shell.rc
942 rc = self.shell.rc
946 logger = self.shell.logger
943 logger = self.shell.logger
947
944
948 # if no args are given, the defaults set in the logger constructor by
945 # if no args are given, the defaults set in the logger constructor by
949 # ipytohn remain valid
946 # ipytohn remain valid
950 if par:
947 if par:
951 try:
948 try:
952 logfname,logmode = par.split()
949 logfname,logmode = par.split()
953 except:
950 except:
954 logfname = par
951 logfname = par
955 logmode = 'backup'
952 logmode = 'backup'
956 else:
953 else:
957 logfname = logger.logfname
954 logfname = logger.logfname
958 logmode = logger.logmode
955 logmode = logger.logmode
959 # put logfname into rc struct as if it had been called on the command
956 # put logfname into rc struct as if it had been called on the command
960 # line, so it ends up saved in the log header Save it in case we need
957 # line, so it ends up saved in the log header Save it in case we need
961 # to restore it...
958 # to restore it...
962 old_logfile = rc.opts.get('logfile','')
959 old_logfile = rc.opts.get('logfile','')
963 if logfname:
960 if logfname:
964 logfname = os.path.expanduser(logfname)
961 logfname = os.path.expanduser(logfname)
965 rc.opts.logfile = logfname
962 rc.opts.logfile = logfname
966 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
963 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
967 try:
964 try:
968 started = logger.logstart(logfname,loghead,logmode,
965 started = logger.logstart(logfname,loghead,logmode,
969 log_output,timestamp)
966 log_output,timestamp)
970 except:
967 except:
971 rc.opts.logfile = old_logfile
968 rc.opts.logfile = old_logfile
972 warn("Couldn't start log: %s" % sys.exc_info()[1])
969 warn("Couldn't start log: %s" % sys.exc_info()[1])
973 else:
970 else:
974 # log input history up to this point, optionally interleaving
971 # log input history up to this point, optionally interleaving
975 # output if requested
972 # output if requested
976
973
977 if timestamp:
974 if timestamp:
978 # disable timestamping for the previous history, since we've
975 # disable timestamping for the previous history, since we've
979 # lost those already (no time machine here).
976 # lost those already (no time machine here).
980 logger.timestamp = False
977 logger.timestamp = False
981 if log_output:
978 if log_output:
982 log_write = logger.log_write
979 log_write = logger.log_write
983 input_hist = self.shell.input_hist
980 input_hist = self.shell.input_hist
984 output_hist = self.shell.output_hist
981 output_hist = self.shell.output_hist
985 for n in range(1,len(input_hist)-1):
982 for n in range(1,len(input_hist)-1):
986 log_write(input_hist[n].rstrip())
983 log_write(input_hist[n].rstrip())
987 if n in output_hist:
984 if n in output_hist:
988 log_write(repr(output_hist[n]),'output')
985 log_write(repr(output_hist[n]),'output')
989 else:
986 else:
990 logger.log_write(self.shell.input_hist[1:])
987 logger.log_write(self.shell.input_hist[1:])
991 if timestamp:
988 if timestamp:
992 # re-enable timestamping
989 # re-enable timestamping
993 logger.timestamp = True
990 logger.timestamp = True
994
991
995 print ('Activating auto-logging. '
992 print ('Activating auto-logging. '
996 'Current session state plus future input saved.')
993 'Current session state plus future input saved.')
997 logger.logstate()
994 logger.logstate()
998
995
999 def magic_logoff(self,parameter_s=''):
996 def magic_logoff(self,parameter_s=''):
1000 """Temporarily stop logging.
997 """Temporarily stop logging.
1001
998
1002 You must have previously started logging."""
999 You must have previously started logging."""
1003 self.shell.logger.switch_log(0)
1000 self.shell.logger.switch_log(0)
1004
1001
1005 def magic_logon(self,parameter_s=''):
1002 def magic_logon(self,parameter_s=''):
1006 """Restart logging.
1003 """Restart logging.
1007
1004
1008 This function is for restarting logging which you've temporarily
1005 This function is for restarting logging which you've temporarily
1009 stopped with %logoff. For starting logging for the first time, you
1006 stopped with %logoff. For starting logging for the first time, you
1010 must use the %logstart function, which allows you to specify an
1007 must use the %logstart function, which allows you to specify an
1011 optional log filename."""
1008 optional log filename."""
1012
1009
1013 self.shell.logger.switch_log(1)
1010 self.shell.logger.switch_log(1)
1014
1011
1015 def magic_logstate(self,parameter_s=''):
1012 def magic_logstate(self,parameter_s=''):
1016 """Print the status of the logging system."""
1013 """Print the status of the logging system."""
1017
1014
1018 self.shell.logger.logstate()
1015 self.shell.logger.logstate()
1019
1016
1020 def magic_pdb(self, parameter_s=''):
1017 def magic_pdb(self, parameter_s=''):
1021 """Control the calling of the pdb interactive debugger.
1018 """Control the calling of the pdb interactive debugger.
1022
1019
1023 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1020 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1024 argument it works as a toggle.
1021 argument it works as a toggle.
1025
1022
1026 When an exception is triggered, IPython can optionally call the
1023 When an exception is triggered, IPython can optionally call the
1027 interactive pdb debugger after the traceback printout. %pdb toggles
1024 interactive pdb debugger after the traceback printout. %pdb toggles
1028 this feature on and off."""
1025 this feature on and off."""
1029
1026
1030 par = parameter_s.strip().lower()
1027 par = parameter_s.strip().lower()
1031
1028
1032 if par:
1029 if par:
1033 try:
1030 try:
1034 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1031 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1035 except KeyError:
1032 except KeyError:
1036 print ('Incorrect argument. Use on/1, off/0, '
1033 print ('Incorrect argument. Use on/1, off/0, '
1037 'or nothing for a toggle.')
1034 'or nothing for a toggle.')
1038 return
1035 return
1039 else:
1036 else:
1040 # toggle
1037 # toggle
1041 new_pdb = not self.shell.InteractiveTB.call_pdb
1038 new_pdb = not self.shell.InteractiveTB.call_pdb
1042
1039
1043 # set on the shell
1040 # set on the shell
1044 self.shell.call_pdb = new_pdb
1041 self.shell.call_pdb = new_pdb
1045 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1042 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1046
1043
1047 def magic_prun(self, parameter_s ='',user_mode=1,
1044 def magic_prun(self, parameter_s ='',user_mode=1,
1048 opts=None,arg_lst=None,prog_ns=None):
1045 opts=None,arg_lst=None,prog_ns=None):
1049
1046
1050 """Run a statement through the python code profiler.
1047 """Run a statement through the python code profiler.
1051
1048
1052 Usage:\\
1049 Usage:\\
1053 %prun [options] statement
1050 %prun [options] statement
1054
1051
1055 The given statement (which doesn't require quote marks) is run via the
1052 The given statement (which doesn't require quote marks) is run via the
1056 python profiler in a manner similar to the profile.run() function.
1053 python profiler in a manner similar to the profile.run() function.
1057 Namespaces are internally managed to work correctly; profile.run
1054 Namespaces are internally managed to work correctly; profile.run
1058 cannot be used in IPython because it makes certain assumptions about
1055 cannot be used in IPython because it makes certain assumptions about
1059 namespaces which do not hold under IPython.
1056 namespaces which do not hold under IPython.
1060
1057
1061 Options:
1058 Options:
1062
1059
1063 -l <limit>: you can place restrictions on what or how much of the
1060 -l <limit>: you can place restrictions on what or how much of the
1064 profile gets printed. The limit value can be:
1061 profile gets printed. The limit value can be:
1065
1062
1066 * A string: only information for function names containing this string
1063 * A string: only information for function names containing this string
1067 is printed.
1064 is printed.
1068
1065
1069 * An integer: only these many lines are printed.
1066 * An integer: only these many lines are printed.
1070
1067
1071 * A float (between 0 and 1): this fraction of the report is printed
1068 * A float (between 0 and 1): this fraction of the report is printed
1072 (for example, use a limit of 0.4 to see the topmost 40% only).
1069 (for example, use a limit of 0.4 to see the topmost 40% only).
1073
1070
1074 You can combine several limits with repeated use of the option. For
1071 You can combine several limits with repeated use of the option. For
1075 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1072 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1076 information about class constructors.
1073 information about class constructors.
1077
1074
1078 -r: return the pstats.Stats object generated by the profiling. This
1075 -r: return the pstats.Stats object generated by the profiling. This
1079 object has all the information about the profile in it, and you can
1076 object has all the information about the profile in it, and you can
1080 later use it for further analysis or in other functions.
1077 later use it for further analysis or in other functions.
1081
1078
1082 Since magic functions have a particular form of calling which prevents
1079 Since magic functions have a particular form of calling which prevents
1083 you from writing something like:\\
1080 you from writing something like:\\
1084 In [1]: p = %prun -r print 4 # invalid!\\
1081 In [1]: p = %prun -r print 4 # invalid!\\
1085 you must instead use IPython's automatic variables to assign this:\\
1082 you must instead use IPython's automatic variables to assign this:\\
1086 In [1]: %prun -r print 4 \\
1083 In [1]: %prun -r print 4 \\
1087 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1084 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1088 In [2]: stats = _
1085 In [2]: stats = _
1089
1086
1090 If you really need to assign this value via an explicit function call,
1087 If you really need to assign this value via an explicit function call,
1091 you can always tap directly into the true name of the magic function
1088 you can always tap directly into the true name of the magic function
1092 by using the ipmagic function (which IPython automatically adds to the
1089 by using the ipmagic function (which IPython automatically adds to the
1093 builtins):\\
1090 builtins):\\
1094 In [3]: stats = ipmagic('prun','-r print 4')
1091 In [3]: stats = ipmagic('prun','-r print 4')
1095
1092
1096 You can type ipmagic? for more details on ipmagic.
1093 You can type ipmagic? for more details on ipmagic.
1097
1094
1098 -s <key>: sort profile by given key. You can provide more than one key
1095 -s <key>: sort profile by given key. You can provide more than one key
1099 by using the option several times: '-s key1 -s key2 -s key3...'. The
1096 by using the option several times: '-s key1 -s key2 -s key3...'. The
1100 default sorting key is 'time'.
1097 default sorting key is 'time'.
1101
1098
1102 The following is copied verbatim from the profile documentation
1099 The following is copied verbatim from the profile documentation
1103 referenced below:
1100 referenced below:
1104
1101
1105 When more than one key is provided, additional keys are used as
1102 When more than one key is provided, additional keys are used as
1106 secondary criteria when the there is equality in all keys selected
1103 secondary criteria when the there is equality in all keys selected
1107 before them.
1104 before them.
1108
1105
1109 Abbreviations can be used for any key names, as long as the
1106 Abbreviations can be used for any key names, as long as the
1110 abbreviation is unambiguous. The following are the keys currently
1107 abbreviation is unambiguous. The following are the keys currently
1111 defined:
1108 defined:
1112
1109
1113 Valid Arg Meaning\\
1110 Valid Arg Meaning\\
1114 "calls" call count\\
1111 "calls" call count\\
1115 "cumulative" cumulative time\\
1112 "cumulative" cumulative time\\
1116 "file" file name\\
1113 "file" file name\\
1117 "module" file name\\
1114 "module" file name\\
1118 "pcalls" primitive call count\\
1115 "pcalls" primitive call count\\
1119 "line" line number\\
1116 "line" line number\\
1120 "name" function name\\
1117 "name" function name\\
1121 "nfl" name/file/line\\
1118 "nfl" name/file/line\\
1122 "stdname" standard name\\
1119 "stdname" standard name\\
1123 "time" internal time
1120 "time" internal time
1124
1121
1125 Note that all sorts on statistics are in descending order (placing
1122 Note that all sorts on statistics are in descending order (placing
1126 most time consuming items first), where as name, file, and line number
1123 most time consuming items first), where as name, file, and line number
1127 searches are in ascending order (i.e., alphabetical). The subtle
1124 searches are in ascending order (i.e., alphabetical). The subtle
1128 distinction between "nfl" and "stdname" is that the standard name is a
1125 distinction between "nfl" and "stdname" is that the standard name is a
1129 sort of the name as printed, which means that the embedded line
1126 sort of the name as printed, which means that the embedded line
1130 numbers get compared in an odd way. For example, lines 3, 20, and 40
1127 numbers get compared in an odd way. For example, lines 3, 20, and 40
1131 would (if the file names were the same) appear in the string order
1128 would (if the file names were the same) appear in the string order
1132 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1129 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1133 line numbers. In fact, sort_stats("nfl") is the same as
1130 line numbers. In fact, sort_stats("nfl") is the same as
1134 sort_stats("name", "file", "line").
1131 sort_stats("name", "file", "line").
1135
1132
1136 -T <filename>: save profile results as shown on screen to a text
1133 -T <filename>: save profile results as shown on screen to a text
1137 file. The profile is still shown on screen.
1134 file. The profile is still shown on screen.
1138
1135
1139 -D <filename>: save (via dump_stats) profile statistics to given
1136 -D <filename>: save (via dump_stats) profile statistics to given
1140 filename. This data is in a format understod by the pstats module, and
1137 filename. This data is in a format understod by the pstats module, and
1141 is generated by a call to the dump_stats() method of profile
1138 is generated by a call to the dump_stats() method of profile
1142 objects. The profile is still shown on screen.
1139 objects. The profile is still shown on screen.
1143
1140
1144 If you want to run complete programs under the profiler's control, use
1141 If you want to run complete programs under the profiler's control, use
1145 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1142 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1146 contains profiler specific options as described here.
1143 contains profiler specific options as described here.
1147
1144
1148 You can read the complete documentation for the profile module with:\\
1145 You can read the complete documentation for the profile module with:\\
1149 In [1]: import profile; profile.help() """
1146 In [1]: import profile; profile.help() """
1150
1147
1151 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1148 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1152 # protect user quote marks
1149 # protect user quote marks
1153 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1150 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1154
1151
1155 if user_mode: # regular user call
1152 if user_mode: # regular user call
1156 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1153 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1157 list_all=1)
1154 list_all=1)
1158 namespace = self.shell.user_ns
1155 namespace = self.shell.user_ns
1159 else: # called to run a program by %run -p
1156 else: # called to run a program by %run -p
1160 try:
1157 try:
1161 filename = get_py_filename(arg_lst[0])
1158 filename = get_py_filename(arg_lst[0])
1162 except IOError,msg:
1159 except IOError,msg:
1163 error(msg)
1160 error(msg)
1164 return
1161 return
1165
1162
1166 arg_str = 'execfile(filename,prog_ns)'
1163 arg_str = 'execfile(filename,prog_ns)'
1167 namespace = locals()
1164 namespace = locals()
1168
1165
1169 opts.merge(opts_def)
1166 opts.merge(opts_def)
1170
1167
1171 prof = profile.Profile()
1168 prof = profile.Profile()
1172 try:
1169 try:
1173 prof = prof.runctx(arg_str,namespace,namespace)
1170 prof = prof.runctx(arg_str,namespace,namespace)
1174 sys_exit = ''
1171 sys_exit = ''
1175 except SystemExit:
1172 except SystemExit:
1176 sys_exit = """*** SystemExit exception caught in code being profiled."""
1173 sys_exit = """*** SystemExit exception caught in code being profiled."""
1177
1174
1178 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1175 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1179
1176
1180 lims = opts.l
1177 lims = opts.l
1181 if lims:
1178 if lims:
1182 lims = [] # rebuild lims with ints/floats/strings
1179 lims = [] # rebuild lims with ints/floats/strings
1183 for lim in opts.l:
1180 for lim in opts.l:
1184 try:
1181 try:
1185 lims.append(int(lim))
1182 lims.append(int(lim))
1186 except ValueError:
1183 except ValueError:
1187 try:
1184 try:
1188 lims.append(float(lim))
1185 lims.append(float(lim))
1189 except ValueError:
1186 except ValueError:
1190 lims.append(lim)
1187 lims.append(lim)
1191
1188
1192 # trap output
1189 # trap output
1193 sys_stdout = sys.stdout
1190 sys_stdout = sys.stdout
1194 stdout_trap = StringIO()
1191 stdout_trap = StringIO()
1195 try:
1192 try:
1196 sys.stdout = stdout_trap
1193 sys.stdout = stdout_trap
1197 stats.print_stats(*lims)
1194 stats.print_stats(*lims)
1198 finally:
1195 finally:
1199 sys.stdout = sys_stdout
1196 sys.stdout = sys_stdout
1200 output = stdout_trap.getvalue()
1197 output = stdout_trap.getvalue()
1201 output = output.rstrip()
1198 output = output.rstrip()
1202
1199
1203 page(output,screen_lines=self.shell.rc.screen_length)
1200 page(output,screen_lines=self.shell.rc.screen_length)
1204 print sys_exit,
1201 print sys_exit,
1205
1202
1206 dump_file = opts.D[0]
1203 dump_file = opts.D[0]
1207 text_file = opts.T[0]
1204 text_file = opts.T[0]
1208 if dump_file:
1205 if dump_file:
1209 prof.dump_stats(dump_file)
1206 prof.dump_stats(dump_file)
1210 print '\n*** Profile stats marshalled to file',\
1207 print '\n*** Profile stats marshalled to file',\
1211 `dump_file`+'.',sys_exit
1208 `dump_file`+'.',sys_exit
1212 if text_file:
1209 if text_file:
1213 file(text_file,'w').write(output)
1210 file(text_file,'w').write(output)
1214 print '\n*** Profile printout saved to text file',\
1211 print '\n*** Profile printout saved to text file',\
1215 `text_file`+'.',sys_exit
1212 `text_file`+'.',sys_exit
1216
1213
1217 if opts.has_key('r'):
1214 if opts.has_key('r'):
1218 return stats
1215 return stats
1219 else:
1216 else:
1220 return None
1217 return None
1221
1218
1222 def magic_run(self, parameter_s ='',runner=None):
1219 def magic_run(self, parameter_s ='',runner=None):
1223 """Run the named file inside IPython as a program.
1220 """Run the named file inside IPython as a program.
1224
1221
1225 Usage:\\
1222 Usage:\\
1226 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1223 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1227
1224
1228 Parameters after the filename are passed as command-line arguments to
1225 Parameters after the filename are passed as command-line arguments to
1229 the program (put in sys.argv). Then, control returns to IPython's
1226 the program (put in sys.argv). Then, control returns to IPython's
1230 prompt.
1227 prompt.
1231
1228
1232 This is similar to running at a system prompt:\\
1229 This is similar to running at a system prompt:\\
1233 $ python file args\\
1230 $ python file args\\
1234 but with the advantage of giving you IPython's tracebacks, and of
1231 but with the advantage of giving you IPython's tracebacks, and of
1235 loading all variables into your interactive namespace for further use
1232 loading all variables into your interactive namespace for further use
1236 (unless -p is used, see below).
1233 (unless -p is used, see below).
1237
1234
1238 The file is executed in a namespace initially consisting only of
1235 The file is executed in a namespace initially consisting only of
1239 __name__=='__main__' and sys.argv constructed as indicated. It thus
1236 __name__=='__main__' and sys.argv constructed as indicated. It thus
1240 sees its environment as if it were being run as a stand-alone
1237 sees its environment as if it were being run as a stand-alone
1241 program. But after execution, the IPython interactive namespace gets
1238 program. But after execution, the IPython interactive namespace gets
1242 updated with all variables defined in the program (except for __name__
1239 updated with all variables defined in the program (except for __name__
1243 and sys.argv). This allows for very convenient loading of code for
1240 and sys.argv). This allows for very convenient loading of code for
1244 interactive work, while giving each program a 'clean sheet' to run in.
1241 interactive work, while giving each program a 'clean sheet' to run in.
1245
1242
1246 Options:
1243 Options:
1247
1244
1248 -n: __name__ is NOT set to '__main__', but to the running file's name
1245 -n: __name__ is NOT set to '__main__', but to the running file's name
1249 without extension (as python does under import). This allows running
1246 without extension (as python does under import). This allows running
1250 scripts and reloading the definitions in them without calling code
1247 scripts and reloading the definitions in them without calling code
1251 protected by an ' if __name__ == "__main__" ' clause.
1248 protected by an ' if __name__ == "__main__" ' clause.
1252
1249
1253 -i: run the file in IPython's namespace instead of an empty one. This
1250 -i: run the file in IPython's namespace instead of an empty one. This
1254 is useful if you are experimenting with code written in a text editor
1251 is useful if you are experimenting with code written in a text editor
1255 which depends on variables defined interactively.
1252 which depends on variables defined interactively.
1256
1253
1257 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1254 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1258 being run. This is particularly useful if IPython is being used to
1255 being run. This is particularly useful if IPython is being used to
1259 run unittests, which always exit with a sys.exit() call. In such
1256 run unittests, which always exit with a sys.exit() call. In such
1260 cases you are interested in the output of the test results, not in
1257 cases you are interested in the output of the test results, not in
1261 seeing a traceback of the unittest module.
1258 seeing a traceback of the unittest module.
1262
1259
1263 -t: print timing information at the end of the run. IPython will give
1260 -t: print timing information at the end of the run. IPython will give
1264 you an estimated CPU time consumption for your script, which under
1261 you an estimated CPU time consumption for your script, which under
1265 Unix uses the resource module to avoid the wraparound problems of
1262 Unix uses the resource module to avoid the wraparound problems of
1266 time.clock(). Under Unix, an estimate of time spent on system tasks
1263 time.clock(). Under Unix, an estimate of time spent on system tasks
1267 is also given (for Windows platforms this is reported as 0.0).
1264 is also given (for Windows platforms this is reported as 0.0).
1268
1265
1269 If -t is given, an additional -N<N> option can be given, where <N>
1266 If -t is given, an additional -N<N> option can be given, where <N>
1270 must be an integer indicating how many times you want the script to
1267 must be an integer indicating how many times you want the script to
1271 run. The final timing report will include total and per run results.
1268 run. The final timing report will include total and per run results.
1272
1269
1273 For example (testing the script uniq_stable.py):
1270 For example (testing the script uniq_stable.py):
1274
1271
1275 In [1]: run -t uniq_stable
1272 In [1]: run -t uniq_stable
1276
1273
1277 IPython CPU timings (estimated):\\
1274 IPython CPU timings (estimated):\\
1278 User : 0.19597 s.\\
1275 User : 0.19597 s.\\
1279 System: 0.0 s.\\
1276 System: 0.0 s.\\
1280
1277
1281 In [2]: run -t -N5 uniq_stable
1278 In [2]: run -t -N5 uniq_stable
1282
1279
1283 IPython CPU timings (estimated):\\
1280 IPython CPU timings (estimated):\\
1284 Total runs performed: 5\\
1281 Total runs performed: 5\\
1285 Times : Total Per run\\
1282 Times : Total Per run\\
1286 User : 0.910862 s, 0.1821724 s.\\
1283 User : 0.910862 s, 0.1821724 s.\\
1287 System: 0.0 s, 0.0 s.
1284 System: 0.0 s, 0.0 s.
1288
1285
1289 -d: run your program under the control of pdb, the Python debugger.
1286 -d: run your program under the control of pdb, the Python debugger.
1290 This allows you to execute your program step by step, watch variables,
1287 This allows you to execute your program step by step, watch variables,
1291 etc. Internally, what IPython does is similar to calling:
1288 etc. Internally, what IPython does is similar to calling:
1292
1289
1293 pdb.run('execfile("YOURFILENAME")')
1290 pdb.run('execfile("YOURFILENAME")')
1294
1291
1295 with a breakpoint set on line 1 of your file. You can change the line
1292 with a breakpoint set on line 1 of your file. You can change the line
1296 number for this automatic breakpoint to be <N> by using the -bN option
1293 number for this automatic breakpoint to be <N> by using the -bN option
1297 (where N must be an integer). For example:
1294 (where N must be an integer). For example:
1298
1295
1299 %run -d -b40 myscript
1296 %run -d -b40 myscript
1300
1297
1301 will set the first breakpoint at line 40 in myscript.py. Note that
1298 will set the first breakpoint at line 40 in myscript.py. Note that
1302 the first breakpoint must be set on a line which actually does
1299 the first breakpoint must be set on a line which actually does
1303 something (not a comment or docstring) for it to stop execution.
1300 something (not a comment or docstring) for it to stop execution.
1304
1301
1305 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1302 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1306 first enter 'c' (without qoutes) to start execution up to the first
1303 first enter 'c' (without qoutes) to start execution up to the first
1307 breakpoint.
1304 breakpoint.
1308
1305
1309 Entering 'help' gives information about the use of the debugger. You
1306 Entering 'help' gives information about the use of the debugger. You
1310 can easily see pdb's full documentation with "import pdb;pdb.help()"
1307 can easily see pdb's full documentation with "import pdb;pdb.help()"
1311 at a prompt.
1308 at a prompt.
1312
1309
1313 -p: run program under the control of the Python profiler module (which
1310 -p: run program under the control of the Python profiler module (which
1314 prints a detailed report of execution times, function calls, etc).
1311 prints a detailed report of execution times, function calls, etc).
1315
1312
1316 You can pass other options after -p which affect the behavior of the
1313 You can pass other options after -p which affect the behavior of the
1317 profiler itself. See the docs for %prun for details.
1314 profiler itself. See the docs for %prun for details.
1318
1315
1319 In this mode, the program's variables do NOT propagate back to the
1316 In this mode, the program's variables do NOT propagate back to the
1320 IPython interactive namespace (because they remain in the namespace
1317 IPython interactive namespace (because they remain in the namespace
1321 where the profiler executes them).
1318 where the profiler executes them).
1322
1319
1323 Internally this triggers a call to %prun, see its documentation for
1320 Internally this triggers a call to %prun, see its documentation for
1324 details on the options available specifically for profiling."""
1321 details on the options available specifically for profiling."""
1325
1322
1326 # get arguments and set sys.argv for program to be run.
1323 # get arguments and set sys.argv for program to be run.
1327 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1324 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1328 mode='list',list_all=1)
1325 mode='list',list_all=1)
1329
1326
1330 try:
1327 try:
1331 filename = get_py_filename(arg_lst[0])
1328 filename = get_py_filename(arg_lst[0])
1332 except IndexError:
1329 except IndexError:
1333 warn('you must provide at least a filename.')
1330 warn('you must provide at least a filename.')
1334 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1331 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1335 return
1332 return
1336 except IOError,msg:
1333 except IOError,msg:
1337 error(msg)
1334 error(msg)
1338 return
1335 return
1339
1336
1340 # Control the response to exit() calls made by the script being run
1337 # Control the response to exit() calls made by the script being run
1341 exit_ignore = opts.has_key('e')
1338 exit_ignore = opts.has_key('e')
1342
1339
1343 # Make sure that the running script gets a proper sys.argv as if it
1340 # Make sure that the running script gets a proper sys.argv as if it
1344 # were run from a system shell.
1341 # were run from a system shell.
1345 save_argv = sys.argv # save it for later restoring
1342 save_argv = sys.argv # save it for later restoring
1346 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1343 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1347
1344
1348 if opts.has_key('i'):
1345 if opts.has_key('i'):
1349 prog_ns = self.shell.user_ns
1346 prog_ns = self.shell.user_ns
1350 __name__save = self.shell.user_ns['__name__']
1347 __name__save = self.shell.user_ns['__name__']
1351 prog_ns['__name__'] = '__main__'
1348 prog_ns['__name__'] = '__main__'
1352 else:
1349 else:
1353 if opts.has_key('n'):
1350 if opts.has_key('n'):
1354 name = os.path.splitext(os.path.basename(filename))[0]
1351 name = os.path.splitext(os.path.basename(filename))[0]
1355 else:
1352 else:
1356 name = '__main__'
1353 name = '__main__'
1357 prog_ns = {'__name__':name}
1354 prog_ns = {'__name__':name}
1358
1355
1359 # pickle fix. See iplib for an explanation
1356 # pickle fix. See iplib for an explanation. But we need to make sure
1357 # that, if we overwrite __main__, we replace it at the end
1358 if prog_ns['__name__'] == '__main__':
1359 restore_main = sys.modules['__main__']
1360 else:
1361 restore_main = False
1362
1360 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1363 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1361
1364
1362 stats = None
1365 stats = None
1363 try:
1366 try:
1364 if opts.has_key('p'):
1367 if opts.has_key('p'):
1365 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1368 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1366 else:
1369 else:
1367 if opts.has_key('d'):
1370 if opts.has_key('d'):
1368 deb = Debugger.Pdb(self.shell.rc.colors)
1371 deb = Debugger.Pdb(self.shell.rc.colors)
1369 # reset Breakpoint state, which is moronically kept
1372 # reset Breakpoint state, which is moronically kept
1370 # in a class
1373 # in a class
1371 bdb.Breakpoint.next = 1
1374 bdb.Breakpoint.next = 1
1372 bdb.Breakpoint.bplist = {}
1375 bdb.Breakpoint.bplist = {}
1373 bdb.Breakpoint.bpbynumber = [None]
1376 bdb.Breakpoint.bpbynumber = [None]
1374 # Set an initial breakpoint to stop execution
1377 # Set an initial breakpoint to stop execution
1375 maxtries = 10
1378 maxtries = 10
1376 bp = int(opts.get('b',[1])[0])
1379 bp = int(opts.get('b',[1])[0])
1377 checkline = deb.checkline(filename,bp)
1380 checkline = deb.checkline(filename,bp)
1378 if not checkline:
1381 if not checkline:
1379 for bp in range(bp+1,bp+maxtries+1):
1382 for bp in range(bp+1,bp+maxtries+1):
1380 if deb.checkline(filename,bp):
1383 if deb.checkline(filename,bp):
1381 break
1384 break
1382 else:
1385 else:
1383 msg = ("\nI failed to find a valid line to set "
1386 msg = ("\nI failed to find a valid line to set "
1384 "a breakpoint\n"
1387 "a breakpoint\n"
1385 "after trying up to line: %s.\n"
1388 "after trying up to line: %s.\n"
1386 "Please set a valid breakpoint manually "
1389 "Please set a valid breakpoint manually "
1387 "with the -b option." % bp)
1390 "with the -b option." % bp)
1388 error(msg)
1391 error(msg)
1389 return
1392 return
1390 # if we find a good linenumber, set the breakpoint
1393 # if we find a good linenumber, set the breakpoint
1391 deb.do_break('%s:%s' % (filename,bp))
1394 deb.do_break('%s:%s' % (filename,bp))
1392 # Start file run
1395 # Start file run
1393 print "NOTE: Enter 'c' at the",
1396 print "NOTE: Enter 'c' at the",
1394 print "ipdb> prompt to start your script."
1397 print "ipdb> prompt to start your script."
1395 try:
1398 try:
1396 deb.run('execfile("%s")' % filename,prog_ns)
1399 deb.run('execfile("%s")' % filename,prog_ns)
1397 except:
1400 except:
1398 etype, value, tb = sys.exc_info()
1401 etype, value, tb = sys.exc_info()
1399 # Skip three frames in the traceback: the %run one,
1402 # Skip three frames in the traceback: the %run one,
1400 # one inside bdb.py, and the command-line typed by the
1403 # one inside bdb.py, and the command-line typed by the
1401 # user (run by exec in pdb itself).
1404 # user (run by exec in pdb itself).
1402 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1405 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1403 else:
1406 else:
1404 if runner is None:
1407 if runner is None:
1405 runner = self.shell.safe_execfile
1408 runner = self.shell.safe_execfile
1406 if opts.has_key('t'):
1409 if opts.has_key('t'):
1407 try:
1410 try:
1408 nruns = int(opts['N'][0])
1411 nruns = int(opts['N'][0])
1409 if nruns < 1:
1412 if nruns < 1:
1410 error('Number of runs must be >=1')
1413 error('Number of runs must be >=1')
1411 return
1414 return
1412 except (KeyError):
1415 except (KeyError):
1413 nruns = 1
1416 nruns = 1
1414 if nruns == 1:
1417 if nruns == 1:
1415 t0 = clock2()
1418 t0 = clock2()
1416 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1419 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1417 t1 = clock2()
1420 t1 = clock2()
1418 t_usr = t1[0]-t0[0]
1421 t_usr = t1[0]-t0[0]
1419 t_sys = t1[1]-t1[1]
1422 t_sys = t1[1]-t1[1]
1420 print "\nIPython CPU timings (estimated):"
1423 print "\nIPython CPU timings (estimated):"
1421 print " User : %10s s." % t_usr
1424 print " User : %10s s." % t_usr
1422 print " System: %10s s." % t_sys
1425 print " System: %10s s." % t_sys
1423 else:
1426 else:
1424 runs = range(nruns)
1427 runs = range(nruns)
1425 t0 = clock2()
1428 t0 = clock2()
1426 for nr in runs:
1429 for nr in runs:
1427 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1430 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1428 t1 = clock2()
1431 t1 = clock2()
1429 t_usr = t1[0]-t0[0]
1432 t_usr = t1[0]-t0[0]
1430 t_sys = t1[1]-t1[1]
1433 t_sys = t1[1]-t1[1]
1431 print "\nIPython CPU timings (estimated):"
1434 print "\nIPython CPU timings (estimated):"
1432 print "Total runs performed:",nruns
1435 print "Total runs performed:",nruns
1433 print " Times : %10s %10s" % ('Total','Per run')
1436 print " Times : %10s %10s" % ('Total','Per run')
1434 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1437 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1435 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1438 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1436
1439
1437 else:
1440 else:
1438 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1441 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1439 if opts.has_key('i'):
1442 if opts.has_key('i'):
1440 self.shell.user_ns['__name__'] = __name__save
1443 self.shell.user_ns['__name__'] = __name__save
1441 else:
1444 else:
1442 # update IPython interactive namespace
1445 # update IPython interactive namespace
1443 del prog_ns['__name__']
1446 del prog_ns['__name__']
1444 self.shell.user_ns.update(prog_ns)
1447 self.shell.user_ns.update(prog_ns)
1445 finally:
1448 finally:
1446 sys.argv = save_argv
1449 sys.argv = save_argv
1450 if restore_main:
1451 sys.modules['__main__'] = restore_main
1447 return stats
1452 return stats
1448
1453
1449 def magic_runlog(self, parameter_s =''):
1454 def magic_runlog(self, parameter_s =''):
1450 """Run files as logs.
1455 """Run files as logs.
1451
1456
1452 Usage:\\
1457 Usage:\\
1453 %runlog file1 file2 ...
1458 %runlog file1 file2 ...
1454
1459
1455 Run the named files (treating them as log files) in sequence inside
1460 Run the named files (treating them as log files) in sequence inside
1456 the interpreter, and return to the prompt. This is much slower than
1461 the interpreter, and return to the prompt. This is much slower than
1457 %run because each line is executed in a try/except block, but it
1462 %run because each line is executed in a try/except block, but it
1458 allows running files with syntax errors in them.
1463 allows running files with syntax errors in them.
1459
1464
1460 Normally IPython will guess when a file is one of its own logfiles, so
1465 Normally IPython will guess when a file is one of its own logfiles, so
1461 you can typically use %run even for logs. This shorthand allows you to
1466 you can typically use %run even for logs. This shorthand allows you to
1462 force any file to be treated as a log file."""
1467 force any file to be treated as a log file."""
1463
1468
1464 for f in parameter_s.split():
1469 for f in parameter_s.split():
1465 self.shell.safe_execfile(f,self.shell.user_ns,
1470 self.shell.safe_execfile(f,self.shell.user_ns,
1466 self.shell.user_ns,islog=1)
1471 self.shell.user_ns,islog=1)
1467
1472
1468 def magic_time(self,parameter_s = ''):
1473 def magic_time(self,parameter_s = ''):
1469 """Time execution of a Python statement or expression.
1474 """Time execution of a Python statement or expression.
1470
1475
1471 The CPU and wall clock times are printed, and the value of the
1476 The CPU and wall clock times are printed, and the value of the
1472 expression (if any) is returned. Note that under Win32, system time
1477 expression (if any) is returned. Note that under Win32, system time
1473 is always reported as 0, since it can not be measured.
1478 is always reported as 0, since it can not be measured.
1474
1479
1475 This function provides very basic timing functionality. In Python
1480 This function provides very basic timing functionality. In Python
1476 2.3, the timeit module offers more control and sophistication, but for
1481 2.3, the timeit module offers more control and sophistication, but for
1477 now IPython supports Python 2.2, so we can not rely on timeit being
1482 now IPython supports Python 2.2, so we can not rely on timeit being
1478 present.
1483 present.
1479
1484
1480 Some examples:
1485 Some examples:
1481
1486
1482 In [1]: time 2**128
1487 In [1]: time 2**128
1483 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1488 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1484 Wall time: 0.00
1489 Wall time: 0.00
1485 Out[1]: 340282366920938463463374607431768211456L
1490 Out[1]: 340282366920938463463374607431768211456L
1486
1491
1487 In [2]: n = 1000000
1492 In [2]: n = 1000000
1488
1493
1489 In [3]: time sum(range(n))
1494 In [3]: time sum(range(n))
1490 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1495 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1491 Wall time: 1.37
1496 Wall time: 1.37
1492 Out[3]: 499999500000L
1497 Out[3]: 499999500000L
1493
1498
1494 In [4]: time print 'hello world'
1499 In [4]: time print 'hello world'
1495 hello world
1500 hello world
1496 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1501 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1497 Wall time: 0.00
1502 Wall time: 0.00
1498 """
1503 """
1499
1504
1500 # fail immediately if the given expression can't be compiled
1505 # fail immediately if the given expression can't be compiled
1501 try:
1506 try:
1502 mode = 'eval'
1507 mode = 'eval'
1503 code = compile(parameter_s,'<timed eval>',mode)
1508 code = compile(parameter_s,'<timed eval>',mode)
1504 except SyntaxError:
1509 except SyntaxError:
1505 mode = 'exec'
1510 mode = 'exec'
1506 code = compile(parameter_s,'<timed exec>',mode)
1511 code = compile(parameter_s,'<timed exec>',mode)
1507 # skew measurement as little as possible
1512 # skew measurement as little as possible
1508 glob = self.shell.user_ns
1513 glob = self.shell.user_ns
1509 clk = clock2
1514 clk = clock2
1510 wtime = time.time
1515 wtime = time.time
1511 # time execution
1516 # time execution
1512 wall_st = wtime()
1517 wall_st = wtime()
1513 if mode=='eval':
1518 if mode=='eval':
1514 st = clk()
1519 st = clk()
1515 out = eval(code,glob)
1520 out = eval(code,glob)
1516 end = clk()
1521 end = clk()
1517 else:
1522 else:
1518 st = clk()
1523 st = clk()
1519 exec code in glob
1524 exec code in glob
1520 end = clk()
1525 end = clk()
1521 out = None
1526 out = None
1522 wall_end = wtime()
1527 wall_end = wtime()
1523 # Compute actual times and report
1528 # Compute actual times and report
1524 wall_time = wall_end-wall_st
1529 wall_time = wall_end-wall_st
1525 cpu_user = end[0]-st[0]
1530 cpu_user = end[0]-st[0]
1526 cpu_sys = end[1]-st[1]
1531 cpu_sys = end[1]-st[1]
1527 cpu_tot = cpu_user+cpu_sys
1532 cpu_tot = cpu_user+cpu_sys
1528 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1533 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1529 (cpu_user,cpu_sys,cpu_tot)
1534 (cpu_user,cpu_sys,cpu_tot)
1530 print "Wall time: %.2f" % wall_time
1535 print "Wall time: %.2f" % wall_time
1531 return out
1536 return out
1532
1537
1533 def magic_macro(self,parameter_s = ''):
1538 def magic_macro(self,parameter_s = ''):
1534 """Define a set of input lines as a macro for future re-execution.
1539 """Define a set of input lines as a macro for future re-execution.
1535
1540
1536 Usage:\\
1541 Usage:\\
1537 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1542 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1538
1543
1539 This will define a global variable called `name` which is a string
1544 This will define a global variable called `name` which is a string
1540 made of joining the slices and lines you specify (n1,n2,... numbers
1545 made of joining the slices and lines you specify (n1,n2,... numbers
1541 above) from your input history into a single string. This variable
1546 above) from your input history into a single string. This variable
1542 acts like an automatic function which re-executes those lines as if
1547 acts like an automatic function which re-executes those lines as if
1543 you had typed them. You just type 'name' at the prompt and the code
1548 you had typed them. You just type 'name' at the prompt and the code
1544 executes.
1549 executes.
1545
1550
1546 Note that the slices use the standard Python slicing notation (5:8
1551 Note that the slices use the standard Python slicing notation (5:8
1547 means include lines numbered 5,6,7).
1552 means include lines numbered 5,6,7).
1548
1553
1549 For example, if your history contains (%hist prints it):
1554 For example, if your history contains (%hist prints it):
1550
1555
1551 44: x=1\\
1556 44: x=1\\
1552 45: y=3\\
1557 45: y=3\\
1553 46: z=x+y\\
1558 46: z=x+y\\
1554 47: print x\\
1559 47: print x\\
1555 48: a=5\\
1560 48: a=5\\
1556 49: print 'x',x,'y',y\\
1561 49: print 'x',x,'y',y\\
1557
1562
1558 you can create a macro with lines 44 through 47 (included) and line 49
1563 you can create a macro with lines 44 through 47 (included) and line 49
1559 called my_macro with:
1564 called my_macro with:
1560
1565
1561 In [51]: %macro my_macro 44:48 49
1566 In [51]: %macro my_macro 44:48 49
1562
1567
1563 Now, typing `my_macro` (without quotes) will re-execute all this code
1568 Now, typing `my_macro` (without quotes) will re-execute all this code
1564 in one pass.
1569 in one pass.
1565
1570
1566 You don't need to give the line-numbers in order, and any given line
1571 You don't need to give the line-numbers in order, and any given line
1567 number can appear multiple times. You can assemble macros with any
1572 number can appear multiple times. You can assemble macros with any
1568 lines from your input history in any order.
1573 lines from your input history in any order.
1569
1574
1570 The macro is a simple object which holds its value in an attribute,
1575 The macro is a simple object which holds its value in an attribute,
1571 but IPython's display system checks for macros and executes them as
1576 but IPython's display system checks for macros and executes them as
1572 code instead of printing them when you type their name.
1577 code instead of printing them when you type their name.
1573
1578
1574 You can view a macro's contents by explicitly printing it with:
1579 You can view a macro's contents by explicitly printing it with:
1575
1580
1576 'print macro_name'.
1581 'print macro_name'.
1577
1582
1578 For one-off cases which DON'T contain magic function calls in them you
1583 For one-off cases which DON'T contain magic function calls in them you
1579 can obtain similar results by explicitly executing slices from your
1584 can obtain similar results by explicitly executing slices from your
1580 input history with:
1585 input history with:
1581
1586
1582 In [60]: exec In[44:48]+In[49]"""
1587 In [60]: exec In[44:48]+In[49]"""
1583
1588
1584 args = parameter_s.split()
1589 args = parameter_s.split()
1585 name,ranges = args[0], args[1:]
1590 name,ranges = args[0], args[1:]
1586 #print 'rng',ranges # dbg
1591 #print 'rng',ranges # dbg
1587 lines = self.extract_input_slices(ranges)
1592 lines = self.extract_input_slices(ranges)
1588 macro = Macro(lines)
1593 macro = Macro(lines)
1589 self.shell.user_ns.update({name:macro})
1594 self.shell.user_ns.update({name:macro})
1590 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1595 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1591 print 'Macro contents:'
1596 print 'Macro contents:'
1592 print macro,
1597 print macro,
1593
1598
1594 def magic_save(self,parameter_s = ''):
1599 def magic_save(self,parameter_s = ''):
1595 """Save a set of lines to a given filename.
1600 """Save a set of lines to a given filename.
1596
1601
1597 Usage:\\
1602 Usage:\\
1598 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1603 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1599
1604
1600 This function uses the same syntax as %macro for line extraction, but
1605 This function uses the same syntax as %macro for line extraction, but
1601 instead of creating a macro it saves the resulting string to the
1606 instead of creating a macro it saves the resulting string to the
1602 filename you specify.
1607 filename you specify.
1603
1608
1604 It adds a '.py' extension to the file if you don't do so yourself, and
1609 It adds a '.py' extension to the file if you don't do so yourself, and
1605 it asks for confirmation before overwriting existing files."""
1610 it asks for confirmation before overwriting existing files."""
1606
1611
1607 args = parameter_s.split()
1612 args = parameter_s.split()
1608 fname,ranges = args[0], args[1:]
1613 fname,ranges = args[0], args[1:]
1609 if not fname.endswith('.py'):
1614 if not fname.endswith('.py'):
1610 fname += '.py'
1615 fname += '.py'
1611 if os.path.isfile(fname):
1616 if os.path.isfile(fname):
1612 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1617 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1613 if ans.lower() not in ['y','yes']:
1618 if ans.lower() not in ['y','yes']:
1614 print 'Operation cancelled.'
1619 print 'Operation cancelled.'
1615 return
1620 return
1616 cmds = ''.join(self.extract_input_slices(ranges))
1621 cmds = ''.join(self.extract_input_slices(ranges))
1617 f = file(fname,'w')
1622 f = file(fname,'w')
1618 f.write(cmds)
1623 f.write(cmds)
1619 f.close()
1624 f.close()
1620 print 'The following commands were written to file `%s`:' % fname
1625 print 'The following commands were written to file `%s`:' % fname
1621 print cmds
1626 print cmds
1622
1627
1623 def magic_ed(self,parameter_s = ''):
1628 def magic_ed(self,parameter_s = ''):
1624 """Alias to %edit."""
1629 """Alias to %edit."""
1625 return self.magic_edit(parameter_s)
1630 return self.magic_edit(parameter_s)
1626
1631
1627 def magic_edit(self,parameter_s = '',last_call=['','']):
1632 def magic_edit(self,parameter_s = '',last_call=['','']):
1628 """Bring up an editor and execute the resulting code.
1633 """Bring up an editor and execute the resulting code.
1629
1634
1630 Usage:
1635 Usage:
1631 %edit [options] [args]
1636 %edit [options] [args]
1632
1637
1633 %edit runs IPython's editor hook. The default version of this hook is
1638 %edit runs IPython's editor hook. The default version of this hook is
1634 set to call the __IPYTHON__.rc.editor command. This is read from your
1639 set to call the __IPYTHON__.rc.editor command. This is read from your
1635 environment variable $EDITOR. If this isn't found, it will default to
1640 environment variable $EDITOR. If this isn't found, it will default to
1636 vi under Linux/Unix and to notepad under Windows. See the end of this
1641 vi under Linux/Unix and to notepad under Windows. See the end of this
1637 docstring for how to change the editor hook.
1642 docstring for how to change the editor hook.
1638
1643
1639 You can also set the value of this editor via the command line option
1644 You can also set the value of this editor via the command line option
1640 '-editor' or in your ipythonrc file. This is useful if you wish to use
1645 '-editor' or in your ipythonrc file. This is useful if you wish to use
1641 specifically for IPython an editor different from your typical default
1646 specifically for IPython an editor different from your typical default
1642 (and for Windows users who typically don't set environment variables).
1647 (and for Windows users who typically don't set environment variables).
1643
1648
1644 This command allows you to conveniently edit multi-line code right in
1649 This command allows you to conveniently edit multi-line code right in
1645 your IPython session.
1650 your IPython session.
1646
1651
1647 If called without arguments, %edit opens up an empty editor with a
1652 If called without arguments, %edit opens up an empty editor with a
1648 temporary file and will execute the contents of this file when you
1653 temporary file and will execute the contents of this file when you
1649 close it (don't forget to save it!).
1654 close it (don't forget to save it!).
1650
1655
1651 Options:
1656 Options:
1652
1657
1653 -p: this will call the editor with the same data as the previous time
1658 -p: this will call the editor with the same data as the previous time
1654 it was used, regardless of how long ago (in your current session) it
1659 it was used, regardless of how long ago (in your current session) it
1655 was.
1660 was.
1656
1661
1657 -x: do not execute the edited code immediately upon exit. This is
1662 -x: do not execute the edited code immediately upon exit. This is
1658 mainly useful if you are editing programs which need to be called with
1663 mainly useful if you are editing programs which need to be called with
1659 command line arguments, which you can then do using %run.
1664 command line arguments, which you can then do using %run.
1660
1665
1661 Arguments:
1666 Arguments:
1662
1667
1663 If arguments are given, the following possibilites exist:
1668 If arguments are given, the following possibilites exist:
1664
1669
1665 - The arguments are numbers or pairs of colon-separated numbers (like
1670 - The arguments are numbers or pairs of colon-separated numbers (like
1666 1 4:8 9). These are interpreted as lines of previous input to be
1671 1 4:8 9). These are interpreted as lines of previous input to be
1667 loaded into the editor. The syntax is the same of the %macro command.
1672 loaded into the editor. The syntax is the same of the %macro command.
1668
1673
1669 - If the argument doesn't start with a number, it is evaluated as a
1674 - If the argument doesn't start with a number, it is evaluated as a
1670 variable and its contents loaded into the editor. You can thus edit
1675 variable and its contents loaded into the editor. You can thus edit
1671 any string which contains python code (including the result of
1676 any string which contains python code (including the result of
1672 previous edits).
1677 previous edits).
1673
1678
1674 - If the argument is the name of an object (other than a string),
1679 - If the argument is the name of an object (other than a string),
1675 IPython will try to locate the file where it was defined and open the
1680 IPython will try to locate the file where it was defined and open the
1676 editor at the point where it is defined. You can use `%edit function`
1681 editor at the point where it is defined. You can use `%edit function`
1677 to load an editor exactly at the point where 'function' is defined,
1682 to load an editor exactly at the point where 'function' is defined,
1678 edit it and have the file be executed automatically.
1683 edit it and have the file be executed automatically.
1679
1684
1680 Note: opening at an exact line is only supported under Unix, and some
1685 Note: opening at an exact line is only supported under Unix, and some
1681 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1686 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1682 '+NUMBER' parameter necessary for this feature. Good editors like
1687 '+NUMBER' parameter necessary for this feature. Good editors like
1683 (X)Emacs, vi, jed, pico and joe all do.
1688 (X)Emacs, vi, jed, pico and joe all do.
1684
1689
1685 - If the argument is not found as a variable, IPython will look for a
1690 - If the argument is not found as a variable, IPython will look for a
1686 file with that name (adding .py if necessary) and load it into the
1691 file with that name (adding .py if necessary) and load it into the
1687 editor. It will execute its contents with execfile() when you exit,
1692 editor. It will execute its contents with execfile() when you exit,
1688 loading any code in the file into your interactive namespace.
1693 loading any code in the file into your interactive namespace.
1689
1694
1690 After executing your code, %edit will return as output the code you
1695 After executing your code, %edit will return as output the code you
1691 typed in the editor (except when it was an existing file). This way
1696 typed in the editor (except when it was an existing file). This way
1692 you can reload the code in further invocations of %edit as a variable,
1697 you can reload the code in further invocations of %edit as a variable,
1693 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1698 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1694 the output.
1699 the output.
1695
1700
1696 Note that %edit is also available through the alias %ed.
1701 Note that %edit is also available through the alias %ed.
1697
1702
1698 This is an example of creating a simple function inside the editor and
1703 This is an example of creating a simple function inside the editor and
1699 then modifying it. First, start up the editor:
1704 then modifying it. First, start up the editor:
1700
1705
1701 In [1]: ed\\
1706 In [1]: ed\\
1702 Editing... done. Executing edited code...\\
1707 Editing... done. Executing edited code...\\
1703 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1708 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1704
1709
1705 We can then call the function foo():
1710 We can then call the function foo():
1706
1711
1707 In [2]: foo()\\
1712 In [2]: foo()\\
1708 foo() was defined in an editing session
1713 foo() was defined in an editing session
1709
1714
1710 Now we edit foo. IPython automatically loads the editor with the
1715 Now we edit foo. IPython automatically loads the editor with the
1711 (temporary) file where foo() was previously defined:
1716 (temporary) file where foo() was previously defined:
1712
1717
1713 In [3]: ed foo\\
1718 In [3]: ed foo\\
1714 Editing... done. Executing edited code...
1719 Editing... done. Executing edited code...
1715
1720
1716 And if we call foo() again we get the modified version:
1721 And if we call foo() again we get the modified version:
1717
1722
1718 In [4]: foo()\\
1723 In [4]: foo()\\
1719 foo() has now been changed!
1724 foo() has now been changed!
1720
1725
1721 Here is an example of how to edit a code snippet successive
1726 Here is an example of how to edit a code snippet successive
1722 times. First we call the editor:
1727 times. First we call the editor:
1723
1728
1724 In [8]: ed\\
1729 In [8]: ed\\
1725 Editing... done. Executing edited code...\\
1730 Editing... done. Executing edited code...\\
1726 hello\\
1731 hello\\
1727 Out[8]: "print 'hello'\\n"
1732 Out[8]: "print 'hello'\\n"
1728
1733
1729 Now we call it again with the previous output (stored in _):
1734 Now we call it again with the previous output (stored in _):
1730
1735
1731 In [9]: ed _\\
1736 In [9]: ed _\\
1732 Editing... done. Executing edited code...\\
1737 Editing... done. Executing edited code...\\
1733 hello world\\
1738 hello world\\
1734 Out[9]: "print 'hello world'\\n"
1739 Out[9]: "print 'hello world'\\n"
1735
1740
1736 Now we call it with the output #8 (stored in _8, also as Out[8]):
1741 Now we call it with the output #8 (stored in _8, also as Out[8]):
1737
1742
1738 In [10]: ed _8\\
1743 In [10]: ed _8\\
1739 Editing... done. Executing edited code...\\
1744 Editing... done. Executing edited code...\\
1740 hello again\\
1745 hello again\\
1741 Out[10]: "print 'hello again'\\n"
1746 Out[10]: "print 'hello again'\\n"
1742
1747
1743
1748
1744 Changing the default editor hook:
1749 Changing the default editor hook:
1745
1750
1746 If you wish to write your own editor hook, you can put it in a
1751 If you wish to write your own editor hook, you can put it in a
1747 configuration file which you load at startup time. The default hook
1752 configuration file which you load at startup time. The default hook
1748 is defined in the IPython.hooks module, and you can use that as a
1753 is defined in the IPython.hooks module, and you can use that as a
1749 starting example for further modifications. That file also has
1754 starting example for further modifications. That file also has
1750 general instructions on how to set a new hook for use once you've
1755 general instructions on how to set a new hook for use once you've
1751 defined it."""
1756 defined it."""
1752
1757
1753 # FIXME: This function has become a convoluted mess. It needs a
1758 # FIXME: This function has become a convoluted mess. It needs a
1754 # ground-up rewrite with clean, simple logic.
1759 # ground-up rewrite with clean, simple logic.
1755
1760
1756 def make_filename(arg):
1761 def make_filename(arg):
1757 "Make a filename from the given args"
1762 "Make a filename from the given args"
1758 try:
1763 try:
1759 filename = get_py_filename(arg)
1764 filename = get_py_filename(arg)
1760 except IOError:
1765 except IOError:
1761 if args.endswith('.py'):
1766 if args.endswith('.py'):
1762 filename = arg
1767 filename = arg
1763 else:
1768 else:
1764 filename = None
1769 filename = None
1765 return filename
1770 return filename
1766
1771
1767 # custom exceptions
1772 # custom exceptions
1768 class DataIsObject(Exception): pass
1773 class DataIsObject(Exception): pass
1769
1774
1770 opts,args = self.parse_options(parameter_s,'px')
1775 opts,args = self.parse_options(parameter_s,'px')
1771
1776
1772 # Default line number value
1777 # Default line number value
1773 lineno = None
1778 lineno = None
1774 if opts.has_key('p'):
1779 if opts.has_key('p'):
1775 args = '_%s' % last_call[0]
1780 args = '_%s' % last_call[0]
1776 if not self.shell.user_ns.has_key(args):
1781 if not self.shell.user_ns.has_key(args):
1777 args = last_call[1]
1782 args = last_call[1]
1778
1783
1779 # use last_call to remember the state of the previous call, but don't
1784 # use last_call to remember the state of the previous call, but don't
1780 # let it be clobbered by successive '-p' calls.
1785 # let it be clobbered by successive '-p' calls.
1781 try:
1786 try:
1782 last_call[0] = self.shell.outputcache.prompt_count
1787 last_call[0] = self.shell.outputcache.prompt_count
1783 if not opts.has_key('p'):
1788 if not opts.has_key('p'):
1784 last_call[1] = parameter_s
1789 last_call[1] = parameter_s
1785 except:
1790 except:
1786 pass
1791 pass
1787
1792
1788 # by default this is done with temp files, except when the given
1793 # by default this is done with temp files, except when the given
1789 # arg is a filename
1794 # arg is a filename
1790 use_temp = 1
1795 use_temp = 1
1791
1796
1792 if re.match(r'\d',args):
1797 if re.match(r'\d',args):
1793 # Mode where user specifies ranges of lines, like in %macro.
1798 # Mode where user specifies ranges of lines, like in %macro.
1794 # This means that you can't edit files whose names begin with
1799 # This means that you can't edit files whose names begin with
1795 # numbers this way. Tough.
1800 # numbers this way. Tough.
1796 ranges = args.split()
1801 ranges = args.split()
1797 data = ''.join(self.extract_input_slices(ranges))
1802 data = ''.join(self.extract_input_slices(ranges))
1798 elif args.endswith('.py'):
1803 elif args.endswith('.py'):
1799 filename = make_filename(args)
1804 filename = make_filename(args)
1800 data = ''
1805 data = ''
1801 use_temp = 0
1806 use_temp = 0
1802 elif args:
1807 elif args:
1803 try:
1808 try:
1804 # Load the parameter given as a variable. If not a string,
1809 # Load the parameter given as a variable. If not a string,
1805 # process it as an object instead (below)
1810 # process it as an object instead (below)
1806
1811
1807 #print '*** args',args,'type',type(args) # dbg
1812 #print '*** args',args,'type',type(args) # dbg
1808 data = eval(args,self.shell.user_ns)
1813 data = eval(args,self.shell.user_ns)
1809 if not type(data) in StringTypes:
1814 if not type(data) in StringTypes:
1810 raise DataIsObject
1815 raise DataIsObject
1811 except (NameError,SyntaxError):
1816 except (NameError,SyntaxError):
1812 # given argument is not a variable, try as a filename
1817 # given argument is not a variable, try as a filename
1813 filename = make_filename(args)
1818 filename = make_filename(args)
1814 if filename is None:
1819 if filename is None:
1815 warn("Argument given (%s) can't be found as a variable "
1820 warn("Argument given (%s) can't be found as a variable "
1816 "or as a filename." % args)
1821 "or as a filename." % args)
1817 return
1822 return
1818 data = ''
1823 data = ''
1819 use_temp = 0
1824 use_temp = 0
1820 except DataIsObject:
1825 except DataIsObject:
1821 # For objects, try to edit the file where they are defined
1826 # For objects, try to edit the file where they are defined
1822 try:
1827 try:
1823 filename = inspect.getabsfile(data)
1828 filename = inspect.getabsfile(data)
1824 datafile = 1
1829 datafile = 1
1825 except TypeError:
1830 except TypeError:
1826 filename = make_filename(args)
1831 filename = make_filename(args)
1827 datafile = 1
1832 datafile = 1
1828 warn('Could not find file where `%s` is defined.\n'
1833 warn('Could not find file where `%s` is defined.\n'
1829 'Opening a file named `%s`' % (args,filename))
1834 'Opening a file named `%s`' % (args,filename))
1830 # Now, make sure we can actually read the source (if it was in
1835 # Now, make sure we can actually read the source (if it was in
1831 # a temp file it's gone by now).
1836 # a temp file it's gone by now).
1832 if datafile:
1837 if datafile:
1833 try:
1838 try:
1834 lineno = inspect.getsourcelines(data)[1]
1839 lineno = inspect.getsourcelines(data)[1]
1835 except IOError:
1840 except IOError:
1836 filename = make_filename(args)
1841 filename = make_filename(args)
1837 if filename is None:
1842 if filename is None:
1838 warn('The file `%s` where `%s` was defined cannot '
1843 warn('The file `%s` where `%s` was defined cannot '
1839 'be read.' % (filename,data))
1844 'be read.' % (filename,data))
1840 return
1845 return
1841 use_temp = 0
1846 use_temp = 0
1842 else:
1847 else:
1843 data = ''
1848 data = ''
1844
1849
1845 if use_temp:
1850 if use_temp:
1846 filename = tempfile.mktemp('.py')
1851 filename = tempfile.mktemp('.py')
1847 self.shell.tempfiles.append(filename)
1852 self.shell.tempfiles.append(filename)
1848
1853
1849 if data and use_temp:
1854 if data and use_temp:
1850 tmp_file = open(filename,'w')
1855 tmp_file = open(filename,'w')
1851 tmp_file.write(data)
1856 tmp_file.write(data)
1852 tmp_file.close()
1857 tmp_file.close()
1853
1858
1854 # do actual editing here
1859 # do actual editing here
1855 print 'Editing...',
1860 print 'Editing...',
1856 sys.stdout.flush()
1861 sys.stdout.flush()
1857 self.shell.hooks.editor(filename,lineno)
1862 self.shell.hooks.editor(filename,lineno)
1858 if opts.has_key('x'): # -x prevents actual execution
1863 if opts.has_key('x'): # -x prevents actual execution
1859 print
1864 print
1860 else:
1865 else:
1861 print 'done. Executing edited code...'
1866 print 'done. Executing edited code...'
1862 try:
1867 try:
1863 self.shell.safe_execfile(filename,self.shell.user_ns)
1868 self.shell.safe_execfile(filename,self.shell.user_ns)
1864 except IOError,msg:
1869 except IOError,msg:
1865 if msg.filename == filename:
1870 if msg.filename == filename:
1866 warn('File not found. Did you forget to save?')
1871 warn('File not found. Did you forget to save?')
1867 return
1872 return
1868 else:
1873 else:
1869 self.shell.showtraceback()
1874 self.shell.showtraceback()
1870 except:
1875 except:
1871 self.shell.showtraceback()
1876 self.shell.showtraceback()
1872 if use_temp:
1877 if use_temp:
1873 contents = open(filename).read()
1878 contents = open(filename).read()
1874 return contents
1879 return contents
1875
1880
1876 def magic_xmode(self,parameter_s = ''):
1881 def magic_xmode(self,parameter_s = ''):
1877 """Switch modes for the exception handlers.
1882 """Switch modes for the exception handlers.
1878
1883
1879 Valid modes: Plain, Context and Verbose.
1884 Valid modes: Plain, Context and Verbose.
1880
1885
1881 If called without arguments, acts as a toggle."""
1886 If called without arguments, acts as a toggle."""
1882
1887
1883 def xmode_switch_err(name):
1888 def xmode_switch_err(name):
1884 warn('Error changing %s exception modes.\n%s' %
1889 warn('Error changing %s exception modes.\n%s' %
1885 (name,sys.exc_info()[1]))
1890 (name,sys.exc_info()[1]))
1886
1891
1887 shell = self.shell
1892 shell = self.shell
1888 new_mode = parameter_s.strip().capitalize()
1893 new_mode = parameter_s.strip().capitalize()
1889 try:
1894 try:
1890 shell.InteractiveTB.set_mode(mode=new_mode)
1895 shell.InteractiveTB.set_mode(mode=new_mode)
1891 print 'Exception reporting mode:',shell.InteractiveTB.mode
1896 print 'Exception reporting mode:',shell.InteractiveTB.mode
1892 except:
1897 except:
1893 xmode_switch_err('user')
1898 xmode_switch_err('user')
1894
1899
1895 # threaded shells use a special handler in sys.excepthook
1900 # threaded shells use a special handler in sys.excepthook
1896 if shell.isthreaded:
1901 if shell.isthreaded:
1897 try:
1902 try:
1898 shell.sys_excepthook.set_mode(mode=new_mode)
1903 shell.sys_excepthook.set_mode(mode=new_mode)
1899 except:
1904 except:
1900 xmode_switch_err('threaded')
1905 xmode_switch_err('threaded')
1901
1906
1902 def magic_colors(self,parameter_s = ''):
1907 def magic_colors(self,parameter_s = ''):
1903 """Switch color scheme for prompts, info system and exception handlers.
1908 """Switch color scheme for prompts, info system and exception handlers.
1904
1909
1905 Currently implemented schemes: NoColor, Linux, LightBG.
1910 Currently implemented schemes: NoColor, Linux, LightBG.
1906
1911
1907 Color scheme names are not case-sensitive."""
1912 Color scheme names are not case-sensitive."""
1908
1913
1909 def color_switch_err(name):
1914 def color_switch_err(name):
1910 warn('Error changing %s color schemes.\n%s' %
1915 warn('Error changing %s color schemes.\n%s' %
1911 (name,sys.exc_info()[1]))
1916 (name,sys.exc_info()[1]))
1912
1917
1913
1918
1914 new_scheme = parameter_s.strip()
1919 new_scheme = parameter_s.strip()
1915 if not new_scheme:
1920 if not new_scheme:
1916 print 'You must specify a color scheme.'
1921 print 'You must specify a color scheme.'
1917 return
1922 return
1918 # Under Windows, check for Gary Bishop's readline, which is necessary
1923 # Under Windows, check for Gary Bishop's readline, which is necessary
1919 # for ANSI coloring
1924 # for ANSI coloring
1920 if os.name in ['nt','dos']:
1925 if os.name in ['nt','dos']:
1921 try:
1926 try:
1922 import readline
1927 import readline
1923 except ImportError:
1928 except ImportError:
1924 has_readline = 0
1929 has_readline = 0
1925 else:
1930 else:
1926 try:
1931 try:
1927 readline.GetOutputFile()
1932 readline.GetOutputFile()
1928 except AttributeError:
1933 except AttributeError:
1929 has_readline = 0
1934 has_readline = 0
1930 else:
1935 else:
1931 has_readline = 1
1936 has_readline = 1
1932 if not has_readline:
1937 if not has_readline:
1933 msg = """\
1938 msg = """\
1934 Proper color support under MS Windows requires Gary Bishop's readline library.
1939 Proper color support under MS Windows requires Gary Bishop's readline library.
1935 You can find it at:
1940 You can find it at:
1936 http://sourceforge.net/projects/uncpythontools
1941 http://sourceforge.net/projects/uncpythontools
1937 Gary's readline needs the ctypes module, from:
1942 Gary's readline needs the ctypes module, from:
1938 http://starship.python.net/crew/theller/ctypes
1943 http://starship.python.net/crew/theller/ctypes
1939
1944
1940 Defaulting color scheme to 'NoColor'"""
1945 Defaulting color scheme to 'NoColor'"""
1941 new_scheme = 'NoColor'
1946 new_scheme = 'NoColor'
1942 warn(msg)
1947 warn(msg)
1943 # local shortcut
1948 # local shortcut
1944 shell = self.shell
1949 shell = self.shell
1945
1950
1946 # Set prompt colors
1951 # Set prompt colors
1947 try:
1952 try:
1948 shell.outputcache.set_colors(new_scheme)
1953 shell.outputcache.set_colors(new_scheme)
1949 except:
1954 except:
1950 color_switch_err('prompt')
1955 color_switch_err('prompt')
1951 else:
1956 else:
1952 shell.rc.colors = \
1957 shell.rc.colors = \
1953 shell.outputcache.color_table.active_scheme_name
1958 shell.outputcache.color_table.active_scheme_name
1954 # Set exception colors
1959 # Set exception colors
1955 try:
1960 try:
1956 shell.InteractiveTB.set_colors(scheme = new_scheme)
1961 shell.InteractiveTB.set_colors(scheme = new_scheme)
1957 shell.SyntaxTB.set_colors(scheme = new_scheme)
1962 shell.SyntaxTB.set_colors(scheme = new_scheme)
1958 except:
1963 except:
1959 color_switch_err('exception')
1964 color_switch_err('exception')
1960
1965
1961 # threaded shells use a verbose traceback in sys.excepthook
1966 # threaded shells use a verbose traceback in sys.excepthook
1962 if shell.isthreaded:
1967 if shell.isthreaded:
1963 try:
1968 try:
1964 shell.sys_excepthook.set_colors(scheme=new_scheme)
1969 shell.sys_excepthook.set_colors(scheme=new_scheme)
1965 except:
1970 except:
1966 color_switch_err('system exception handler')
1971 color_switch_err('system exception handler')
1967
1972
1968 # Set info (for 'object?') colors
1973 # Set info (for 'object?') colors
1969 if shell.rc.color_info:
1974 if shell.rc.color_info:
1970 try:
1975 try:
1971 shell.inspector.set_active_scheme(new_scheme)
1976 shell.inspector.set_active_scheme(new_scheme)
1972 except:
1977 except:
1973 color_switch_err('object inspector')
1978 color_switch_err('object inspector')
1974 else:
1979 else:
1975 shell.inspector.set_active_scheme('NoColor')
1980 shell.inspector.set_active_scheme('NoColor')
1976
1981
1977 def magic_color_info(self,parameter_s = ''):
1982 def magic_color_info(self,parameter_s = ''):
1978 """Toggle color_info.
1983 """Toggle color_info.
1979
1984
1980 The color_info configuration parameter controls whether colors are
1985 The color_info configuration parameter controls whether colors are
1981 used for displaying object details (by things like %psource, %pfile or
1986 used for displaying object details (by things like %psource, %pfile or
1982 the '?' system). This function toggles this value with each call.
1987 the '?' system). This function toggles this value with each call.
1983
1988
1984 Note that unless you have a fairly recent pager (less works better
1989 Note that unless you have a fairly recent pager (less works better
1985 than more) in your system, using colored object information displays
1990 than more) in your system, using colored object information displays
1986 will not work properly. Test it and see."""
1991 will not work properly. Test it and see."""
1987
1992
1988 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1993 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1989 self.magic_colors(self.shell.rc.colors)
1994 self.magic_colors(self.shell.rc.colors)
1990 print 'Object introspection functions have now coloring:',
1995 print 'Object introspection functions have now coloring:',
1991 print ['OFF','ON'][self.shell.rc.color_info]
1996 print ['OFF','ON'][self.shell.rc.color_info]
1992
1997
1993 def magic_Pprint(self, parameter_s=''):
1998 def magic_Pprint(self, parameter_s=''):
1994 """Toggle pretty printing on/off."""
1999 """Toggle pretty printing on/off."""
1995
2000
1996 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2001 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1997 print 'Pretty printing has been turned', \
2002 print 'Pretty printing has been turned', \
1998 ['OFF','ON'][self.shell.outputcache.Pprint]
2003 ['OFF','ON'][self.shell.outputcache.Pprint]
1999
2004
2000 def magic_exit(self, parameter_s=''):
2005 def magic_exit(self, parameter_s=''):
2001 """Exit IPython, confirming if configured to do so.
2006 """Exit IPython, confirming if configured to do so.
2002
2007
2003 You can configure whether IPython asks for confirmation upon exit by
2008 You can configure whether IPython asks for confirmation upon exit by
2004 setting the confirm_exit flag in the ipythonrc file."""
2009 setting the confirm_exit flag in the ipythonrc file."""
2005
2010
2006 self.shell.exit()
2011 self.shell.exit()
2007
2012
2008 def magic_quit(self, parameter_s=''):
2013 def magic_quit(self, parameter_s=''):
2009 """Exit IPython, confirming if configured to do so (like %exit)"""
2014 """Exit IPython, confirming if configured to do so (like %exit)"""
2010
2015
2011 self.shell.exit()
2016 self.shell.exit()
2012
2017
2013 def magic_Exit(self, parameter_s=''):
2018 def magic_Exit(self, parameter_s=''):
2014 """Exit IPython without confirmation."""
2019 """Exit IPython without confirmation."""
2015
2020
2016 self.shell.exit_now = True
2021 self.shell.exit_now = True
2017
2022
2018 def magic_Quit(self, parameter_s=''):
2023 def magic_Quit(self, parameter_s=''):
2019 """Exit IPython without confirmation (like %Exit)."""
2024 """Exit IPython without confirmation (like %Exit)."""
2020
2025
2021 self.shell.exit_now = True
2026 self.shell.exit_now = True
2022
2027
2023 #......................................................................
2028 #......................................................................
2024 # Functions to implement unix shell-type things
2029 # Functions to implement unix shell-type things
2025
2030
2026 def magic_alias(self, parameter_s = ''):
2031 def magic_alias(self, parameter_s = ''):
2027 """Define an alias for a system command.
2032 """Define an alias for a system command.
2028
2033
2029 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2034 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2030
2035
2031 Then, typing 'alias_name params' will execute the system command 'cmd
2036 Then, typing 'alias_name params' will execute the system command 'cmd
2032 params' (from your underlying operating system).
2037 params' (from your underlying operating system).
2033
2038
2034 Aliases have lower precedence than magic functions and Python normal
2039 Aliases have lower precedence than magic functions and Python normal
2035 variables, so if 'foo' is both a Python variable and an alias, the
2040 variables, so if 'foo' is both a Python variable and an alias, the
2036 alias can not be executed until 'del foo' removes the Python variable.
2041 alias can not be executed until 'del foo' removes the Python variable.
2037
2042
2038 You can use the %l specifier in an alias definition to represent the
2043 You can use the %l specifier in an alias definition to represent the
2039 whole line when the alias is called. For example:
2044 whole line when the alias is called. For example:
2040
2045
2041 In [2]: alias all echo "Input in brackets: <%l>"\\
2046 In [2]: alias all echo "Input in brackets: <%l>"\\
2042 In [3]: all hello world\\
2047 In [3]: all hello world\\
2043 Input in brackets: <hello world>
2048 Input in brackets: <hello world>
2044
2049
2045 You can also define aliases with parameters using %s specifiers (one
2050 You can also define aliases with parameters using %s specifiers (one
2046 per parameter):
2051 per parameter):
2047
2052
2048 In [1]: alias parts echo first %s second %s\\
2053 In [1]: alias parts echo first %s second %s\\
2049 In [2]: %parts A B\\
2054 In [2]: %parts A B\\
2050 first A second B\\
2055 first A second B\\
2051 In [3]: %parts A\\
2056 In [3]: %parts A\\
2052 Incorrect number of arguments: 2 expected.\\
2057 Incorrect number of arguments: 2 expected.\\
2053 parts is an alias to: 'echo first %s second %s'
2058 parts is an alias to: 'echo first %s second %s'
2054
2059
2055 Note that %l and %s are mutually exclusive. You can only use one or
2060 Note that %l and %s are mutually exclusive. You can only use one or
2056 the other in your aliases.
2061 the other in your aliases.
2057
2062
2058 Aliases expand Python variables just like system calls using ! or !!
2063 Aliases expand Python variables just like system calls using ! or !!
2059 do: all expressions prefixed with '$' get expanded. For details of
2064 do: all expressions prefixed with '$' get expanded. For details of
2060 the semantic rules, see PEP-215:
2065 the semantic rules, see PEP-215:
2061 http://www.python.org/peps/pep-0215.html. This is the library used by
2066 http://www.python.org/peps/pep-0215.html. This is the library used by
2062 IPython for variable expansion. If you want to access a true shell
2067 IPython for variable expansion. If you want to access a true shell
2063 variable, an extra $ is necessary to prevent its expansion by IPython:
2068 variable, an extra $ is necessary to prevent its expansion by IPython:
2064
2069
2065 In [6]: alias show echo\\
2070 In [6]: alias show echo\\
2066 In [7]: PATH='A Python string'\\
2071 In [7]: PATH='A Python string'\\
2067 In [8]: show $PATH\\
2072 In [8]: show $PATH\\
2068 A Python string\\
2073 A Python string\\
2069 In [9]: show $$PATH\\
2074 In [9]: show $$PATH\\
2070 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2075 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2071
2076
2072 You can use the alias facility to acess all of $PATH. See the %rehash
2077 You can use the alias facility to acess all of $PATH. See the %rehash
2073 and %rehashx functions, which automatically create aliases for the
2078 and %rehashx functions, which automatically create aliases for the
2074 contents of your $PATH.
2079 contents of your $PATH.
2075
2080
2076 If called with no parameters, %alias prints the current alias table."""
2081 If called with no parameters, %alias prints the current alias table."""
2077
2082
2078 par = parameter_s.strip()
2083 par = parameter_s.strip()
2079 if not par:
2084 if not par:
2080 if self.shell.rc.automagic:
2085 if self.shell.rc.automagic:
2081 prechar = ''
2086 prechar = ''
2082 else:
2087 else:
2083 prechar = self.shell.ESC_MAGIC
2088 prechar = self.shell.ESC_MAGIC
2084 print 'Alias\t\tSystem Command\n'+'-'*30
2089 print 'Alias\t\tSystem Command\n'+'-'*30
2085 atab = self.shell.alias_table
2090 atab = self.shell.alias_table
2086 aliases = atab.keys()
2091 aliases = atab.keys()
2087 aliases.sort()
2092 aliases.sort()
2088 for alias in aliases:
2093 for alias in aliases:
2089 print prechar+alias+'\t\t'+atab[alias][1]
2094 print prechar+alias+'\t\t'+atab[alias][1]
2090 print '-'*30+'\nTotal number of aliases:',len(aliases)
2095 print '-'*30+'\nTotal number of aliases:',len(aliases)
2091 return
2096 return
2092 try:
2097 try:
2093 alias,cmd = par.split(None,1)
2098 alias,cmd = par.split(None,1)
2094 except:
2099 except:
2095 print OInspect.getdoc(self.magic_alias)
2100 print OInspect.getdoc(self.magic_alias)
2096 else:
2101 else:
2097 nargs = cmd.count('%s')
2102 nargs = cmd.count('%s')
2098 if nargs>0 and cmd.find('%l')>=0:
2103 if nargs>0 and cmd.find('%l')>=0:
2099 error('The %s and %l specifiers are mutually exclusive '
2104 error('The %s and %l specifiers are mutually exclusive '
2100 'in alias definitions.')
2105 'in alias definitions.')
2101 else: # all looks OK
2106 else: # all looks OK
2102 self.shell.alias_table[alias] = (nargs,cmd)
2107 self.shell.alias_table[alias] = (nargs,cmd)
2103 self.shell.alias_table_validate(verbose=1)
2108 self.shell.alias_table_validate(verbose=1)
2104 # end magic_alias
2109 # end magic_alias
2105
2110
2106 def magic_unalias(self, parameter_s = ''):
2111 def magic_unalias(self, parameter_s = ''):
2107 """Remove an alias"""
2112 """Remove an alias"""
2108
2113
2109 aname = parameter_s.strip()
2114 aname = parameter_s.strip()
2110 if aname in self.shell.alias_table:
2115 if aname in self.shell.alias_table:
2111 del self.shell.alias_table[aname]
2116 del self.shell.alias_table[aname]
2112
2117
2113 def magic_rehash(self, parameter_s = ''):
2118 def magic_rehash(self, parameter_s = ''):
2114 """Update the alias table with all entries in $PATH.
2119 """Update the alias table with all entries in $PATH.
2115
2120
2116 This version does no checks on execute permissions or whether the
2121 This version does no checks on execute permissions or whether the
2117 contents of $PATH are truly files (instead of directories or something
2122 contents of $PATH are truly files (instead of directories or something
2118 else). For such a safer (but slower) version, use %rehashx."""
2123 else). For such a safer (but slower) version, use %rehashx."""
2119
2124
2120 # This function (and rehashx) manipulate the alias_table directly
2125 # This function (and rehashx) manipulate the alias_table directly
2121 # rather than calling magic_alias, for speed reasons. A rehash on a
2126 # rather than calling magic_alias, for speed reasons. A rehash on a
2122 # typical Linux box involves several thousand entries, so efficiency
2127 # typical Linux box involves several thousand entries, so efficiency
2123 # here is a top concern.
2128 # here is a top concern.
2124
2129
2125 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2130 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2126 alias_table = self.shell.alias_table
2131 alias_table = self.shell.alias_table
2127 for pdir in path:
2132 for pdir in path:
2128 for ff in os.listdir(pdir):
2133 for ff in os.listdir(pdir):
2129 # each entry in the alias table must be (N,name), where
2134 # each entry in the alias table must be (N,name), where
2130 # N is the number of positional arguments of the alias.
2135 # N is the number of positional arguments of the alias.
2131 alias_table[ff] = (0,ff)
2136 alias_table[ff] = (0,ff)
2132 # Make sure the alias table doesn't contain keywords or builtins
2137 # Make sure the alias table doesn't contain keywords or builtins
2133 self.shell.alias_table_validate()
2138 self.shell.alias_table_validate()
2134 # Call again init_auto_alias() so we get 'rm -i' and other modified
2139 # Call again init_auto_alias() so we get 'rm -i' and other modified
2135 # aliases since %rehash will probably clobber them
2140 # aliases since %rehash will probably clobber them
2136 self.shell.init_auto_alias()
2141 self.shell.init_auto_alias()
2137
2142
2138 def magic_rehashx(self, parameter_s = ''):
2143 def magic_rehashx(self, parameter_s = ''):
2139 """Update the alias table with all executable files in $PATH.
2144 """Update the alias table with all executable files in $PATH.
2140
2145
2141 This version explicitly checks that every entry in $PATH is a file
2146 This version explicitly checks that every entry in $PATH is a file
2142 with execute access (os.X_OK), so it is much slower than %rehash.
2147 with execute access (os.X_OK), so it is much slower than %rehash.
2143
2148
2144 Under Windows, it checks executability as a match agains a
2149 Under Windows, it checks executability as a match agains a
2145 '|'-separated string of extensions, stored in the IPython config
2150 '|'-separated string of extensions, stored in the IPython config
2146 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2151 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2147
2152
2148 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2153 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2149 alias_table = self.shell.alias_table
2154 alias_table = self.shell.alias_table
2150
2155
2151 if os.name == 'posix':
2156 if os.name == 'posix':
2152 isexec = lambda fname:os.path.isfile(fname) and \
2157 isexec = lambda fname:os.path.isfile(fname) and \
2153 os.access(fname,os.X_OK)
2158 os.access(fname,os.X_OK)
2154 else:
2159 else:
2155
2160
2156 try:
2161 try:
2157 winext = os.environ['pathext'].replace(';','|').replace('.','')
2162 winext = os.environ['pathext'].replace(';','|').replace('.','')
2158 except KeyError:
2163 except KeyError:
2159 winext = 'exe|com|bat'
2164 winext = 'exe|com|bat'
2160
2165
2161 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2166 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2162 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2167 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2163 savedir = os.getcwd()
2168 savedir = os.getcwd()
2164 try:
2169 try:
2165 # write the whole loop for posix/Windows so we don't have an if in
2170 # write the whole loop for posix/Windows so we don't have an if in
2166 # the innermost part
2171 # the innermost part
2167 if os.name == 'posix':
2172 if os.name == 'posix':
2168 for pdir in path:
2173 for pdir in path:
2169 os.chdir(pdir)
2174 os.chdir(pdir)
2170 for ff in os.listdir(pdir):
2175 for ff in os.listdir(pdir):
2171 if isexec(ff):
2176 if isexec(ff):
2172 # each entry in the alias table must be (N,name),
2177 # each entry in the alias table must be (N,name),
2173 # where N is the number of positional arguments of the
2178 # where N is the number of positional arguments of the
2174 # alias.
2179 # alias.
2175 alias_table[ff] = (0,ff)
2180 alias_table[ff] = (0,ff)
2176 else:
2181 else:
2177 for pdir in path:
2182 for pdir in path:
2178 os.chdir(pdir)
2183 os.chdir(pdir)
2179 for ff in os.listdir(pdir):
2184 for ff in os.listdir(pdir):
2180 if isexec(ff):
2185 if isexec(ff):
2181 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2186 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2182 # Make sure the alias table doesn't contain keywords or builtins
2187 # Make sure the alias table doesn't contain keywords or builtins
2183 self.shell.alias_table_validate()
2188 self.shell.alias_table_validate()
2184 # Call again init_auto_alias() so we get 'rm -i' and other
2189 # Call again init_auto_alias() so we get 'rm -i' and other
2185 # modified aliases since %rehashx will probably clobber them
2190 # modified aliases since %rehashx will probably clobber them
2186 self.shell.init_auto_alias()
2191 self.shell.init_auto_alias()
2187 finally:
2192 finally:
2188 os.chdir(savedir)
2193 os.chdir(savedir)
2189
2194
2190 def magic_pwd(self, parameter_s = ''):
2195 def magic_pwd(self, parameter_s = ''):
2191 """Return the current working directory path."""
2196 """Return the current working directory path."""
2192 return os.getcwd()
2197 return os.getcwd()
2193
2198
2194 def magic_cd(self, parameter_s=''):
2199 def magic_cd(self, parameter_s=''):
2195 """Change the current working directory.
2200 """Change the current working directory.
2196
2201
2197 This command automatically maintains an internal list of directories
2202 This command automatically maintains an internal list of directories
2198 you visit during your IPython session, in the variable _dh. The
2203 you visit during your IPython session, in the variable _dh. The
2199 command %dhist shows this history nicely formatted.
2204 command %dhist shows this history nicely formatted.
2200
2205
2201 Usage:
2206 Usage:
2202
2207
2203 cd 'dir': changes to directory 'dir'.
2208 cd 'dir': changes to directory 'dir'.
2204
2209
2205 cd -: changes to the last visited directory.
2210 cd -: changes to the last visited directory.
2206
2211
2207 cd -<n>: changes to the n-th directory in the directory history.
2212 cd -<n>: changes to the n-th directory in the directory history.
2208
2213
2209 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2214 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2210 (note: cd <bookmark_name> is enough if there is no
2215 (note: cd <bookmark_name> is enough if there is no
2211 directory <bookmark_name>, but a bookmark with the name exists.)
2216 directory <bookmark_name>, but a bookmark with the name exists.)
2212
2217
2213 Options:
2218 Options:
2214
2219
2215 -q: quiet. Do not print the working directory after the cd command is
2220 -q: quiet. Do not print the working directory after the cd command is
2216 executed. By default IPython's cd command does print this directory,
2221 executed. By default IPython's cd command does print this directory,
2217 since the default prompts do not display path information.
2222 since the default prompts do not display path information.
2218
2223
2219 Note that !cd doesn't work for this purpose because the shell where
2224 Note that !cd doesn't work for this purpose because the shell where
2220 !command runs is immediately discarded after executing 'command'."""
2225 !command runs is immediately discarded after executing 'command'."""
2221
2226
2222 parameter_s = parameter_s.strip()
2227 parameter_s = parameter_s.strip()
2223 bkms = self.shell.persist.get("bookmarks",{})
2228 bkms = self.shell.persist.get("bookmarks",{})
2224
2229
2225 numcd = re.match(r'(-)(\d+)$',parameter_s)
2230 numcd = re.match(r'(-)(\d+)$',parameter_s)
2226 # jump in directory history by number
2231 # jump in directory history by number
2227 if numcd:
2232 if numcd:
2228 nn = int(numcd.group(2))
2233 nn = int(numcd.group(2))
2229 try:
2234 try:
2230 ps = self.shell.user_ns['_dh'][nn]
2235 ps = self.shell.user_ns['_dh'][nn]
2231 except IndexError:
2236 except IndexError:
2232 print 'The requested directory does not exist in history.'
2237 print 'The requested directory does not exist in history.'
2233 return
2238 return
2234 else:
2239 else:
2235 opts = {}
2240 opts = {}
2236 else:
2241 else:
2237 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2242 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2238 # jump to previous
2243 # jump to previous
2239 if ps == '-':
2244 if ps == '-':
2240 try:
2245 try:
2241 ps = self.shell.user_ns['_dh'][-2]
2246 ps = self.shell.user_ns['_dh'][-2]
2242 except IndexError:
2247 except IndexError:
2243 print 'No previous directory to change to.'
2248 print 'No previous directory to change to.'
2244 return
2249 return
2245 # jump to bookmark
2250 # jump to bookmark
2246 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2251 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2247 if bkms.has_key(ps):
2252 if bkms.has_key(ps):
2248 target = bkms[ps]
2253 target = bkms[ps]
2249 print '(bookmark:%s) -> %s' % (ps,target)
2254 print '(bookmark:%s) -> %s' % (ps,target)
2250 ps = target
2255 ps = target
2251 else:
2256 else:
2252 if bkms:
2257 if bkms:
2253 error("Bookmark '%s' not found. "
2258 error("Bookmark '%s' not found. "
2254 "Use '%bookmark -l' to see your bookmarks." % ps)
2259 "Use '%bookmark -l' to see your bookmarks." % ps)
2255 else:
2260 else:
2256 print "Bookmarks not set - use %bookmark <bookmarkname>"
2261 print "Bookmarks not set - use %bookmark <bookmarkname>"
2257 return
2262 return
2258
2263
2259 # at this point ps should point to the target dir
2264 # at this point ps should point to the target dir
2260 if ps:
2265 if ps:
2261 try:
2266 try:
2262 os.chdir(os.path.expanduser(ps))
2267 os.chdir(os.path.expanduser(ps))
2263 except OSError:
2268 except OSError:
2264 print sys.exc_info()[1]
2269 print sys.exc_info()[1]
2265 else:
2270 else:
2266 self.shell.user_ns['_dh'].append(os.getcwd())
2271 self.shell.user_ns['_dh'].append(os.getcwd())
2267 else:
2272 else:
2268 os.chdir(self.shell.home_dir)
2273 os.chdir(self.shell.home_dir)
2269 self.shell.user_ns['_dh'].append(os.getcwd())
2274 self.shell.user_ns['_dh'].append(os.getcwd())
2270 if not 'q' in opts:
2275 if not 'q' in opts:
2271 print self.shell.user_ns['_dh'][-1]
2276 print self.shell.user_ns['_dh'][-1]
2272
2277
2273 def magic_dhist(self, parameter_s=''):
2278 def magic_dhist(self, parameter_s=''):
2274 """Print your history of visited directories.
2279 """Print your history of visited directories.
2275
2280
2276 %dhist -> print full history\\
2281 %dhist -> print full history\\
2277 %dhist n -> print last n entries only\\
2282 %dhist n -> print last n entries only\\
2278 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2283 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2279
2284
2280 This history is automatically maintained by the %cd command, and
2285 This history is automatically maintained by the %cd command, and
2281 always available as the global list variable _dh. You can use %cd -<n>
2286 always available as the global list variable _dh. You can use %cd -<n>
2282 to go to directory number <n>."""
2287 to go to directory number <n>."""
2283
2288
2284 dh = self.shell.user_ns['_dh']
2289 dh = self.shell.user_ns['_dh']
2285 if parameter_s:
2290 if parameter_s:
2286 try:
2291 try:
2287 args = map(int,parameter_s.split())
2292 args = map(int,parameter_s.split())
2288 except:
2293 except:
2289 self.arg_err(Magic.magic_dhist)
2294 self.arg_err(Magic.magic_dhist)
2290 return
2295 return
2291 if len(args) == 1:
2296 if len(args) == 1:
2292 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2297 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2293 elif len(args) == 2:
2298 elif len(args) == 2:
2294 ini,fin = args
2299 ini,fin = args
2295 else:
2300 else:
2296 self.arg_err(Magic.magic_dhist)
2301 self.arg_err(Magic.magic_dhist)
2297 return
2302 return
2298 else:
2303 else:
2299 ini,fin = 0,len(dh)
2304 ini,fin = 0,len(dh)
2300 nlprint(dh,
2305 nlprint(dh,
2301 header = 'Directory history (kept in _dh)',
2306 header = 'Directory history (kept in _dh)',
2302 start=ini,stop=fin)
2307 start=ini,stop=fin)
2303
2308
2304 def magic_env(self, parameter_s=''):
2309 def magic_env(self, parameter_s=''):
2305 """List environment variables."""
2310 """List environment variables."""
2306
2311
2307 return os.environ.data
2312 return os.environ.data
2308
2313
2309 def magic_pushd(self, parameter_s=''):
2314 def magic_pushd(self, parameter_s=''):
2310 """Place the current dir on stack and change directory.
2315 """Place the current dir on stack and change directory.
2311
2316
2312 Usage:\\
2317 Usage:\\
2313 %pushd ['dirname']
2318 %pushd ['dirname']
2314
2319
2315 %pushd with no arguments does a %pushd to your home directory.
2320 %pushd with no arguments does a %pushd to your home directory.
2316 """
2321 """
2317 if parameter_s == '': parameter_s = '~'
2322 if parameter_s == '': parameter_s = '~'
2318 dir_s = self.shell.dir_stack
2323 dir_s = self.shell.dir_stack
2319 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2324 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2320 os.path.expanduser(self.shell.dir_stack[0]):
2325 os.path.expanduser(self.shell.dir_stack[0]):
2321 try:
2326 try:
2322 self.magic_cd(parameter_s)
2327 self.magic_cd(parameter_s)
2323 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2328 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2324 self.magic_dirs()
2329 self.magic_dirs()
2325 except:
2330 except:
2326 print 'Invalid directory'
2331 print 'Invalid directory'
2327 else:
2332 else:
2328 print 'You are already there!'
2333 print 'You are already there!'
2329
2334
2330 def magic_popd(self, parameter_s=''):
2335 def magic_popd(self, parameter_s=''):
2331 """Change to directory popped off the top of the stack.
2336 """Change to directory popped off the top of the stack.
2332 """
2337 """
2333 if len (self.shell.dir_stack) > 1:
2338 if len (self.shell.dir_stack) > 1:
2334 self.shell.dir_stack.pop(0)
2339 self.shell.dir_stack.pop(0)
2335 self.magic_cd(self.shell.dir_stack[0])
2340 self.magic_cd(self.shell.dir_stack[0])
2336 print self.shell.dir_stack[0]
2341 print self.shell.dir_stack[0]
2337 else:
2342 else:
2338 print "You can't remove the starting directory from the stack:",\
2343 print "You can't remove the starting directory from the stack:",\
2339 self.shell.dir_stack
2344 self.shell.dir_stack
2340
2345
2341 def magic_dirs(self, parameter_s=''):
2346 def magic_dirs(self, parameter_s=''):
2342 """Return the current directory stack."""
2347 """Return the current directory stack."""
2343
2348
2344 return self.shell.dir_stack[:]
2349 return self.shell.dir_stack[:]
2345
2350
2346 def magic_sc(self, parameter_s=''):
2351 def magic_sc(self, parameter_s=''):
2347 """Shell capture - execute a shell command and capture its output.
2352 """Shell capture - execute a shell command and capture its output.
2348
2353
2349 %sc [options] varname=command
2354 %sc [options] varname=command
2350
2355
2351 IPython will run the given command using commands.getoutput(), and
2356 IPython will run the given command using commands.getoutput(), and
2352 will then update the user's interactive namespace with a variable
2357 will then update the user's interactive namespace with a variable
2353 called varname, containing the value of the call. Your command can
2358 called varname, containing the value of the call. Your command can
2354 contain shell wildcards, pipes, etc.
2359 contain shell wildcards, pipes, etc.
2355
2360
2356 The '=' sign in the syntax is mandatory, and the variable name you
2361 The '=' sign in the syntax is mandatory, and the variable name you
2357 supply must follow Python's standard conventions for valid names.
2362 supply must follow Python's standard conventions for valid names.
2358
2363
2359 Options:
2364 Options:
2360
2365
2361 -l: list output. Split the output on newlines into a list before
2366 -l: list output. Split the output on newlines into a list before
2362 assigning it to the given variable. By default the output is stored
2367 assigning it to the given variable. By default the output is stored
2363 as a single string.
2368 as a single string.
2364
2369
2365 -v: verbose. Print the contents of the variable.
2370 -v: verbose. Print the contents of the variable.
2366
2371
2367 In most cases you should not need to split as a list, because the
2372 In most cases you should not need to split as a list, because the
2368 returned value is a special type of string which can automatically
2373 returned value is a special type of string which can automatically
2369 provide its contents either as a list (split on newlines) or as a
2374 provide its contents either as a list (split on newlines) or as a
2370 space-separated string. These are convenient, respectively, either
2375 space-separated string. These are convenient, respectively, either
2371 for sequential processing or to be passed to a shell command.
2376 for sequential processing or to be passed to a shell command.
2372
2377
2373 For example:
2378 For example:
2374
2379
2375 # Capture into variable a
2380 # Capture into variable a
2376 In [9]: sc a=ls *py
2381 In [9]: sc a=ls *py
2377
2382
2378 # a is a string with embedded newlines
2383 # a is a string with embedded newlines
2379 In [10]: a
2384 In [10]: a
2380 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2385 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2381
2386
2382 # which can be seen as a list:
2387 # which can be seen as a list:
2383 In [11]: a.l
2388 In [11]: a.l
2384 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2389 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2385
2390
2386 # or as a whitespace-separated string:
2391 # or as a whitespace-separated string:
2387 In [12]: a.s
2392 In [12]: a.s
2388 Out[12]: 'setup.py win32_manual_post_install.py'
2393 Out[12]: 'setup.py win32_manual_post_install.py'
2389
2394
2390 # a.s is useful to pass as a single command line:
2395 # a.s is useful to pass as a single command line:
2391 In [13]: !wc -l $a.s
2396 In [13]: !wc -l $a.s
2392 146 setup.py
2397 146 setup.py
2393 130 win32_manual_post_install.py
2398 130 win32_manual_post_install.py
2394 276 total
2399 276 total
2395
2400
2396 # while the list form is useful to loop over:
2401 # while the list form is useful to loop over:
2397 In [14]: for f in a.l:
2402 In [14]: for f in a.l:
2398 ....: !wc -l $f
2403 ....: !wc -l $f
2399 ....:
2404 ....:
2400 146 setup.py
2405 146 setup.py
2401 130 win32_manual_post_install.py
2406 130 win32_manual_post_install.py
2402
2407
2403 Similiarly, the lists returned by the -l option are also special, in
2408 Similiarly, the lists returned by the -l option are also special, in
2404 the sense that you can equally invoke the .s attribute on them to
2409 the sense that you can equally invoke the .s attribute on them to
2405 automatically get a whitespace-separated string from their contents:
2410 automatically get a whitespace-separated string from their contents:
2406
2411
2407 In [1]: sc -l b=ls *py
2412 In [1]: sc -l b=ls *py
2408
2413
2409 In [2]: b
2414 In [2]: b
2410 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2415 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2411
2416
2412 In [3]: b.s
2417 In [3]: b.s
2413 Out[3]: 'setup.py win32_manual_post_install.py'
2418 Out[3]: 'setup.py win32_manual_post_install.py'
2414
2419
2415 In summary, both the lists and strings used for ouptut capture have
2420 In summary, both the lists and strings used for ouptut capture have
2416 the following special attributes:
2421 the following special attributes:
2417
2422
2418 .l (or .list) : value as list.
2423 .l (or .list) : value as list.
2419 .n (or .nlstr): value as newline-separated string.
2424 .n (or .nlstr): value as newline-separated string.
2420 .s (or .spstr): value as space-separated string.
2425 .s (or .spstr): value as space-separated string.
2421 """
2426 """
2422
2427
2423 opts,args = self.parse_options(parameter_s,'lv')
2428 opts,args = self.parse_options(parameter_s,'lv')
2424 # Try to get a variable name and command to run
2429 # Try to get a variable name and command to run
2425 try:
2430 try:
2426 # the variable name must be obtained from the parse_options
2431 # the variable name must be obtained from the parse_options
2427 # output, which uses shlex.split to strip options out.
2432 # output, which uses shlex.split to strip options out.
2428 var,_ = args.split('=',1)
2433 var,_ = args.split('=',1)
2429 var = var.strip()
2434 var = var.strip()
2430 # But the the command has to be extracted from the original input
2435 # But the the command has to be extracted from the original input
2431 # parameter_s, not on what parse_options returns, to avoid the
2436 # parameter_s, not on what parse_options returns, to avoid the
2432 # quote stripping which shlex.split performs on it.
2437 # quote stripping which shlex.split performs on it.
2433 _,cmd = parameter_s.split('=',1)
2438 _,cmd = parameter_s.split('=',1)
2434 except ValueError:
2439 except ValueError:
2435 var,cmd = '',''
2440 var,cmd = '',''
2436 if not var:
2441 if not var:
2437 error('you must specify a variable to assign the command to.')
2442 error('you must specify a variable to assign the command to.')
2438 return
2443 return
2439 # If all looks ok, proceed
2444 # If all looks ok, proceed
2440 out,err = self.shell.getoutputerror(cmd)
2445 out,err = self.shell.getoutputerror(cmd)
2441 if err:
2446 if err:
2442 print >> Term.cerr,err
2447 print >> Term.cerr,err
2443 if opts.has_key('l'):
2448 if opts.has_key('l'):
2444 out = SList(out.split('\n'))
2449 out = SList(out.split('\n'))
2445 else:
2450 else:
2446 out = LSString(out)
2451 out = LSString(out)
2447 if opts.has_key('v'):
2452 if opts.has_key('v'):
2448 print '%s ==\n%s' % (var,pformat(out))
2453 print '%s ==\n%s' % (var,pformat(out))
2449 self.shell.user_ns.update({var:out})
2454 self.shell.user_ns.update({var:out})
2450
2455
2451 def magic_sx(self, parameter_s=''):
2456 def magic_sx(self, parameter_s=''):
2452 """Shell execute - run a shell command and capture its output.
2457 """Shell execute - run a shell command and capture its output.
2453
2458
2454 %sx command
2459 %sx command
2455
2460
2456 IPython will run the given command using commands.getoutput(), and
2461 IPython will run the given command using commands.getoutput(), and
2457 return the result formatted as a list (split on '\\n'). Since the
2462 return the result formatted as a list (split on '\\n'). Since the
2458 output is _returned_, it will be stored in ipython's regular output
2463 output is _returned_, it will be stored in ipython's regular output
2459 cache Out[N] and in the '_N' automatic variables.
2464 cache Out[N] and in the '_N' automatic variables.
2460
2465
2461 Notes:
2466 Notes:
2462
2467
2463 1) If an input line begins with '!!', then %sx is automatically
2468 1) If an input line begins with '!!', then %sx is automatically
2464 invoked. That is, while:
2469 invoked. That is, while:
2465 !ls
2470 !ls
2466 causes ipython to simply issue system('ls'), typing
2471 causes ipython to simply issue system('ls'), typing
2467 !!ls
2472 !!ls
2468 is a shorthand equivalent to:
2473 is a shorthand equivalent to:
2469 %sx ls
2474 %sx ls
2470
2475
2471 2) %sx differs from %sc in that %sx automatically splits into a list,
2476 2) %sx differs from %sc in that %sx automatically splits into a list,
2472 like '%sc -l'. The reason for this is to make it as easy as possible
2477 like '%sc -l'. The reason for this is to make it as easy as possible
2473 to process line-oriented shell output via further python commands.
2478 to process line-oriented shell output via further python commands.
2474 %sc is meant to provide much finer control, but requires more
2479 %sc is meant to provide much finer control, but requires more
2475 typing.
2480 typing.
2476
2481
2477 3) Just like %sc -l, this is a list with special attributes:
2482 3) Just like %sc -l, this is a list with special attributes:
2478
2483
2479 .l (or .list) : value as list.
2484 .l (or .list) : value as list.
2480 .n (or .nlstr): value as newline-separated string.
2485 .n (or .nlstr): value as newline-separated string.
2481 .s (or .spstr): value as whitespace-separated string.
2486 .s (or .spstr): value as whitespace-separated string.
2482
2487
2483 This is very useful when trying to use such lists as arguments to
2488 This is very useful when trying to use such lists as arguments to
2484 system commands."""
2489 system commands."""
2485
2490
2486 if parameter_s:
2491 if parameter_s:
2487 out,err = self.shell.getoutputerror(parameter_s)
2492 out,err = self.shell.getoutputerror(parameter_s)
2488 if err:
2493 if err:
2489 print >> Term.cerr,err
2494 print >> Term.cerr,err
2490 return SList(out.split('\n'))
2495 return SList(out.split('\n'))
2491
2496
2492 def magic_bg(self, parameter_s=''):
2497 def magic_bg(self, parameter_s=''):
2493 """Run a job in the background, in a separate thread.
2498 """Run a job in the background, in a separate thread.
2494
2499
2495 For example,
2500 For example,
2496
2501
2497 %bg myfunc(x,y,z=1)
2502 %bg myfunc(x,y,z=1)
2498
2503
2499 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2504 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2500 execution starts, a message will be printed indicating the job
2505 execution starts, a message will be printed indicating the job
2501 number. If your job number is 5, you can use
2506 number. If your job number is 5, you can use
2502
2507
2503 myvar = jobs.result(5) or myvar = jobs[5].result
2508 myvar = jobs.result(5) or myvar = jobs[5].result
2504
2509
2505 to assign this result to variable 'myvar'.
2510 to assign this result to variable 'myvar'.
2506
2511
2507 IPython has a job manager, accessible via the 'jobs' object. You can
2512 IPython has a job manager, accessible via the 'jobs' object. You can
2508 type jobs? to get more information about it, and use jobs.<TAB> to see
2513 type jobs? to get more information about it, and use jobs.<TAB> to see
2509 its attributes. All attributes not starting with an underscore are
2514 its attributes. All attributes not starting with an underscore are
2510 meant for public use.
2515 meant for public use.
2511
2516
2512 In particular, look at the jobs.new() method, which is used to create
2517 In particular, look at the jobs.new() method, which is used to create
2513 new jobs. This magic %bg function is just a convenience wrapper
2518 new jobs. This magic %bg function is just a convenience wrapper
2514 around jobs.new(), for expression-based jobs. If you want to create a
2519 around jobs.new(), for expression-based jobs. If you want to create a
2515 new job with an explicit function object and arguments, you must call
2520 new job with an explicit function object and arguments, you must call
2516 jobs.new() directly.
2521 jobs.new() directly.
2517
2522
2518 The jobs.new docstring also describes in detail several important
2523 The jobs.new docstring also describes in detail several important
2519 caveats associated with a thread-based model for background job
2524 caveats associated with a thread-based model for background job
2520 execution. Type jobs.new? for details.
2525 execution. Type jobs.new? for details.
2521
2526
2522 You can check the status of all jobs with jobs.status().
2527 You can check the status of all jobs with jobs.status().
2523
2528
2524 The jobs variable is set by IPython into the Python builtin namespace.
2529 The jobs variable is set by IPython into the Python builtin namespace.
2525 If you ever declare a variable named 'jobs', you will shadow this
2530 If you ever declare a variable named 'jobs', you will shadow this
2526 name. You can either delete your global jobs variable to regain
2531 name. You can either delete your global jobs variable to regain
2527 access to the job manager, or make a new name and assign it manually
2532 access to the job manager, or make a new name and assign it manually
2528 to the manager (stored in IPython's namespace). For example, to
2533 to the manager (stored in IPython's namespace). For example, to
2529 assign the job manager to the Jobs name, use:
2534 assign the job manager to the Jobs name, use:
2530
2535
2531 Jobs = __builtins__.jobs"""
2536 Jobs = __builtins__.jobs"""
2532
2537
2533 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2538 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2534
2539
2535 def magic_store(self, parameter_s=''):
2540 def magic_store(self, parameter_s=''):
2536 """Lightweight persistence for python variables.
2541 """Lightweight persistence for python variables.
2537
2542
2538 Example:
2543 Example:
2539
2544
2540 ville@badger[~]|1> A = ['hello',10,'world']\\
2545 ville@badger[~]|1> A = ['hello',10,'world']\\
2541 ville@badger[~]|2> %store A\\
2546 ville@badger[~]|2> %store A\\
2542 ville@badger[~]|3> Exit
2547 ville@badger[~]|3> Exit
2543
2548
2544 (IPython session is closed and started again...)
2549 (IPython session is closed and started again...)
2545
2550
2546 ville@badger:~$ ipython -p pysh\\
2551 ville@badger:~$ ipython -p pysh\\
2547 ville@badger[~]|1> print A
2552 ville@badger[~]|1> print A
2548
2553
2549 ['hello', 10, 'world']
2554 ['hello', 10, 'world']
2550
2555
2551 Usage:
2556 Usage:
2552
2557
2553 %store - Show list of all variables and their current values\\
2558 %store - Show list of all variables and their current values\\
2554 %store <var> - Store the *current* value of the variable to disk\\
2559 %store <var> - Store the *current* value of the variable to disk\\
2555 %store -d - Remove the variable and its value from storage\\
2560 %store -d - Remove the variable and its value from storage\\
2556 %store -r - Remove all variables from storage
2561 %store -r - Remove all variables from storage
2557
2562
2558 It should be noted that if you change the value of a variable, you
2563 It should be noted that if you change the value of a variable, you
2559 need to %store it again if you want to persist the new value.
2564 need to %store it again if you want to persist the new value.
2560
2565
2561 Note also that the variables will need to be pickleable; most basic
2566 Note also that the variables will need to be pickleable; most basic
2562 python types can be safely %stored.
2567 python types can be safely %stored.
2563 """
2568 """
2564
2569
2565 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2570 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2566 # delete
2571 # delete
2567 if opts.has_key('d'):
2572 if opts.has_key('d'):
2568 try:
2573 try:
2569 todel = args[0]
2574 todel = args[0]
2570 except IndexError:
2575 except IndexError:
2571 error('You must provide the variable to forget')
2576 error('You must provide the variable to forget')
2572 else:
2577 else:
2573 try:
2578 try:
2574 del self.shell.persist['S:' + todel]
2579 del self.shell.persist['S:' + todel]
2575 except:
2580 except:
2576 error("Can't delete variable '%s'" % todel)
2581 error("Can't delete variable '%s'" % todel)
2577 # reset
2582 # reset
2578 elif opts.has_key('r'):
2583 elif opts.has_key('r'):
2579 for k in self.shell.persist.keys():
2584 for k in self.shell.persist.keys():
2580 if k.startswith('S:'):
2585 if k.startswith('S:'):
2581 del self.shell.persist[k]
2586 del self.shell.persist[k]
2582
2587
2583 # run without arguments -> list variables & values
2588 # run without arguments -> list variables & values
2584 elif not args:
2589 elif not args:
2585 vars = [v[2:] for v in self.shell.persist.keys()
2590 vars = [v[2:] for v in self.shell.persist.keys()
2586 if v.startswith('S:')]
2591 if v.startswith('S:')]
2587 vars.sort()
2592 vars.sort()
2588 if vars:
2593 if vars:
2589 size = max(map(len,vars))
2594 size = max(map(len,vars))
2590 else:
2595 else:
2591 size = 0
2596 size = 0
2592
2597
2593 print 'Stored variables and their in-memory values:'
2598 print 'Stored variables and their in-memory values:'
2594 fmt = '%-'+str(size)+'s -> %s'
2599 fmt = '%-'+str(size)+'s -> %s'
2595 get = self.shell.user_ns.get
2600 get = self.shell.user_ns.get
2596 for var in vars:
2601 for var in vars:
2597 # print 30 first characters from every var
2602 # print 30 first characters from every var
2598 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2603 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2599
2604
2600 # default action - store the variable
2605 # default action - store the variable
2601 else:
2606 else:
2602 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2607 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2603 self.shell.persist[ 'S:' + args[0] ] = pickled
2608 self.shell.persist[ 'S:' + args[0] ] = pickled
2604 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2609 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2605
2610
2606 def magic_bookmark(self, parameter_s=''):
2611 def magic_bookmark(self, parameter_s=''):
2607 """Manage IPython's bookmark system.
2612 """Manage IPython's bookmark system.
2608
2613
2609 %bookmark <name> - set bookmark to current dir
2614 %bookmark <name> - set bookmark to current dir
2610 %bookmark <name> <dir> - set bookmark to <dir>
2615 %bookmark <name> <dir> - set bookmark to <dir>
2611 %bookmark -l - list all bookmarks
2616 %bookmark -l - list all bookmarks
2612 %bookmark -d <name> - remove bookmark
2617 %bookmark -d <name> - remove bookmark
2613 %bookmark -r - remove all bookmarks
2618 %bookmark -r - remove all bookmarks
2614
2619
2615 You can later on access a bookmarked folder with:
2620 You can later on access a bookmarked folder with:
2616 %cd -b <name>
2621 %cd -b <name>
2617 or simply '%cd <name>' if there is no directory called <name> AND
2622 or simply '%cd <name>' if there is no directory called <name> AND
2618 there is such a bookmark defined.
2623 there is such a bookmark defined.
2619
2624
2620 Your bookmarks persist through IPython sessions, but they are
2625 Your bookmarks persist through IPython sessions, but they are
2621 associated with each profile."""
2626 associated with each profile."""
2622
2627
2623 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2628 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2624 if len(args) > 2:
2629 if len(args) > 2:
2625 error('You can only give at most two arguments')
2630 error('You can only give at most two arguments')
2626 return
2631 return
2627
2632
2628 bkms = self.shell.persist.get('bookmarks',{})
2633 bkms = self.shell.persist.get('bookmarks',{})
2629
2634
2630 if opts.has_key('d'):
2635 if opts.has_key('d'):
2631 try:
2636 try:
2632 todel = args[0]
2637 todel = args[0]
2633 except IndexError:
2638 except IndexError:
2634 error('You must provide a bookmark to delete')
2639 error('You must provide a bookmark to delete')
2635 else:
2640 else:
2636 try:
2641 try:
2637 del bkms[todel]
2642 del bkms[todel]
2638 except:
2643 except:
2639 error("Can't delete bookmark '%s'" % todel)
2644 error("Can't delete bookmark '%s'" % todel)
2640 elif opts.has_key('r'):
2645 elif opts.has_key('r'):
2641 bkms = {}
2646 bkms = {}
2642 elif opts.has_key('l'):
2647 elif opts.has_key('l'):
2643 bks = bkms.keys()
2648 bks = bkms.keys()
2644 bks.sort()
2649 bks.sort()
2645 if bks:
2650 if bks:
2646 size = max(map(len,bks))
2651 size = max(map(len,bks))
2647 else:
2652 else:
2648 size = 0
2653 size = 0
2649 fmt = '%-'+str(size)+'s -> %s'
2654 fmt = '%-'+str(size)+'s -> %s'
2650 print 'Current bookmarks:'
2655 print 'Current bookmarks:'
2651 for bk in bks:
2656 for bk in bks:
2652 print fmt % (bk,bkms[bk])
2657 print fmt % (bk,bkms[bk])
2653 else:
2658 else:
2654 if not args:
2659 if not args:
2655 error("You must specify the bookmark name")
2660 error("You must specify the bookmark name")
2656 elif len(args)==1:
2661 elif len(args)==1:
2657 bkms[args[0]] = os.getcwd()
2662 bkms[args[0]] = os.getcwd()
2658 elif len(args)==2:
2663 elif len(args)==2:
2659 bkms[args[0]] = args[1]
2664 bkms[args[0]] = args[1]
2660 self.shell.persist['bookmarks'] = bkms
2665 self.shell.persist['bookmarks'] = bkms
2661
2666
2662 def magic_pycat(self, parameter_s=''):
2667 def magic_pycat(self, parameter_s=''):
2663 """Show a syntax-highlighted file through a pager.
2668 """Show a syntax-highlighted file through a pager.
2664
2669
2665 This magic is similar to the cat utility, but it will assume the file
2670 This magic is similar to the cat utility, but it will assume the file
2666 to be Python source and will show it with syntax highlighting. """
2671 to be Python source and will show it with syntax highlighting. """
2667
2672
2668 filename = get_py_filename(parameter_s)
2673 filename = get_py_filename(parameter_s)
2669 page(self.shell.colorize(file_read(filename)),
2674 page(self.shell.colorize(file_read(filename)),
2670 screen_lines=self.shell.rc.screen_length)
2675 screen_lines=self.shell.rc.screen_length)
2671
2676
2672 # end Magic
2677 # end Magic
@@ -1,76 +1,76 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Release data for the IPython project.
2 """Release data for the IPython project.
3
3
4 $Id: Release.py 982 2005-12-30 23:57:07Z fperez $"""
4 $Id: Release.py 984 2005-12-31 08:40:31Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
10 # <n8gray@caltech.edu>
10 # <n8gray@caltech.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 # Name of the package for release purposes. This is the name which labels
16 # Name of the package for release purposes. This is the name which labels
17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
18 name = 'ipython'
18 name = 'ipython'
19
19
20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
21 # the new substring. We have to avoid using either dashes or underscores,
21 # the new substring. We have to avoid using either dashes or underscores,
22 # because bdist_rpm does not accept dashes (an RPM) convention, and
22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 # bdist_deb does not accept underscores (a Debian convention).
23 # bdist_deb does not accept underscores (a Debian convention).
24
24
25 version = '0.7.0.rc3'
25 version = '0.7.0.rc4'
26
26
27 revision = '$Revision: 982 $'
27 revision = '$Revision: 984 $'
28
28
29 description = "An enhanced interactive Python shell."
29 description = "An enhanced interactive Python shell."
30
30
31 long_description = \
31 long_description = \
32 """
32 """
33 IPython provides a replacement for the interactive Python interpreter with
33 IPython provides a replacement for the interactive Python interpreter with
34 extra functionality.
34 extra functionality.
35
35
36 Main features:
36 Main features:
37
37
38 * Comprehensive object introspection.
38 * Comprehensive object introspection.
39
39
40 * Input history, persistent across sessions.
40 * Input history, persistent across sessions.
41
41
42 * Caching of output results during a session with automatically generated
42 * Caching of output results during a session with automatically generated
43 references.
43 references.
44
44
45 * Readline based name completion.
45 * Readline based name completion.
46
46
47 * Extensible system of 'magic' commands for controlling the environment and
47 * Extensible system of 'magic' commands for controlling the environment and
48 performing many tasks related either to IPython or the operating system.
48 performing many tasks related either to IPython or the operating system.
49
49
50 * Configuration system with easy switching between different setups (simpler
50 * Configuration system with easy switching between different setups (simpler
51 than changing $PYTHONSTARTUP environment variables every time).
51 than changing $PYTHONSTARTUP environment variables every time).
52
52
53 * Session logging and reloading.
53 * Session logging and reloading.
54
54
55 * Extensible syntax processing for special purpose situations.
55 * Extensible syntax processing for special purpose situations.
56
56
57 * Access to the system shell with user-extensible alias system.
57 * Access to the system shell with user-extensible alias system.
58
58
59 * Easily embeddable in other Python programs.
59 * Easily embeddable in other Python programs.
60
60
61 * Integrated access to the pdb debugger and the Python profiler. """
61 * Integrated access to the pdb debugger and the Python profiler. """
62
62
63 license = 'BSD'
63 license = 'BSD'
64
64
65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu')
67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu')
68 }
68 }
69
69
70 url = 'http://ipython.scipy.org'
70 url = 'http://ipython.scipy.org'
71
71
72 download_url = 'http://ipython.scipy.org/dist'
72 download_url = 'http://ipython.scipy.org/dist'
73
73
74 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
74 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
75
75
76 keywords = ['Interactive','Interpreter','Shell']
76 keywords = ['Interactive','Interpreter','Shell']
@@ -1,2060 +1,2058 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 983 2005-12-31 00:04:25Z fperez $
9 $Id: iplib.py 984 2005-12-31 08:40:31Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import traceback
58 import traceback
59 import types
59 import types
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.Struct import Struct
72 from IPython.Struct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76
76
77 # store the builtin raw_input globally, and use this always, in case user code
77 # store the builtin raw_input globally, and use this always, in case user code
78 # overwrites it (like wx.py.PyShell does)
78 # overwrites it (like wx.py.PyShell does)
79 raw_input_original = raw_input
79 raw_input_original = raw_input
80
80
81 # compiled regexps for autoindent management
81 # compiled regexps for autoindent management
82 ini_spaces_re = re.compile(r'^(\s+)')
82 ini_spaces_re = re.compile(r'^(\s+)')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84
84
85 #****************************************************************************
85 #****************************************************************************
86 # Some utility function definitions
86 # Some utility function definitions
87
87
88 def softspace(file, newvalue):
88 def softspace(file, newvalue):
89 """Copied from code.py, to remove the dependency"""
89 """Copied from code.py, to remove the dependency"""
90 oldvalue = 0
90 oldvalue = 0
91 try:
91 try:
92 oldvalue = file.softspace
92 oldvalue = file.softspace
93 except AttributeError:
93 except AttributeError:
94 pass
94 pass
95 try:
95 try:
96 file.softspace = newvalue
96 file.softspace = newvalue
97 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
98 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
99 pass
99 pass
100 return oldvalue
100 return oldvalue
101
101
102 #****************************************************************************
102 #****************************************************************************
103 # These special functions get installed in the builtin namespace, to provide
103 # These special functions get installed in the builtin namespace, to provide
104 # programmatic (pure python) access to magics, aliases and system calls. This
104 # programmatic (pure python) access to magics, aliases and system calls. This
105 # is important for logging, user scripting, and more.
105 # is important for logging, user scripting, and more.
106
106
107 # We are basically exposing, via normal python functions, the three mechanisms
107 # We are basically exposing, via normal python functions, the three mechanisms
108 # in which ipython offers special call modes (magics for internal control,
108 # in which ipython offers special call modes (magics for internal control,
109 # aliases for direct system access via pre-selected names, and !cmd for
109 # aliases for direct system access via pre-selected names, and !cmd for
110 # calling arbitrary system commands).
110 # calling arbitrary system commands).
111
111
112 def ipmagic(arg_s):
112 def ipmagic(arg_s):
113 """Call a magic function by name.
113 """Call a magic function by name.
114
114
115 Input: a string containing the name of the magic function to call and any
115 Input: a string containing the name of the magic function to call and any
116 additional arguments to be passed to the magic.
116 additional arguments to be passed to the magic.
117
117
118 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
118 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
119 prompt:
119 prompt:
120
120
121 In[1]: %name -opt foo bar
121 In[1]: %name -opt foo bar
122
122
123 To call a magic without arguments, simply use ipmagic('name').
123 To call a magic without arguments, simply use ipmagic('name').
124
124
125 This provides a proper Python function to call IPython's magics in any
125 This provides a proper Python function to call IPython's magics in any
126 valid Python code you can type at the interpreter, including loops and
126 valid Python code you can type at the interpreter, including loops and
127 compound statements. It is added by IPython to the Python builtin
127 compound statements. It is added by IPython to the Python builtin
128 namespace upon initialization."""
128 namespace upon initialization."""
129
129
130 args = arg_s.split(' ',1)
130 args = arg_s.split(' ',1)
131 magic_name = args[0]
131 magic_name = args[0]
132 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
132 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
133 magic_name = magic_name[1:]
133 magic_name = magic_name[1:]
134 try:
134 try:
135 magic_args = args[1]
135 magic_args = args[1]
136 except IndexError:
136 except IndexError:
137 magic_args = ''
137 magic_args = ''
138 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
138 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
139 if fn is None:
139 if fn is None:
140 error("Magic function `%s` not found." % magic_name)
140 error("Magic function `%s` not found." % magic_name)
141 else:
141 else:
142 magic_args = __IPYTHON__.var_expand(magic_args)
142 magic_args = __IPYTHON__.var_expand(magic_args)
143 return fn(magic_args)
143 return fn(magic_args)
144
144
145 def ipalias(arg_s):
145 def ipalias(arg_s):
146 """Call an alias by name.
146 """Call an alias by name.
147
147
148 Input: a string containing the name of the alias to call and any
148 Input: a string containing the name of the alias to call and any
149 additional arguments to be passed to the magic.
149 additional arguments to be passed to the magic.
150
150
151 ipalias('name -opt foo bar') is equivalent to typing at the ipython
151 ipalias('name -opt foo bar') is equivalent to typing at the ipython
152 prompt:
152 prompt:
153
153
154 In[1]: name -opt foo bar
154 In[1]: name -opt foo bar
155
155
156 To call an alias without arguments, simply use ipalias('name').
156 To call an alias without arguments, simply use ipalias('name').
157
157
158 This provides a proper Python function to call IPython's aliases in any
158 This provides a proper Python function to call IPython's aliases in any
159 valid Python code you can type at the interpreter, including loops and
159 valid Python code you can type at the interpreter, including loops and
160 compound statements. It is added by IPython to the Python builtin
160 compound statements. It is added by IPython to the Python builtin
161 namespace upon initialization."""
161 namespace upon initialization."""
162
162
163 args = arg_s.split(' ',1)
163 args = arg_s.split(' ',1)
164 alias_name = args[0]
164 alias_name = args[0]
165 try:
165 try:
166 alias_args = args[1]
166 alias_args = args[1]
167 except IndexError:
167 except IndexError:
168 alias_args = ''
168 alias_args = ''
169 if alias_name in __IPYTHON__.alias_table:
169 if alias_name in __IPYTHON__.alias_table:
170 __IPYTHON__.call_alias(alias_name,alias_args)
170 __IPYTHON__.call_alias(alias_name,alias_args)
171 else:
171 else:
172 error("Alias `%s` not found." % alias_name)
172 error("Alias `%s` not found." % alias_name)
173
173
174 def ipsystem(arg_s):
174 def ipsystem(arg_s):
175 """Make a system call, using IPython."""
175 """Make a system call, using IPython."""
176 __IPYTHON__.system(arg_s)
176 __IPYTHON__.system(arg_s)
177
177
178
178
179 #****************************************************************************
179 #****************************************************************************
180 # Local use exceptions
180 # Local use exceptions
181 class SpaceInInput(exceptions.Exception): pass
181 class SpaceInInput(exceptions.Exception): pass
182
182
183 #****************************************************************************
183 #****************************************************************************
184 # Local use classes
184 # Local use classes
185 class Bunch: pass
185 class Bunch: pass
186
186
187 class InputList(list):
187 class InputList(list):
188 """Class to store user input.
188 """Class to store user input.
189
189
190 It's basically a list, but slices return a string instead of a list, thus
190 It's basically a list, but slices return a string instead of a list, thus
191 allowing things like (assuming 'In' is an instance):
191 allowing things like (assuming 'In' is an instance):
192
192
193 exec In[4:7]
193 exec In[4:7]
194
194
195 or
195 or
196
196
197 exec In[5:9] + In[14] + In[21:25]"""
197 exec In[5:9] + In[14] + In[21:25]"""
198
198
199 def __getslice__(self,i,j):
199 def __getslice__(self,i,j):
200 return ''.join(list.__getslice__(self,i,j))
200 return ''.join(list.__getslice__(self,i,j))
201
201
202 class SyntaxTB(ultraTB.ListTB):
202 class SyntaxTB(ultraTB.ListTB):
203 """Extension which holds some state: the last exception value"""
203 """Extension which holds some state: the last exception value"""
204
204
205 def __init__(self,color_scheme = 'NoColor'):
205 def __init__(self,color_scheme = 'NoColor'):
206 ultraTB.ListTB.__init__(self,color_scheme)
206 ultraTB.ListTB.__init__(self,color_scheme)
207 self.last_syntax_error = None
207 self.last_syntax_error = None
208
208
209 def __call__(self, etype, value, elist):
209 def __call__(self, etype, value, elist):
210 self.last_syntax_error = value
210 self.last_syntax_error = value
211 ultraTB.ListTB.__call__(self,etype,value,elist)
211 ultraTB.ListTB.__call__(self,etype,value,elist)
212
212
213 def clear_err_state(self):
213 def clear_err_state(self):
214 """Return the current error state and clear it"""
214 """Return the current error state and clear it"""
215 e = self.last_syntax_error
215 e = self.last_syntax_error
216 self.last_syntax_error = None
216 self.last_syntax_error = None
217 return e
217 return e
218
218
219 #****************************************************************************
219 #****************************************************************************
220 # Main IPython class
220 # Main IPython class
221
221
222 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
222 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
223 # until a full rewrite is made. I've cleaned all cross-class uses of
223 # until a full rewrite is made. I've cleaned all cross-class uses of
224 # attributes and methods, but too much user code out there relies on the
224 # attributes and methods, but too much user code out there relies on the
225 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
225 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
226 #
226 #
227 # But at least now, all the pieces have been separated and we could, in
227 # But at least now, all the pieces have been separated and we could, in
228 # principle, stop using the mixin. This will ease the transition to the
228 # principle, stop using the mixin. This will ease the transition to the
229 # chainsaw branch.
229 # chainsaw branch.
230
230
231 # For reference, the following is the list of 'self.foo' uses in the Magic
231 # For reference, the following is the list of 'self.foo' uses in the Magic
232 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
232 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
233 # class, to prevent clashes.
233 # class, to prevent clashes.
234
234
235 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
235 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
236 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
236 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
237 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
237 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
238 # 'self.value']
238 # 'self.value']
239
239
240 class InteractiveShell(Magic):
240 class InteractiveShell(object,Magic):
241 """An enhanced console for Python."""
241 """An enhanced console for Python."""
242
242
243 # class attribute to indicate whether the class supports threads or not.
243 # class attribute to indicate whether the class supports threads or not.
244 # Subclasses with thread support should override this as needed.
244 # Subclasses with thread support should override this as needed.
245 isthreaded = False
245 isthreaded = False
246
246
247 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
247 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
248 user_ns = None,user_global_ns=None,banner2='',
248 user_ns = None,user_global_ns=None,banner2='',
249 custom_exceptions=((),None),embedded=False):
249 custom_exceptions=((),None),embedded=False):
250
250
251 # some minimal strict typechecks. For some core data structures, I
251 # some minimal strict typechecks. For some core data structures, I
252 # want actual basic python types, not just anything that looks like
252 # want actual basic python types, not just anything that looks like
253 # one. This is especially true for namespaces.
253 # one. This is especially true for namespaces.
254 for ns in (user_ns,user_global_ns):
254 for ns in (user_ns,user_global_ns):
255 if ns is not None and type(ns) != types.DictType:
255 if ns is not None and type(ns) != types.DictType:
256 raise TypeError,'namespace must be a dictionary'
256 raise TypeError,'namespace must be a dictionary'
257
257
258 # Put a reference to self in builtins so that any form of embedded or
258 # Put a reference to self in builtins so that any form of embedded or
259 # imported code can test for being inside IPython.
259 # imported code can test for being inside IPython.
260 __builtin__.__IPYTHON__ = self
260 __builtin__.__IPYTHON__ = self
261
261
262 # And load into builtins ipmagic/ipalias/ipsystem as well
262 # And load into builtins ipmagic/ipalias/ipsystem as well
263 __builtin__.ipmagic = ipmagic
263 __builtin__.ipmagic = ipmagic
264 __builtin__.ipalias = ipalias
264 __builtin__.ipalias = ipalias
265 __builtin__.ipsystem = ipsystem
265 __builtin__.ipsystem = ipsystem
266
266
267 # Add to __builtin__ other parts of IPython's public API
267 # Add to __builtin__ other parts of IPython's public API
268 __builtin__.ip_set_hook = self.set_hook
268 __builtin__.ip_set_hook = self.set_hook
269
269
270 # Keep in the builtins a flag for when IPython is active. We set it
270 # Keep in the builtins a flag for when IPython is active. We set it
271 # with setdefault so that multiple nested IPythons don't clobber one
271 # with setdefault so that multiple nested IPythons don't clobber one
272 # another. Each will increase its value by one upon being activated,
272 # another. Each will increase its value by one upon being activated,
273 # which also gives us a way to determine the nesting level.
273 # which also gives us a way to determine the nesting level.
274 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
274 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
275
275
276 # Do the intuitively correct thing for quit/exit: we remove the
276 # Do the intuitively correct thing for quit/exit: we remove the
277 # builtins if they exist, and our own prefilter routine will handle
277 # builtins if they exist, and our own prefilter routine will handle
278 # these special cases
278 # these special cases
279 try:
279 try:
280 del __builtin__.exit, __builtin__.quit
280 del __builtin__.exit, __builtin__.quit
281 except AttributeError:
281 except AttributeError:
282 pass
282 pass
283
283
284 # Store the actual shell's name
284 # Store the actual shell's name
285 self.name = name
285 self.name = name
286
286
287 # We need to know whether the instance is meant for embedding, since
287 # We need to know whether the instance is meant for embedding, since
288 # global/local namespaces need to be handled differently in that case
288 # global/local namespaces need to be handled differently in that case
289 self.embedded = embedded
289 self.embedded = embedded
290
290
291 # command compiler
291 # command compiler
292 self.compile = codeop.CommandCompiler()
292 self.compile = codeop.CommandCompiler()
293
293
294 # User input buffer
294 # User input buffer
295 self.buffer = []
295 self.buffer = []
296
296
297 # Default name given in compilation of code
297 # Default name given in compilation of code
298 self.filename = '<ipython console>'
298 self.filename = '<ipython console>'
299
299
300 # Create the namespace where the user will operate. user_ns is
300 # Create the namespace where the user will operate. user_ns is
301 # normally the only one used, and it is passed to the exec calls as
301 # normally the only one used, and it is passed to the exec calls as
302 # the locals argument. But we do carry a user_global_ns namespace
302 # the locals argument. But we do carry a user_global_ns namespace
303 # given as the exec 'globals' argument, This is useful in embedding
303 # given as the exec 'globals' argument, This is useful in embedding
304 # situations where the ipython shell opens in a context where the
304 # situations where the ipython shell opens in a context where the
305 # distinction between locals and globals is meaningful.
305 # distinction between locals and globals is meaningful.
306
306
307 # FIXME. For some strange reason, __builtins__ is showing up at user
307 # FIXME. For some strange reason, __builtins__ is showing up at user
308 # level as a dict instead of a module. This is a manual fix, but I
308 # level as a dict instead of a module. This is a manual fix, but I
309 # should really track down where the problem is coming from. Alex
309 # should really track down where the problem is coming from. Alex
310 # Schmolck reported this problem first.
310 # Schmolck reported this problem first.
311
311
312 # A useful post by Alex Martelli on this topic:
312 # A useful post by Alex Martelli on this topic:
313 # Re: inconsistent value from __builtins__
313 # Re: inconsistent value from __builtins__
314 # Von: Alex Martelli <aleaxit@yahoo.com>
314 # Von: Alex Martelli <aleaxit@yahoo.com>
315 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
315 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
316 # Gruppen: comp.lang.python
316 # Gruppen: comp.lang.python
317
317
318 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
318 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
319 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
319 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
320 # > <type 'dict'>
320 # > <type 'dict'>
321 # > >>> print type(__builtins__)
321 # > >>> print type(__builtins__)
322 # > <type 'module'>
322 # > <type 'module'>
323 # > Is this difference in return value intentional?
323 # > Is this difference in return value intentional?
324
324
325 # Well, it's documented that '__builtins__' can be either a dictionary
325 # Well, it's documented that '__builtins__' can be either a dictionary
326 # or a module, and it's been that way for a long time. Whether it's
326 # or a module, and it's been that way for a long time. Whether it's
327 # intentional (or sensible), I don't know. In any case, the idea is
327 # intentional (or sensible), I don't know. In any case, the idea is
328 # that if you need to access the built-in namespace directly, you
328 # that if you need to access the built-in namespace directly, you
329 # should start with "import __builtin__" (note, no 's') which will
329 # should start with "import __builtin__" (note, no 's') which will
330 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
330 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
331
331
332 if user_ns is None:
332 if user_ns is None:
333 # Set __name__ to __main__ to better match the behavior of the
333 # Set __name__ to __main__ to better match the behavior of the
334 # normal interpreter.
334 # normal interpreter.
335 user_ns = {'__name__' :'__main__',
335 user_ns = {'__name__' :'__main__',
336 '__builtins__' : __builtin__,
336 '__builtins__' : __builtin__,
337 }
337 }
338
338
339 if user_global_ns is None:
339 if user_global_ns is None:
340 user_global_ns = {}
340 user_global_ns = {}
341
341
342 # Assign namespaces
342 # Assign namespaces
343 # This is the namespace where all normal user variables live
343 # This is the namespace where all normal user variables live
344 self.user_ns = user_ns
344 self.user_ns = user_ns
345 # Embedded instances require a separate namespace for globals.
345 # Embedded instances require a separate namespace for globals.
346 # Normally this one is unused by non-embedded instances.
346 # Normally this one is unused by non-embedded instances.
347 self.user_global_ns = user_global_ns
347 self.user_global_ns = user_global_ns
348 # A namespace to keep track of internal data structures to prevent
348 # A namespace to keep track of internal data structures to prevent
349 # them from cluttering user-visible stuff. Will be updated later
349 # them from cluttering user-visible stuff. Will be updated later
350 self.internal_ns = {}
350 self.internal_ns = {}
351
351
352 # Namespace of system aliases. Each entry in the alias
352 # Namespace of system aliases. Each entry in the alias
353 # table must be a 2-tuple of the form (N,name), where N is the number
353 # table must be a 2-tuple of the form (N,name), where N is the number
354 # of positional arguments of the alias.
354 # of positional arguments of the alias.
355 self.alias_table = {}
355 self.alias_table = {}
356
356
357 # A table holding all the namespaces IPython deals with, so that
357 # A table holding all the namespaces IPython deals with, so that
358 # introspection facilities can search easily.
358 # introspection facilities can search easily.
359 self.ns_table = {'user':user_ns,
359 self.ns_table = {'user':user_ns,
360 'user_global':user_global_ns,
360 'user_global':user_global_ns,
361 'alias':self.alias_table,
361 'alias':self.alias_table,
362 'internal':self.internal_ns,
362 'internal':self.internal_ns,
363 'builtin':__builtin__.__dict__
363 'builtin':__builtin__.__dict__
364 }
364 }
365
365
366 # The user namespace MUST have a pointer to the shell itself.
366 # The user namespace MUST have a pointer to the shell itself.
367 self.user_ns[name] = self
367 self.user_ns[name] = self
368
368
369 # We need to insert into sys.modules something that looks like a
369 # We need to insert into sys.modules something that looks like a
370 # module but which accesses the IPython namespace, for shelve and
370 # module but which accesses the IPython namespace, for shelve and
371 # pickle to work interactively. Normally they rely on getting
371 # pickle to work interactively. Normally they rely on getting
372 # everything out of __main__, but for embedding purposes each IPython
372 # everything out of __main__, but for embedding purposes each IPython
373 # instance has its own private namespace, so we can't go shoving
373 # instance has its own private namespace, so we can't go shoving
374 # everything into __main__.
374 # everything into __main__.
375
375
376 # note, however, that we should only do this for non-embedded
376 # note, however, that we should only do this for non-embedded
377 # ipythons, which really mimic the __main__.__dict__ with their own
377 # ipythons, which really mimic the __main__.__dict__ with their own
378 # namespace. Embedded instances, on the other hand, should not do
378 # namespace. Embedded instances, on the other hand, should not do
379 # this because they need to manage the user local/global namespaces
379 # this because they need to manage the user local/global namespaces
380 # only, but they live within a 'normal' __main__ (meaning, they
380 # only, but they live within a 'normal' __main__ (meaning, they
381 # shouldn't overtake the execution environment of the script they're
381 # shouldn't overtake the execution environment of the script they're
382 # embedded in).
382 # embedded in).
383
383
384 if not embedded:
384 if not embedded:
385 try:
385 try:
386 main_name = self.user_ns['__name__']
386 main_name = self.user_ns['__name__']
387 except KeyError:
387 except KeyError:
388 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
388 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
389 else:
389 else:
390 #print "pickle hack in place" # dbg
390 #print "pickle hack in place" # dbg
391 #print 'main_name:',main_name # dbg
391 sys.modules[main_name] = FakeModule(self.user_ns)
392 sys.modules[main_name] = FakeModule(self.user_ns)
392
393
393 # List of input with multi-line handling.
394 # List of input with multi-line handling.
394 # Fill its zero entry, user counter starts at 1
395 # Fill its zero entry, user counter starts at 1
395 self.input_hist = InputList(['\n'])
396 self.input_hist = InputList(['\n'])
396
397
397 # list of visited directories
398 # list of visited directories
398 try:
399 try:
399 self.dir_hist = [os.getcwd()]
400 self.dir_hist = [os.getcwd()]
400 except IOError, e:
401 except IOError, e:
401 self.dir_hist = []
402 self.dir_hist = []
402
403
403 # dict of output history
404 # dict of output history
404 self.output_hist = {}
405 self.output_hist = {}
405
406
406 # dict of things NOT to alias (keywords, builtins and some magics)
407 # dict of things NOT to alias (keywords, builtins and some magics)
407 no_alias = {}
408 no_alias = {}
408 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
409 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
409 for key in keyword.kwlist + no_alias_magics:
410 for key in keyword.kwlist + no_alias_magics:
410 no_alias[key] = 1
411 no_alias[key] = 1
411 no_alias.update(__builtin__.__dict__)
412 no_alias.update(__builtin__.__dict__)
412 self.no_alias = no_alias
413 self.no_alias = no_alias
413
414
414 # make global variables for user access to these
415 # make global variables for user access to these
415 self.user_ns['_ih'] = self.input_hist
416 self.user_ns['_ih'] = self.input_hist
416 self.user_ns['_oh'] = self.output_hist
417 self.user_ns['_oh'] = self.output_hist
417 self.user_ns['_dh'] = self.dir_hist
418 self.user_ns['_dh'] = self.dir_hist
418
419
419 # user aliases to input and output histories
420 # user aliases to input and output histories
420 self.user_ns['In'] = self.input_hist
421 self.user_ns['In'] = self.input_hist
421 self.user_ns['Out'] = self.output_hist
422 self.user_ns['Out'] = self.output_hist
422
423
423 # Object variable to store code object waiting execution. This is
424 # Object variable to store code object waiting execution. This is
424 # used mainly by the multithreaded shells, but it can come in handy in
425 # used mainly by the multithreaded shells, but it can come in handy in
425 # other situations. No need to use a Queue here, since it's a single
426 # other situations. No need to use a Queue here, since it's a single
426 # item which gets cleared once run.
427 # item which gets cleared once run.
427 self.code_to_run = None
428 self.code_to_run = None
428
429
429 # Job manager (for jobs run as background threads)
430 # Job manager (for jobs run as background threads)
430 self.jobs = BackgroundJobManager()
431 self.jobs = BackgroundJobManager()
431 # Put the job manager into builtins so it's always there.
432 # Put the job manager into builtins so it's always there.
432 __builtin__.jobs = self.jobs
433 __builtin__.jobs = self.jobs
433
434
434 # escapes for automatic behavior on the command line
435 # escapes for automatic behavior on the command line
435 self.ESC_SHELL = '!'
436 self.ESC_SHELL = '!'
436 self.ESC_HELP = '?'
437 self.ESC_HELP = '?'
437 self.ESC_MAGIC = '%'
438 self.ESC_MAGIC = '%'
438 self.ESC_QUOTE = ','
439 self.ESC_QUOTE = ','
439 self.ESC_QUOTE2 = ';'
440 self.ESC_QUOTE2 = ';'
440 self.ESC_PAREN = '/'
441 self.ESC_PAREN = '/'
441
442
442 # And their associated handlers
443 # And their associated handlers
443 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
444 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
444 self.ESC_QUOTE : self.handle_auto,
445 self.ESC_QUOTE : self.handle_auto,
445 self.ESC_QUOTE2 : self.handle_auto,
446 self.ESC_QUOTE2 : self.handle_auto,
446 self.ESC_MAGIC : self.handle_magic,
447 self.ESC_MAGIC : self.handle_magic,
447 self.ESC_HELP : self.handle_help,
448 self.ESC_HELP : self.handle_help,
448 self.ESC_SHELL : self.handle_shell_escape,
449 self.ESC_SHELL : self.handle_shell_escape,
449 }
450 }
450
451
451 # class initializations
452 # class initializations
452 Magic.__init__(self,self)
453 Magic.__init__(self,self)
453
454
454 # Python source parser/formatter for syntax highlighting
455 # Python source parser/formatter for syntax highlighting
455 pyformat = PyColorize.Parser().format
456 pyformat = PyColorize.Parser().format
456 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
457 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
457
458
458 # hooks holds pointers used for user-side customizations
459 # hooks holds pointers used for user-side customizations
459 self.hooks = Struct()
460 self.hooks = Struct()
460
461
461 # Set all default hooks, defined in the IPython.hooks module.
462 # Set all default hooks, defined in the IPython.hooks module.
462 hooks = IPython.hooks
463 hooks = IPython.hooks
463 for hook_name in hooks.__all__:
464 for hook_name in hooks.__all__:
464 self.set_hook(hook_name,getattr(hooks,hook_name))
465 self.set_hook(hook_name,getattr(hooks,hook_name))
465
466
466 # Flag to mark unconditional exit
467 # Flag to mark unconditional exit
467 self.exit_now = False
468 self.exit_now = False
468
469
469 self.usage_min = """\
470 self.usage_min = """\
470 An enhanced console for Python.
471 An enhanced console for Python.
471 Some of its features are:
472 Some of its features are:
472 - Readline support if the readline library is present.
473 - Readline support if the readline library is present.
473 - Tab completion in the local namespace.
474 - Tab completion in the local namespace.
474 - Logging of input, see command-line options.
475 - Logging of input, see command-line options.
475 - System shell escape via ! , eg !ls.
476 - System shell escape via ! , eg !ls.
476 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
477 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
477 - Keeps track of locally defined variables via %who, %whos.
478 - Keeps track of locally defined variables via %who, %whos.
478 - Show object information with a ? eg ?x or x? (use ?? for more info).
479 - Show object information with a ? eg ?x or x? (use ?? for more info).
479 """
480 """
480 if usage: self.usage = usage
481 if usage: self.usage = usage
481 else: self.usage = self.usage_min
482 else: self.usage = self.usage_min
482
483
483 # Storage
484 # Storage
484 self.rc = rc # This will hold all configuration information
485 self.rc = rc # This will hold all configuration information
485 self.pager = 'less'
486 self.pager = 'less'
486 # temporary files used for various purposes. Deleted at exit.
487 # temporary files used for various purposes. Deleted at exit.
487 self.tempfiles = []
488 self.tempfiles = []
488
489
489 # Keep track of readline usage (later set by init_readline)
490 # Keep track of readline usage (later set by init_readline)
490 self.has_readline = False
491 self.has_readline = False
491
492
492 # template for logfile headers. It gets resolved at runtime by the
493 # template for logfile headers. It gets resolved at runtime by the
493 # logstart method.
494 # logstart method.
494 self.loghead_tpl = \
495 self.loghead_tpl = \
495 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
496 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
496 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
497 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
497 #log# opts = %s
498 #log# opts = %s
498 #log# args = %s
499 #log# args = %s
499 #log# It is safe to make manual edits below here.
500 #log# It is safe to make manual edits below here.
500 #log#-----------------------------------------------------------------------
501 #log#-----------------------------------------------------------------------
501 """
502 """
502 # for pushd/popd management
503 # for pushd/popd management
503 try:
504 try:
504 self.home_dir = get_home_dir()
505 self.home_dir = get_home_dir()
505 except HomeDirError,msg:
506 except HomeDirError,msg:
506 fatal(msg)
507 fatal(msg)
507
508
508 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
509 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
509
510
510 # Functions to call the underlying shell.
511 # Functions to call the underlying shell.
511
512
512 # utility to expand user variables via Itpl
513 # utility to expand user variables via Itpl
513 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
514 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
514 self.user_ns))
515 self.user_ns))
515 # The first is similar to os.system, but it doesn't return a value,
516 # The first is similar to os.system, but it doesn't return a value,
516 # and it allows interpolation of variables in the user's namespace.
517 # and it allows interpolation of variables in the user's namespace.
517 self.system = lambda cmd: shell(self.var_expand(cmd),
518 self.system = lambda cmd: shell(self.var_expand(cmd),
518 header='IPython system call: ',
519 header='IPython system call: ',
519 verbose=self.rc.system_verbose)
520 verbose=self.rc.system_verbose)
520 # These are for getoutput and getoutputerror:
521 # These are for getoutput and getoutputerror:
521 self.getoutput = lambda cmd: \
522 self.getoutput = lambda cmd: \
522 getoutput(self.var_expand(cmd),
523 getoutput(self.var_expand(cmd),
523 header='IPython system call: ',
524 header='IPython system call: ',
524 verbose=self.rc.system_verbose)
525 verbose=self.rc.system_verbose)
525 self.getoutputerror = lambda cmd: \
526 self.getoutputerror = lambda cmd: \
526 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
527 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
527 self.user_ns)),
528 self.user_ns)),
528 header='IPython system call: ',
529 header='IPython system call: ',
529 verbose=self.rc.system_verbose)
530 verbose=self.rc.system_verbose)
530
531
531 # RegExp for splitting line contents into pre-char//first
532 # RegExp for splitting line contents into pre-char//first
532 # word-method//rest. For clarity, each group in on one line.
533 # word-method//rest. For clarity, each group in on one line.
533
534
534 # WARNING: update the regexp if the above escapes are changed, as they
535 # WARNING: update the regexp if the above escapes are changed, as they
535 # are hardwired in.
536 # are hardwired in.
536
537
537 # Don't get carried away with trying to make the autocalling catch too
538 # Don't get carried away with trying to make the autocalling catch too
538 # much: it's better to be conservative rather than to trigger hidden
539 # much: it's better to be conservative rather than to trigger hidden
539 # evals() somewhere and end up causing side effects.
540 # evals() somewhere and end up causing side effects.
540
541
541 self.line_split = re.compile(r'^([\s*,;/])'
542 self.line_split = re.compile(r'^([\s*,;/])'
542 r'([\?\w\.]+\w*\s*)'
543 r'([\?\w\.]+\w*\s*)'
543 r'(\(?.*$)')
544 r'(\(?.*$)')
544
545
545 # Original re, keep around for a while in case changes break something
546 # Original re, keep around for a while in case changes break something
546 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
547 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
547 # r'(\s*[\?\w\.]+\w*\s*)'
548 # r'(\s*[\?\w\.]+\w*\s*)'
548 # r'(\(?.*$)')
549 # r'(\(?.*$)')
549
550
550 # RegExp to identify potential function names
551 # RegExp to identify potential function names
551 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
552 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
552 # RegExp to exclude strings with this start from autocalling
553 # RegExp to exclude strings with this start from autocalling
553 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
554 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
554
555
555 # try to catch also methods for stuff in lists/tuples/dicts: off
556 # try to catch also methods for stuff in lists/tuples/dicts: off
556 # (experimental). For this to work, the line_split regexp would need
557 # (experimental). For this to work, the line_split regexp would need
557 # to be modified so it wouldn't break things at '['. That line is
558 # to be modified so it wouldn't break things at '['. That line is
558 # nasty enough that I shouldn't change it until I can test it _well_.
559 # nasty enough that I shouldn't change it until I can test it _well_.
559 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
560 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
560
561
561 # keep track of where we started running (mainly for crash post-mortem)
562 # keep track of where we started running (mainly for crash post-mortem)
562 self.starting_dir = os.getcwd()
563 self.starting_dir = os.getcwd()
563
564
564 # Various switches which can be set
565 # Various switches which can be set
565 self.CACHELENGTH = 5000 # this is cheap, it's just text
566 self.CACHELENGTH = 5000 # this is cheap, it's just text
566 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
567 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
567 self.banner2 = banner2
568 self.banner2 = banner2
568
569
569 # TraceBack handlers:
570 # TraceBack handlers:
570
571
571 # Syntax error handler.
572 # Syntax error handler.
572 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
573 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
573
574
574 # The interactive one is initialized with an offset, meaning we always
575 # The interactive one is initialized with an offset, meaning we always
575 # want to remove the topmost item in the traceback, which is our own
576 # want to remove the topmost item in the traceback, which is our own
576 # internal code. Valid modes: ['Plain','Context','Verbose']
577 # internal code. Valid modes: ['Plain','Context','Verbose']
577 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
578 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
578 color_scheme='NoColor',
579 color_scheme='NoColor',
579 tb_offset = 1)
580 tb_offset = 1)
580
581
581 # IPython itself shouldn't crash. This will produce a detailed
582 # IPython itself shouldn't crash. This will produce a detailed
582 # post-mortem if it does. But we only install the crash handler for
583 # post-mortem if it does. But we only install the crash handler for
583 # non-threaded shells, the threaded ones use a normal verbose reporter
584 # non-threaded shells, the threaded ones use a normal verbose reporter
584 # and lose the crash handler. This is because exceptions in the main
585 # and lose the crash handler. This is because exceptions in the main
585 # thread (such as in GUI code) propagate directly to sys.excepthook,
586 # thread (such as in GUI code) propagate directly to sys.excepthook,
586 # and there's no point in printing crash dumps for every user exception.
587 # and there's no point in printing crash dumps for every user exception.
587 if self.isthreaded:
588 if self.isthreaded:
588 sys.excepthook = ultraTB.FormattedTB()
589 sys.excepthook = ultraTB.FormattedTB()
589 else:
590 else:
590 from IPython import CrashHandler
591 from IPython import CrashHandler
591 sys.excepthook = CrashHandler.CrashHandler(self)
592 sys.excepthook = CrashHandler.CrashHandler(self)
592
593
593 # The instance will store a pointer to this, so that runtime code
594 # The instance will store a pointer to this, so that runtime code
594 # (such as magics) can access it. This is because during the
595 # (such as magics) can access it. This is because during the
595 # read-eval loop, it gets temporarily overwritten (to deal with GUI
596 # read-eval loop, it gets temporarily overwritten (to deal with GUI
596 # frameworks).
597 # frameworks).
597 self.sys_excepthook = sys.excepthook
598 self.sys_excepthook = sys.excepthook
598
599
599 # and add any custom exception handlers the user may have specified
600 # and add any custom exception handlers the user may have specified
600 self.set_custom_exc(*custom_exceptions)
601 self.set_custom_exc(*custom_exceptions)
601
602
602 # Object inspector
603 # Object inspector
603 self.inspector = OInspect.Inspector(OInspect.InspectColors,
604 self.inspector = OInspect.Inspector(OInspect.InspectColors,
604 PyColorize.ANSICodeColors,
605 PyColorize.ANSICodeColors,
605 'NoColor')
606 'NoColor')
606 # indentation management
607 # indentation management
607 self.autoindent = False
608 self.autoindent = False
608 self.indent_current_nsp = 0
609 self.indent_current_nsp = 0
609 self.indent_current = '' # actual indent string
610 self.indent_current = '' # actual indent string
610
611
611 # Make some aliases automatically
612 # Make some aliases automatically
612 # Prepare list of shell aliases to auto-define
613 # Prepare list of shell aliases to auto-define
613 if os.name == 'posix':
614 if os.name == 'posix':
614 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
615 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
615 'mv mv -i','rm rm -i','cp cp -i',
616 'mv mv -i','rm rm -i','cp cp -i',
616 'cat cat','less less','clear clear',
617 'cat cat','less less','clear clear',
617 # a better ls
618 # a better ls
618 'ls ls -F',
619 'ls ls -F',
619 # long ls
620 # long ls
620 'll ls -lF',
621 'll ls -lF',
621 # color ls
622 # color ls
622 'lc ls -F -o --color',
623 'lc ls -F -o --color',
623 # ls normal files only
624 # ls normal files only
624 'lf ls -F -o --color %l | grep ^-',
625 'lf ls -F -o --color %l | grep ^-',
625 # ls symbolic links
626 # ls symbolic links
626 'lk ls -F -o --color %l | grep ^l',
627 'lk ls -F -o --color %l | grep ^l',
627 # directories or links to directories,
628 # directories or links to directories,
628 'ldir ls -F -o --color %l | grep /$',
629 'ldir ls -F -o --color %l | grep /$',
629 # things which are executable
630 # things which are executable
630 'lx ls -F -o --color %l | grep ^-..x',
631 'lx ls -F -o --color %l | grep ^-..x',
631 )
632 )
632 elif os.name in ['nt','dos']:
633 elif os.name in ['nt','dos']:
633 auto_alias = ('dir dir /on', 'ls dir /on',
634 auto_alias = ('dir dir /on', 'ls dir /on',
634 'ddir dir /ad /on', 'ldir dir /ad /on',
635 'ddir dir /ad /on', 'ldir dir /ad /on',
635 'mkdir mkdir','rmdir rmdir','echo echo',
636 'mkdir mkdir','rmdir rmdir','echo echo',
636 'ren ren','cls cls','copy copy')
637 'ren ren','cls cls','copy copy')
637 else:
638 else:
638 auto_alias = ()
639 auto_alias = ()
639 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
640 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
640 # Call the actual (public) initializer
641 # Call the actual (public) initializer
641 self.init_auto_alias()
642 self.init_auto_alias()
642 # end __init__
643 # end __init__
643
644
644 def post_config_initialization(self):
645 def post_config_initialization(self):
645 """Post configuration init method
646 """Post configuration init method
646
647
647 This is called after the configuration files have been processed to
648 This is called after the configuration files have been processed to
648 'finalize' the initialization."""
649 'finalize' the initialization."""
649
650
650 rc = self.rc
651 rc = self.rc
651
652
652 # Load readline proper
653 # Load readline proper
653 if rc.readline:
654 if rc.readline:
654 self.init_readline()
655 self.init_readline()
655
656
656 # log system
657 # log system
657 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
658 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
658 # local shortcut, this is used a LOT
659 # local shortcut, this is used a LOT
659 self.log = self.logger.log
660 self.log = self.logger.log
660
661
661 # Initialize cache, set in/out prompts and printing system
662 # Initialize cache, set in/out prompts and printing system
662 self.outputcache = CachedOutput(self,
663 self.outputcache = CachedOutput(self,
663 rc.cache_size,
664 rc.cache_size,
664 rc.pprint,
665 rc.pprint,
665 input_sep = rc.separate_in,
666 input_sep = rc.separate_in,
666 output_sep = rc.separate_out,
667 output_sep = rc.separate_out,
667 output_sep2 = rc.separate_out2,
668 output_sep2 = rc.separate_out2,
668 ps1 = rc.prompt_in1,
669 ps1 = rc.prompt_in1,
669 ps2 = rc.prompt_in2,
670 ps2 = rc.prompt_in2,
670 ps_out = rc.prompt_out,
671 ps_out = rc.prompt_out,
671 pad_left = rc.prompts_pad_left)
672 pad_left = rc.prompts_pad_left)
672
673
673 # user may have over-ridden the default print hook:
674 # user may have over-ridden the default print hook:
674 try:
675 try:
675 self.outputcache.__class__.display = self.hooks.display
676 self.outputcache.__class__.display = self.hooks.display
676 except AttributeError:
677 except AttributeError:
677 pass
678 pass
678
679
679 # I don't like assigning globally to sys, because it means when embedding
680 # I don't like assigning globally to sys, because it means when embedding
680 # instances, each embedded instance overrides the previous choice. But
681 # instances, each embedded instance overrides the previous choice. But
681 # sys.displayhook seems to be called internally by exec, so I don't see a
682 # sys.displayhook seems to be called internally by exec, so I don't see a
682 # way around it.
683 # way around it.
683 sys.displayhook = self.outputcache
684 sys.displayhook = self.outputcache
684
685
685 # Set user colors (don't do it in the constructor above so that it
686 # Set user colors (don't do it in the constructor above so that it
686 # doesn't crash if colors option is invalid)
687 # doesn't crash if colors option is invalid)
687 self.magic_colors(rc.colors)
688 self.magic_colors(rc.colors)
688
689
689 # Set calling of pdb on exceptions
690 # Set calling of pdb on exceptions
690 self.call_pdb = rc.pdb
691 self.call_pdb = rc.pdb
691
692
692 # Load user aliases
693 # Load user aliases
693 for alias in rc.alias:
694 for alias in rc.alias:
694 self.magic_alias(alias)
695 self.magic_alias(alias)
695
696
696 # dynamic data that survives through sessions
697 # dynamic data that survives through sessions
697 # XXX make the filename a config option?
698 # XXX make the filename a config option?
698 persist_base = 'persist'
699 persist_base = 'persist'
699 if rc.profile:
700 if rc.profile:
700 persist_base += '_%s' % rc.profile
701 persist_base += '_%s' % rc.profile
701 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
702 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
702
703
703 try:
704 try:
704 self.persist = pickle.load(file(self.persist_fname))
705 self.persist = pickle.load(file(self.persist_fname))
705 except:
706 except:
706 self.persist = {}
707 self.persist = {}
707
708
708
709
709 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
710 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
710 try:
711 try:
711 obj = pickle.loads(value)
712 obj = pickle.loads(value)
712 except:
713 except:
713
714
714 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
715 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
715 print "The error was:",sys.exc_info()[0]
716 print "The error was:",sys.exc_info()[0]
716 continue
717 continue
717
718
718
719
719 self.user_ns[key] = obj
720 self.user_ns[key] = obj
720
721
721
722
723
724 def set_hook(self,name,hook):
722 def set_hook(self,name,hook):
725 """set_hook(name,hook) -> sets an internal IPython hook.
723 """set_hook(name,hook) -> sets an internal IPython hook.
726
724
727 IPython exposes some of its internal API as user-modifiable hooks. By
725 IPython exposes some of its internal API as user-modifiable hooks. By
728 resetting one of these hooks, you can modify IPython's behavior to
726 resetting one of these hooks, you can modify IPython's behavior to
729 call at runtime your own routines."""
727 call at runtime your own routines."""
730
728
731 # At some point in the future, this should validate the hook before it
729 # At some point in the future, this should validate the hook before it
732 # accepts it. Probably at least check that the hook takes the number
730 # accepts it. Probably at least check that the hook takes the number
733 # of args it's supposed to.
731 # of args it's supposed to.
734 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
732 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
735
733
736 def set_custom_exc(self,exc_tuple,handler):
734 def set_custom_exc(self,exc_tuple,handler):
737 """set_custom_exc(exc_tuple,handler)
735 """set_custom_exc(exc_tuple,handler)
738
736
739 Set a custom exception handler, which will be called if any of the
737 Set a custom exception handler, which will be called if any of the
740 exceptions in exc_tuple occur in the mainloop (specifically, in the
738 exceptions in exc_tuple occur in the mainloop (specifically, in the
741 runcode() method.
739 runcode() method.
742
740
743 Inputs:
741 Inputs:
744
742
745 - exc_tuple: a *tuple* of valid exceptions to call the defined
743 - exc_tuple: a *tuple* of valid exceptions to call the defined
746 handler for. It is very important that you use a tuple, and NOT A
744 handler for. It is very important that you use a tuple, and NOT A
747 LIST here, because of the way Python's except statement works. If
745 LIST here, because of the way Python's except statement works. If
748 you only want to trap a single exception, use a singleton tuple:
746 you only want to trap a single exception, use a singleton tuple:
749
747
750 exc_tuple == (MyCustomException,)
748 exc_tuple == (MyCustomException,)
751
749
752 - handler: this must be defined as a function with the following
750 - handler: this must be defined as a function with the following
753 basic interface: def my_handler(self,etype,value,tb).
751 basic interface: def my_handler(self,etype,value,tb).
754
752
755 This will be made into an instance method (via new.instancemethod)
753 This will be made into an instance method (via new.instancemethod)
756 of IPython itself, and it will be called if any of the exceptions
754 of IPython itself, and it will be called if any of the exceptions
757 listed in the exc_tuple are caught. If the handler is None, an
755 listed in the exc_tuple are caught. If the handler is None, an
758 internal basic one is used, which just prints basic info.
756 internal basic one is used, which just prints basic info.
759
757
760 WARNING: by putting in your own exception handler into IPython's main
758 WARNING: by putting in your own exception handler into IPython's main
761 execution loop, you run a very good chance of nasty crashes. This
759 execution loop, you run a very good chance of nasty crashes. This
762 facility should only be used if you really know what you are doing."""
760 facility should only be used if you really know what you are doing."""
763
761
764 assert type(exc_tuple)==type(()) , \
762 assert type(exc_tuple)==type(()) , \
765 "The custom exceptions must be given AS A TUPLE."
763 "The custom exceptions must be given AS A TUPLE."
766
764
767 def dummy_handler(self,etype,value,tb):
765 def dummy_handler(self,etype,value,tb):
768 print '*** Simple custom exception handler ***'
766 print '*** Simple custom exception handler ***'
769 print 'Exception type :',etype
767 print 'Exception type :',etype
770 print 'Exception value:',value
768 print 'Exception value:',value
771 print 'Traceback :',tb
769 print 'Traceback :',tb
772 print 'Source code :','\n'.join(self.buffer)
770 print 'Source code :','\n'.join(self.buffer)
773
771
774 if handler is None: handler = dummy_handler
772 if handler is None: handler = dummy_handler
775
773
776 self.CustomTB = new.instancemethod(handler,self,self.__class__)
774 self.CustomTB = new.instancemethod(handler,self,self.__class__)
777 self.custom_exceptions = exc_tuple
775 self.custom_exceptions = exc_tuple
778
776
779 def set_custom_completer(self,completer,pos=0):
777 def set_custom_completer(self,completer,pos=0):
780 """set_custom_completer(completer,pos=0)
778 """set_custom_completer(completer,pos=0)
781
779
782 Adds a new custom completer function.
780 Adds a new custom completer function.
783
781
784 The position argument (defaults to 0) is the index in the completers
782 The position argument (defaults to 0) is the index in the completers
785 list where you want the completer to be inserted."""
783 list where you want the completer to be inserted."""
786
784
787 newcomp = new.instancemethod(completer,self.Completer,
785 newcomp = new.instancemethod(completer,self.Completer,
788 self.Completer.__class__)
786 self.Completer.__class__)
789 self.Completer.matchers.insert(pos,newcomp)
787 self.Completer.matchers.insert(pos,newcomp)
790
788
791 def _get_call_pdb(self):
789 def _get_call_pdb(self):
792 return self._call_pdb
790 return self._call_pdb
793
791
794 def _set_call_pdb(self,val):
792 def _set_call_pdb(self,val):
795
793
796 if val not in (0,1,False,True):
794 if val not in (0,1,False,True):
797 raise ValueError,'new call_pdb value must be boolean'
795 raise ValueError,'new call_pdb value must be boolean'
798
796
799 # store value in instance
797 # store value in instance
800 self._call_pdb = val
798 self._call_pdb = val
801
799
802 # notify the actual exception handlers
800 # notify the actual exception handlers
803 self.InteractiveTB.call_pdb = val
801 self.InteractiveTB.call_pdb = val
804 if self.isthreaded:
802 if self.isthreaded:
805 try:
803 try:
806 self.sys_excepthook.call_pdb = val
804 self.sys_excepthook.call_pdb = val
807 except:
805 except:
808 warn('Failed to activate pdb for threaded exception handler')
806 warn('Failed to activate pdb for threaded exception handler')
809
807
810 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
808 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
811 'Control auto-activation of pdb at exceptions')
809 'Control auto-activation of pdb at exceptions')
812
810
813 def complete(self,text):
811 def complete(self,text):
814 """Return a sorted list of all possible completions on text.
812 """Return a sorted list of all possible completions on text.
815
813
816 Inputs:
814 Inputs:
817
815
818 - text: a string of text to be completed on.
816 - text: a string of text to be completed on.
819
817
820 This is a wrapper around the completion mechanism, similar to what
818 This is a wrapper around the completion mechanism, similar to what
821 readline does at the command line when the TAB key is hit. By
819 readline does at the command line when the TAB key is hit. By
822 exposing it as a method, it can be used by other non-readline
820 exposing it as a method, it can be used by other non-readline
823 environments (such as GUIs) for text completion.
821 environments (such as GUIs) for text completion.
824
822
825 Simple usage example:
823 Simple usage example:
826
824
827 In [1]: x = 'hello'
825 In [1]: x = 'hello'
828
826
829 In [2]: __IP.complete('x.l')
827 In [2]: __IP.complete('x.l')
830 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
828 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
831
829
832 complete = self.Completer.complete
830 complete = self.Completer.complete
833 state = 0
831 state = 0
834 # use a dict so we get unique keys, since ipyhton's multiple
832 # use a dict so we get unique keys, since ipyhton's multiple
835 # completers can return duplicates.
833 # completers can return duplicates.
836 comps = {}
834 comps = {}
837 while True:
835 while True:
838 newcomp = complete(text,state)
836 newcomp = complete(text,state)
839 if newcomp is None:
837 if newcomp is None:
840 break
838 break
841 comps[newcomp] = 1
839 comps[newcomp] = 1
842 state += 1
840 state += 1
843 outcomps = comps.keys()
841 outcomps = comps.keys()
844 outcomps.sort()
842 outcomps.sort()
845 return outcomps
843 return outcomps
846
844
847 def set_completer_frame(self, frame):
845 def set_completer_frame(self, frame):
848 if frame:
846 if frame:
849 self.Completer.namespace = frame.f_locals
847 self.Completer.namespace = frame.f_locals
850 self.Completer.global_namespace = frame.f_globals
848 self.Completer.global_namespace = frame.f_globals
851 else:
849 else:
852 self.Completer.namespace = self.user_ns
850 self.Completer.namespace = self.user_ns
853 self.Completer.global_namespace = self.user_global_ns
851 self.Completer.global_namespace = self.user_global_ns
854
852
855 def init_auto_alias(self):
853 def init_auto_alias(self):
856 """Define some aliases automatically.
854 """Define some aliases automatically.
857
855
858 These are ALL parameter-less aliases"""
856 These are ALL parameter-less aliases"""
859 for alias,cmd in self.auto_alias:
857 for alias,cmd in self.auto_alias:
860 self.alias_table[alias] = (0,cmd)
858 self.alias_table[alias] = (0,cmd)
861
859
862 def alias_table_validate(self,verbose=0):
860 def alias_table_validate(self,verbose=0):
863 """Update information about the alias table.
861 """Update information about the alias table.
864
862
865 In particular, make sure no Python keywords/builtins are in it."""
863 In particular, make sure no Python keywords/builtins are in it."""
866
864
867 no_alias = self.no_alias
865 no_alias = self.no_alias
868 for k in self.alias_table.keys():
866 for k in self.alias_table.keys():
869 if k in no_alias:
867 if k in no_alias:
870 del self.alias_table[k]
868 del self.alias_table[k]
871 if verbose:
869 if verbose:
872 print ("Deleting alias <%s>, it's a Python "
870 print ("Deleting alias <%s>, it's a Python "
873 "keyword or builtin." % k)
871 "keyword or builtin." % k)
874
872
875 def set_autoindent(self,value=None):
873 def set_autoindent(self,value=None):
876 """Set the autoindent flag, checking for readline support.
874 """Set the autoindent flag, checking for readline support.
877
875
878 If called with no arguments, it acts as a toggle."""
876 If called with no arguments, it acts as a toggle."""
879
877
880 if not self.has_readline:
878 if not self.has_readline:
881 if os.name == 'posix':
879 if os.name == 'posix':
882 warn("The auto-indent feature requires the readline library")
880 warn("The auto-indent feature requires the readline library")
883 self.autoindent = 0
881 self.autoindent = 0
884 return
882 return
885 if value is None:
883 if value is None:
886 self.autoindent = not self.autoindent
884 self.autoindent = not self.autoindent
887 else:
885 else:
888 self.autoindent = value
886 self.autoindent = value
889
887
890 def rc_set_toggle(self,rc_field,value=None):
888 def rc_set_toggle(self,rc_field,value=None):
891 """Set or toggle a field in IPython's rc config. structure.
889 """Set or toggle a field in IPython's rc config. structure.
892
890
893 If called with no arguments, it acts as a toggle.
891 If called with no arguments, it acts as a toggle.
894
892
895 If called with a non-existent field, the resulting AttributeError
893 If called with a non-existent field, the resulting AttributeError
896 exception will propagate out."""
894 exception will propagate out."""
897
895
898 rc_val = getattr(self.rc,rc_field)
896 rc_val = getattr(self.rc,rc_field)
899 if value is None:
897 if value is None:
900 value = not rc_val
898 value = not rc_val
901 setattr(self.rc,rc_field,value)
899 setattr(self.rc,rc_field,value)
902
900
903 def user_setup(self,ipythondir,rc_suffix,mode='install'):
901 def user_setup(self,ipythondir,rc_suffix,mode='install'):
904 """Install the user configuration directory.
902 """Install the user configuration directory.
905
903
906 Can be called when running for the first time or to upgrade the user's
904 Can be called when running for the first time or to upgrade the user's
907 .ipython/ directory with the mode parameter. Valid modes are 'install'
905 .ipython/ directory with the mode parameter. Valid modes are 'install'
908 and 'upgrade'."""
906 and 'upgrade'."""
909
907
910 def wait():
908 def wait():
911 try:
909 try:
912 raw_input("Please press <RETURN> to start IPython.")
910 raw_input("Please press <RETURN> to start IPython.")
913 except EOFError:
911 except EOFError:
914 print >> Term.cout
912 print >> Term.cout
915 print '*'*70
913 print '*'*70
916
914
917 cwd = os.getcwd() # remember where we started
915 cwd = os.getcwd() # remember where we started
918 glb = glob.glob
916 glb = glob.glob
919 print '*'*70
917 print '*'*70
920 if mode == 'install':
918 if mode == 'install':
921 print \
919 print \
922 """Welcome to IPython. I will try to create a personal configuration directory
920 """Welcome to IPython. I will try to create a personal configuration directory
923 where you can customize many aspects of IPython's functionality in:\n"""
921 where you can customize many aspects of IPython's functionality in:\n"""
924 else:
922 else:
925 print 'I am going to upgrade your configuration in:'
923 print 'I am going to upgrade your configuration in:'
926
924
927 print ipythondir
925 print ipythondir
928
926
929 rcdirend = os.path.join('IPython','UserConfig')
927 rcdirend = os.path.join('IPython','UserConfig')
930 cfg = lambda d: os.path.join(d,rcdirend)
928 cfg = lambda d: os.path.join(d,rcdirend)
931 try:
929 try:
932 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
930 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
933 except IOError:
931 except IOError:
934 warning = """
932 warning = """
935 Installation error. IPython's directory was not found.
933 Installation error. IPython's directory was not found.
936
934
937 Check the following:
935 Check the following:
938
936
939 The ipython/IPython directory should be in a directory belonging to your
937 The ipython/IPython directory should be in a directory belonging to your
940 PYTHONPATH environment variable (that is, it should be in a directory
938 PYTHONPATH environment variable (that is, it should be in a directory
941 belonging to sys.path). You can copy it explicitly there or just link to it.
939 belonging to sys.path). You can copy it explicitly there or just link to it.
942
940
943 IPython will proceed with builtin defaults.
941 IPython will proceed with builtin defaults.
944 """
942 """
945 warn(warning)
943 warn(warning)
946 wait()
944 wait()
947 return
945 return
948
946
949 if mode == 'install':
947 if mode == 'install':
950 try:
948 try:
951 shutil.copytree(rcdir,ipythondir)
949 shutil.copytree(rcdir,ipythondir)
952 os.chdir(ipythondir)
950 os.chdir(ipythondir)
953 rc_files = glb("ipythonrc*")
951 rc_files = glb("ipythonrc*")
954 for rc_file in rc_files:
952 for rc_file in rc_files:
955 os.rename(rc_file,rc_file+rc_suffix)
953 os.rename(rc_file,rc_file+rc_suffix)
956 except:
954 except:
957 warning = """
955 warning = """
958
956
959 There was a problem with the installation:
957 There was a problem with the installation:
960 %s
958 %s
961 Try to correct it or contact the developers if you think it's a bug.
959 Try to correct it or contact the developers if you think it's a bug.
962 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
960 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
963 warn(warning)
961 warn(warning)
964 wait()
962 wait()
965 return
963 return
966
964
967 elif mode == 'upgrade':
965 elif mode == 'upgrade':
968 try:
966 try:
969 os.chdir(ipythondir)
967 os.chdir(ipythondir)
970 except:
968 except:
971 print """
969 print """
972 Can not upgrade: changing to directory %s failed. Details:
970 Can not upgrade: changing to directory %s failed. Details:
973 %s
971 %s
974 """ % (ipythondir,sys.exc_info()[1])
972 """ % (ipythondir,sys.exc_info()[1])
975 wait()
973 wait()
976 return
974 return
977 else:
975 else:
978 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
976 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
979 for new_full_path in sources:
977 for new_full_path in sources:
980 new_filename = os.path.basename(new_full_path)
978 new_filename = os.path.basename(new_full_path)
981 if new_filename.startswith('ipythonrc'):
979 if new_filename.startswith('ipythonrc'):
982 new_filename = new_filename + rc_suffix
980 new_filename = new_filename + rc_suffix
983 # The config directory should only contain files, skip any
981 # The config directory should only contain files, skip any
984 # directories which may be there (like CVS)
982 # directories which may be there (like CVS)
985 if os.path.isdir(new_full_path):
983 if os.path.isdir(new_full_path):
986 continue
984 continue
987 if os.path.exists(new_filename):
985 if os.path.exists(new_filename):
988 old_file = new_filename+'.old'
986 old_file = new_filename+'.old'
989 if os.path.exists(old_file):
987 if os.path.exists(old_file):
990 os.remove(old_file)
988 os.remove(old_file)
991 os.rename(new_filename,old_file)
989 os.rename(new_filename,old_file)
992 shutil.copy(new_full_path,new_filename)
990 shutil.copy(new_full_path,new_filename)
993 else:
991 else:
994 raise ValueError,'unrecognized mode for install:',`mode`
992 raise ValueError,'unrecognized mode for install:',`mode`
995
993
996 # Fix line-endings to those native to each platform in the config
994 # Fix line-endings to those native to each platform in the config
997 # directory.
995 # directory.
998 try:
996 try:
999 os.chdir(ipythondir)
997 os.chdir(ipythondir)
1000 except:
998 except:
1001 print """
999 print """
1002 Problem: changing to directory %s failed.
1000 Problem: changing to directory %s failed.
1003 Details:
1001 Details:
1004 %s
1002 %s
1005
1003
1006 Some configuration files may have incorrect line endings. This should not
1004 Some configuration files may have incorrect line endings. This should not
1007 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1005 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1008 wait()
1006 wait()
1009 else:
1007 else:
1010 for fname in glb('ipythonrc*'):
1008 for fname in glb('ipythonrc*'):
1011 try:
1009 try:
1012 native_line_ends(fname,backup=0)
1010 native_line_ends(fname,backup=0)
1013 except IOError:
1011 except IOError:
1014 pass
1012 pass
1015
1013
1016 if mode == 'install':
1014 if mode == 'install':
1017 print """
1015 print """
1018 Successful installation!
1016 Successful installation!
1019
1017
1020 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1018 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1021 IPython manual (there are both HTML and PDF versions supplied with the
1019 IPython manual (there are both HTML and PDF versions supplied with the
1022 distribution) to make sure that your system environment is properly configured
1020 distribution) to make sure that your system environment is properly configured
1023 to take advantage of IPython's features."""
1021 to take advantage of IPython's features."""
1024 else:
1022 else:
1025 print """
1023 print """
1026 Successful upgrade!
1024 Successful upgrade!
1027
1025
1028 All files in your directory:
1026 All files in your directory:
1029 %(ipythondir)s
1027 %(ipythondir)s
1030 which would have been overwritten by the upgrade were backed up with a .old
1028 which would have been overwritten by the upgrade were backed up with a .old
1031 extension. If you had made particular customizations in those files you may
1029 extension. If you had made particular customizations in those files you may
1032 want to merge them back into the new files.""" % locals()
1030 want to merge them back into the new files.""" % locals()
1033 wait()
1031 wait()
1034 os.chdir(cwd)
1032 os.chdir(cwd)
1035 # end user_setup()
1033 # end user_setup()
1036
1034
1037 def atexit_operations(self):
1035 def atexit_operations(self):
1038 """This will be executed at the time of exit.
1036 """This will be executed at the time of exit.
1039
1037
1040 Saving of persistent data should be performed here. """
1038 Saving of persistent data should be performed here. """
1041
1039
1042 # input history
1040 # input history
1043 self.savehist()
1041 self.savehist()
1044
1042
1045 # Cleanup all tempfiles left around
1043 # Cleanup all tempfiles left around
1046 for tfile in self.tempfiles:
1044 for tfile in self.tempfiles:
1047 try:
1045 try:
1048 os.unlink(tfile)
1046 os.unlink(tfile)
1049 except OSError:
1047 except OSError:
1050 pass
1048 pass
1051
1049
1052 # save the "persistent data" catch-all dictionary
1050 # save the "persistent data" catch-all dictionary
1053 try:
1051 try:
1054 pickle.dump(self.persist, open(self.persist_fname,"w"))
1052 pickle.dump(self.persist, open(self.persist_fname,"w"))
1055 except:
1053 except:
1056 print "*** ERROR *** persistent data saving failed."
1054 print "*** ERROR *** persistent data saving failed."
1057
1055
1058 def savehist(self):
1056 def savehist(self):
1059 """Save input history to a file (via readline library)."""
1057 """Save input history to a file (via readline library)."""
1060 try:
1058 try:
1061 self.readline.write_history_file(self.histfile)
1059 self.readline.write_history_file(self.histfile)
1062 except:
1060 except:
1063 print 'Unable to save IPython command history to file: ' + \
1061 print 'Unable to save IPython command history to file: ' + \
1064 `self.histfile`
1062 `self.histfile`
1065
1063
1066 def pre_readline(self):
1064 def pre_readline(self):
1067 """readline hook to be used at the start of each line.
1065 """readline hook to be used at the start of each line.
1068
1066
1069 Currently it handles auto-indent only."""
1067 Currently it handles auto-indent only."""
1070
1068
1071 self.readline.insert_text(self.indent_current)
1069 self.readline.insert_text(self.indent_current)
1072
1070
1073 def init_readline(self):
1071 def init_readline(self):
1074 """Command history completion/saving/reloading."""
1072 """Command history completion/saving/reloading."""
1075 try:
1073 try:
1076 import readline
1074 import readline
1077 except ImportError:
1075 except ImportError:
1078 self.has_readline = 0
1076 self.has_readline = 0
1079 self.readline = None
1077 self.readline = None
1080 # no point in bugging windows users with this every time:
1078 # no point in bugging windows users with this every time:
1081 if os.name == 'posix':
1079 if os.name == 'posix':
1082 warn('Readline services not available on this platform.')
1080 warn('Readline services not available on this platform.')
1083 else:
1081 else:
1084 import atexit
1082 import atexit
1085 from IPython.completer import IPCompleter
1083 from IPython.completer import IPCompleter
1086 self.Completer = IPCompleter(self,
1084 self.Completer = IPCompleter(self,
1087 self.user_ns,
1085 self.user_ns,
1088 self.user_global_ns,
1086 self.user_global_ns,
1089 self.rc.readline_omit__names,
1087 self.rc.readline_omit__names,
1090 self.alias_table)
1088 self.alias_table)
1091
1089
1092 # Platform-specific configuration
1090 # Platform-specific configuration
1093 if os.name == 'nt':
1091 if os.name == 'nt':
1094 self.readline_startup_hook = readline.set_pre_input_hook
1092 self.readline_startup_hook = readline.set_pre_input_hook
1095 else:
1093 else:
1096 self.readline_startup_hook = readline.set_startup_hook
1094 self.readline_startup_hook = readline.set_startup_hook
1097
1095
1098 # Load user's initrc file (readline config)
1096 # Load user's initrc file (readline config)
1099 inputrc_name = os.environ.get('INPUTRC')
1097 inputrc_name = os.environ.get('INPUTRC')
1100 if inputrc_name is None:
1098 if inputrc_name is None:
1101 home_dir = get_home_dir()
1099 home_dir = get_home_dir()
1102 if home_dir is not None:
1100 if home_dir is not None:
1103 inputrc_name = os.path.join(home_dir,'.inputrc')
1101 inputrc_name = os.path.join(home_dir,'.inputrc')
1104 if os.path.isfile(inputrc_name):
1102 if os.path.isfile(inputrc_name):
1105 try:
1103 try:
1106 readline.read_init_file(inputrc_name)
1104 readline.read_init_file(inputrc_name)
1107 except:
1105 except:
1108 warn('Problems reading readline initialization file <%s>'
1106 warn('Problems reading readline initialization file <%s>'
1109 % inputrc_name)
1107 % inputrc_name)
1110
1108
1111 self.has_readline = 1
1109 self.has_readline = 1
1112 self.readline = readline
1110 self.readline = readline
1113 # save this in sys so embedded copies can restore it properly
1111 # save this in sys so embedded copies can restore it properly
1114 sys.ipcompleter = self.Completer.complete
1112 sys.ipcompleter = self.Completer.complete
1115 readline.set_completer(self.Completer.complete)
1113 readline.set_completer(self.Completer.complete)
1116
1114
1117 # Configure readline according to user's prefs
1115 # Configure readline according to user's prefs
1118 for rlcommand in self.rc.readline_parse_and_bind:
1116 for rlcommand in self.rc.readline_parse_and_bind:
1119 readline.parse_and_bind(rlcommand)
1117 readline.parse_and_bind(rlcommand)
1120
1118
1121 # remove some chars from the delimiters list
1119 # remove some chars from the delimiters list
1122 delims = readline.get_completer_delims()
1120 delims = readline.get_completer_delims()
1123 delims = delims.translate(string._idmap,
1121 delims = delims.translate(string._idmap,
1124 self.rc.readline_remove_delims)
1122 self.rc.readline_remove_delims)
1125 readline.set_completer_delims(delims)
1123 readline.set_completer_delims(delims)
1126 # otherwise we end up with a monster history after a while:
1124 # otherwise we end up with a monster history after a while:
1127 readline.set_history_length(1000)
1125 readline.set_history_length(1000)
1128 try:
1126 try:
1129 #print '*** Reading readline history' # dbg
1127 #print '*** Reading readline history' # dbg
1130 readline.read_history_file(self.histfile)
1128 readline.read_history_file(self.histfile)
1131 except IOError:
1129 except IOError:
1132 pass # It doesn't exist yet.
1130 pass # It doesn't exist yet.
1133
1131
1134 atexit.register(self.atexit_operations)
1132 atexit.register(self.atexit_operations)
1135 del atexit
1133 del atexit
1136
1134
1137 # Configure auto-indent for all platforms
1135 # Configure auto-indent for all platforms
1138 self.set_autoindent(self.rc.autoindent)
1136 self.set_autoindent(self.rc.autoindent)
1139
1137
1140 def _should_recompile(self,e):
1138 def _should_recompile(self,e):
1141 """Utility routine for edit_syntax_error"""
1139 """Utility routine for edit_syntax_error"""
1142
1140
1143 if e.filename in ('<ipython console>','<input>','<string>',
1141 if e.filename in ('<ipython console>','<input>','<string>',
1144 '<console>'):
1142 '<console>'):
1145 return False
1143 return False
1146 try:
1144 try:
1147 if not ask_yes_no('Return to editor to correct syntax error? '
1145 if not ask_yes_no('Return to editor to correct syntax error? '
1148 '[Y/n] ','y'):
1146 '[Y/n] ','y'):
1149 return False
1147 return False
1150 except EOFError:
1148 except EOFError:
1151 return False
1149 return False
1152 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1150 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1153 return True
1151 return True
1154
1152
1155 def edit_syntax_error(self):
1153 def edit_syntax_error(self):
1156 """The bottom half of the syntax error handler called in the main loop.
1154 """The bottom half of the syntax error handler called in the main loop.
1157
1155
1158 Loop until syntax error is fixed or user cancels.
1156 Loop until syntax error is fixed or user cancels.
1159 """
1157 """
1160
1158
1161 while self.SyntaxTB.last_syntax_error:
1159 while self.SyntaxTB.last_syntax_error:
1162 # copy and clear last_syntax_error
1160 # copy and clear last_syntax_error
1163 err = self.SyntaxTB.clear_err_state()
1161 err = self.SyntaxTB.clear_err_state()
1164 if not self._should_recompile(err):
1162 if not self._should_recompile(err):
1165 return
1163 return
1166 try:
1164 try:
1167 # may set last_syntax_error again if a SyntaxError is raised
1165 # may set last_syntax_error again if a SyntaxError is raised
1168 self.safe_execfile(err.filename,self.shell.user_ns)
1166 self.safe_execfile(err.filename,self.shell.user_ns)
1169 except:
1167 except:
1170 self.showtraceback()
1168 self.showtraceback()
1171 else:
1169 else:
1172 f = file(err.filename)
1170 f = file(err.filename)
1173 try:
1171 try:
1174 sys.displayhook(f.read())
1172 sys.displayhook(f.read())
1175 finally:
1173 finally:
1176 f.close()
1174 f.close()
1177
1175
1178 def showsyntaxerror(self, filename=None):
1176 def showsyntaxerror(self, filename=None):
1179 """Display the syntax error that just occurred.
1177 """Display the syntax error that just occurred.
1180
1178
1181 This doesn't display a stack trace because there isn't one.
1179 This doesn't display a stack trace because there isn't one.
1182
1180
1183 If a filename is given, it is stuffed in the exception instead
1181 If a filename is given, it is stuffed in the exception instead
1184 of what was there before (because Python's parser always uses
1182 of what was there before (because Python's parser always uses
1185 "<string>" when reading from a string).
1183 "<string>" when reading from a string).
1186 """
1184 """
1187 etype, value, last_traceback = sys.exc_info()
1185 etype, value, last_traceback = sys.exc_info()
1188 if filename and etype is SyntaxError:
1186 if filename and etype is SyntaxError:
1189 # Work hard to stuff the correct filename in the exception
1187 # Work hard to stuff the correct filename in the exception
1190 try:
1188 try:
1191 msg, (dummy_filename, lineno, offset, line) = value
1189 msg, (dummy_filename, lineno, offset, line) = value
1192 except:
1190 except:
1193 # Not the format we expect; leave it alone
1191 # Not the format we expect; leave it alone
1194 pass
1192 pass
1195 else:
1193 else:
1196 # Stuff in the right filename
1194 # Stuff in the right filename
1197 try:
1195 try:
1198 # Assume SyntaxError is a class exception
1196 # Assume SyntaxError is a class exception
1199 value = SyntaxError(msg, (filename, lineno, offset, line))
1197 value = SyntaxError(msg, (filename, lineno, offset, line))
1200 except:
1198 except:
1201 # If that failed, assume SyntaxError is a string
1199 # If that failed, assume SyntaxError is a string
1202 value = msg, (filename, lineno, offset, line)
1200 value = msg, (filename, lineno, offset, line)
1203 self.SyntaxTB(etype,value,[])
1201 self.SyntaxTB(etype,value,[])
1204
1202
1205 def debugger(self):
1203 def debugger(self):
1206 """Call the pdb debugger."""
1204 """Call the pdb debugger."""
1207
1205
1208 if not self.rc.pdb:
1206 if not self.rc.pdb:
1209 return
1207 return
1210 pdb.pm()
1208 pdb.pm()
1211
1209
1212 def showtraceback(self,exc_tuple = None,filename=None):
1210 def showtraceback(self,exc_tuple = None,filename=None):
1213 """Display the exception that just occurred."""
1211 """Display the exception that just occurred."""
1214
1212
1215 # Though this won't be called by syntax errors in the input line,
1213 # Though this won't be called by syntax errors in the input line,
1216 # there may be SyntaxError cases whith imported code.
1214 # there may be SyntaxError cases whith imported code.
1217 if exc_tuple is None:
1215 if exc_tuple is None:
1218 type, value, tb = sys.exc_info()
1216 type, value, tb = sys.exc_info()
1219 else:
1217 else:
1220 type, value, tb = exc_tuple
1218 type, value, tb = exc_tuple
1221 if type is SyntaxError:
1219 if type is SyntaxError:
1222 self.showsyntaxerror(filename)
1220 self.showsyntaxerror(filename)
1223 else:
1221 else:
1224 self.InteractiveTB()
1222 self.InteractiveTB()
1225 if self.InteractiveTB.call_pdb and self.has_readline:
1223 if self.InteractiveTB.call_pdb and self.has_readline:
1226 # pdb mucks up readline, fix it back
1224 # pdb mucks up readline, fix it back
1227 self.readline.set_completer(self.Completer.complete)
1225 self.readline.set_completer(self.Completer.complete)
1228
1226
1229 def mainloop(self,banner=None):
1227 def mainloop(self,banner=None):
1230 """Creates the local namespace and starts the mainloop.
1228 """Creates the local namespace and starts the mainloop.
1231
1229
1232 If an optional banner argument is given, it will override the
1230 If an optional banner argument is given, it will override the
1233 internally created default banner."""
1231 internally created default banner."""
1234
1232
1235 if self.rc.c: # Emulate Python's -c option
1233 if self.rc.c: # Emulate Python's -c option
1236 self.exec_init_cmd()
1234 self.exec_init_cmd()
1237 if banner is None:
1235 if banner is None:
1238 if self.rc.banner:
1236 if self.rc.banner:
1239 banner = self.BANNER+self.banner2
1237 banner = self.BANNER+self.banner2
1240 else:
1238 else:
1241 banner = ''
1239 banner = ''
1242 self.interact(banner)
1240 self.interact(banner)
1243
1241
1244 def exec_init_cmd(self):
1242 def exec_init_cmd(self):
1245 """Execute a command given at the command line.
1243 """Execute a command given at the command line.
1246
1244
1247 This emulates Python's -c option."""
1245 This emulates Python's -c option."""
1248
1246
1249 sys.argv = ['-c']
1247 sys.argv = ['-c']
1250 self.push(self.rc.c)
1248 self.push(self.rc.c)
1251
1249
1252 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1250 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1253 """Embeds IPython into a running python program.
1251 """Embeds IPython into a running python program.
1254
1252
1255 Input:
1253 Input:
1256
1254
1257 - header: An optional header message can be specified.
1255 - header: An optional header message can be specified.
1258
1256
1259 - local_ns, global_ns: working namespaces. If given as None, the
1257 - local_ns, global_ns: working namespaces. If given as None, the
1260 IPython-initialized one is updated with __main__.__dict__, so that
1258 IPython-initialized one is updated with __main__.__dict__, so that
1261 program variables become visible but user-specific configuration
1259 program variables become visible but user-specific configuration
1262 remains possible.
1260 remains possible.
1263
1261
1264 - stack_depth: specifies how many levels in the stack to go to
1262 - stack_depth: specifies how many levels in the stack to go to
1265 looking for namespaces (when local_ns and global_ns are None). This
1263 looking for namespaces (when local_ns and global_ns are None). This
1266 allows an intermediate caller to make sure that this function gets
1264 allows an intermediate caller to make sure that this function gets
1267 the namespace from the intended level in the stack. By default (0)
1265 the namespace from the intended level in the stack. By default (0)
1268 it will get its locals and globals from the immediate caller.
1266 it will get its locals and globals from the immediate caller.
1269
1267
1270 Warning: it's possible to use this in a program which is being run by
1268 Warning: it's possible to use this in a program which is being run by
1271 IPython itself (via %run), but some funny things will happen (a few
1269 IPython itself (via %run), but some funny things will happen (a few
1272 globals get overwritten). In the future this will be cleaned up, as
1270 globals get overwritten). In the future this will be cleaned up, as
1273 there is no fundamental reason why it can't work perfectly."""
1271 there is no fundamental reason why it can't work perfectly."""
1274
1272
1275 # Get locals and globals from caller
1273 # Get locals and globals from caller
1276 if local_ns is None or global_ns is None:
1274 if local_ns is None or global_ns is None:
1277 call_frame = sys._getframe(stack_depth).f_back
1275 call_frame = sys._getframe(stack_depth).f_back
1278
1276
1279 if local_ns is None:
1277 if local_ns is None:
1280 local_ns = call_frame.f_locals
1278 local_ns = call_frame.f_locals
1281 if global_ns is None:
1279 if global_ns is None:
1282 global_ns = call_frame.f_globals
1280 global_ns = call_frame.f_globals
1283
1281
1284 # Update namespaces and fire up interpreter
1282 # Update namespaces and fire up interpreter
1285 self.user_ns = local_ns
1283 self.user_ns = local_ns
1286 self.user_global_ns = global_ns
1284 self.user_global_ns = global_ns
1287
1285
1288 # Patch for global embedding to make sure that things don't overwrite
1286 # Patch for global embedding to make sure that things don't overwrite
1289 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1287 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1290 # FIXME. Test this a bit more carefully (the if.. is new)
1288 # FIXME. Test this a bit more carefully (the if.. is new)
1291 if local_ns is None and global_ns is None:
1289 if local_ns is None and global_ns is None:
1292 self.user_global_ns.update(__main__.__dict__)
1290 self.user_global_ns.update(__main__.__dict__)
1293
1291
1294 # make sure the tab-completer has the correct frame information, so it
1292 # make sure the tab-completer has the correct frame information, so it
1295 # actually completes using the frame's locals/globals
1293 # actually completes using the frame's locals/globals
1296 self.set_completer_frame(call_frame)
1294 self.set_completer_frame(call_frame)
1297
1295
1298 self.interact(header)
1296 self.interact(header)
1299
1297
1300 def interact(self, banner=None):
1298 def interact(self, banner=None):
1301 """Closely emulate the interactive Python console.
1299 """Closely emulate the interactive Python console.
1302
1300
1303 The optional banner argument specify the banner to print
1301 The optional banner argument specify the banner to print
1304 before the first interaction; by default it prints a banner
1302 before the first interaction; by default it prints a banner
1305 similar to the one printed by the real Python interpreter,
1303 similar to the one printed by the real Python interpreter,
1306 followed by the current class name in parentheses (so as not
1304 followed by the current class name in parentheses (so as not
1307 to confuse this with the real interpreter -- since it's so
1305 to confuse this with the real interpreter -- since it's so
1308 close!).
1306 close!).
1309
1307
1310 """
1308 """
1311 cprt = 'Type "copyright", "credits" or "license" for more information.'
1309 cprt = 'Type "copyright", "credits" or "license" for more information.'
1312 if banner is None:
1310 if banner is None:
1313 self.write("Python %s on %s\n%s\n(%s)\n" %
1311 self.write("Python %s on %s\n%s\n(%s)\n" %
1314 (sys.version, sys.platform, cprt,
1312 (sys.version, sys.platform, cprt,
1315 self.__class__.__name__))
1313 self.__class__.__name__))
1316 else:
1314 else:
1317 self.write(banner)
1315 self.write(banner)
1318
1316
1319 more = 0
1317 more = 0
1320
1318
1321 # Mark activity in the builtins
1319 # Mark activity in the builtins
1322 __builtin__.__dict__['__IPYTHON__active'] += 1
1320 __builtin__.__dict__['__IPYTHON__active'] += 1
1323
1321
1324 # exit_now is set by a call to %Exit or %Quit
1322 # exit_now is set by a call to %Exit or %Quit
1325 while not self.exit_now:
1323 while not self.exit_now:
1326 try:
1324 try:
1327 if more:
1325 if more:
1328 prompt = self.outputcache.prompt2
1326 prompt = self.outputcache.prompt2
1329 if self.autoindent:
1327 if self.autoindent:
1330 self.readline_startup_hook(self.pre_readline)
1328 self.readline_startup_hook(self.pre_readline)
1331 else:
1329 else:
1332 prompt = self.outputcache.prompt1
1330 prompt = self.outputcache.prompt1
1333 try:
1331 try:
1334 line = self.raw_input(prompt,more)
1332 line = self.raw_input(prompt,more)
1335 if self.autoindent:
1333 if self.autoindent:
1336 self.readline_startup_hook(None)
1334 self.readline_startup_hook(None)
1337 except EOFError:
1335 except EOFError:
1338 if self.autoindent:
1336 if self.autoindent:
1339 self.readline_startup_hook(None)
1337 self.readline_startup_hook(None)
1340 self.write("\n")
1338 self.write("\n")
1341 self.exit()
1339 self.exit()
1342 else:
1340 else:
1343 more = self.push(line)
1341 more = self.push(line)
1344
1342
1345 if (self.SyntaxTB.last_syntax_error and
1343 if (self.SyntaxTB.last_syntax_error and
1346 self.rc.autoedit_syntax):
1344 self.rc.autoedit_syntax):
1347 self.edit_syntax_error()
1345 self.edit_syntax_error()
1348
1346
1349 except KeyboardInterrupt:
1347 except KeyboardInterrupt:
1350 self.write("\nKeyboardInterrupt\n")
1348 self.write("\nKeyboardInterrupt\n")
1351 self.resetbuffer()
1349 self.resetbuffer()
1352 more = 0
1350 more = 0
1353 # keep cache in sync with the prompt counter:
1351 # keep cache in sync with the prompt counter:
1354 self.outputcache.prompt_count -= 1
1352 self.outputcache.prompt_count -= 1
1355
1353
1356 if self.autoindent:
1354 if self.autoindent:
1357 self.indent_current_nsp = 0
1355 self.indent_current_nsp = 0
1358 self.indent_current = ' '* self.indent_current_nsp
1356 self.indent_current = ' '* self.indent_current_nsp
1359
1357
1360 except bdb.BdbQuit:
1358 except bdb.BdbQuit:
1361 warn("The Python debugger has exited with a BdbQuit exception.\n"
1359 warn("The Python debugger has exited with a BdbQuit exception.\n"
1362 "Because of how pdb handles the stack, it is impossible\n"
1360 "Because of how pdb handles the stack, it is impossible\n"
1363 "for IPython to properly format this particular exception.\n"
1361 "for IPython to properly format this particular exception.\n"
1364 "IPython will resume normal operation.")
1362 "IPython will resume normal operation.")
1365
1363
1366 # We are off again...
1364 # We are off again...
1367 __builtin__.__dict__['__IPYTHON__active'] -= 1
1365 __builtin__.__dict__['__IPYTHON__active'] -= 1
1368
1366
1369 def excepthook(self, type, value, tb):
1367 def excepthook(self, type, value, tb):
1370 """One more defense for GUI apps that call sys.excepthook.
1368 """One more defense for GUI apps that call sys.excepthook.
1371
1369
1372 GUI frameworks like wxPython trap exceptions and call
1370 GUI frameworks like wxPython trap exceptions and call
1373 sys.excepthook themselves. I guess this is a feature that
1371 sys.excepthook themselves. I guess this is a feature that
1374 enables them to keep running after exceptions that would
1372 enables them to keep running after exceptions that would
1375 otherwise kill their mainloop. This is a bother for IPython
1373 otherwise kill their mainloop. This is a bother for IPython
1376 which excepts to catch all of the program exceptions with a try:
1374 which excepts to catch all of the program exceptions with a try:
1377 except: statement.
1375 except: statement.
1378
1376
1379 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1377 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1380 any app directly invokes sys.excepthook, it will look to the user like
1378 any app directly invokes sys.excepthook, it will look to the user like
1381 IPython crashed. In order to work around this, we can disable the
1379 IPython crashed. In order to work around this, we can disable the
1382 CrashHandler and replace it with this excepthook instead, which prints a
1380 CrashHandler and replace it with this excepthook instead, which prints a
1383 regular traceback using our InteractiveTB. In this fashion, apps which
1381 regular traceback using our InteractiveTB. In this fashion, apps which
1384 call sys.excepthook will generate a regular-looking exception from
1382 call sys.excepthook will generate a regular-looking exception from
1385 IPython, and the CrashHandler will only be triggered by real IPython
1383 IPython, and the CrashHandler will only be triggered by real IPython
1386 crashes.
1384 crashes.
1387
1385
1388 This hook should be used sparingly, only in places which are not likely
1386 This hook should be used sparingly, only in places which are not likely
1389 to be true IPython errors.
1387 to be true IPython errors.
1390 """
1388 """
1391
1389
1392 self.InteractiveTB(type, value, tb, tb_offset=0)
1390 self.InteractiveTB(type, value, tb, tb_offset=0)
1393 if self.InteractiveTB.call_pdb and self.has_readline:
1391 if self.InteractiveTB.call_pdb and self.has_readline:
1394 self.readline.set_completer(self.Completer.complete)
1392 self.readline.set_completer(self.Completer.complete)
1395
1393
1396 def call_alias(self,alias,rest=''):
1394 def call_alias(self,alias,rest=''):
1397 """Call an alias given its name and the rest of the line.
1395 """Call an alias given its name and the rest of the line.
1398
1396
1399 This function MUST be given a proper alias, because it doesn't make
1397 This function MUST be given a proper alias, because it doesn't make
1400 any checks when looking up into the alias table. The caller is
1398 any checks when looking up into the alias table. The caller is
1401 responsible for invoking it only with a valid alias."""
1399 responsible for invoking it only with a valid alias."""
1402
1400
1403 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1401 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1404 nargs,cmd = self.alias_table[alias]
1402 nargs,cmd = self.alias_table[alias]
1405 # Expand the %l special to be the user's input line
1403 # Expand the %l special to be the user's input line
1406 if cmd.find('%l') >= 0:
1404 if cmd.find('%l') >= 0:
1407 cmd = cmd.replace('%l',rest)
1405 cmd = cmd.replace('%l',rest)
1408 rest = ''
1406 rest = ''
1409 if nargs==0:
1407 if nargs==0:
1410 # Simple, argument-less aliases
1408 # Simple, argument-less aliases
1411 cmd = '%s %s' % (cmd,rest)
1409 cmd = '%s %s' % (cmd,rest)
1412 else:
1410 else:
1413 # Handle aliases with positional arguments
1411 # Handle aliases with positional arguments
1414 args = rest.split(None,nargs)
1412 args = rest.split(None,nargs)
1415 if len(args)< nargs:
1413 if len(args)< nargs:
1416 error('Alias <%s> requires %s arguments, %s given.' %
1414 error('Alias <%s> requires %s arguments, %s given.' %
1417 (alias,nargs,len(args)))
1415 (alias,nargs,len(args)))
1418 return
1416 return
1419 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1417 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1420 # Now call the macro, evaluating in the user's namespace
1418 # Now call the macro, evaluating in the user's namespace
1421 try:
1419 try:
1422 self.system(cmd)
1420 self.system(cmd)
1423 except:
1421 except:
1424 self.showtraceback()
1422 self.showtraceback()
1425
1423
1426 def autoindent_update(self,line):
1424 def autoindent_update(self,line):
1427 """Keep track of the indent level."""
1425 """Keep track of the indent level."""
1428 if self.autoindent:
1426 if self.autoindent:
1429 if line:
1427 if line:
1430 ini_spaces = ini_spaces_re.match(line)
1428 ini_spaces = ini_spaces_re.match(line)
1431 if ini_spaces:
1429 if ini_spaces:
1432 nspaces = ini_spaces.end()
1430 nspaces = ini_spaces.end()
1433 else:
1431 else:
1434 nspaces = 0
1432 nspaces = 0
1435 self.indent_current_nsp = nspaces
1433 self.indent_current_nsp = nspaces
1436
1434
1437 if line[-1] == ':':
1435 if line[-1] == ':':
1438 self.indent_current_nsp += 4
1436 self.indent_current_nsp += 4
1439 elif dedent_re.match(line):
1437 elif dedent_re.match(line):
1440 self.indent_current_nsp -= 4
1438 self.indent_current_nsp -= 4
1441 else:
1439 else:
1442 self.indent_current_nsp = 0
1440 self.indent_current_nsp = 0
1443
1441
1444 # indent_current is the actual string to be inserted
1442 # indent_current is the actual string to be inserted
1445 # by the readline hooks for indentation
1443 # by the readline hooks for indentation
1446 self.indent_current = ' '* self.indent_current_nsp
1444 self.indent_current = ' '* self.indent_current_nsp
1447
1445
1448 def runlines(self,lines):
1446 def runlines(self,lines):
1449 """Run a string of one or more lines of source.
1447 """Run a string of one or more lines of source.
1450
1448
1451 This method is capable of running a string containing multiple source
1449 This method is capable of running a string containing multiple source
1452 lines, as if they had been entered at the IPython prompt. Since it
1450 lines, as if they had been entered at the IPython prompt. Since it
1453 exposes IPython's processing machinery, the given strings can contain
1451 exposes IPython's processing machinery, the given strings can contain
1454 magic calls (%magic), special shell access (!cmd), etc."""
1452 magic calls (%magic), special shell access (!cmd), etc."""
1455
1453
1456 # We must start with a clean buffer, in case this is run from an
1454 # We must start with a clean buffer, in case this is run from an
1457 # interactive IPython session (via a magic, for example).
1455 # interactive IPython session (via a magic, for example).
1458 self.resetbuffer()
1456 self.resetbuffer()
1459 lines = lines.split('\n')
1457 lines = lines.split('\n')
1460 more = 0
1458 more = 0
1461 for line in lines:
1459 for line in lines:
1462 # skip blank lines so we don't mess up the prompt counter, but do
1460 # skip blank lines so we don't mess up the prompt counter, but do
1463 # NOT skip even a blank line if we are in a code block (more is
1461 # NOT skip even a blank line if we are in a code block (more is
1464 # true)
1462 # true)
1465 if line or more:
1463 if line or more:
1466 more = self.push(self.prefilter(line,more))
1464 more = self.push(self.prefilter(line,more))
1467 # IPython's runsource returns None if there was an error
1465 # IPython's runsource returns None if there was an error
1468 # compiling the code. This allows us to stop processing right
1466 # compiling the code. This allows us to stop processing right
1469 # away, so the user gets the error message at the right place.
1467 # away, so the user gets the error message at the right place.
1470 if more is None:
1468 if more is None:
1471 break
1469 break
1472 # final newline in case the input didn't have it, so that the code
1470 # final newline in case the input didn't have it, so that the code
1473 # actually does get executed
1471 # actually does get executed
1474 if more:
1472 if more:
1475 self.push('\n')
1473 self.push('\n')
1476
1474
1477 def runsource(self, source, filename='<input>', symbol='single'):
1475 def runsource(self, source, filename='<input>', symbol='single'):
1478 """Compile and run some source in the interpreter.
1476 """Compile and run some source in the interpreter.
1479
1477
1480 Arguments are as for compile_command().
1478 Arguments are as for compile_command().
1481
1479
1482 One several things can happen:
1480 One several things can happen:
1483
1481
1484 1) The input is incorrect; compile_command() raised an
1482 1) The input is incorrect; compile_command() raised an
1485 exception (SyntaxError or OverflowError). A syntax traceback
1483 exception (SyntaxError or OverflowError). A syntax traceback
1486 will be printed by calling the showsyntaxerror() method.
1484 will be printed by calling the showsyntaxerror() method.
1487
1485
1488 2) The input is incomplete, and more input is required;
1486 2) The input is incomplete, and more input is required;
1489 compile_command() returned None. Nothing happens.
1487 compile_command() returned None. Nothing happens.
1490
1488
1491 3) The input is complete; compile_command() returned a code
1489 3) The input is complete; compile_command() returned a code
1492 object. The code is executed by calling self.runcode() (which
1490 object. The code is executed by calling self.runcode() (which
1493 also handles run-time exceptions, except for SystemExit).
1491 also handles run-time exceptions, except for SystemExit).
1494
1492
1495 The return value is:
1493 The return value is:
1496
1494
1497 - True in case 2
1495 - True in case 2
1498
1496
1499 - False in the other cases, unless an exception is raised, where
1497 - False in the other cases, unless an exception is raised, where
1500 None is returned instead. This can be used by external callers to
1498 None is returned instead. This can be used by external callers to
1501 know whether to continue feeding input or not.
1499 know whether to continue feeding input or not.
1502
1500
1503 The return value can be used to decide whether to use sys.ps1 or
1501 The return value can be used to decide whether to use sys.ps1 or
1504 sys.ps2 to prompt the next line."""
1502 sys.ps2 to prompt the next line."""
1505
1503
1506 try:
1504 try:
1507 code = self.compile(source,filename,symbol)
1505 code = self.compile(source,filename,symbol)
1508 except (OverflowError, SyntaxError, ValueError):
1506 except (OverflowError, SyntaxError, ValueError):
1509 # Case 1
1507 # Case 1
1510 self.showsyntaxerror(filename)
1508 self.showsyntaxerror(filename)
1511 return None
1509 return None
1512
1510
1513 if code is None:
1511 if code is None:
1514 # Case 2
1512 # Case 2
1515 return True
1513 return True
1516
1514
1517 # Case 3
1515 # Case 3
1518 # We store the code object so that threaded shells and
1516 # We store the code object so that threaded shells and
1519 # custom exception handlers can access all this info if needed.
1517 # custom exception handlers can access all this info if needed.
1520 # The source corresponding to this can be obtained from the
1518 # The source corresponding to this can be obtained from the
1521 # buffer attribute as '\n'.join(self.buffer).
1519 # buffer attribute as '\n'.join(self.buffer).
1522 self.code_to_run = code
1520 self.code_to_run = code
1523 # now actually execute the code object
1521 # now actually execute the code object
1524 if self.runcode(code) == 0:
1522 if self.runcode(code) == 0:
1525 return False
1523 return False
1526 else:
1524 else:
1527 return None
1525 return None
1528
1526
1529 def runcode(self,code_obj):
1527 def runcode(self,code_obj):
1530 """Execute a code object.
1528 """Execute a code object.
1531
1529
1532 When an exception occurs, self.showtraceback() is called to display a
1530 When an exception occurs, self.showtraceback() is called to display a
1533 traceback.
1531 traceback.
1534
1532
1535 Return value: a flag indicating whether the code to be run completed
1533 Return value: a flag indicating whether the code to be run completed
1536 successfully:
1534 successfully:
1537
1535
1538 - 0: successful execution.
1536 - 0: successful execution.
1539 - 1: an error occurred.
1537 - 1: an error occurred.
1540 """
1538 """
1541
1539
1542 # Set our own excepthook in case the user code tries to call it
1540 # Set our own excepthook in case the user code tries to call it
1543 # directly, so that the IPython crash handler doesn't get triggered
1541 # directly, so that the IPython crash handler doesn't get triggered
1544 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1542 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1545
1543
1546 # we save the original sys.excepthook in the instance, in case config
1544 # we save the original sys.excepthook in the instance, in case config
1547 # code (such as magics) needs access to it.
1545 # code (such as magics) needs access to it.
1548 self.sys_excepthook = old_excepthook
1546 self.sys_excepthook = old_excepthook
1549 outflag = 1 # happens in more places, so it's easier as default
1547 outflag = 1 # happens in more places, so it's easier as default
1550 try:
1548 try:
1551 try:
1549 try:
1552 # Embedded instances require separate global/local namespaces
1550 # Embedded instances require separate global/local namespaces
1553 # so they can see both the surrounding (local) namespace and
1551 # so they can see both the surrounding (local) namespace and
1554 # the module-level globals when called inside another function.
1552 # the module-level globals when called inside another function.
1555 if self.embedded:
1553 if self.embedded:
1556 exec code_obj in self.user_global_ns, self.user_ns
1554 exec code_obj in self.user_global_ns, self.user_ns
1557 # Normal (non-embedded) instances should only have a single
1555 # Normal (non-embedded) instances should only have a single
1558 # namespace for user code execution, otherwise functions won't
1556 # namespace for user code execution, otherwise functions won't
1559 # see interactive top-level globals.
1557 # see interactive top-level globals.
1560 else:
1558 else:
1561 exec code_obj in self.user_ns
1559 exec code_obj in self.user_ns
1562 finally:
1560 finally:
1563 # Reset our crash handler in place
1561 # Reset our crash handler in place
1564 sys.excepthook = old_excepthook
1562 sys.excepthook = old_excepthook
1565 except SystemExit:
1563 except SystemExit:
1566 self.resetbuffer()
1564 self.resetbuffer()
1567 self.showtraceback()
1565 self.showtraceback()
1568 warn("Type exit or quit to exit IPython "
1566 warn("Type exit or quit to exit IPython "
1569 "(%Exit or %Quit do so unconditionally).",level=1)
1567 "(%Exit or %Quit do so unconditionally).",level=1)
1570 except self.custom_exceptions:
1568 except self.custom_exceptions:
1571 etype,value,tb = sys.exc_info()
1569 etype,value,tb = sys.exc_info()
1572 self.CustomTB(etype,value,tb)
1570 self.CustomTB(etype,value,tb)
1573 except:
1571 except:
1574 self.showtraceback()
1572 self.showtraceback()
1575 else:
1573 else:
1576 outflag = 0
1574 outflag = 0
1577 if softspace(sys.stdout, 0):
1575 if softspace(sys.stdout, 0):
1578 print
1576 print
1579 # Flush out code object which has been run (and source)
1577 # Flush out code object which has been run (and source)
1580 self.code_to_run = None
1578 self.code_to_run = None
1581 return outflag
1579 return outflag
1582
1580
1583 def push(self, line):
1581 def push(self, line):
1584 """Push a line to the interpreter.
1582 """Push a line to the interpreter.
1585
1583
1586 The line should not have a trailing newline; it may have
1584 The line should not have a trailing newline; it may have
1587 internal newlines. The line is appended to a buffer and the
1585 internal newlines. The line is appended to a buffer and the
1588 interpreter's runsource() method is called with the
1586 interpreter's runsource() method is called with the
1589 concatenated contents of the buffer as source. If this
1587 concatenated contents of the buffer as source. If this
1590 indicates that the command was executed or invalid, the buffer
1588 indicates that the command was executed or invalid, the buffer
1591 is reset; otherwise, the command is incomplete, and the buffer
1589 is reset; otherwise, the command is incomplete, and the buffer
1592 is left as it was after the line was appended. The return
1590 is left as it was after the line was appended. The return
1593 value is 1 if more input is required, 0 if the line was dealt
1591 value is 1 if more input is required, 0 if the line was dealt
1594 with in some way (this is the same as runsource()).
1592 with in some way (this is the same as runsource()).
1595 """
1593 """
1596
1594
1597 # autoindent management should be done here, and not in the
1595 # autoindent management should be done here, and not in the
1598 # interactive loop, since that one is only seen by keyboard input. We
1596 # interactive loop, since that one is only seen by keyboard input. We
1599 # need this done correctly even for code run via runlines (which uses
1597 # need this done correctly even for code run via runlines (which uses
1600 # push).
1598 # push).
1601
1599
1602 #print 'push line: <%s>' % line # dbg
1600 #print 'push line: <%s>' % line # dbg
1603 self.autoindent_update(line)
1601 self.autoindent_update(line)
1604
1602
1605 self.buffer.append(line)
1603 self.buffer.append(line)
1606 more = self.runsource('\n'.join(self.buffer), self.filename)
1604 more = self.runsource('\n'.join(self.buffer), self.filename)
1607 if not more:
1605 if not more:
1608 self.resetbuffer()
1606 self.resetbuffer()
1609 return more
1607 return more
1610
1608
1611 def resetbuffer(self):
1609 def resetbuffer(self):
1612 """Reset the input buffer."""
1610 """Reset the input buffer."""
1613 self.buffer[:] = []
1611 self.buffer[:] = []
1614
1612
1615 def raw_input(self,prompt='',continue_prompt=False):
1613 def raw_input(self,prompt='',continue_prompt=False):
1616 """Write a prompt and read a line.
1614 """Write a prompt and read a line.
1617
1615
1618 The returned line does not include the trailing newline.
1616 The returned line does not include the trailing newline.
1619 When the user enters the EOF key sequence, EOFError is raised.
1617 When the user enters the EOF key sequence, EOFError is raised.
1620
1618
1621 Optional inputs:
1619 Optional inputs:
1622
1620
1623 - prompt(''): a string to be printed to prompt the user.
1621 - prompt(''): a string to be printed to prompt the user.
1624
1622
1625 - continue_prompt(False): whether this line is the first one or a
1623 - continue_prompt(False): whether this line is the first one or a
1626 continuation in a sequence of inputs.
1624 continuation in a sequence of inputs.
1627 """
1625 """
1628
1626
1629 line = raw_input_original(prompt)
1627 line = raw_input_original(prompt)
1630 # Try to be reasonably smart about not re-indenting pasted input more
1628 # Try to be reasonably smart about not re-indenting pasted input more
1631 # than necessary. We do this by trimming out the auto-indent initial
1629 # than necessary. We do this by trimming out the auto-indent initial
1632 # spaces, if the user's actual input started itself with whitespace.
1630 # spaces, if the user's actual input started itself with whitespace.
1633 if self.autoindent:
1631 if self.autoindent:
1634 line2 = line[self.indent_current_nsp:]
1632 line2 = line[self.indent_current_nsp:]
1635 if line2[0:1] in (' ','\t'):
1633 if line2[0:1] in (' ','\t'):
1636 line = line2
1634 line = line2
1637 return self.prefilter(line,continue_prompt)
1635 return self.prefilter(line,continue_prompt)
1638
1636
1639 def split_user_input(self,line):
1637 def split_user_input(self,line):
1640 """Split user input into pre-char, function part and rest."""
1638 """Split user input into pre-char, function part and rest."""
1641
1639
1642 lsplit = self.line_split.match(line)
1640 lsplit = self.line_split.match(line)
1643 if lsplit is None: # no regexp match returns None
1641 if lsplit is None: # no regexp match returns None
1644 try:
1642 try:
1645 iFun,theRest = line.split(None,1)
1643 iFun,theRest = line.split(None,1)
1646 except ValueError:
1644 except ValueError:
1647 iFun,theRest = line,''
1645 iFun,theRest = line,''
1648 pre = re.match('^(\s*)(.*)',line).groups()[0]
1646 pre = re.match('^(\s*)(.*)',line).groups()[0]
1649 else:
1647 else:
1650 pre,iFun,theRest = lsplit.groups()
1648 pre,iFun,theRest = lsplit.groups()
1651
1649
1652 #print 'line:<%s>' % line # dbg
1650 #print 'line:<%s>' % line # dbg
1653 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1651 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1654 return pre,iFun.strip(),theRest
1652 return pre,iFun.strip(),theRest
1655
1653
1656 def _prefilter(self, line, continue_prompt):
1654 def _prefilter(self, line, continue_prompt):
1657 """Calls different preprocessors, depending on the form of line."""
1655 """Calls different preprocessors, depending on the form of line."""
1658
1656
1659 # All handlers *must* return a value, even if it's blank ('').
1657 # All handlers *must* return a value, even if it's blank ('').
1660
1658
1661 # Lines are NOT logged here. Handlers should process the line as
1659 # Lines are NOT logged here. Handlers should process the line as
1662 # needed, update the cache AND log it (so that the input cache array
1660 # needed, update the cache AND log it (so that the input cache array
1663 # stays synced).
1661 # stays synced).
1664
1662
1665 # This function is _very_ delicate, and since it's also the one which
1663 # This function is _very_ delicate, and since it's also the one which
1666 # determines IPython's response to user input, it must be as efficient
1664 # determines IPython's response to user input, it must be as efficient
1667 # as possible. For this reason it has _many_ returns in it, trying
1665 # as possible. For this reason it has _many_ returns in it, trying
1668 # always to exit as quickly as it can figure out what it needs to do.
1666 # always to exit as quickly as it can figure out what it needs to do.
1669
1667
1670 # This function is the main responsible for maintaining IPython's
1668 # This function is the main responsible for maintaining IPython's
1671 # behavior respectful of Python's semantics. So be _very_ careful if
1669 # behavior respectful of Python's semantics. So be _very_ careful if
1672 # making changes to anything here.
1670 # making changes to anything here.
1673
1671
1674 #.....................................................................
1672 #.....................................................................
1675 # Code begins
1673 # Code begins
1676
1674
1677 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1675 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1678
1676
1679 # save the line away in case we crash, so the post-mortem handler can
1677 # save the line away in case we crash, so the post-mortem handler can
1680 # record it
1678 # record it
1681 self._last_input_line = line
1679 self._last_input_line = line
1682
1680
1683 #print '***line: <%s>' % line # dbg
1681 #print '***line: <%s>' % line # dbg
1684
1682
1685 # the input history needs to track even empty lines
1683 # the input history needs to track even empty lines
1686 if not line.strip():
1684 if not line.strip():
1687 if not continue_prompt:
1685 if not continue_prompt:
1688 self.outputcache.prompt_count -= 1
1686 self.outputcache.prompt_count -= 1
1689 return self.handle_normal(line,continue_prompt)
1687 return self.handle_normal(line,continue_prompt)
1690 #return self.handle_normal('',continue_prompt)
1688 #return self.handle_normal('',continue_prompt)
1691
1689
1692 # print '***cont',continue_prompt # dbg
1690 # print '***cont',continue_prompt # dbg
1693 # special handlers are only allowed for single line statements
1691 # special handlers are only allowed for single line statements
1694 if continue_prompt and not self.rc.multi_line_specials:
1692 if continue_prompt and not self.rc.multi_line_specials:
1695 return self.handle_normal(line,continue_prompt)
1693 return self.handle_normal(line,continue_prompt)
1696
1694
1697 # For the rest, we need the structure of the input
1695 # For the rest, we need the structure of the input
1698 pre,iFun,theRest = self.split_user_input(line)
1696 pre,iFun,theRest = self.split_user_input(line)
1699 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1697 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1700
1698
1701 # First check for explicit escapes in the last/first character
1699 # First check for explicit escapes in the last/first character
1702 handler = None
1700 handler = None
1703 if line[-1] == self.ESC_HELP:
1701 if line[-1] == self.ESC_HELP:
1704 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1702 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1705 if handler is None:
1703 if handler is None:
1706 # look at the first character of iFun, NOT of line, so we skip
1704 # look at the first character of iFun, NOT of line, so we skip
1707 # leading whitespace in multiline input
1705 # leading whitespace in multiline input
1708 handler = self.esc_handlers.get(iFun[0:1])
1706 handler = self.esc_handlers.get(iFun[0:1])
1709 if handler is not None:
1707 if handler is not None:
1710 return handler(line,continue_prompt,pre,iFun,theRest)
1708 return handler(line,continue_prompt,pre,iFun,theRest)
1711 # Emacs ipython-mode tags certain input lines
1709 # Emacs ipython-mode tags certain input lines
1712 if line.endswith('# PYTHON-MODE'):
1710 if line.endswith('# PYTHON-MODE'):
1713 return self.handle_emacs(line,continue_prompt)
1711 return self.handle_emacs(line,continue_prompt)
1714
1712
1715 # Next, check if we can automatically execute this thing
1713 # Next, check if we can automatically execute this thing
1716
1714
1717 # Allow ! in multi-line statements if multi_line_specials is on:
1715 # Allow ! in multi-line statements if multi_line_specials is on:
1718 if continue_prompt and self.rc.multi_line_specials and \
1716 if continue_prompt and self.rc.multi_line_specials and \
1719 iFun.startswith(self.ESC_SHELL):
1717 iFun.startswith(self.ESC_SHELL):
1720 return self.handle_shell_escape(line,continue_prompt,
1718 return self.handle_shell_escape(line,continue_prompt,
1721 pre=pre,iFun=iFun,
1719 pre=pre,iFun=iFun,
1722 theRest=theRest)
1720 theRest=theRest)
1723
1721
1724 # Let's try to find if the input line is a magic fn
1722 # Let's try to find if the input line is a magic fn
1725 oinfo = None
1723 oinfo = None
1726 if hasattr(self,'magic_'+iFun):
1724 if hasattr(self,'magic_'+iFun):
1727 # WARNING: _ofind uses getattr(), so it can consume generators and
1725 # WARNING: _ofind uses getattr(), so it can consume generators and
1728 # cause other side effects.
1726 # cause other side effects.
1729 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1727 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1730 if oinfo['ismagic']:
1728 if oinfo['ismagic']:
1731 # Be careful not to call magics when a variable assignment is
1729 # Be careful not to call magics when a variable assignment is
1732 # being made (ls='hi', for example)
1730 # being made (ls='hi', for example)
1733 if self.rc.automagic and \
1731 if self.rc.automagic and \
1734 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1732 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1735 (self.rc.multi_line_specials or not continue_prompt):
1733 (self.rc.multi_line_specials or not continue_prompt):
1736 return self.handle_magic(line,continue_prompt,
1734 return self.handle_magic(line,continue_prompt,
1737 pre,iFun,theRest)
1735 pre,iFun,theRest)
1738 else:
1736 else:
1739 return self.handle_normal(line,continue_prompt)
1737 return self.handle_normal(line,continue_prompt)
1740
1738
1741 # If the rest of the line begins with an (in)equality, assginment or
1739 # If the rest of the line begins with an (in)equality, assginment or
1742 # function call, we should not call _ofind but simply execute it.
1740 # function call, we should not call _ofind but simply execute it.
1743 # This avoids spurious geattr() accesses on objects upon assignment.
1741 # This avoids spurious geattr() accesses on objects upon assignment.
1744 #
1742 #
1745 # It also allows users to assign to either alias or magic names true
1743 # It also allows users to assign to either alias or magic names true
1746 # python variables (the magic/alias systems always take second seat to
1744 # python variables (the magic/alias systems always take second seat to
1747 # true python code).
1745 # true python code).
1748 if theRest and theRest[0] in '!=()':
1746 if theRest and theRest[0] in '!=()':
1749 return self.handle_normal(line,continue_prompt)
1747 return self.handle_normal(line,continue_prompt)
1750
1748
1751 if oinfo is None:
1749 if oinfo is None:
1752 # let's try to ensure that _oinfo is ONLY called when autocall is
1750 # let's try to ensure that _oinfo is ONLY called when autocall is
1753 # on. Since it has inevitable potential side effects, at least
1751 # on. Since it has inevitable potential side effects, at least
1754 # having autocall off should be a guarantee to the user that no
1752 # having autocall off should be a guarantee to the user that no
1755 # weird things will happen.
1753 # weird things will happen.
1756
1754
1757 if self.rc.autocall:
1755 if self.rc.autocall:
1758 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1756 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1759 else:
1757 else:
1760 # in this case, all that's left is either an alias or
1758 # in this case, all that's left is either an alias or
1761 # processing the line normally.
1759 # processing the line normally.
1762 if iFun in self.alias_table:
1760 if iFun in self.alias_table:
1763 return self.handle_alias(line,continue_prompt,
1761 return self.handle_alias(line,continue_prompt,
1764 pre,iFun,theRest)
1762 pre,iFun,theRest)
1765 else:
1763 else:
1766 return self.handle_normal(line,continue_prompt)
1764 return self.handle_normal(line,continue_prompt)
1767
1765
1768 if not oinfo['found']:
1766 if not oinfo['found']:
1769 return self.handle_normal(line,continue_prompt)
1767 return self.handle_normal(line,continue_prompt)
1770 else:
1768 else:
1771 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1769 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1772 if oinfo['isalias']:
1770 if oinfo['isalias']:
1773 return self.handle_alias(line,continue_prompt,
1771 return self.handle_alias(line,continue_prompt,
1774 pre,iFun,theRest)
1772 pre,iFun,theRest)
1775
1773
1776 if self.rc.autocall and \
1774 if self.rc.autocall and \
1777 not self.re_exclude_auto.match(theRest) and \
1775 not self.re_exclude_auto.match(theRest) and \
1778 self.re_fun_name.match(iFun) and \
1776 self.re_fun_name.match(iFun) and \
1779 callable(oinfo['obj']) :
1777 callable(oinfo['obj']) :
1780 #print 'going auto' # dbg
1778 #print 'going auto' # dbg
1781 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1779 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1782 else:
1780 else:
1783 #print 'was callable?', callable(oinfo['obj']) # dbg
1781 #print 'was callable?', callable(oinfo['obj']) # dbg
1784 return self.handle_normal(line,continue_prompt)
1782 return self.handle_normal(line,continue_prompt)
1785
1783
1786 # If we get here, we have a normal Python line. Log and return.
1784 # If we get here, we have a normal Python line. Log and return.
1787 return self.handle_normal(line,continue_prompt)
1785 return self.handle_normal(line,continue_prompt)
1788
1786
1789 def _prefilter_dumb(self, line, continue_prompt):
1787 def _prefilter_dumb(self, line, continue_prompt):
1790 """simple prefilter function, for debugging"""
1788 """simple prefilter function, for debugging"""
1791 return self.handle_normal(line,continue_prompt)
1789 return self.handle_normal(line,continue_prompt)
1792
1790
1793 # Set the default prefilter() function (this can be user-overridden)
1791 # Set the default prefilter() function (this can be user-overridden)
1794 prefilter = _prefilter
1792 prefilter = _prefilter
1795
1793
1796 def handle_normal(self,line,continue_prompt=None,
1794 def handle_normal(self,line,continue_prompt=None,
1797 pre=None,iFun=None,theRest=None):
1795 pre=None,iFun=None,theRest=None):
1798 """Handle normal input lines. Use as a template for handlers."""
1796 """Handle normal input lines. Use as a template for handlers."""
1799
1797
1800 # With autoindent on, we need some way to exit the input loop, and I
1798 # With autoindent on, we need some way to exit the input loop, and I
1801 # don't want to force the user to have to backspace all the way to
1799 # don't want to force the user to have to backspace all the way to
1802 # clear the line. The rule will be in this case, that either two
1800 # clear the line. The rule will be in this case, that either two
1803 # lines of pure whitespace in a row, or a line of pure whitespace but
1801 # lines of pure whitespace in a row, or a line of pure whitespace but
1804 # of a size different to the indent level, will exit the input loop.
1802 # of a size different to the indent level, will exit the input loop.
1805
1803
1806 if (continue_prompt and self.autoindent and isspace(line) and
1804 if (continue_prompt and self.autoindent and isspace(line) and
1807 (line != self.indent_current or isspace(self.buffer[-1]))):
1805 (line != self.indent_current or isspace(self.buffer[-1]))):
1808 line = ''
1806 line = ''
1809
1807
1810 self.log(line,continue_prompt)
1808 self.log(line,continue_prompt)
1811 return line
1809 return line
1812
1810
1813 def handle_alias(self,line,continue_prompt=None,
1811 def handle_alias(self,line,continue_prompt=None,
1814 pre=None,iFun=None,theRest=None):
1812 pre=None,iFun=None,theRest=None):
1815 """Handle alias input lines. """
1813 """Handle alias input lines. """
1816
1814
1817 # pre is needed, because it carries the leading whitespace. Otherwise
1815 # pre is needed, because it carries the leading whitespace. Otherwise
1818 # aliases won't work in indented sections.
1816 # aliases won't work in indented sections.
1819 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1817 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1820 self.log(line_out,continue_prompt)
1818 self.log(line_out,continue_prompt)
1821 return line_out
1819 return line_out
1822
1820
1823 def handle_shell_escape(self, line, continue_prompt=None,
1821 def handle_shell_escape(self, line, continue_prompt=None,
1824 pre=None,iFun=None,theRest=None):
1822 pre=None,iFun=None,theRest=None):
1825 """Execute the line in a shell, empty return value"""
1823 """Execute the line in a shell, empty return value"""
1826
1824
1827 #print 'line in :', `line` # dbg
1825 #print 'line in :', `line` # dbg
1828 # Example of a special handler. Others follow a similar pattern.
1826 # Example of a special handler. Others follow a similar pattern.
1829 if continue_prompt: # multi-line statements
1827 if continue_prompt: # multi-line statements
1830 if iFun.startswith('!!'):
1828 if iFun.startswith('!!'):
1831 print 'SyntaxError: !! is not allowed in multiline statements'
1829 print 'SyntaxError: !! is not allowed in multiline statements'
1832 return pre
1830 return pre
1833 else:
1831 else:
1834 cmd = ("%s %s" % (iFun[1:],theRest))
1832 cmd = ("%s %s" % (iFun[1:],theRest))
1835 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1833 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1836 else: # single-line input
1834 else: # single-line input
1837 if line.startswith('!!'):
1835 if line.startswith('!!'):
1838 # rewrite iFun/theRest to properly hold the call to %sx and
1836 # rewrite iFun/theRest to properly hold the call to %sx and
1839 # the actual command to be executed, so handle_magic can work
1837 # the actual command to be executed, so handle_magic can work
1840 # correctly
1838 # correctly
1841 theRest = '%s %s' % (iFun[2:],theRest)
1839 theRest = '%s %s' % (iFun[2:],theRest)
1842 iFun = 'sx'
1840 iFun = 'sx'
1843 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1841 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1844 continue_prompt,pre,iFun,theRest)
1842 continue_prompt,pre,iFun,theRest)
1845 else:
1843 else:
1846 cmd=line[1:]
1844 cmd=line[1:]
1847 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1845 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1848 # update cache/log and return
1846 # update cache/log and return
1849 self.log(line_out,continue_prompt)
1847 self.log(line_out,continue_prompt)
1850 return line_out
1848 return line_out
1851
1849
1852 def handle_magic(self, line, continue_prompt=None,
1850 def handle_magic(self, line, continue_prompt=None,
1853 pre=None,iFun=None,theRest=None):
1851 pre=None,iFun=None,theRest=None):
1854 """Execute magic functions.
1852 """Execute magic functions.
1855
1853
1856 Also log them with a prepended # so the log is clean Python."""
1854 Also log them with a prepended # so the log is clean Python."""
1857
1855
1858 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1856 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1859 self.log(cmd,continue_prompt)
1857 self.log(cmd,continue_prompt)
1860 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1858 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1861 return cmd
1859 return cmd
1862
1860
1863 def handle_auto(self, line, continue_prompt=None,
1861 def handle_auto(self, line, continue_prompt=None,
1864 pre=None,iFun=None,theRest=None):
1862 pre=None,iFun=None,theRest=None):
1865 """Hande lines which can be auto-executed, quoting if requested."""
1863 """Hande lines which can be auto-executed, quoting if requested."""
1866
1864
1867 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1865 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1868
1866
1869 # This should only be active for single-line input!
1867 # This should only be active for single-line input!
1870 if continue_prompt:
1868 if continue_prompt:
1871 return line
1869 return line
1872
1870
1873 if pre == self.ESC_QUOTE:
1871 if pre == self.ESC_QUOTE:
1874 # Auto-quote splitting on whitespace
1872 # Auto-quote splitting on whitespace
1875 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1873 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1876 elif pre == self.ESC_QUOTE2:
1874 elif pre == self.ESC_QUOTE2:
1877 # Auto-quote whole string
1875 # Auto-quote whole string
1878 newcmd = '%s("%s")' % (iFun,theRest)
1876 newcmd = '%s("%s")' % (iFun,theRest)
1879 else:
1877 else:
1880 # Auto-paren
1878 # Auto-paren
1881 if theRest[0:1] in ('=','['):
1879 if theRest[0:1] in ('=','['):
1882 # Don't autocall in these cases. They can be either
1880 # Don't autocall in these cases. They can be either
1883 # rebindings of an existing callable's name, or item access
1881 # rebindings of an existing callable's name, or item access
1884 # for an object which is BOTH callable and implements
1882 # for an object which is BOTH callable and implements
1885 # __getitem__.
1883 # __getitem__.
1886 return '%s %s' % (iFun,theRest)
1884 return '%s %s' % (iFun,theRest)
1887 if theRest.endswith(';'):
1885 if theRest.endswith(';'):
1888 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1886 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1889 else:
1887 else:
1890 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1888 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1891
1889
1892 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1890 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1893 # log what is now valid Python, not the actual user input (without the
1891 # log what is now valid Python, not the actual user input (without the
1894 # final newline)
1892 # final newline)
1895 self.log(newcmd,continue_prompt)
1893 self.log(newcmd,continue_prompt)
1896 return newcmd
1894 return newcmd
1897
1895
1898 def handle_help(self, line, continue_prompt=None,
1896 def handle_help(self, line, continue_prompt=None,
1899 pre=None,iFun=None,theRest=None):
1897 pre=None,iFun=None,theRest=None):
1900 """Try to get some help for the object.
1898 """Try to get some help for the object.
1901
1899
1902 obj? or ?obj -> basic information.
1900 obj? or ?obj -> basic information.
1903 obj?? or ??obj -> more details.
1901 obj?? or ??obj -> more details.
1904 """
1902 """
1905
1903
1906 # We need to make sure that we don't process lines which would be
1904 # We need to make sure that we don't process lines which would be
1907 # otherwise valid python, such as "x=1 # what?"
1905 # otherwise valid python, such as "x=1 # what?"
1908 try:
1906 try:
1909 codeop.compile_command(line)
1907 codeop.compile_command(line)
1910 except SyntaxError:
1908 except SyntaxError:
1911 # We should only handle as help stuff which is NOT valid syntax
1909 # We should only handle as help stuff which is NOT valid syntax
1912 if line[0]==self.ESC_HELP:
1910 if line[0]==self.ESC_HELP:
1913 line = line[1:]
1911 line = line[1:]
1914 elif line[-1]==self.ESC_HELP:
1912 elif line[-1]==self.ESC_HELP:
1915 line = line[:-1]
1913 line = line[:-1]
1916 self.log('#?'+line)
1914 self.log('#?'+line)
1917 if line:
1915 if line:
1918 self.magic_pinfo(line)
1916 self.magic_pinfo(line)
1919 else:
1917 else:
1920 page(self.usage,screen_lines=self.rc.screen_length)
1918 page(self.usage,screen_lines=self.rc.screen_length)
1921 return '' # Empty string is needed here!
1919 return '' # Empty string is needed here!
1922 except:
1920 except:
1923 # Pass any other exceptions through to the normal handler
1921 # Pass any other exceptions through to the normal handler
1924 return self.handle_normal(line,continue_prompt)
1922 return self.handle_normal(line,continue_prompt)
1925 else:
1923 else:
1926 # If the code compiles ok, we should handle it normally
1924 # If the code compiles ok, we should handle it normally
1927 return self.handle_normal(line,continue_prompt)
1925 return self.handle_normal(line,continue_prompt)
1928
1926
1929 def handle_emacs(self,line,continue_prompt=None,
1927 def handle_emacs(self,line,continue_prompt=None,
1930 pre=None,iFun=None,theRest=None):
1928 pre=None,iFun=None,theRest=None):
1931 """Handle input lines marked by python-mode."""
1929 """Handle input lines marked by python-mode."""
1932
1930
1933 # Currently, nothing is done. Later more functionality can be added
1931 # Currently, nothing is done. Later more functionality can be added
1934 # here if needed.
1932 # here if needed.
1935
1933
1936 # The input cache shouldn't be updated
1934 # The input cache shouldn't be updated
1937
1935
1938 return line
1936 return line
1939
1937
1940 def write(self,data):
1938 def write(self,data):
1941 """Write a string to the default output"""
1939 """Write a string to the default output"""
1942 Term.cout.write(data)
1940 Term.cout.write(data)
1943
1941
1944 def write_err(self,data):
1942 def write_err(self,data):
1945 """Write a string to the default error output"""
1943 """Write a string to the default error output"""
1946 Term.cerr.write(data)
1944 Term.cerr.write(data)
1947
1945
1948 def exit(self):
1946 def exit(self):
1949 """Handle interactive exit.
1947 """Handle interactive exit.
1950
1948
1951 This method sets the exit_now attribute."""
1949 This method sets the exit_now attribute."""
1952
1950
1953 if self.rc.confirm_exit:
1951 if self.rc.confirm_exit:
1954 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1952 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1955 self.exit_now = True
1953 self.exit_now = True
1956 else:
1954 else:
1957 self.exit_now = True
1955 self.exit_now = True
1958 return self.exit_now
1956 return self.exit_now
1959
1957
1960 def safe_execfile(self,fname,*where,**kw):
1958 def safe_execfile(self,fname,*where,**kw):
1961 fname = os.path.expanduser(fname)
1959 fname = os.path.expanduser(fname)
1962
1960
1963 # find things also in current directory
1961 # find things also in current directory
1964 dname = os.path.dirname(fname)
1962 dname = os.path.dirname(fname)
1965 if not sys.path.count(dname):
1963 if not sys.path.count(dname):
1966 sys.path.append(dname)
1964 sys.path.append(dname)
1967
1965
1968 try:
1966 try:
1969 xfile = open(fname)
1967 xfile = open(fname)
1970 except:
1968 except:
1971 print >> Term.cerr, \
1969 print >> Term.cerr, \
1972 'Could not open file <%s> for safe execution.' % fname
1970 'Could not open file <%s> for safe execution.' % fname
1973 return None
1971 return None
1974
1972
1975 kw.setdefault('islog',0)
1973 kw.setdefault('islog',0)
1976 kw.setdefault('quiet',1)
1974 kw.setdefault('quiet',1)
1977 kw.setdefault('exit_ignore',0)
1975 kw.setdefault('exit_ignore',0)
1978 first = xfile.readline()
1976 first = xfile.readline()
1979 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1977 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1980 xfile.close()
1978 xfile.close()
1981 # line by line execution
1979 # line by line execution
1982 if first.startswith(loghead) or kw['islog']:
1980 if first.startswith(loghead) or kw['islog']:
1983 print 'Loading log file <%s> one line at a time...' % fname
1981 print 'Loading log file <%s> one line at a time...' % fname
1984 if kw['quiet']:
1982 if kw['quiet']:
1985 stdout_save = sys.stdout
1983 stdout_save = sys.stdout
1986 sys.stdout = StringIO.StringIO()
1984 sys.stdout = StringIO.StringIO()
1987 try:
1985 try:
1988 globs,locs = where[0:2]
1986 globs,locs = where[0:2]
1989 except:
1987 except:
1990 try:
1988 try:
1991 globs = locs = where[0]
1989 globs = locs = where[0]
1992 except:
1990 except:
1993 globs = locs = globals()
1991 globs = locs = globals()
1994 badblocks = []
1992 badblocks = []
1995
1993
1996 # we also need to identify indented blocks of code when replaying
1994 # we also need to identify indented blocks of code when replaying
1997 # logs and put them together before passing them to an exec
1995 # logs and put them together before passing them to an exec
1998 # statement. This takes a bit of regexp and look-ahead work in the
1996 # statement. This takes a bit of regexp and look-ahead work in the
1999 # file. It's easiest if we swallow the whole thing in memory
1997 # file. It's easiest if we swallow the whole thing in memory
2000 # first, and manually walk through the lines list moving the
1998 # first, and manually walk through the lines list moving the
2001 # counter ourselves.
1999 # counter ourselves.
2002 indent_re = re.compile('\s+\S')
2000 indent_re = re.compile('\s+\S')
2003 xfile = open(fname)
2001 xfile = open(fname)
2004 filelines = xfile.readlines()
2002 filelines = xfile.readlines()
2005 xfile.close()
2003 xfile.close()
2006 nlines = len(filelines)
2004 nlines = len(filelines)
2007 lnum = 0
2005 lnum = 0
2008 while lnum < nlines:
2006 while lnum < nlines:
2009 line = filelines[lnum]
2007 line = filelines[lnum]
2010 lnum += 1
2008 lnum += 1
2011 # don't re-insert logger status info into cache
2009 # don't re-insert logger status info into cache
2012 if line.startswith('#log#'):
2010 if line.startswith('#log#'):
2013 continue
2011 continue
2014 else:
2012 else:
2015 # build a block of code (maybe a single line) for execution
2013 # build a block of code (maybe a single line) for execution
2016 block = line
2014 block = line
2017 try:
2015 try:
2018 next = filelines[lnum] # lnum has already incremented
2016 next = filelines[lnum] # lnum has already incremented
2019 except:
2017 except:
2020 next = None
2018 next = None
2021 while next and indent_re.match(next):
2019 while next and indent_re.match(next):
2022 block += next
2020 block += next
2023 lnum += 1
2021 lnum += 1
2024 try:
2022 try:
2025 next = filelines[lnum]
2023 next = filelines[lnum]
2026 except:
2024 except:
2027 next = None
2025 next = None
2028 # now execute the block of one or more lines
2026 # now execute the block of one or more lines
2029 try:
2027 try:
2030 exec block in globs,locs
2028 exec block in globs,locs
2031 except SystemExit:
2029 except SystemExit:
2032 pass
2030 pass
2033 except:
2031 except:
2034 badblocks.append(block.rstrip())
2032 badblocks.append(block.rstrip())
2035 if kw['quiet']: # restore stdout
2033 if kw['quiet']: # restore stdout
2036 sys.stdout.close()
2034 sys.stdout.close()
2037 sys.stdout = stdout_save
2035 sys.stdout = stdout_save
2038 print 'Finished replaying log file <%s>' % fname
2036 print 'Finished replaying log file <%s>' % fname
2039 if badblocks:
2037 if badblocks:
2040 print >> sys.stderr, ('\nThe following lines/blocks in file '
2038 print >> sys.stderr, ('\nThe following lines/blocks in file '
2041 '<%s> reported errors:' % fname)
2039 '<%s> reported errors:' % fname)
2042
2040
2043 for badline in badblocks:
2041 for badline in badblocks:
2044 print >> sys.stderr, badline
2042 print >> sys.stderr, badline
2045 else: # regular file execution
2043 else: # regular file execution
2046 try:
2044 try:
2047 execfile(fname,*where)
2045 execfile(fname,*where)
2048 except SyntaxError:
2046 except SyntaxError:
2049 etype,evalue = sys.exc_info()[:2]
2047 etype,evalue = sys.exc_info()[:2]
2050 self.SyntaxTB(etype,evalue,[])
2048 self.SyntaxTB(etype,evalue,[])
2051 warn('Failure executing file: <%s>' % fname)
2049 warn('Failure executing file: <%s>' % fname)
2052 except SystemExit,status:
2050 except SystemExit,status:
2053 if not kw['exit_ignore']:
2051 if not kw['exit_ignore']:
2054 self.InteractiveTB()
2052 self.InteractiveTB()
2055 warn('Failure executing file: <%s>' % fname)
2053 warn('Failure executing file: <%s>' % fname)
2056 except:
2054 except:
2057 self.InteractiveTB()
2055 self.InteractiveTB()
2058 warn('Failure executing file: <%s>' % fname)
2056 warn('Failure executing file: <%s>' % fname)
2059
2057
2060 #************************* end of file <iplib.py> *****************************
2058 #************************* end of file <iplib.py> *****************************
@@ -1,4682 +1,4708 b''
1 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/Logger.py (Logger.log): fix a history handling bug. I
4 don't know if this is the end of it, but the behavior now is
5 certainly much more correct. Note that coupled with macros,
6 slightly surprising (at first) behavior may occur: a macro will in
7 general expand to multiple lines of input, so upon exiting, the
8 in/out counters will both be bumped by the corresponding amount
9 (as if the macro's contents had been typed interactively). Typing
10 %hist will reveal the intermediate (silently processed) lines.
11
12 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
13 pickle to fail (%run was overwriting __main__ and not restoring
14 it, but pickle relies on __main__ to operate).
15
16 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
17 using properties, but forgot to make the main InteractiveShell
18 class a new-style class. Properties fail silently, and
19 misteriously, with old-style class (getters work, but
20 setters don't do anything).
21
1 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
22 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
2
23
24 * IPython/Magic.py (magic_history): fix history reporting bug (I
25 know some nasties are still there, I just can't seem to find a
26 reproducible test case to track them down; the input history is
27 falling out of sync...)
28
3 * IPython/iplib.py (handle_shell_escape): fix bug where both
29 * IPython/iplib.py (handle_shell_escape): fix bug where both
4 aliases and system accesses where broken for indented code (such
30 aliases and system accesses where broken for indented code (such
5 as loops).
31 as loops).
6
32
7 * IPython/genutils.py (shell): fix small but critical bug for
33 * IPython/genutils.py (shell): fix small but critical bug for
8 win32 system access.
34 win32 system access.
9
35
10 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
36 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
11
37
12 * IPython/iplib.py (showtraceback): remove use of the
38 * IPython/iplib.py (showtraceback): remove use of the
13 sys.last_{type/value/traceback} structures, which are non
39 sys.last_{type/value/traceback} structures, which are non
14 thread-safe.
40 thread-safe.
15 (_prefilter): change control flow to ensure that we NEVER
41 (_prefilter): change control flow to ensure that we NEVER
16 introspect objects when autocall is off. This will guarantee that
42 introspect objects when autocall is off. This will guarantee that
17 having an input line of the form 'x.y', where access to attribute
43 having an input line of the form 'x.y', where access to attribute
18 'y' has side effects, doesn't trigger the side effect TWICE. It
44 'y' has side effects, doesn't trigger the side effect TWICE. It
19 is important to note that, with autocall on, these side effects
45 is important to note that, with autocall on, these side effects
20 can still happen.
46 can still happen.
21 (ipsystem): new builtin, to complete the ip{magic/alias/system}
47 (ipsystem): new builtin, to complete the ip{magic/alias/system}
22 trio. IPython offers these three kinds of special calls which are
48 trio. IPython offers these three kinds of special calls which are
23 not python code, and it's a good thing to have their call method
49 not python code, and it's a good thing to have their call method
24 be accessible as pure python functions (not just special syntax at
50 be accessible as pure python functions (not just special syntax at
25 the command line). It gives us a better internal implementation
51 the command line). It gives us a better internal implementation
26 structure, as well as exposing these for user scripting more
52 structure, as well as exposing these for user scripting more
27 cleanly.
53 cleanly.
28
54
29 * IPython/macro.py (Macro.__init__): moved macros to a standalone
55 * IPython/macro.py (Macro.__init__): moved macros to a standalone
30 file. Now that they'll be more likely to be used with the
56 file. Now that they'll be more likely to be used with the
31 persistance system (%store), I want to make sure their module path
57 persistance system (%store), I want to make sure their module path
32 doesn't change in the future, so that we don't break things for
58 doesn't change in the future, so that we don't break things for
33 users' persisted data.
59 users' persisted data.
34
60
35 * IPython/iplib.py (autoindent_update): move indentation
61 * IPython/iplib.py (autoindent_update): move indentation
36 management into the _text_ processing loop, not the keyboard
62 management into the _text_ processing loop, not the keyboard
37 interactive one. This is necessary to correctly process non-typed
63 interactive one. This is necessary to correctly process non-typed
38 multiline input (such as macros).
64 multiline input (such as macros).
39
65
40 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
66 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
41 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
67 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
42 which was producing problems in the resulting manual.
68 which was producing problems in the resulting manual.
43 (magic_whos): improve reporting of instances (show their class,
69 (magic_whos): improve reporting of instances (show their class,
44 instead of simply printing 'instance' which isn't terribly
70 instead of simply printing 'instance' which isn't terribly
45 informative).
71 informative).
46
72
47 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
73 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
48 (minor mods) to support network shares under win32.
74 (minor mods) to support network shares under win32.
49
75
50 * IPython/winconsole.py (get_console_size): add new winconsole
76 * IPython/winconsole.py (get_console_size): add new winconsole
51 module and fixes to page_dumb() to improve its behavior under
77 module and fixes to page_dumb() to improve its behavior under
52 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
78 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
53
79
54 * IPython/Magic.py (Macro): simplified Macro class to just
80 * IPython/Magic.py (Macro): simplified Macro class to just
55 subclass list. We've had only 2.2 compatibility for a very long
81 subclass list. We've had only 2.2 compatibility for a very long
56 time, yet I was still avoiding subclassing the builtin types. No
82 time, yet I was still avoiding subclassing the builtin types. No
57 more (I'm also starting to use properties, though I won't shift to
83 more (I'm also starting to use properties, though I won't shift to
58 2.3-specific features quite yet).
84 2.3-specific features quite yet).
59 (magic_store): added Ville's patch for lightweight variable
85 (magic_store): added Ville's patch for lightweight variable
60 persistence, after a request on the user list by Matt Wilkie
86 persistence, after a request on the user list by Matt Wilkie
61 <maphew-AT-gmail.com>. The new %store magic's docstring has full
87 <maphew-AT-gmail.com>. The new %store magic's docstring has full
62 details.
88 details.
63
89
64 * IPython/iplib.py (InteractiveShell.post_config_initialization):
90 * IPython/iplib.py (InteractiveShell.post_config_initialization):
65 changed the default logfile name from 'ipython.log' to
91 changed the default logfile name from 'ipython.log' to
66 'ipython_log.py'. These logs are real python files, and now that
92 'ipython_log.py'. These logs are real python files, and now that
67 we have much better multiline support, people are more likely to
93 we have much better multiline support, people are more likely to
68 want to use them as such. Might as well name them correctly.
94 want to use them as such. Might as well name them correctly.
69
95
70 * IPython/Magic.py: substantial cleanup. While we can't stop
96 * IPython/Magic.py: substantial cleanup. While we can't stop
71 using magics as mixins, due to the existing customizations 'out
97 using magics as mixins, due to the existing customizations 'out
72 there' which rely on the mixin naming conventions, at least I
98 there' which rely on the mixin naming conventions, at least I
73 cleaned out all cross-class name usage. So once we are OK with
99 cleaned out all cross-class name usage. So once we are OK with
74 breaking compatibility, the two systems can be separated.
100 breaking compatibility, the two systems can be separated.
75
101
76 * IPython/Logger.py: major cleanup. This one is NOT a mixin
102 * IPython/Logger.py: major cleanup. This one is NOT a mixin
77 anymore, and the class is a fair bit less hideous as well. New
103 anymore, and the class is a fair bit less hideous as well. New
78 features were also introduced: timestamping of input, and logging
104 features were also introduced: timestamping of input, and logging
79 of output results. These are user-visible with the -t and -o
105 of output results. These are user-visible with the -t and -o
80 options to %logstart. Closes
106 options to %logstart. Closes
81 http://www.scipy.net/roundup/ipython/issue11 and a request by
107 http://www.scipy.net/roundup/ipython/issue11 and a request by
82 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
108 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
83
109
84 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
110 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
85
111
86 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
112 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
87 better hadnle backslashes in paths. See the thread 'More Windows
113 better hadnle backslashes in paths. See the thread 'More Windows
88 questions part 2 - \/ characters revisited' on the iypthon user
114 questions part 2 - \/ characters revisited' on the iypthon user
89 list:
115 list:
90 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
116 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
91
117
92 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
118 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
93
119
94 (InteractiveShell.__init__): change threaded shells to not use the
120 (InteractiveShell.__init__): change threaded shells to not use the
95 ipython crash handler. This was causing more problems than not,
121 ipython crash handler. This was causing more problems than not,
96 as exceptions in the main thread (GUI code, typically) would
122 as exceptions in the main thread (GUI code, typically) would
97 always show up as a 'crash', when they really weren't.
123 always show up as a 'crash', when they really weren't.
98
124
99 The colors and exception mode commands (%colors/%xmode) have been
125 The colors and exception mode commands (%colors/%xmode) have been
100 synchronized to also take this into account, so users can get
126 synchronized to also take this into account, so users can get
101 verbose exceptions for their threaded code as well. I also added
127 verbose exceptions for their threaded code as well. I also added
102 support for activating pdb inside this exception handler as well,
128 support for activating pdb inside this exception handler as well,
103 so now GUI authors can use IPython's enhanced pdb at runtime.
129 so now GUI authors can use IPython's enhanced pdb at runtime.
104
130
105 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
131 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
106 true by default, and add it to the shipped ipythonrc file. Since
132 true by default, and add it to the shipped ipythonrc file. Since
107 this asks the user before proceeding, I think it's OK to make it
133 this asks the user before proceeding, I think it's OK to make it
108 true by default.
134 true by default.
109
135
110 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
136 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
111 of the previous special-casing of input in the eval loop. I think
137 of the previous special-casing of input in the eval loop. I think
112 this is cleaner, as they really are commands and shouldn't have
138 this is cleaner, as they really are commands and shouldn't have
113 a special role in the middle of the core code.
139 a special role in the middle of the core code.
114
140
115 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
141 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
116
142
117 * IPython/iplib.py (edit_syntax_error): added support for
143 * IPython/iplib.py (edit_syntax_error): added support for
118 automatically reopening the editor if the file had a syntax error
144 automatically reopening the editor if the file had a syntax error
119 in it. Thanks to scottt who provided the patch at:
145 in it. Thanks to scottt who provided the patch at:
120 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
146 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
121 version committed).
147 version committed).
122
148
123 * IPython/iplib.py (handle_normal): add suport for multi-line
149 * IPython/iplib.py (handle_normal): add suport for multi-line
124 input with emtpy lines. This fixes
150 input with emtpy lines. This fixes
125 http://www.scipy.net/roundup/ipython/issue43 and a similar
151 http://www.scipy.net/roundup/ipython/issue43 and a similar
126 discussion on the user list.
152 discussion on the user list.
127
153
128 WARNING: a behavior change is necessarily introduced to support
154 WARNING: a behavior change is necessarily introduced to support
129 blank lines: now a single blank line with whitespace does NOT
155 blank lines: now a single blank line with whitespace does NOT
130 break the input loop, which means that when autoindent is on, by
156 break the input loop, which means that when autoindent is on, by
131 default hitting return on the next (indented) line does NOT exit.
157 default hitting return on the next (indented) line does NOT exit.
132
158
133 Instead, to exit a multiline input you can either have:
159 Instead, to exit a multiline input you can either have:
134
160
135 - TWO whitespace lines (just hit return again), or
161 - TWO whitespace lines (just hit return again), or
136 - a single whitespace line of a different length than provided
162 - a single whitespace line of a different length than provided
137 by the autoindent (add or remove a space).
163 by the autoindent (add or remove a space).
138
164
139 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
165 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
140 module to better organize all readline-related functionality.
166 module to better organize all readline-related functionality.
141 I've deleted FlexCompleter and put all completion clases here.
167 I've deleted FlexCompleter and put all completion clases here.
142
168
143 * IPython/iplib.py (raw_input): improve indentation management.
169 * IPython/iplib.py (raw_input): improve indentation management.
144 It is now possible to paste indented code with autoindent on, and
170 It is now possible to paste indented code with autoindent on, and
145 the code is interpreted correctly (though it still looks bad on
171 the code is interpreted correctly (though it still looks bad on
146 screen, due to the line-oriented nature of ipython).
172 screen, due to the line-oriented nature of ipython).
147 (MagicCompleter.complete): change behavior so that a TAB key on an
173 (MagicCompleter.complete): change behavior so that a TAB key on an
148 otherwise empty line actually inserts a tab, instead of completing
174 otherwise empty line actually inserts a tab, instead of completing
149 on the entire global namespace. This makes it easier to use the
175 on the entire global namespace. This makes it easier to use the
150 TAB key for indentation. After a request by Hans Meine
176 TAB key for indentation. After a request by Hans Meine
151 <hans_meine-AT-gmx.net>
177 <hans_meine-AT-gmx.net>
152 (_prefilter): add support so that typing plain 'exit' or 'quit'
178 (_prefilter): add support so that typing plain 'exit' or 'quit'
153 does a sensible thing. Originally I tried to deviate as little as
179 does a sensible thing. Originally I tried to deviate as little as
154 possible from the default python behavior, but even that one may
180 possible from the default python behavior, but even that one may
155 change in this direction (thread on python-dev to that effect).
181 change in this direction (thread on python-dev to that effect).
156 Regardless, ipython should do the right thing even if CPython's
182 Regardless, ipython should do the right thing even if CPython's
157 '>>>' prompt doesn't.
183 '>>>' prompt doesn't.
158 (InteractiveShell): removed subclassing code.InteractiveConsole
184 (InteractiveShell): removed subclassing code.InteractiveConsole
159 class. By now we'd overridden just about all of its methods: I've
185 class. By now we'd overridden just about all of its methods: I've
160 copied the remaining two over, and now ipython is a standalone
186 copied the remaining two over, and now ipython is a standalone
161 class. This will provide a clearer picture for the chainsaw
187 class. This will provide a clearer picture for the chainsaw
162 branch refactoring.
188 branch refactoring.
163
189
164 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
190 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
165
191
166 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
192 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
167 failures for objects which break when dir() is called on them.
193 failures for objects which break when dir() is called on them.
168
194
169 * IPython/FlexCompleter.py (Completer.__init__): Added support for
195 * IPython/FlexCompleter.py (Completer.__init__): Added support for
170 distinct local and global namespaces in the completer API. This
196 distinct local and global namespaces in the completer API. This
171 change allows us top properly handle completion with distinct
197 change allows us top properly handle completion with distinct
172 scopes, including in embedded instances (this had never really
198 scopes, including in embedded instances (this had never really
173 worked correctly).
199 worked correctly).
174
200
175 Note: this introduces a change in the constructor for
201 Note: this introduces a change in the constructor for
176 MagicCompleter, as a new global_namespace parameter is now the
202 MagicCompleter, as a new global_namespace parameter is now the
177 second argument (the others were bumped one position).
203 second argument (the others were bumped one position).
178
204
179 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
205 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
180
206
181 * IPython/iplib.py (embed_mainloop): fix tab-completion in
207 * IPython/iplib.py (embed_mainloop): fix tab-completion in
182 embedded instances (which can be done now thanks to Vivian's
208 embedded instances (which can be done now thanks to Vivian's
183 frame-handling fixes for pdb).
209 frame-handling fixes for pdb).
184 (InteractiveShell.__init__): Fix namespace handling problem in
210 (InteractiveShell.__init__): Fix namespace handling problem in
185 embedded instances. We were overwriting __main__ unconditionally,
211 embedded instances. We were overwriting __main__ unconditionally,
186 and this should only be done for 'full' (non-embedded) IPython;
212 and this should only be done for 'full' (non-embedded) IPython;
187 embedded instances must respect the caller's __main__. Thanks to
213 embedded instances must respect the caller's __main__. Thanks to
188 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
214 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
189
215
190 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
216 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
191
217
192 * setup.py: added download_url to setup(). This registers the
218 * setup.py: added download_url to setup(). This registers the
193 download address at PyPI, which is not only useful to humans
219 download address at PyPI, which is not only useful to humans
194 browsing the site, but is also picked up by setuptools (the Eggs
220 browsing the site, but is also picked up by setuptools (the Eggs
195 machinery). Thanks to Ville and R. Kern for the info/discussion
221 machinery). Thanks to Ville and R. Kern for the info/discussion
196 on this.
222 on this.
197
223
198 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
224 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
199
225
200 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
226 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
201 This brings a lot of nice functionality to the pdb mode, which now
227 This brings a lot of nice functionality to the pdb mode, which now
202 has tab-completion, syntax highlighting, and better stack handling
228 has tab-completion, syntax highlighting, and better stack handling
203 than before. Many thanks to Vivian De Smedt
229 than before. Many thanks to Vivian De Smedt
204 <vivian-AT-vdesmedt.com> for the original patches.
230 <vivian-AT-vdesmedt.com> for the original patches.
205
231
206 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
232 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
207
233
208 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
234 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
209 sequence to consistently accept the banner argument. The
235 sequence to consistently accept the banner argument. The
210 inconsistency was tripping SAGE, thanks to Gary Zablackis
236 inconsistency was tripping SAGE, thanks to Gary Zablackis
211 <gzabl-AT-yahoo.com> for the report.
237 <gzabl-AT-yahoo.com> for the report.
212
238
213 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
239 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
214
240
215 * IPython/iplib.py (InteractiveShell.post_config_initialization):
241 * IPython/iplib.py (InteractiveShell.post_config_initialization):
216 Fix bug where a naked 'alias' call in the ipythonrc file would
242 Fix bug where a naked 'alias' call in the ipythonrc file would
217 cause a crash. Bug reported by Jorgen Stenarson.
243 cause a crash. Bug reported by Jorgen Stenarson.
218
244
219 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
245 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
220
246
221 * IPython/ipmaker.py (make_IPython): cleanups which should improve
247 * IPython/ipmaker.py (make_IPython): cleanups which should improve
222 startup time.
248 startup time.
223
249
224 * IPython/iplib.py (runcode): my globals 'fix' for embedded
250 * IPython/iplib.py (runcode): my globals 'fix' for embedded
225 instances had introduced a bug with globals in normal code. Now
251 instances had introduced a bug with globals in normal code. Now
226 it's working in all cases.
252 it's working in all cases.
227
253
228 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
254 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
229 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
255 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
230 has been introduced to set the default case sensitivity of the
256 has been introduced to set the default case sensitivity of the
231 searches. Users can still select either mode at runtime on a
257 searches. Users can still select either mode at runtime on a
232 per-search basis.
258 per-search basis.
233
259
234 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
260 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
235
261
236 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
262 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
237 attributes in wildcard searches for subclasses. Modified version
263 attributes in wildcard searches for subclasses. Modified version
238 of a patch by Jorgen.
264 of a patch by Jorgen.
239
265
240 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
266 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
241
267
242 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
268 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
243 embedded instances. I added a user_global_ns attribute to the
269 embedded instances. I added a user_global_ns attribute to the
244 InteractiveShell class to handle this.
270 InteractiveShell class to handle this.
245
271
246 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
272 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
247
273
248 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
274 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
249 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
275 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
250 (reported under win32, but may happen also in other platforms).
276 (reported under win32, but may happen also in other platforms).
251 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
277 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
252
278
253 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
279 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
254
280
255 * IPython/Magic.py (magic_psearch): new support for wildcard
281 * IPython/Magic.py (magic_psearch): new support for wildcard
256 patterns. Now, typing ?a*b will list all names which begin with a
282 patterns. Now, typing ?a*b will list all names which begin with a
257 and end in b, for example. The %psearch magic has full
283 and end in b, for example. The %psearch magic has full
258 docstrings. Many thanks to JΓΆrgen Stenarson
284 docstrings. Many thanks to JΓΆrgen Stenarson
259 <jorgen.stenarson-AT-bostream.nu>, author of the patches
285 <jorgen.stenarson-AT-bostream.nu>, author of the patches
260 implementing this functionality.
286 implementing this functionality.
261
287
262 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
288 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
263
289
264 * Manual: fixed long-standing annoyance of double-dashes (as in
290 * Manual: fixed long-standing annoyance of double-dashes (as in
265 --prefix=~, for example) being stripped in the HTML version. This
291 --prefix=~, for example) being stripped in the HTML version. This
266 is a latex2html bug, but a workaround was provided. Many thanks
292 is a latex2html bug, but a workaround was provided. Many thanks
267 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
293 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
268 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
294 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
269 rolling. This seemingly small issue had tripped a number of users
295 rolling. This seemingly small issue had tripped a number of users
270 when first installing, so I'm glad to see it gone.
296 when first installing, so I'm glad to see it gone.
271
297
272 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
298 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
273
299
274 * IPython/Extensions/numeric_formats.py: fix missing import,
300 * IPython/Extensions/numeric_formats.py: fix missing import,
275 reported by Stephen Walton.
301 reported by Stephen Walton.
276
302
277 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
303 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
278
304
279 * IPython/demo.py: finish demo module, fully documented now.
305 * IPython/demo.py: finish demo module, fully documented now.
280
306
281 * IPython/genutils.py (file_read): simple little utility to read a
307 * IPython/genutils.py (file_read): simple little utility to read a
282 file and ensure it's closed afterwards.
308 file and ensure it's closed afterwards.
283
309
284 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
310 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
285
311
286 * IPython/demo.py (Demo.__init__): added support for individually
312 * IPython/demo.py (Demo.__init__): added support for individually
287 tagging blocks for automatic execution.
313 tagging blocks for automatic execution.
288
314
289 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
315 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
290 syntax-highlighted python sources, requested by John.
316 syntax-highlighted python sources, requested by John.
291
317
292 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
318 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
293
319
294 * IPython/demo.py (Demo.again): fix bug where again() blocks after
320 * IPython/demo.py (Demo.again): fix bug where again() blocks after
295 finishing.
321 finishing.
296
322
297 * IPython/genutils.py (shlex_split): moved from Magic to here,
323 * IPython/genutils.py (shlex_split): moved from Magic to here,
298 where all 2.2 compatibility stuff lives. I needed it for demo.py.
324 where all 2.2 compatibility stuff lives. I needed it for demo.py.
299
325
300 * IPython/demo.py (Demo.__init__): added support for silent
326 * IPython/demo.py (Demo.__init__): added support for silent
301 blocks, improved marks as regexps, docstrings written.
327 blocks, improved marks as regexps, docstrings written.
302 (Demo.__init__): better docstring, added support for sys.argv.
328 (Demo.__init__): better docstring, added support for sys.argv.
303
329
304 * IPython/genutils.py (marquee): little utility used by the demo
330 * IPython/genutils.py (marquee): little utility used by the demo
305 code, handy in general.
331 code, handy in general.
306
332
307 * IPython/demo.py (Demo.__init__): new class for interactive
333 * IPython/demo.py (Demo.__init__): new class for interactive
308 demos. Not documented yet, I just wrote it in a hurry for
334 demos. Not documented yet, I just wrote it in a hurry for
309 scipy'05. Will docstring later.
335 scipy'05. Will docstring later.
310
336
311 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
337 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
312
338
313 * IPython/Shell.py (sigint_handler): Drastic simplification which
339 * IPython/Shell.py (sigint_handler): Drastic simplification which
314 also seems to make Ctrl-C work correctly across threads! This is
340 also seems to make Ctrl-C work correctly across threads! This is
315 so simple, that I can't beleive I'd missed it before. Needs more
341 so simple, that I can't beleive I'd missed it before. Needs more
316 testing, though.
342 testing, though.
317 (KBINT): Never mind, revert changes. I'm sure I'd tried something
343 (KBINT): Never mind, revert changes. I'm sure I'd tried something
318 like this before...
344 like this before...
319
345
320 * IPython/genutils.py (get_home_dir): add protection against
346 * IPython/genutils.py (get_home_dir): add protection against
321 non-dirs in win32 registry.
347 non-dirs in win32 registry.
322
348
323 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
349 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
324 bug where dict was mutated while iterating (pysh crash).
350 bug where dict was mutated while iterating (pysh crash).
325
351
326 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
352 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
327
353
328 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
354 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
329 spurious newlines added by this routine. After a report by
355 spurious newlines added by this routine. After a report by
330 F. Mantegazza.
356 F. Mantegazza.
331
357
332 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
358 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
333
359
334 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
360 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
335 calls. These were a leftover from the GTK 1.x days, and can cause
361 calls. These were a leftover from the GTK 1.x days, and can cause
336 problems in certain cases (after a report by John Hunter).
362 problems in certain cases (after a report by John Hunter).
337
363
338 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
364 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
339 os.getcwd() fails at init time. Thanks to patch from David Remahl
365 os.getcwd() fails at init time. Thanks to patch from David Remahl
340 <chmod007-AT-mac.com>.
366 <chmod007-AT-mac.com>.
341 (InteractiveShell.__init__): prevent certain special magics from
367 (InteractiveShell.__init__): prevent certain special magics from
342 being shadowed by aliases. Closes
368 being shadowed by aliases. Closes
343 http://www.scipy.net/roundup/ipython/issue41.
369 http://www.scipy.net/roundup/ipython/issue41.
344
370
345 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
371 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
346
372
347 * IPython/iplib.py (InteractiveShell.complete): Added new
373 * IPython/iplib.py (InteractiveShell.complete): Added new
348 top-level completion method to expose the completion mechanism
374 top-level completion method to expose the completion mechanism
349 beyond readline-based environments.
375 beyond readline-based environments.
350
376
351 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
377 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
352
378
353 * tools/ipsvnc (svnversion): fix svnversion capture.
379 * tools/ipsvnc (svnversion): fix svnversion capture.
354
380
355 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
381 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
356 attribute to self, which was missing. Before, it was set by a
382 attribute to self, which was missing. Before, it was set by a
357 routine which in certain cases wasn't being called, so the
383 routine which in certain cases wasn't being called, so the
358 instance could end up missing the attribute. This caused a crash.
384 instance could end up missing the attribute. This caused a crash.
359 Closes http://www.scipy.net/roundup/ipython/issue40.
385 Closes http://www.scipy.net/roundup/ipython/issue40.
360
386
361 2005-08-16 Fernando Perez <fperez@colorado.edu>
387 2005-08-16 Fernando Perez <fperez@colorado.edu>
362
388
363 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
389 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
364 contains non-string attribute. Closes
390 contains non-string attribute. Closes
365 http://www.scipy.net/roundup/ipython/issue38.
391 http://www.scipy.net/roundup/ipython/issue38.
366
392
367 2005-08-14 Fernando Perez <fperez@colorado.edu>
393 2005-08-14 Fernando Perez <fperez@colorado.edu>
368
394
369 * tools/ipsvnc: Minor improvements, to add changeset info.
395 * tools/ipsvnc: Minor improvements, to add changeset info.
370
396
371 2005-08-12 Fernando Perez <fperez@colorado.edu>
397 2005-08-12 Fernando Perez <fperez@colorado.edu>
372
398
373 * IPython/iplib.py (runsource): remove self.code_to_run_src
399 * IPython/iplib.py (runsource): remove self.code_to_run_src
374 attribute. I realized this is nothing more than
400 attribute. I realized this is nothing more than
375 '\n'.join(self.buffer), and having the same data in two different
401 '\n'.join(self.buffer), and having the same data in two different
376 places is just asking for synchronization bugs. This may impact
402 places is just asking for synchronization bugs. This may impact
377 people who have custom exception handlers, so I need to warn
403 people who have custom exception handlers, so I need to warn
378 ipython-dev about it (F. Mantegazza may use them).
404 ipython-dev about it (F. Mantegazza may use them).
379
405
380 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
406 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
381
407
382 * IPython/genutils.py: fix 2.2 compatibility (generators)
408 * IPython/genutils.py: fix 2.2 compatibility (generators)
383
409
384 2005-07-18 Fernando Perez <fperez@colorado.edu>
410 2005-07-18 Fernando Perez <fperez@colorado.edu>
385
411
386 * IPython/genutils.py (get_home_dir): fix to help users with
412 * IPython/genutils.py (get_home_dir): fix to help users with
387 invalid $HOME under win32.
413 invalid $HOME under win32.
388
414
389 2005-07-17 Fernando Perez <fperez@colorado.edu>
415 2005-07-17 Fernando Perez <fperez@colorado.edu>
390
416
391 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
417 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
392 some old hacks and clean up a bit other routines; code should be
418 some old hacks and clean up a bit other routines; code should be
393 simpler and a bit faster.
419 simpler and a bit faster.
394
420
395 * IPython/iplib.py (interact): removed some last-resort attempts
421 * IPython/iplib.py (interact): removed some last-resort attempts
396 to survive broken stdout/stderr. That code was only making it
422 to survive broken stdout/stderr. That code was only making it
397 harder to abstract out the i/o (necessary for gui integration),
423 harder to abstract out the i/o (necessary for gui integration),
398 and the crashes it could prevent were extremely rare in practice
424 and the crashes it could prevent were extremely rare in practice
399 (besides being fully user-induced in a pretty violent manner).
425 (besides being fully user-induced in a pretty violent manner).
400
426
401 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
427 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
402 Nothing major yet, but the code is simpler to read; this should
428 Nothing major yet, but the code is simpler to read; this should
403 make it easier to do more serious modifications in the future.
429 make it easier to do more serious modifications in the future.
404
430
405 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
431 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
406 which broke in .15 (thanks to a report by Ville).
432 which broke in .15 (thanks to a report by Ville).
407
433
408 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
434 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
409 be quite correct, I know next to nothing about unicode). This
435 be quite correct, I know next to nothing about unicode). This
410 will allow unicode strings to be used in prompts, amongst other
436 will allow unicode strings to be used in prompts, amongst other
411 cases. It also will prevent ipython from crashing when unicode
437 cases. It also will prevent ipython from crashing when unicode
412 shows up unexpectedly in many places. If ascii encoding fails, we
438 shows up unexpectedly in many places. If ascii encoding fails, we
413 assume utf_8. Currently the encoding is not a user-visible
439 assume utf_8. Currently the encoding is not a user-visible
414 setting, though it could be made so if there is demand for it.
440 setting, though it could be made so if there is demand for it.
415
441
416 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
442 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
417
443
418 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
444 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
419
445
420 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
446 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
421
447
422 * IPython/genutils.py: Add 2.2 compatibility here, so all other
448 * IPython/genutils.py: Add 2.2 compatibility here, so all other
423 code can work transparently for 2.2/2.3.
449 code can work transparently for 2.2/2.3.
424
450
425 2005-07-16 Fernando Perez <fperez@colorado.edu>
451 2005-07-16 Fernando Perez <fperez@colorado.edu>
426
452
427 * IPython/ultraTB.py (ExceptionColors): Make a global variable
453 * IPython/ultraTB.py (ExceptionColors): Make a global variable
428 out of the color scheme table used for coloring exception
454 out of the color scheme table used for coloring exception
429 tracebacks. This allows user code to add new schemes at runtime.
455 tracebacks. This allows user code to add new schemes at runtime.
430 This is a minimally modified version of the patch at
456 This is a minimally modified version of the patch at
431 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
457 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
432 for the contribution.
458 for the contribution.
433
459
434 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
460 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
435 slightly modified version of the patch in
461 slightly modified version of the patch in
436 http://www.scipy.net/roundup/ipython/issue34, which also allows me
462 http://www.scipy.net/roundup/ipython/issue34, which also allows me
437 to remove the previous try/except solution (which was costlier).
463 to remove the previous try/except solution (which was costlier).
438 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
464 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
439
465
440 2005-06-08 Fernando Perez <fperez@colorado.edu>
466 2005-06-08 Fernando Perez <fperez@colorado.edu>
441
467
442 * IPython/iplib.py (write/write_err): Add methods to abstract all
468 * IPython/iplib.py (write/write_err): Add methods to abstract all
443 I/O a bit more.
469 I/O a bit more.
444
470
445 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
471 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
446 warning, reported by Aric Hagberg, fix by JD Hunter.
472 warning, reported by Aric Hagberg, fix by JD Hunter.
447
473
448 2005-06-02 *** Released version 0.6.15
474 2005-06-02 *** Released version 0.6.15
449
475
450 2005-06-01 Fernando Perez <fperez@colorado.edu>
476 2005-06-01 Fernando Perez <fperez@colorado.edu>
451
477
452 * IPython/iplib.py (MagicCompleter.file_matches): Fix
478 * IPython/iplib.py (MagicCompleter.file_matches): Fix
453 tab-completion of filenames within open-quoted strings. Note that
479 tab-completion of filenames within open-quoted strings. Note that
454 this requires that in ~/.ipython/ipythonrc, users change the
480 this requires that in ~/.ipython/ipythonrc, users change the
455 readline delimiters configuration to read:
481 readline delimiters configuration to read:
456
482
457 readline_remove_delims -/~
483 readline_remove_delims -/~
458
484
459
485
460 2005-05-31 *** Released version 0.6.14
486 2005-05-31 *** Released version 0.6.14
461
487
462 2005-05-29 Fernando Perez <fperez@colorado.edu>
488 2005-05-29 Fernando Perez <fperez@colorado.edu>
463
489
464 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
490 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
465 with files not on the filesystem. Reported by Eliyahu Sandler
491 with files not on the filesystem. Reported by Eliyahu Sandler
466 <eli@gondolin.net>
492 <eli@gondolin.net>
467
493
468 2005-05-22 Fernando Perez <fperez@colorado.edu>
494 2005-05-22 Fernando Perez <fperez@colorado.edu>
469
495
470 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
496 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
471 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
497 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
472
498
473 2005-05-19 Fernando Perez <fperez@colorado.edu>
499 2005-05-19 Fernando Perez <fperez@colorado.edu>
474
500
475 * IPython/iplib.py (safe_execfile): close a file which could be
501 * IPython/iplib.py (safe_execfile): close a file which could be
476 left open (causing problems in win32, which locks open files).
502 left open (causing problems in win32, which locks open files).
477 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
503 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
478
504
479 2005-05-18 Fernando Perez <fperez@colorado.edu>
505 2005-05-18 Fernando Perez <fperez@colorado.edu>
480
506
481 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
507 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
482 keyword arguments correctly to safe_execfile().
508 keyword arguments correctly to safe_execfile().
483
509
484 2005-05-13 Fernando Perez <fperez@colorado.edu>
510 2005-05-13 Fernando Perez <fperez@colorado.edu>
485
511
486 * ipython.1: Added info about Qt to manpage, and threads warning
512 * ipython.1: Added info about Qt to manpage, and threads warning
487 to usage page (invoked with --help).
513 to usage page (invoked with --help).
488
514
489 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
515 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
490 new matcher (it goes at the end of the priority list) to do
516 new matcher (it goes at the end of the priority list) to do
491 tab-completion on named function arguments. Submitted by George
517 tab-completion on named function arguments. Submitted by George
492 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
518 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
493 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
519 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
494 for more details.
520 for more details.
495
521
496 * IPython/Magic.py (magic_run): Added new -e flag to ignore
522 * IPython/Magic.py (magic_run): Added new -e flag to ignore
497 SystemExit exceptions in the script being run. Thanks to a report
523 SystemExit exceptions in the script being run. Thanks to a report
498 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
524 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
499 producing very annoying behavior when running unit tests.
525 producing very annoying behavior when running unit tests.
500
526
501 2005-05-12 Fernando Perez <fperez@colorado.edu>
527 2005-05-12 Fernando Perez <fperez@colorado.edu>
502
528
503 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
529 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
504 which I'd broken (again) due to a changed regexp. In the process,
530 which I'd broken (again) due to a changed regexp. In the process,
505 added ';' as an escape to auto-quote the whole line without
531 added ';' as an escape to auto-quote the whole line without
506 splitting its arguments. Thanks to a report by Jerry McRae
532 splitting its arguments. Thanks to a report by Jerry McRae
507 <qrs0xyc02-AT-sneakemail.com>.
533 <qrs0xyc02-AT-sneakemail.com>.
508
534
509 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
535 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
510 possible crashes caused by a TokenError. Reported by Ed Schofield
536 possible crashes caused by a TokenError. Reported by Ed Schofield
511 <schofield-AT-ftw.at>.
537 <schofield-AT-ftw.at>.
512
538
513 2005-05-06 Fernando Perez <fperez@colorado.edu>
539 2005-05-06 Fernando Perez <fperez@colorado.edu>
514
540
515 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
541 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
516
542
517 2005-04-29 Fernando Perez <fperez@colorado.edu>
543 2005-04-29 Fernando Perez <fperez@colorado.edu>
518
544
519 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
545 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
520 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
546 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
521 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
547 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
522 which provides support for Qt interactive usage (similar to the
548 which provides support for Qt interactive usage (similar to the
523 existing one for WX and GTK). This had been often requested.
549 existing one for WX and GTK). This had been often requested.
524
550
525 2005-04-14 *** Released version 0.6.13
551 2005-04-14 *** Released version 0.6.13
526
552
527 2005-04-08 Fernando Perez <fperez@colorado.edu>
553 2005-04-08 Fernando Perez <fperez@colorado.edu>
528
554
529 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
555 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
530 from _ofind, which gets called on almost every input line. Now,
556 from _ofind, which gets called on almost every input line. Now,
531 we only try to get docstrings if they are actually going to be
557 we only try to get docstrings if they are actually going to be
532 used (the overhead of fetching unnecessary docstrings can be
558 used (the overhead of fetching unnecessary docstrings can be
533 noticeable for certain objects, such as Pyro proxies).
559 noticeable for certain objects, such as Pyro proxies).
534
560
535 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
561 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
536 for completers. For some reason I had been passing them the state
562 for completers. For some reason I had been passing them the state
537 variable, which completers never actually need, and was in
563 variable, which completers never actually need, and was in
538 conflict with the rlcompleter API. Custom completers ONLY need to
564 conflict with the rlcompleter API. Custom completers ONLY need to
539 take the text parameter.
565 take the text parameter.
540
566
541 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
567 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
542 work correctly in pysh. I've also moved all the logic which used
568 work correctly in pysh. I've also moved all the logic which used
543 to be in pysh.py here, which will prevent problems with future
569 to be in pysh.py here, which will prevent problems with future
544 upgrades. However, this time I must warn users to update their
570 upgrades. However, this time I must warn users to update their
545 pysh profile to include the line
571 pysh profile to include the line
546
572
547 import_all IPython.Extensions.InterpreterExec
573 import_all IPython.Extensions.InterpreterExec
548
574
549 because otherwise things won't work for them. They MUST also
575 because otherwise things won't work for them. They MUST also
550 delete pysh.py and the line
576 delete pysh.py and the line
551
577
552 execfile pysh.py
578 execfile pysh.py
553
579
554 from their ipythonrc-pysh.
580 from their ipythonrc-pysh.
555
581
556 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
582 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
557 robust in the face of objects whose dir() returns non-strings
583 robust in the face of objects whose dir() returns non-strings
558 (which it shouldn't, but some broken libs like ITK do). Thanks to
584 (which it shouldn't, but some broken libs like ITK do). Thanks to
559 a patch by John Hunter (implemented differently, though). Also
585 a patch by John Hunter (implemented differently, though). Also
560 minor improvements by using .extend instead of + on lists.
586 minor improvements by using .extend instead of + on lists.
561
587
562 * pysh.py:
588 * pysh.py:
563
589
564 2005-04-06 Fernando Perez <fperez@colorado.edu>
590 2005-04-06 Fernando Perez <fperez@colorado.edu>
565
591
566 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
592 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
567 by default, so that all users benefit from it. Those who don't
593 by default, so that all users benefit from it. Those who don't
568 want it can still turn it off.
594 want it can still turn it off.
569
595
570 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
596 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
571 config file, I'd forgotten about this, so users were getting it
597 config file, I'd forgotten about this, so users were getting it
572 off by default.
598 off by default.
573
599
574 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
600 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
575 consistency. Now magics can be called in multiline statements,
601 consistency. Now magics can be called in multiline statements,
576 and python variables can be expanded in magic calls via $var.
602 and python variables can be expanded in magic calls via $var.
577 This makes the magic system behave just like aliases or !system
603 This makes the magic system behave just like aliases or !system
578 calls.
604 calls.
579
605
580 2005-03-28 Fernando Perez <fperez@colorado.edu>
606 2005-03-28 Fernando Perez <fperez@colorado.edu>
581
607
582 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
608 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
583 expensive string additions for building command. Add support for
609 expensive string additions for building command. Add support for
584 trailing ';' when autocall is used.
610 trailing ';' when autocall is used.
585
611
586 2005-03-26 Fernando Perez <fperez@colorado.edu>
612 2005-03-26 Fernando Perez <fperez@colorado.edu>
587
613
588 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
614 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
589 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
615 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
590 ipython.el robust against prompts with any number of spaces
616 ipython.el robust against prompts with any number of spaces
591 (including 0) after the ':' character.
617 (including 0) after the ':' character.
592
618
593 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
619 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
594 continuation prompt, which misled users to think the line was
620 continuation prompt, which misled users to think the line was
595 already indented. Closes debian Bug#300847, reported to me by
621 already indented. Closes debian Bug#300847, reported to me by
596 Norbert Tretkowski <tretkowski-AT-inittab.de>.
622 Norbert Tretkowski <tretkowski-AT-inittab.de>.
597
623
598 2005-03-23 Fernando Perez <fperez@colorado.edu>
624 2005-03-23 Fernando Perez <fperez@colorado.edu>
599
625
600 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
626 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
601 properly aligned if they have embedded newlines.
627 properly aligned if they have embedded newlines.
602
628
603 * IPython/iplib.py (runlines): Add a public method to expose
629 * IPython/iplib.py (runlines): Add a public method to expose
604 IPython's code execution machinery, so that users can run strings
630 IPython's code execution machinery, so that users can run strings
605 as if they had been typed at the prompt interactively.
631 as if they had been typed at the prompt interactively.
606 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
632 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
607 methods which can call the system shell, but with python variable
633 methods which can call the system shell, but with python variable
608 expansion. The three such methods are: __IPYTHON__.system,
634 expansion. The three such methods are: __IPYTHON__.system,
609 .getoutput and .getoutputerror. These need to be documented in a
635 .getoutput and .getoutputerror. These need to be documented in a
610 'public API' section (to be written) of the manual.
636 'public API' section (to be written) of the manual.
611
637
612 2005-03-20 Fernando Perez <fperez@colorado.edu>
638 2005-03-20 Fernando Perez <fperez@colorado.edu>
613
639
614 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
640 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
615 for custom exception handling. This is quite powerful, and it
641 for custom exception handling. This is quite powerful, and it
616 allows for user-installable exception handlers which can trap
642 allows for user-installable exception handlers which can trap
617 custom exceptions at runtime and treat them separately from
643 custom exceptions at runtime and treat them separately from
618 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
644 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
619 Mantegazza <mantegazza-AT-ill.fr>.
645 Mantegazza <mantegazza-AT-ill.fr>.
620 (InteractiveShell.set_custom_completer): public API function to
646 (InteractiveShell.set_custom_completer): public API function to
621 add new completers at runtime.
647 add new completers at runtime.
622
648
623 2005-03-19 Fernando Perez <fperez@colorado.edu>
649 2005-03-19 Fernando Perez <fperez@colorado.edu>
624
650
625 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
651 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
626 allow objects which provide their docstrings via non-standard
652 allow objects which provide their docstrings via non-standard
627 mechanisms (like Pyro proxies) to still be inspected by ipython's
653 mechanisms (like Pyro proxies) to still be inspected by ipython's
628 ? system.
654 ? system.
629
655
630 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
656 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
631 automatic capture system. I tried quite hard to make it work
657 automatic capture system. I tried quite hard to make it work
632 reliably, and simply failed. I tried many combinations with the
658 reliably, and simply failed. I tried many combinations with the
633 subprocess module, but eventually nothing worked in all needed
659 subprocess module, but eventually nothing worked in all needed
634 cases (not blocking stdin for the child, duplicating stdout
660 cases (not blocking stdin for the child, duplicating stdout
635 without blocking, etc). The new %sc/%sx still do capture to these
661 without blocking, etc). The new %sc/%sx still do capture to these
636 magical list/string objects which make shell use much more
662 magical list/string objects which make shell use much more
637 conveninent, so not all is lost.
663 conveninent, so not all is lost.
638
664
639 XXX - FIX MANUAL for the change above!
665 XXX - FIX MANUAL for the change above!
640
666
641 (runsource): I copied code.py's runsource() into ipython to modify
667 (runsource): I copied code.py's runsource() into ipython to modify
642 it a bit. Now the code object and source to be executed are
668 it a bit. Now the code object and source to be executed are
643 stored in ipython. This makes this info accessible to third-party
669 stored in ipython. This makes this info accessible to third-party
644 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
670 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
645 Mantegazza <mantegazza-AT-ill.fr>.
671 Mantegazza <mantegazza-AT-ill.fr>.
646
672
647 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
673 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
648 history-search via readline (like C-p/C-n). I'd wanted this for a
674 history-search via readline (like C-p/C-n). I'd wanted this for a
649 long time, but only recently found out how to do it. For users
675 long time, but only recently found out how to do it. For users
650 who already have their ipythonrc files made and want this, just
676 who already have their ipythonrc files made and want this, just
651 add:
677 add:
652
678
653 readline_parse_and_bind "\e[A": history-search-backward
679 readline_parse_and_bind "\e[A": history-search-backward
654 readline_parse_and_bind "\e[B": history-search-forward
680 readline_parse_and_bind "\e[B": history-search-forward
655
681
656 2005-03-18 Fernando Perez <fperez@colorado.edu>
682 2005-03-18 Fernando Perez <fperez@colorado.edu>
657
683
658 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
684 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
659 LSString and SList classes which allow transparent conversions
685 LSString and SList classes which allow transparent conversions
660 between list mode and whitespace-separated string.
686 between list mode and whitespace-separated string.
661 (magic_r): Fix recursion problem in %r.
687 (magic_r): Fix recursion problem in %r.
662
688
663 * IPython/genutils.py (LSString): New class to be used for
689 * IPython/genutils.py (LSString): New class to be used for
664 automatic storage of the results of all alias/system calls in _o
690 automatic storage of the results of all alias/system calls in _o
665 and _e (stdout/err). These provide a .l/.list attribute which
691 and _e (stdout/err). These provide a .l/.list attribute which
666 does automatic splitting on newlines. This means that for most
692 does automatic splitting on newlines. This means that for most
667 uses, you'll never need to do capturing of output with %sc/%sx
693 uses, you'll never need to do capturing of output with %sc/%sx
668 anymore, since ipython keeps this always done for you. Note that
694 anymore, since ipython keeps this always done for you. Note that
669 only the LAST results are stored, the _o/e variables are
695 only the LAST results are stored, the _o/e variables are
670 overwritten on each call. If you need to save their contents
696 overwritten on each call. If you need to save their contents
671 further, simply bind them to any other name.
697 further, simply bind them to any other name.
672
698
673 2005-03-17 Fernando Perez <fperez@colorado.edu>
699 2005-03-17 Fernando Perez <fperez@colorado.edu>
674
700
675 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
701 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
676 prompt namespace handling.
702 prompt namespace handling.
677
703
678 2005-03-16 Fernando Perez <fperez@colorado.edu>
704 2005-03-16 Fernando Perez <fperez@colorado.edu>
679
705
680 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
706 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
681 classic prompts to be '>>> ' (final space was missing, and it
707 classic prompts to be '>>> ' (final space was missing, and it
682 trips the emacs python mode).
708 trips the emacs python mode).
683 (BasePrompt.__str__): Added safe support for dynamic prompt
709 (BasePrompt.__str__): Added safe support for dynamic prompt
684 strings. Now you can set your prompt string to be '$x', and the
710 strings. Now you can set your prompt string to be '$x', and the
685 value of x will be printed from your interactive namespace. The
711 value of x will be printed from your interactive namespace. The
686 interpolation syntax includes the full Itpl support, so
712 interpolation syntax includes the full Itpl support, so
687 ${foo()+x+bar()} is a valid prompt string now, and the function
713 ${foo()+x+bar()} is a valid prompt string now, and the function
688 calls will be made at runtime.
714 calls will be made at runtime.
689
715
690 2005-03-15 Fernando Perez <fperez@colorado.edu>
716 2005-03-15 Fernando Perez <fperez@colorado.edu>
691
717
692 * IPython/Magic.py (magic_history): renamed %hist to %history, to
718 * IPython/Magic.py (magic_history): renamed %hist to %history, to
693 avoid name clashes in pylab. %hist still works, it just forwards
719 avoid name clashes in pylab. %hist still works, it just forwards
694 the call to %history.
720 the call to %history.
695
721
696 2005-03-02 *** Released version 0.6.12
722 2005-03-02 *** Released version 0.6.12
697
723
698 2005-03-02 Fernando Perez <fperez@colorado.edu>
724 2005-03-02 Fernando Perez <fperez@colorado.edu>
699
725
700 * IPython/iplib.py (handle_magic): log magic calls properly as
726 * IPython/iplib.py (handle_magic): log magic calls properly as
701 ipmagic() function calls.
727 ipmagic() function calls.
702
728
703 * IPython/Magic.py (magic_time): Improved %time to support
729 * IPython/Magic.py (magic_time): Improved %time to support
704 statements and provide wall-clock as well as CPU time.
730 statements and provide wall-clock as well as CPU time.
705
731
706 2005-02-27 Fernando Perez <fperez@colorado.edu>
732 2005-02-27 Fernando Perez <fperez@colorado.edu>
707
733
708 * IPython/hooks.py: New hooks module, to expose user-modifiable
734 * IPython/hooks.py: New hooks module, to expose user-modifiable
709 IPython functionality in a clean manner. For now only the editor
735 IPython functionality in a clean manner. For now only the editor
710 hook is actually written, and other thigns which I intend to turn
736 hook is actually written, and other thigns which I intend to turn
711 into proper hooks aren't yet there. The display and prefilter
737 into proper hooks aren't yet there. The display and prefilter
712 stuff, for example, should be hooks. But at least now the
738 stuff, for example, should be hooks. But at least now the
713 framework is in place, and the rest can be moved here with more
739 framework is in place, and the rest can be moved here with more
714 time later. IPython had had a .hooks variable for a long time for
740 time later. IPython had had a .hooks variable for a long time for
715 this purpose, but I'd never actually used it for anything.
741 this purpose, but I'd never actually used it for anything.
716
742
717 2005-02-26 Fernando Perez <fperez@colorado.edu>
743 2005-02-26 Fernando Perez <fperez@colorado.edu>
718
744
719 * IPython/ipmaker.py (make_IPython): make the default ipython
745 * IPython/ipmaker.py (make_IPython): make the default ipython
720 directory be called _ipython under win32, to follow more the
746 directory be called _ipython under win32, to follow more the
721 naming peculiarities of that platform (where buggy software like
747 naming peculiarities of that platform (where buggy software like
722 Visual Sourcesafe breaks with .named directories). Reported by
748 Visual Sourcesafe breaks with .named directories). Reported by
723 Ville Vainio.
749 Ville Vainio.
724
750
725 2005-02-23 Fernando Perez <fperez@colorado.edu>
751 2005-02-23 Fernando Perez <fperez@colorado.edu>
726
752
727 * IPython/iplib.py (InteractiveShell.__init__): removed a few
753 * IPython/iplib.py (InteractiveShell.__init__): removed a few
728 auto_aliases for win32 which were causing problems. Users can
754 auto_aliases for win32 which were causing problems. Users can
729 define the ones they personally like.
755 define the ones they personally like.
730
756
731 2005-02-21 Fernando Perez <fperez@colorado.edu>
757 2005-02-21 Fernando Perez <fperez@colorado.edu>
732
758
733 * IPython/Magic.py (magic_time): new magic to time execution of
759 * IPython/Magic.py (magic_time): new magic to time execution of
734 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
760 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
735
761
736 2005-02-19 Fernando Perez <fperez@colorado.edu>
762 2005-02-19 Fernando Perez <fperez@colorado.edu>
737
763
738 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
764 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
739 into keys (for prompts, for example).
765 into keys (for prompts, for example).
740
766
741 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
767 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
742 prompts in case users want them. This introduces a small behavior
768 prompts in case users want them. This introduces a small behavior
743 change: ipython does not automatically add a space to all prompts
769 change: ipython does not automatically add a space to all prompts
744 anymore. To get the old prompts with a space, users should add it
770 anymore. To get the old prompts with a space, users should add it
745 manually to their ipythonrc file, so for example prompt_in1 should
771 manually to their ipythonrc file, so for example prompt_in1 should
746 now read 'In [\#]: ' instead of 'In [\#]:'.
772 now read 'In [\#]: ' instead of 'In [\#]:'.
747 (BasePrompt.__init__): New option prompts_pad_left (only in rc
773 (BasePrompt.__init__): New option prompts_pad_left (only in rc
748 file) to control left-padding of secondary prompts.
774 file) to control left-padding of secondary prompts.
749
775
750 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
776 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
751 the profiler can't be imported. Fix for Debian, which removed
777 the profiler can't be imported. Fix for Debian, which removed
752 profile.py because of License issues. I applied a slightly
778 profile.py because of License issues. I applied a slightly
753 modified version of the original Debian patch at
779 modified version of the original Debian patch at
754 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
780 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
755
781
756 2005-02-17 Fernando Perez <fperez@colorado.edu>
782 2005-02-17 Fernando Perez <fperez@colorado.edu>
757
783
758 * IPython/genutils.py (native_line_ends): Fix bug which would
784 * IPython/genutils.py (native_line_ends): Fix bug which would
759 cause improper line-ends under win32 b/c I was not opening files
785 cause improper line-ends under win32 b/c I was not opening files
760 in binary mode. Bug report and fix thanks to Ville.
786 in binary mode. Bug report and fix thanks to Ville.
761
787
762 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
788 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
763 trying to catch spurious foo[1] autocalls. My fix actually broke
789 trying to catch spurious foo[1] autocalls. My fix actually broke
764 ',/' autoquote/call with explicit escape (bad regexp).
790 ',/' autoquote/call with explicit escape (bad regexp).
765
791
766 2005-02-15 *** Released version 0.6.11
792 2005-02-15 *** Released version 0.6.11
767
793
768 2005-02-14 Fernando Perez <fperez@colorado.edu>
794 2005-02-14 Fernando Perez <fperez@colorado.edu>
769
795
770 * IPython/background_jobs.py: New background job management
796 * IPython/background_jobs.py: New background job management
771 subsystem. This is implemented via a new set of classes, and
797 subsystem. This is implemented via a new set of classes, and
772 IPython now provides a builtin 'jobs' object for background job
798 IPython now provides a builtin 'jobs' object for background job
773 execution. A convenience %bg magic serves as a lightweight
799 execution. A convenience %bg magic serves as a lightweight
774 frontend for starting the more common type of calls. This was
800 frontend for starting the more common type of calls. This was
775 inspired by discussions with B. Granger and the BackgroundCommand
801 inspired by discussions with B. Granger and the BackgroundCommand
776 class described in the book Python Scripting for Computational
802 class described in the book Python Scripting for Computational
777 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
803 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
778 (although ultimately no code from this text was used, as IPython's
804 (although ultimately no code from this text was used, as IPython's
779 system is a separate implementation).
805 system is a separate implementation).
780
806
781 * IPython/iplib.py (MagicCompleter.python_matches): add new option
807 * IPython/iplib.py (MagicCompleter.python_matches): add new option
782 to control the completion of single/double underscore names
808 to control the completion of single/double underscore names
783 separately. As documented in the example ipytonrc file, the
809 separately. As documented in the example ipytonrc file, the
784 readline_omit__names variable can now be set to 2, to omit even
810 readline_omit__names variable can now be set to 2, to omit even
785 single underscore names. Thanks to a patch by Brian Wong
811 single underscore names. Thanks to a patch by Brian Wong
786 <BrianWong-AT-AirgoNetworks.Com>.
812 <BrianWong-AT-AirgoNetworks.Com>.
787 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
813 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
788 be autocalled as foo([1]) if foo were callable. A problem for
814 be autocalled as foo([1]) if foo were callable. A problem for
789 things which are both callable and implement __getitem__.
815 things which are both callable and implement __getitem__.
790 (init_readline): Fix autoindentation for win32. Thanks to a patch
816 (init_readline): Fix autoindentation for win32. Thanks to a patch
791 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
817 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
792
818
793 2005-02-12 Fernando Perez <fperez@colorado.edu>
819 2005-02-12 Fernando Perez <fperez@colorado.edu>
794
820
795 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
821 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
796 which I had written long ago to sort out user error messages which
822 which I had written long ago to sort out user error messages which
797 may occur during startup. This seemed like a good idea initially,
823 may occur during startup. This seemed like a good idea initially,
798 but it has proven a disaster in retrospect. I don't want to
824 but it has proven a disaster in retrospect. I don't want to
799 change much code for now, so my fix is to set the internal 'debug'
825 change much code for now, so my fix is to set the internal 'debug'
800 flag to true everywhere, whose only job was precisely to control
826 flag to true everywhere, whose only job was precisely to control
801 this subsystem. This closes issue 28 (as well as avoiding all
827 this subsystem. This closes issue 28 (as well as avoiding all
802 sorts of strange hangups which occur from time to time).
828 sorts of strange hangups which occur from time to time).
803
829
804 2005-02-07 Fernando Perez <fperez@colorado.edu>
830 2005-02-07 Fernando Perez <fperez@colorado.edu>
805
831
806 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
832 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
807 previous call produced a syntax error.
833 previous call produced a syntax error.
808
834
809 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
835 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
810 classes without constructor.
836 classes without constructor.
811
837
812 2005-02-06 Fernando Perez <fperez@colorado.edu>
838 2005-02-06 Fernando Perez <fperez@colorado.edu>
813
839
814 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
840 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
815 completions with the results of each matcher, so we return results
841 completions with the results of each matcher, so we return results
816 to the user from all namespaces. This breaks with ipython
842 to the user from all namespaces. This breaks with ipython
817 tradition, but I think it's a nicer behavior. Now you get all
843 tradition, but I think it's a nicer behavior. Now you get all
818 possible completions listed, from all possible namespaces (python,
844 possible completions listed, from all possible namespaces (python,
819 filesystem, magics...) After a request by John Hunter
845 filesystem, magics...) After a request by John Hunter
820 <jdhunter-AT-nitace.bsd.uchicago.edu>.
846 <jdhunter-AT-nitace.bsd.uchicago.edu>.
821
847
822 2005-02-05 Fernando Perez <fperez@colorado.edu>
848 2005-02-05 Fernando Perez <fperez@colorado.edu>
823
849
824 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
850 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
825 the call had quote characters in it (the quotes were stripped).
851 the call had quote characters in it (the quotes were stripped).
826
852
827 2005-01-31 Fernando Perez <fperez@colorado.edu>
853 2005-01-31 Fernando Perez <fperez@colorado.edu>
828
854
829 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
855 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
830 Itpl.itpl() to make the code more robust against psyco
856 Itpl.itpl() to make the code more robust against psyco
831 optimizations.
857 optimizations.
832
858
833 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
859 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
834 of causing an exception. Quicker, cleaner.
860 of causing an exception. Quicker, cleaner.
835
861
836 2005-01-28 Fernando Perez <fperez@colorado.edu>
862 2005-01-28 Fernando Perez <fperez@colorado.edu>
837
863
838 * scripts/ipython_win_post_install.py (install): hardcode
864 * scripts/ipython_win_post_install.py (install): hardcode
839 sys.prefix+'python.exe' as the executable path. It turns out that
865 sys.prefix+'python.exe' as the executable path. It turns out that
840 during the post-installation run, sys.executable resolves to the
866 during the post-installation run, sys.executable resolves to the
841 name of the binary installer! I should report this as a distutils
867 name of the binary installer! I should report this as a distutils
842 bug, I think. I updated the .10 release with this tiny fix, to
868 bug, I think. I updated the .10 release with this tiny fix, to
843 avoid annoying the lists further.
869 avoid annoying the lists further.
844
870
845 2005-01-27 *** Released version 0.6.10
871 2005-01-27 *** Released version 0.6.10
846
872
847 2005-01-27 Fernando Perez <fperez@colorado.edu>
873 2005-01-27 Fernando Perez <fperez@colorado.edu>
848
874
849 * IPython/numutils.py (norm): Added 'inf' as optional name for
875 * IPython/numutils.py (norm): Added 'inf' as optional name for
850 L-infinity norm, included references to mathworld.com for vector
876 L-infinity norm, included references to mathworld.com for vector
851 norm definitions.
877 norm definitions.
852 (amin/amax): added amin/amax for array min/max. Similar to what
878 (amin/amax): added amin/amax for array min/max. Similar to what
853 pylab ships with after the recent reorganization of names.
879 pylab ships with after the recent reorganization of names.
854 (spike/spike_odd): removed deprecated spike/spike_odd functions.
880 (spike/spike_odd): removed deprecated spike/spike_odd functions.
855
881
856 * ipython.el: committed Alex's recent fixes and improvements.
882 * ipython.el: committed Alex's recent fixes and improvements.
857 Tested with python-mode from CVS, and it looks excellent. Since
883 Tested with python-mode from CVS, and it looks excellent. Since
858 python-mode hasn't released anything in a while, I'm temporarily
884 python-mode hasn't released anything in a while, I'm temporarily
859 putting a copy of today's CVS (v 4.70) of python-mode in:
885 putting a copy of today's CVS (v 4.70) of python-mode in:
860 http://ipython.scipy.org/tmp/python-mode.el
886 http://ipython.scipy.org/tmp/python-mode.el
861
887
862 * scripts/ipython_win_post_install.py (install): Win32 fix to use
888 * scripts/ipython_win_post_install.py (install): Win32 fix to use
863 sys.executable for the executable name, instead of assuming it's
889 sys.executable for the executable name, instead of assuming it's
864 called 'python.exe' (the post-installer would have produced broken
890 called 'python.exe' (the post-installer would have produced broken
865 setups on systems with a differently named python binary).
891 setups on systems with a differently named python binary).
866
892
867 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
893 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
868 references to os.linesep, to make the code more
894 references to os.linesep, to make the code more
869 platform-independent. This is also part of the win32 coloring
895 platform-independent. This is also part of the win32 coloring
870 fixes.
896 fixes.
871
897
872 * IPython/genutils.py (page_dumb): Remove attempts to chop long
898 * IPython/genutils.py (page_dumb): Remove attempts to chop long
873 lines, which actually cause coloring bugs because the length of
899 lines, which actually cause coloring bugs because the length of
874 the line is very difficult to correctly compute with embedded
900 the line is very difficult to correctly compute with embedded
875 escapes. This was the source of all the coloring problems under
901 escapes. This was the source of all the coloring problems under
876 Win32. I think that _finally_, Win32 users have a properly
902 Win32. I think that _finally_, Win32 users have a properly
877 working ipython in all respects. This would never have happened
903 working ipython in all respects. This would never have happened
878 if not for Gary Bishop and Viktor Ransmayr's great help and work.
904 if not for Gary Bishop and Viktor Ransmayr's great help and work.
879
905
880 2005-01-26 *** Released version 0.6.9
906 2005-01-26 *** Released version 0.6.9
881
907
882 2005-01-25 Fernando Perez <fperez@colorado.edu>
908 2005-01-25 Fernando Perez <fperez@colorado.edu>
883
909
884 * setup.py: finally, we have a true Windows installer, thanks to
910 * setup.py: finally, we have a true Windows installer, thanks to
885 the excellent work of Viktor Ransmayr
911 the excellent work of Viktor Ransmayr
886 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
912 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
887 Windows users. The setup routine is quite a bit cleaner thanks to
913 Windows users. The setup routine is quite a bit cleaner thanks to
888 this, and the post-install script uses the proper functions to
914 this, and the post-install script uses the proper functions to
889 allow a clean de-installation using the standard Windows Control
915 allow a clean de-installation using the standard Windows Control
890 Panel.
916 Panel.
891
917
892 * IPython/genutils.py (get_home_dir): changed to use the $HOME
918 * IPython/genutils.py (get_home_dir): changed to use the $HOME
893 environment variable under all OSes (including win32) if
919 environment variable under all OSes (including win32) if
894 available. This will give consistency to win32 users who have set
920 available. This will give consistency to win32 users who have set
895 this variable for any reason. If os.environ['HOME'] fails, the
921 this variable for any reason. If os.environ['HOME'] fails, the
896 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
922 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
897
923
898 2005-01-24 Fernando Perez <fperez@colorado.edu>
924 2005-01-24 Fernando Perez <fperez@colorado.edu>
899
925
900 * IPython/numutils.py (empty_like): add empty_like(), similar to
926 * IPython/numutils.py (empty_like): add empty_like(), similar to
901 zeros_like() but taking advantage of the new empty() Numeric routine.
927 zeros_like() but taking advantage of the new empty() Numeric routine.
902
928
903 2005-01-23 *** Released version 0.6.8
929 2005-01-23 *** Released version 0.6.8
904
930
905 2005-01-22 Fernando Perez <fperez@colorado.edu>
931 2005-01-22 Fernando Perez <fperez@colorado.edu>
906
932
907 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
933 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
908 automatic show() calls. After discussing things with JDH, it
934 automatic show() calls. After discussing things with JDH, it
909 turns out there are too many corner cases where this can go wrong.
935 turns out there are too many corner cases where this can go wrong.
910 It's best not to try to be 'too smart', and simply have ipython
936 It's best not to try to be 'too smart', and simply have ipython
911 reproduce as much as possible the default behavior of a normal
937 reproduce as much as possible the default behavior of a normal
912 python shell.
938 python shell.
913
939
914 * IPython/iplib.py (InteractiveShell.__init__): Modified the
940 * IPython/iplib.py (InteractiveShell.__init__): Modified the
915 line-splitting regexp and _prefilter() to avoid calling getattr()
941 line-splitting regexp and _prefilter() to avoid calling getattr()
916 on assignments. This closes
942 on assignments. This closes
917 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
943 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
918 readline uses getattr(), so a simple <TAB> keypress is still
944 readline uses getattr(), so a simple <TAB> keypress is still
919 enough to trigger getattr() calls on an object.
945 enough to trigger getattr() calls on an object.
920
946
921 2005-01-21 Fernando Perez <fperez@colorado.edu>
947 2005-01-21 Fernando Perez <fperez@colorado.edu>
922
948
923 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
949 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
924 docstring under pylab so it doesn't mask the original.
950 docstring under pylab so it doesn't mask the original.
925
951
926 2005-01-21 *** Released version 0.6.7
952 2005-01-21 *** Released version 0.6.7
927
953
928 2005-01-21 Fernando Perez <fperez@colorado.edu>
954 2005-01-21 Fernando Perez <fperez@colorado.edu>
929
955
930 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
956 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
931 signal handling for win32 users in multithreaded mode.
957 signal handling for win32 users in multithreaded mode.
932
958
933 2005-01-17 Fernando Perez <fperez@colorado.edu>
959 2005-01-17 Fernando Perez <fperez@colorado.edu>
934
960
935 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
961 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
936 instances with no __init__. After a crash report by Norbert Nemec
962 instances with no __init__. After a crash report by Norbert Nemec
937 <Norbert-AT-nemec-online.de>.
963 <Norbert-AT-nemec-online.de>.
938
964
939 2005-01-14 Fernando Perez <fperez@colorado.edu>
965 2005-01-14 Fernando Perez <fperez@colorado.edu>
940
966
941 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
967 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
942 names for verbose exceptions, when multiple dotted names and the
968 names for verbose exceptions, when multiple dotted names and the
943 'parent' object were present on the same line.
969 'parent' object were present on the same line.
944
970
945 2005-01-11 Fernando Perez <fperez@colorado.edu>
971 2005-01-11 Fernando Perez <fperez@colorado.edu>
946
972
947 * IPython/genutils.py (flag_calls): new utility to trap and flag
973 * IPython/genutils.py (flag_calls): new utility to trap and flag
948 calls in functions. I need it to clean up matplotlib support.
974 calls in functions. I need it to clean up matplotlib support.
949 Also removed some deprecated code in genutils.
975 Also removed some deprecated code in genutils.
950
976
951 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
977 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
952 that matplotlib scripts called with %run, which don't call show()
978 that matplotlib scripts called with %run, which don't call show()
953 themselves, still have their plotting windows open.
979 themselves, still have their plotting windows open.
954
980
955 2005-01-05 Fernando Perez <fperez@colorado.edu>
981 2005-01-05 Fernando Perez <fperez@colorado.edu>
956
982
957 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
983 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
958 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
984 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
959
985
960 2004-12-19 Fernando Perez <fperez@colorado.edu>
986 2004-12-19 Fernando Perez <fperez@colorado.edu>
961
987
962 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
988 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
963 parent_runcode, which was an eyesore. The same result can be
989 parent_runcode, which was an eyesore. The same result can be
964 obtained with Python's regular superclass mechanisms.
990 obtained with Python's regular superclass mechanisms.
965
991
966 2004-12-17 Fernando Perez <fperez@colorado.edu>
992 2004-12-17 Fernando Perez <fperez@colorado.edu>
967
993
968 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
994 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
969 reported by Prabhu.
995 reported by Prabhu.
970 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
996 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
971 sys.stderr) instead of explicitly calling sys.stderr. This helps
997 sys.stderr) instead of explicitly calling sys.stderr. This helps
972 maintain our I/O abstractions clean, for future GUI embeddings.
998 maintain our I/O abstractions clean, for future GUI embeddings.
973
999
974 * IPython/genutils.py (info): added new utility for sys.stderr
1000 * IPython/genutils.py (info): added new utility for sys.stderr
975 unified info message handling (thin wrapper around warn()).
1001 unified info message handling (thin wrapper around warn()).
976
1002
977 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1003 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
978 composite (dotted) names on verbose exceptions.
1004 composite (dotted) names on verbose exceptions.
979 (VerboseTB.nullrepr): harden against another kind of errors which
1005 (VerboseTB.nullrepr): harden against another kind of errors which
980 Python's inspect module can trigger, and which were crashing
1006 Python's inspect module can trigger, and which were crashing
981 IPython. Thanks to a report by Marco Lombardi
1007 IPython. Thanks to a report by Marco Lombardi
982 <mlombard-AT-ma010192.hq.eso.org>.
1008 <mlombard-AT-ma010192.hq.eso.org>.
983
1009
984 2004-12-13 *** Released version 0.6.6
1010 2004-12-13 *** Released version 0.6.6
985
1011
986 2004-12-12 Fernando Perez <fperez@colorado.edu>
1012 2004-12-12 Fernando Perez <fperez@colorado.edu>
987
1013
988 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1014 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
989 generated by pygtk upon initialization if it was built without
1015 generated by pygtk upon initialization if it was built without
990 threads (for matplotlib users). After a crash reported by
1016 threads (for matplotlib users). After a crash reported by
991 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1017 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
992
1018
993 * IPython/ipmaker.py (make_IPython): fix small bug in the
1019 * IPython/ipmaker.py (make_IPython): fix small bug in the
994 import_some parameter for multiple imports.
1020 import_some parameter for multiple imports.
995
1021
996 * IPython/iplib.py (ipmagic): simplified the interface of
1022 * IPython/iplib.py (ipmagic): simplified the interface of
997 ipmagic() to take a single string argument, just as it would be
1023 ipmagic() to take a single string argument, just as it would be
998 typed at the IPython cmd line.
1024 typed at the IPython cmd line.
999 (ipalias): Added new ipalias() with an interface identical to
1025 (ipalias): Added new ipalias() with an interface identical to
1000 ipmagic(). This completes exposing a pure python interface to the
1026 ipmagic(). This completes exposing a pure python interface to the
1001 alias and magic system, which can be used in loops or more complex
1027 alias and magic system, which can be used in loops or more complex
1002 code where IPython's automatic line mangling is not active.
1028 code where IPython's automatic line mangling is not active.
1003
1029
1004 * IPython/genutils.py (timing): changed interface of timing to
1030 * IPython/genutils.py (timing): changed interface of timing to
1005 simply run code once, which is the most common case. timings()
1031 simply run code once, which is the most common case. timings()
1006 remains unchanged, for the cases where you want multiple runs.
1032 remains unchanged, for the cases where you want multiple runs.
1007
1033
1008 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1034 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1009 bug where Python2.2 crashes with exec'ing code which does not end
1035 bug where Python2.2 crashes with exec'ing code which does not end
1010 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1036 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1011 before.
1037 before.
1012
1038
1013 2004-12-10 Fernando Perez <fperez@colorado.edu>
1039 2004-12-10 Fernando Perez <fperez@colorado.edu>
1014
1040
1015 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1041 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1016 -t to -T, to accomodate the new -t flag in %run (the %run and
1042 -t to -T, to accomodate the new -t flag in %run (the %run and
1017 %prun options are kind of intermixed, and it's not easy to change
1043 %prun options are kind of intermixed, and it's not easy to change
1018 this with the limitations of python's getopt).
1044 this with the limitations of python's getopt).
1019
1045
1020 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1046 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1021 the execution of scripts. It's not as fine-tuned as timeit.py,
1047 the execution of scripts. It's not as fine-tuned as timeit.py,
1022 but it works from inside ipython (and under 2.2, which lacks
1048 but it works from inside ipython (and under 2.2, which lacks
1023 timeit.py). Optionally a number of runs > 1 can be given for
1049 timeit.py). Optionally a number of runs > 1 can be given for
1024 timing very short-running code.
1050 timing very short-running code.
1025
1051
1026 * IPython/genutils.py (uniq_stable): new routine which returns a
1052 * IPython/genutils.py (uniq_stable): new routine which returns a
1027 list of unique elements in any iterable, but in stable order of
1053 list of unique elements in any iterable, but in stable order of
1028 appearance. I needed this for the ultraTB fixes, and it's a handy
1054 appearance. I needed this for the ultraTB fixes, and it's a handy
1029 utility.
1055 utility.
1030
1056
1031 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1057 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1032 dotted names in Verbose exceptions. This had been broken since
1058 dotted names in Verbose exceptions. This had been broken since
1033 the very start, now x.y will properly be printed in a Verbose
1059 the very start, now x.y will properly be printed in a Verbose
1034 traceback, instead of x being shown and y appearing always as an
1060 traceback, instead of x being shown and y appearing always as an
1035 'undefined global'. Getting this to work was a bit tricky,
1061 'undefined global'. Getting this to work was a bit tricky,
1036 because by default python tokenizers are stateless. Saved by
1062 because by default python tokenizers are stateless. Saved by
1037 python's ability to easily add a bit of state to an arbitrary
1063 python's ability to easily add a bit of state to an arbitrary
1038 function (without needing to build a full-blown callable object).
1064 function (without needing to build a full-blown callable object).
1039
1065
1040 Also big cleanup of this code, which had horrendous runtime
1066 Also big cleanup of this code, which had horrendous runtime
1041 lookups of zillions of attributes for colorization. Moved all
1067 lookups of zillions of attributes for colorization. Moved all
1042 this code into a few templates, which make it cleaner and quicker.
1068 this code into a few templates, which make it cleaner and quicker.
1043
1069
1044 Printout quality was also improved for Verbose exceptions: one
1070 Printout quality was also improved for Verbose exceptions: one
1045 variable per line, and memory addresses are printed (this can be
1071 variable per line, and memory addresses are printed (this can be
1046 quite handy in nasty debugging situations, which is what Verbose
1072 quite handy in nasty debugging situations, which is what Verbose
1047 is for).
1073 is for).
1048
1074
1049 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1075 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1050 the command line as scripts to be loaded by embedded instances.
1076 the command line as scripts to be loaded by embedded instances.
1051 Doing so has the potential for an infinite recursion if there are
1077 Doing so has the potential for an infinite recursion if there are
1052 exceptions thrown in the process. This fixes a strange crash
1078 exceptions thrown in the process. This fixes a strange crash
1053 reported by Philippe MULLER <muller-AT-irit.fr>.
1079 reported by Philippe MULLER <muller-AT-irit.fr>.
1054
1080
1055 2004-12-09 Fernando Perez <fperez@colorado.edu>
1081 2004-12-09 Fernando Perez <fperez@colorado.edu>
1056
1082
1057 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1083 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1058 to reflect new names in matplotlib, which now expose the
1084 to reflect new names in matplotlib, which now expose the
1059 matlab-compatible interface via a pylab module instead of the
1085 matlab-compatible interface via a pylab module instead of the
1060 'matlab' name. The new code is backwards compatible, so users of
1086 'matlab' name. The new code is backwards compatible, so users of
1061 all matplotlib versions are OK. Patch by J. Hunter.
1087 all matplotlib versions are OK. Patch by J. Hunter.
1062
1088
1063 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1089 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1064 of __init__ docstrings for instances (class docstrings are already
1090 of __init__ docstrings for instances (class docstrings are already
1065 automatically printed). Instances with customized docstrings
1091 automatically printed). Instances with customized docstrings
1066 (indep. of the class) are also recognized and all 3 separate
1092 (indep. of the class) are also recognized and all 3 separate
1067 docstrings are printed (instance, class, constructor). After some
1093 docstrings are printed (instance, class, constructor). After some
1068 comments/suggestions by J. Hunter.
1094 comments/suggestions by J. Hunter.
1069
1095
1070 2004-12-05 Fernando Perez <fperez@colorado.edu>
1096 2004-12-05 Fernando Perez <fperez@colorado.edu>
1071
1097
1072 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1098 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1073 warnings when tab-completion fails and triggers an exception.
1099 warnings when tab-completion fails and triggers an exception.
1074
1100
1075 2004-12-03 Fernando Perez <fperez@colorado.edu>
1101 2004-12-03 Fernando Perez <fperez@colorado.edu>
1076
1102
1077 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1103 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1078 be triggered when using 'run -p'. An incorrect option flag was
1104 be triggered when using 'run -p'. An incorrect option flag was
1079 being set ('d' instead of 'D').
1105 being set ('d' instead of 'D').
1080 (manpage): fix missing escaped \- sign.
1106 (manpage): fix missing escaped \- sign.
1081
1107
1082 2004-11-30 *** Released version 0.6.5
1108 2004-11-30 *** Released version 0.6.5
1083
1109
1084 2004-11-30 Fernando Perez <fperez@colorado.edu>
1110 2004-11-30 Fernando Perez <fperez@colorado.edu>
1085
1111
1086 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1112 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1087 setting with -d option.
1113 setting with -d option.
1088
1114
1089 * setup.py (docfiles): Fix problem where the doc glob I was using
1115 * setup.py (docfiles): Fix problem where the doc glob I was using
1090 was COMPLETELY BROKEN. It was giving the right files by pure
1116 was COMPLETELY BROKEN. It was giving the right files by pure
1091 accident, but failed once I tried to include ipython.el. Note:
1117 accident, but failed once I tried to include ipython.el. Note:
1092 glob() does NOT allow you to do exclusion on multiple endings!
1118 glob() does NOT allow you to do exclusion on multiple endings!
1093
1119
1094 2004-11-29 Fernando Perez <fperez@colorado.edu>
1120 2004-11-29 Fernando Perez <fperez@colorado.edu>
1095
1121
1096 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1122 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1097 the manpage as the source. Better formatting & consistency.
1123 the manpage as the source. Better formatting & consistency.
1098
1124
1099 * IPython/Magic.py (magic_run): Added new -d option, to run
1125 * IPython/Magic.py (magic_run): Added new -d option, to run
1100 scripts under the control of the python pdb debugger. Note that
1126 scripts under the control of the python pdb debugger. Note that
1101 this required changing the %prun option -d to -D, to avoid a clash
1127 this required changing the %prun option -d to -D, to avoid a clash
1102 (since %run must pass options to %prun, and getopt is too dumb to
1128 (since %run must pass options to %prun, and getopt is too dumb to
1103 handle options with string values with embedded spaces). Thanks
1129 handle options with string values with embedded spaces). Thanks
1104 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1130 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1105 (magic_who_ls): added type matching to %who and %whos, so that one
1131 (magic_who_ls): added type matching to %who and %whos, so that one
1106 can filter their output to only include variables of certain
1132 can filter their output to only include variables of certain
1107 types. Another suggestion by Matthew.
1133 types. Another suggestion by Matthew.
1108 (magic_whos): Added memory summaries in kb and Mb for arrays.
1134 (magic_whos): Added memory summaries in kb and Mb for arrays.
1109 (magic_who): Improve formatting (break lines every 9 vars).
1135 (magic_who): Improve formatting (break lines every 9 vars).
1110
1136
1111 2004-11-28 Fernando Perez <fperez@colorado.edu>
1137 2004-11-28 Fernando Perez <fperez@colorado.edu>
1112
1138
1113 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1139 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1114 cache when empty lines were present.
1140 cache when empty lines were present.
1115
1141
1116 2004-11-24 Fernando Perez <fperez@colorado.edu>
1142 2004-11-24 Fernando Perez <fperez@colorado.edu>
1117
1143
1118 * IPython/usage.py (__doc__): document the re-activated threading
1144 * IPython/usage.py (__doc__): document the re-activated threading
1119 options for WX and GTK.
1145 options for WX and GTK.
1120
1146
1121 2004-11-23 Fernando Perez <fperez@colorado.edu>
1147 2004-11-23 Fernando Perez <fperez@colorado.edu>
1122
1148
1123 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1149 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1124 the -wthread and -gthread options, along with a new -tk one to try
1150 the -wthread and -gthread options, along with a new -tk one to try
1125 and coordinate Tk threading with wx/gtk. The tk support is very
1151 and coordinate Tk threading with wx/gtk. The tk support is very
1126 platform dependent, since it seems to require Tcl and Tk to be
1152 platform dependent, since it seems to require Tcl and Tk to be
1127 built with threads (Fedora1/2 appears NOT to have it, but in
1153 built with threads (Fedora1/2 appears NOT to have it, but in
1128 Prabhu's Debian boxes it works OK). But even with some Tk
1154 Prabhu's Debian boxes it works OK). But even with some Tk
1129 limitations, this is a great improvement.
1155 limitations, this is a great improvement.
1130
1156
1131 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1157 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1132 info in user prompts. Patch by Prabhu.
1158 info in user prompts. Patch by Prabhu.
1133
1159
1134 2004-11-18 Fernando Perez <fperez@colorado.edu>
1160 2004-11-18 Fernando Perez <fperez@colorado.edu>
1135
1161
1136 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1162 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1137 EOFErrors and bail, to avoid infinite loops if a non-terminating
1163 EOFErrors and bail, to avoid infinite loops if a non-terminating
1138 file is fed into ipython. Patch submitted in issue 19 by user,
1164 file is fed into ipython. Patch submitted in issue 19 by user,
1139 many thanks.
1165 many thanks.
1140
1166
1141 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1167 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1142 autoquote/parens in continuation prompts, which can cause lots of
1168 autoquote/parens in continuation prompts, which can cause lots of
1143 problems. Closes roundup issue 20.
1169 problems. Closes roundup issue 20.
1144
1170
1145 2004-11-17 Fernando Perez <fperez@colorado.edu>
1171 2004-11-17 Fernando Perez <fperez@colorado.edu>
1146
1172
1147 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1173 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1148 reported as debian bug #280505. I'm not sure my local changelog
1174 reported as debian bug #280505. I'm not sure my local changelog
1149 entry has the proper debian format (Jack?).
1175 entry has the proper debian format (Jack?).
1150
1176
1151 2004-11-08 *** Released version 0.6.4
1177 2004-11-08 *** Released version 0.6.4
1152
1178
1153 2004-11-08 Fernando Perez <fperez@colorado.edu>
1179 2004-11-08 Fernando Perez <fperez@colorado.edu>
1154
1180
1155 * IPython/iplib.py (init_readline): Fix exit message for Windows
1181 * IPython/iplib.py (init_readline): Fix exit message for Windows
1156 when readline is active. Thanks to a report by Eric Jones
1182 when readline is active. Thanks to a report by Eric Jones
1157 <eric-AT-enthought.com>.
1183 <eric-AT-enthought.com>.
1158
1184
1159 2004-11-07 Fernando Perez <fperez@colorado.edu>
1185 2004-11-07 Fernando Perez <fperez@colorado.edu>
1160
1186
1161 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1187 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1162 sometimes seen by win2k/cygwin users.
1188 sometimes seen by win2k/cygwin users.
1163
1189
1164 2004-11-06 Fernando Perez <fperez@colorado.edu>
1190 2004-11-06 Fernando Perez <fperez@colorado.edu>
1165
1191
1166 * IPython/iplib.py (interact): Change the handling of %Exit from
1192 * IPython/iplib.py (interact): Change the handling of %Exit from
1167 trying to propagate a SystemExit to an internal ipython flag.
1193 trying to propagate a SystemExit to an internal ipython flag.
1168 This is less elegant than using Python's exception mechanism, but
1194 This is less elegant than using Python's exception mechanism, but
1169 I can't get that to work reliably with threads, so under -pylab
1195 I can't get that to work reliably with threads, so under -pylab
1170 %Exit was hanging IPython. Cross-thread exception handling is
1196 %Exit was hanging IPython. Cross-thread exception handling is
1171 really a bitch. Thaks to a bug report by Stephen Walton
1197 really a bitch. Thaks to a bug report by Stephen Walton
1172 <stephen.walton-AT-csun.edu>.
1198 <stephen.walton-AT-csun.edu>.
1173
1199
1174 2004-11-04 Fernando Perez <fperez@colorado.edu>
1200 2004-11-04 Fernando Perez <fperez@colorado.edu>
1175
1201
1176 * IPython/iplib.py (raw_input_original): store a pointer to the
1202 * IPython/iplib.py (raw_input_original): store a pointer to the
1177 true raw_input to harden against code which can modify it
1203 true raw_input to harden against code which can modify it
1178 (wx.py.PyShell does this and would otherwise crash ipython).
1204 (wx.py.PyShell does this and would otherwise crash ipython).
1179 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1205 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1180
1206
1181 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1207 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1182 Ctrl-C problem, which does not mess up the input line.
1208 Ctrl-C problem, which does not mess up the input line.
1183
1209
1184 2004-11-03 Fernando Perez <fperez@colorado.edu>
1210 2004-11-03 Fernando Perez <fperez@colorado.edu>
1185
1211
1186 * IPython/Release.py: Changed licensing to BSD, in all files.
1212 * IPython/Release.py: Changed licensing to BSD, in all files.
1187 (name): lowercase name for tarball/RPM release.
1213 (name): lowercase name for tarball/RPM release.
1188
1214
1189 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1215 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1190 use throughout ipython.
1216 use throughout ipython.
1191
1217
1192 * IPython/Magic.py (Magic._ofind): Switch to using the new
1218 * IPython/Magic.py (Magic._ofind): Switch to using the new
1193 OInspect.getdoc() function.
1219 OInspect.getdoc() function.
1194
1220
1195 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1221 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1196 of the line currently being canceled via Ctrl-C. It's extremely
1222 of the line currently being canceled via Ctrl-C. It's extremely
1197 ugly, but I don't know how to do it better (the problem is one of
1223 ugly, but I don't know how to do it better (the problem is one of
1198 handling cross-thread exceptions).
1224 handling cross-thread exceptions).
1199
1225
1200 2004-10-28 Fernando Perez <fperez@colorado.edu>
1226 2004-10-28 Fernando Perez <fperez@colorado.edu>
1201
1227
1202 * IPython/Shell.py (signal_handler): add signal handlers to trap
1228 * IPython/Shell.py (signal_handler): add signal handlers to trap
1203 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1229 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1204 report by Francesc Alted.
1230 report by Francesc Alted.
1205
1231
1206 2004-10-21 Fernando Perez <fperez@colorado.edu>
1232 2004-10-21 Fernando Perez <fperez@colorado.edu>
1207
1233
1208 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1234 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1209 to % for pysh syntax extensions.
1235 to % for pysh syntax extensions.
1210
1236
1211 2004-10-09 Fernando Perez <fperez@colorado.edu>
1237 2004-10-09 Fernando Perez <fperez@colorado.edu>
1212
1238
1213 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1239 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1214 arrays to print a more useful summary, without calling str(arr).
1240 arrays to print a more useful summary, without calling str(arr).
1215 This avoids the problem of extremely lengthy computations which
1241 This avoids the problem of extremely lengthy computations which
1216 occur if arr is large, and appear to the user as a system lockup
1242 occur if arr is large, and appear to the user as a system lockup
1217 with 100% cpu activity. After a suggestion by Kristian Sandberg
1243 with 100% cpu activity. After a suggestion by Kristian Sandberg
1218 <Kristian.Sandberg@colorado.edu>.
1244 <Kristian.Sandberg@colorado.edu>.
1219 (Magic.__init__): fix bug in global magic escapes not being
1245 (Magic.__init__): fix bug in global magic escapes not being
1220 correctly set.
1246 correctly set.
1221
1247
1222 2004-10-08 Fernando Perez <fperez@colorado.edu>
1248 2004-10-08 Fernando Perez <fperez@colorado.edu>
1223
1249
1224 * IPython/Magic.py (__license__): change to absolute imports of
1250 * IPython/Magic.py (__license__): change to absolute imports of
1225 ipython's own internal packages, to start adapting to the absolute
1251 ipython's own internal packages, to start adapting to the absolute
1226 import requirement of PEP-328.
1252 import requirement of PEP-328.
1227
1253
1228 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1254 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1229 files, and standardize author/license marks through the Release
1255 files, and standardize author/license marks through the Release
1230 module instead of having per/file stuff (except for files with
1256 module instead of having per/file stuff (except for files with
1231 particular licenses, like the MIT/PSF-licensed codes).
1257 particular licenses, like the MIT/PSF-licensed codes).
1232
1258
1233 * IPython/Debugger.py: remove dead code for python 2.1
1259 * IPython/Debugger.py: remove dead code for python 2.1
1234
1260
1235 2004-10-04 Fernando Perez <fperez@colorado.edu>
1261 2004-10-04 Fernando Perez <fperez@colorado.edu>
1236
1262
1237 * IPython/iplib.py (ipmagic): New function for accessing magics
1263 * IPython/iplib.py (ipmagic): New function for accessing magics
1238 via a normal python function call.
1264 via a normal python function call.
1239
1265
1240 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1266 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1241 from '@' to '%', to accomodate the new @decorator syntax of python
1267 from '@' to '%', to accomodate the new @decorator syntax of python
1242 2.4.
1268 2.4.
1243
1269
1244 2004-09-29 Fernando Perez <fperez@colorado.edu>
1270 2004-09-29 Fernando Perez <fperez@colorado.edu>
1245
1271
1246 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1272 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1247 matplotlib.use to prevent running scripts which try to switch
1273 matplotlib.use to prevent running scripts which try to switch
1248 interactive backends from within ipython. This will just crash
1274 interactive backends from within ipython. This will just crash
1249 the python interpreter, so we can't allow it (but a detailed error
1275 the python interpreter, so we can't allow it (but a detailed error
1250 is given to the user).
1276 is given to the user).
1251
1277
1252 2004-09-28 Fernando Perez <fperez@colorado.edu>
1278 2004-09-28 Fernando Perez <fperez@colorado.edu>
1253
1279
1254 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1280 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1255 matplotlib-related fixes so that using @run with non-matplotlib
1281 matplotlib-related fixes so that using @run with non-matplotlib
1256 scripts doesn't pop up spurious plot windows. This requires
1282 scripts doesn't pop up spurious plot windows. This requires
1257 matplotlib >= 0.63, where I had to make some changes as well.
1283 matplotlib >= 0.63, where I had to make some changes as well.
1258
1284
1259 * IPython/ipmaker.py (make_IPython): update version requirement to
1285 * IPython/ipmaker.py (make_IPython): update version requirement to
1260 python 2.2.
1286 python 2.2.
1261
1287
1262 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1288 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1263 banner arg for embedded customization.
1289 banner arg for embedded customization.
1264
1290
1265 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1291 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1266 explicit uses of __IP as the IPython's instance name. Now things
1292 explicit uses of __IP as the IPython's instance name. Now things
1267 are properly handled via the shell.name value. The actual code
1293 are properly handled via the shell.name value. The actual code
1268 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1294 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1269 is much better than before. I'll clean things completely when the
1295 is much better than before. I'll clean things completely when the
1270 magic stuff gets a real overhaul.
1296 magic stuff gets a real overhaul.
1271
1297
1272 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1298 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1273 minor changes to debian dir.
1299 minor changes to debian dir.
1274
1300
1275 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1301 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1276 pointer to the shell itself in the interactive namespace even when
1302 pointer to the shell itself in the interactive namespace even when
1277 a user-supplied dict is provided. This is needed for embedding
1303 a user-supplied dict is provided. This is needed for embedding
1278 purposes (found by tests with Michel Sanner).
1304 purposes (found by tests with Michel Sanner).
1279
1305
1280 2004-09-27 Fernando Perez <fperez@colorado.edu>
1306 2004-09-27 Fernando Perez <fperez@colorado.edu>
1281
1307
1282 * IPython/UserConfig/ipythonrc: remove []{} from
1308 * IPython/UserConfig/ipythonrc: remove []{} from
1283 readline_remove_delims, so that things like [modname.<TAB> do
1309 readline_remove_delims, so that things like [modname.<TAB> do
1284 proper completion. This disables [].TAB, but that's a less common
1310 proper completion. This disables [].TAB, but that's a less common
1285 case than module names in list comprehensions, for example.
1311 case than module names in list comprehensions, for example.
1286 Thanks to a report by Andrea Riciputi.
1312 Thanks to a report by Andrea Riciputi.
1287
1313
1288 2004-09-09 Fernando Perez <fperez@colorado.edu>
1314 2004-09-09 Fernando Perez <fperez@colorado.edu>
1289
1315
1290 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1316 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1291 blocking problems in win32 and osx. Fix by John.
1317 blocking problems in win32 and osx. Fix by John.
1292
1318
1293 2004-09-08 Fernando Perez <fperez@colorado.edu>
1319 2004-09-08 Fernando Perez <fperez@colorado.edu>
1294
1320
1295 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1321 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1296 for Win32 and OSX. Fix by John Hunter.
1322 for Win32 and OSX. Fix by John Hunter.
1297
1323
1298 2004-08-30 *** Released version 0.6.3
1324 2004-08-30 *** Released version 0.6.3
1299
1325
1300 2004-08-30 Fernando Perez <fperez@colorado.edu>
1326 2004-08-30 Fernando Perez <fperez@colorado.edu>
1301
1327
1302 * setup.py (isfile): Add manpages to list of dependent files to be
1328 * setup.py (isfile): Add manpages to list of dependent files to be
1303 updated.
1329 updated.
1304
1330
1305 2004-08-27 Fernando Perez <fperez@colorado.edu>
1331 2004-08-27 Fernando Perez <fperez@colorado.edu>
1306
1332
1307 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1333 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1308 for now. They don't really work with standalone WX/GTK code
1334 for now. They don't really work with standalone WX/GTK code
1309 (though matplotlib IS working fine with both of those backends).
1335 (though matplotlib IS working fine with both of those backends).
1310 This will neeed much more testing. I disabled most things with
1336 This will neeed much more testing. I disabled most things with
1311 comments, so turning it back on later should be pretty easy.
1337 comments, so turning it back on later should be pretty easy.
1312
1338
1313 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1339 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1314 autocalling of expressions like r'foo', by modifying the line
1340 autocalling of expressions like r'foo', by modifying the line
1315 split regexp. Closes
1341 split regexp. Closes
1316 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1342 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1317 Riley <ipythonbugs-AT-sabi.net>.
1343 Riley <ipythonbugs-AT-sabi.net>.
1318 (InteractiveShell.mainloop): honor --nobanner with banner
1344 (InteractiveShell.mainloop): honor --nobanner with banner
1319 extensions.
1345 extensions.
1320
1346
1321 * IPython/Shell.py: Significant refactoring of all classes, so
1347 * IPython/Shell.py: Significant refactoring of all classes, so
1322 that we can really support ALL matplotlib backends and threading
1348 that we can really support ALL matplotlib backends and threading
1323 models (John spotted a bug with Tk which required this). Now we
1349 models (John spotted a bug with Tk which required this). Now we
1324 should support single-threaded, WX-threads and GTK-threads, both
1350 should support single-threaded, WX-threads and GTK-threads, both
1325 for generic code and for matplotlib.
1351 for generic code and for matplotlib.
1326
1352
1327 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1353 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1328 -pylab, to simplify things for users. Will also remove the pylab
1354 -pylab, to simplify things for users. Will also remove the pylab
1329 profile, since now all of matplotlib configuration is directly
1355 profile, since now all of matplotlib configuration is directly
1330 handled here. This also reduces startup time.
1356 handled here. This also reduces startup time.
1331
1357
1332 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1358 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1333 shell wasn't being correctly called. Also in IPShellWX.
1359 shell wasn't being correctly called. Also in IPShellWX.
1334
1360
1335 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1361 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1336 fine-tune banner.
1362 fine-tune banner.
1337
1363
1338 * IPython/numutils.py (spike): Deprecate these spike functions,
1364 * IPython/numutils.py (spike): Deprecate these spike functions,
1339 delete (long deprecated) gnuplot_exec handler.
1365 delete (long deprecated) gnuplot_exec handler.
1340
1366
1341 2004-08-26 Fernando Perez <fperez@colorado.edu>
1367 2004-08-26 Fernando Perez <fperez@colorado.edu>
1342
1368
1343 * ipython.1: Update for threading options, plus some others which
1369 * ipython.1: Update for threading options, plus some others which
1344 were missing.
1370 were missing.
1345
1371
1346 * IPython/ipmaker.py (__call__): Added -wthread option for
1372 * IPython/ipmaker.py (__call__): Added -wthread option for
1347 wxpython thread handling. Make sure threading options are only
1373 wxpython thread handling. Make sure threading options are only
1348 valid at the command line.
1374 valid at the command line.
1349
1375
1350 * scripts/ipython: moved shell selection into a factory function
1376 * scripts/ipython: moved shell selection into a factory function
1351 in Shell.py, to keep the starter script to a minimum.
1377 in Shell.py, to keep the starter script to a minimum.
1352
1378
1353 2004-08-25 Fernando Perez <fperez@colorado.edu>
1379 2004-08-25 Fernando Perez <fperez@colorado.edu>
1354
1380
1355 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1381 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1356 John. Along with some recent changes he made to matplotlib, the
1382 John. Along with some recent changes he made to matplotlib, the
1357 next versions of both systems should work very well together.
1383 next versions of both systems should work very well together.
1358
1384
1359 2004-08-24 Fernando Perez <fperez@colorado.edu>
1385 2004-08-24 Fernando Perez <fperez@colorado.edu>
1360
1386
1361 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1387 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1362 tried to switch the profiling to using hotshot, but I'm getting
1388 tried to switch the profiling to using hotshot, but I'm getting
1363 strange errors from prof.runctx() there. I may be misreading the
1389 strange errors from prof.runctx() there. I may be misreading the
1364 docs, but it looks weird. For now the profiling code will
1390 docs, but it looks weird. For now the profiling code will
1365 continue to use the standard profiler.
1391 continue to use the standard profiler.
1366
1392
1367 2004-08-23 Fernando Perez <fperez@colorado.edu>
1393 2004-08-23 Fernando Perez <fperez@colorado.edu>
1368
1394
1369 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1395 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1370 threaded shell, by John Hunter. It's not quite ready yet, but
1396 threaded shell, by John Hunter. It's not quite ready yet, but
1371 close.
1397 close.
1372
1398
1373 2004-08-22 Fernando Perez <fperez@colorado.edu>
1399 2004-08-22 Fernando Perez <fperez@colorado.edu>
1374
1400
1375 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1401 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1376 in Magic and ultraTB.
1402 in Magic and ultraTB.
1377
1403
1378 * ipython.1: document threading options in manpage.
1404 * ipython.1: document threading options in manpage.
1379
1405
1380 * scripts/ipython: Changed name of -thread option to -gthread,
1406 * scripts/ipython: Changed name of -thread option to -gthread,
1381 since this is GTK specific. I want to leave the door open for a
1407 since this is GTK specific. I want to leave the door open for a
1382 -wthread option for WX, which will most likely be necessary. This
1408 -wthread option for WX, which will most likely be necessary. This
1383 change affects usage and ipmaker as well.
1409 change affects usage and ipmaker as well.
1384
1410
1385 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1411 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1386 handle the matplotlib shell issues. Code by John Hunter
1412 handle the matplotlib shell issues. Code by John Hunter
1387 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1413 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1388 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1414 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1389 broken (and disabled for end users) for now, but it puts the
1415 broken (and disabled for end users) for now, but it puts the
1390 infrastructure in place.
1416 infrastructure in place.
1391
1417
1392 2004-08-21 Fernando Perez <fperez@colorado.edu>
1418 2004-08-21 Fernando Perez <fperez@colorado.edu>
1393
1419
1394 * ipythonrc-pylab: Add matplotlib support.
1420 * ipythonrc-pylab: Add matplotlib support.
1395
1421
1396 * matplotlib_config.py: new files for matplotlib support, part of
1422 * matplotlib_config.py: new files for matplotlib support, part of
1397 the pylab profile.
1423 the pylab profile.
1398
1424
1399 * IPython/usage.py (__doc__): documented the threading options.
1425 * IPython/usage.py (__doc__): documented the threading options.
1400
1426
1401 2004-08-20 Fernando Perez <fperez@colorado.edu>
1427 2004-08-20 Fernando Perez <fperez@colorado.edu>
1402
1428
1403 * ipython: Modified the main calling routine to handle the -thread
1429 * ipython: Modified the main calling routine to handle the -thread
1404 and -mpthread options. This needs to be done as a top-level hack,
1430 and -mpthread options. This needs to be done as a top-level hack,
1405 because it determines which class to instantiate for IPython
1431 because it determines which class to instantiate for IPython
1406 itself.
1432 itself.
1407
1433
1408 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1434 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1409 classes to support multithreaded GTK operation without blocking,
1435 classes to support multithreaded GTK operation without blocking,
1410 and matplotlib with all backends. This is a lot of still very
1436 and matplotlib with all backends. This is a lot of still very
1411 experimental code, and threads are tricky. So it may still have a
1437 experimental code, and threads are tricky. So it may still have a
1412 few rough edges... This code owes a lot to
1438 few rough edges... This code owes a lot to
1413 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1439 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1414 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1440 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1415 to John Hunter for all the matplotlib work.
1441 to John Hunter for all the matplotlib work.
1416
1442
1417 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1443 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1418 options for gtk thread and matplotlib support.
1444 options for gtk thread and matplotlib support.
1419
1445
1420 2004-08-16 Fernando Perez <fperez@colorado.edu>
1446 2004-08-16 Fernando Perez <fperez@colorado.edu>
1421
1447
1422 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1448 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1423 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1449 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1424 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1450 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1425
1451
1426 2004-08-11 Fernando Perez <fperez@colorado.edu>
1452 2004-08-11 Fernando Perez <fperez@colorado.edu>
1427
1453
1428 * setup.py (isfile): Fix build so documentation gets updated for
1454 * setup.py (isfile): Fix build so documentation gets updated for
1429 rpms (it was only done for .tgz builds).
1455 rpms (it was only done for .tgz builds).
1430
1456
1431 2004-08-10 Fernando Perez <fperez@colorado.edu>
1457 2004-08-10 Fernando Perez <fperez@colorado.edu>
1432
1458
1433 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1459 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1434
1460
1435 * iplib.py : Silence syntax error exceptions in tab-completion.
1461 * iplib.py : Silence syntax error exceptions in tab-completion.
1436
1462
1437 2004-08-05 Fernando Perez <fperez@colorado.edu>
1463 2004-08-05 Fernando Perez <fperez@colorado.edu>
1438
1464
1439 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1465 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1440 'color off' mark for continuation prompts. This was causing long
1466 'color off' mark for continuation prompts. This was causing long
1441 continuation lines to mis-wrap.
1467 continuation lines to mis-wrap.
1442
1468
1443 2004-08-01 Fernando Perez <fperez@colorado.edu>
1469 2004-08-01 Fernando Perez <fperez@colorado.edu>
1444
1470
1445 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1471 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1446 for building ipython to be a parameter. All this is necessary
1472 for building ipython to be a parameter. All this is necessary
1447 right now to have a multithreaded version, but this insane
1473 right now to have a multithreaded version, but this insane
1448 non-design will be cleaned up soon. For now, it's a hack that
1474 non-design will be cleaned up soon. For now, it's a hack that
1449 works.
1475 works.
1450
1476
1451 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1477 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1452 args in various places. No bugs so far, but it's a dangerous
1478 args in various places. No bugs so far, but it's a dangerous
1453 practice.
1479 practice.
1454
1480
1455 2004-07-31 Fernando Perez <fperez@colorado.edu>
1481 2004-07-31 Fernando Perez <fperez@colorado.edu>
1456
1482
1457 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1483 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1458 fix completion of files with dots in their names under most
1484 fix completion of files with dots in their names under most
1459 profiles (pysh was OK because the completion order is different).
1485 profiles (pysh was OK because the completion order is different).
1460
1486
1461 2004-07-27 Fernando Perez <fperez@colorado.edu>
1487 2004-07-27 Fernando Perez <fperez@colorado.edu>
1462
1488
1463 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1489 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1464 keywords manually, b/c the one in keyword.py was removed in python
1490 keywords manually, b/c the one in keyword.py was removed in python
1465 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1491 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1466 This is NOT a bug under python 2.3 and earlier.
1492 This is NOT a bug under python 2.3 and earlier.
1467
1493
1468 2004-07-26 Fernando Perez <fperez@colorado.edu>
1494 2004-07-26 Fernando Perez <fperez@colorado.edu>
1469
1495
1470 * IPython/ultraTB.py (VerboseTB.text): Add another
1496 * IPython/ultraTB.py (VerboseTB.text): Add another
1471 linecache.checkcache() call to try to prevent inspect.py from
1497 linecache.checkcache() call to try to prevent inspect.py from
1472 crashing under python 2.3. I think this fixes
1498 crashing under python 2.3. I think this fixes
1473 http://www.scipy.net/roundup/ipython/issue17.
1499 http://www.scipy.net/roundup/ipython/issue17.
1474
1500
1475 2004-07-26 *** Released version 0.6.2
1501 2004-07-26 *** Released version 0.6.2
1476
1502
1477 2004-07-26 Fernando Perez <fperez@colorado.edu>
1503 2004-07-26 Fernando Perez <fperez@colorado.edu>
1478
1504
1479 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1505 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1480 fail for any number.
1506 fail for any number.
1481 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1507 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1482 empty bookmarks.
1508 empty bookmarks.
1483
1509
1484 2004-07-26 *** Released version 0.6.1
1510 2004-07-26 *** Released version 0.6.1
1485
1511
1486 2004-07-26 Fernando Perez <fperez@colorado.edu>
1512 2004-07-26 Fernando Perez <fperez@colorado.edu>
1487
1513
1488 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1514 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1489
1515
1490 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1516 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1491 escaping '()[]{}' in filenames.
1517 escaping '()[]{}' in filenames.
1492
1518
1493 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1519 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1494 Python 2.2 users who lack a proper shlex.split.
1520 Python 2.2 users who lack a proper shlex.split.
1495
1521
1496 2004-07-19 Fernando Perez <fperez@colorado.edu>
1522 2004-07-19 Fernando Perez <fperez@colorado.edu>
1497
1523
1498 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1524 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1499 for reading readline's init file. I follow the normal chain:
1525 for reading readline's init file. I follow the normal chain:
1500 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1526 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1501 report by Mike Heeter. This closes
1527 report by Mike Heeter. This closes
1502 http://www.scipy.net/roundup/ipython/issue16.
1528 http://www.scipy.net/roundup/ipython/issue16.
1503
1529
1504 2004-07-18 Fernando Perez <fperez@colorado.edu>
1530 2004-07-18 Fernando Perez <fperez@colorado.edu>
1505
1531
1506 * IPython/iplib.py (__init__): Add better handling of '\' under
1532 * IPython/iplib.py (__init__): Add better handling of '\' under
1507 Win32 for filenames. After a patch by Ville.
1533 Win32 for filenames. After a patch by Ville.
1508
1534
1509 2004-07-17 Fernando Perez <fperez@colorado.edu>
1535 2004-07-17 Fernando Perez <fperez@colorado.edu>
1510
1536
1511 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1537 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1512 autocalling would be triggered for 'foo is bar' if foo is
1538 autocalling would be triggered for 'foo is bar' if foo is
1513 callable. I also cleaned up the autocall detection code to use a
1539 callable. I also cleaned up the autocall detection code to use a
1514 regexp, which is faster. Bug reported by Alexander Schmolck.
1540 regexp, which is faster. Bug reported by Alexander Schmolck.
1515
1541
1516 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1542 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1517 '?' in them would confuse the help system. Reported by Alex
1543 '?' in them would confuse the help system. Reported by Alex
1518 Schmolck.
1544 Schmolck.
1519
1545
1520 2004-07-16 Fernando Perez <fperez@colorado.edu>
1546 2004-07-16 Fernando Perez <fperez@colorado.edu>
1521
1547
1522 * IPython/GnuplotInteractive.py (__all__): added plot2.
1548 * IPython/GnuplotInteractive.py (__all__): added plot2.
1523
1549
1524 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1550 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1525 plotting dictionaries, lists or tuples of 1d arrays.
1551 plotting dictionaries, lists or tuples of 1d arrays.
1526
1552
1527 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1553 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1528 optimizations.
1554 optimizations.
1529
1555
1530 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1556 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1531 the information which was there from Janko's original IPP code:
1557 the information which was there from Janko's original IPP code:
1532
1558
1533 03.05.99 20:53 porto.ifm.uni-kiel.de
1559 03.05.99 20:53 porto.ifm.uni-kiel.de
1534 --Started changelog.
1560 --Started changelog.
1535 --make clear do what it say it does
1561 --make clear do what it say it does
1536 --added pretty output of lines from inputcache
1562 --added pretty output of lines from inputcache
1537 --Made Logger a mixin class, simplifies handling of switches
1563 --Made Logger a mixin class, simplifies handling of switches
1538 --Added own completer class. .string<TAB> expands to last history
1564 --Added own completer class. .string<TAB> expands to last history
1539 line which starts with string. The new expansion is also present
1565 line which starts with string. The new expansion is also present
1540 with Ctrl-r from the readline library. But this shows, who this
1566 with Ctrl-r from the readline library. But this shows, who this
1541 can be done for other cases.
1567 can be done for other cases.
1542 --Added convention that all shell functions should accept a
1568 --Added convention that all shell functions should accept a
1543 parameter_string This opens the door for different behaviour for
1569 parameter_string This opens the door for different behaviour for
1544 each function. @cd is a good example of this.
1570 each function. @cd is a good example of this.
1545
1571
1546 04.05.99 12:12 porto.ifm.uni-kiel.de
1572 04.05.99 12:12 porto.ifm.uni-kiel.de
1547 --added logfile rotation
1573 --added logfile rotation
1548 --added new mainloop method which freezes first the namespace
1574 --added new mainloop method which freezes first the namespace
1549
1575
1550 07.05.99 21:24 porto.ifm.uni-kiel.de
1576 07.05.99 21:24 porto.ifm.uni-kiel.de
1551 --added the docreader classes. Now there is a help system.
1577 --added the docreader classes. Now there is a help system.
1552 -This is only a first try. Currently it's not easy to put new
1578 -This is only a first try. Currently it's not easy to put new
1553 stuff in the indices. But this is the way to go. Info would be
1579 stuff in the indices. But this is the way to go. Info would be
1554 better, but HTML is every where and not everybody has an info
1580 better, but HTML is every where and not everybody has an info
1555 system installed and it's not so easy to change html-docs to info.
1581 system installed and it's not so easy to change html-docs to info.
1556 --added global logfile option
1582 --added global logfile option
1557 --there is now a hook for object inspection method pinfo needs to
1583 --there is now a hook for object inspection method pinfo needs to
1558 be provided for this. Can be reached by two '??'.
1584 be provided for this. Can be reached by two '??'.
1559
1585
1560 08.05.99 20:51 porto.ifm.uni-kiel.de
1586 08.05.99 20:51 porto.ifm.uni-kiel.de
1561 --added a README
1587 --added a README
1562 --bug in rc file. Something has changed so functions in the rc
1588 --bug in rc file. Something has changed so functions in the rc
1563 file need to reference the shell and not self. Not clear if it's a
1589 file need to reference the shell and not self. Not clear if it's a
1564 bug or feature.
1590 bug or feature.
1565 --changed rc file for new behavior
1591 --changed rc file for new behavior
1566
1592
1567 2004-07-15 Fernando Perez <fperez@colorado.edu>
1593 2004-07-15 Fernando Perez <fperez@colorado.edu>
1568
1594
1569 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1595 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1570 cache was falling out of sync in bizarre manners when multi-line
1596 cache was falling out of sync in bizarre manners when multi-line
1571 input was present. Minor optimizations and cleanup.
1597 input was present. Minor optimizations and cleanup.
1572
1598
1573 (Logger): Remove old Changelog info for cleanup. This is the
1599 (Logger): Remove old Changelog info for cleanup. This is the
1574 information which was there from Janko's original code:
1600 information which was there from Janko's original code:
1575
1601
1576 Changes to Logger: - made the default log filename a parameter
1602 Changes to Logger: - made the default log filename a parameter
1577
1603
1578 - put a check for lines beginning with !@? in log(). Needed
1604 - put a check for lines beginning with !@? in log(). Needed
1579 (even if the handlers properly log their lines) for mid-session
1605 (even if the handlers properly log their lines) for mid-session
1580 logging activation to work properly. Without this, lines logged
1606 logging activation to work properly. Without this, lines logged
1581 in mid session, which get read from the cache, would end up
1607 in mid session, which get read from the cache, would end up
1582 'bare' (with !@? in the open) in the log. Now they are caught
1608 'bare' (with !@? in the open) in the log. Now they are caught
1583 and prepended with a #.
1609 and prepended with a #.
1584
1610
1585 * IPython/iplib.py (InteractiveShell.init_readline): added check
1611 * IPython/iplib.py (InteractiveShell.init_readline): added check
1586 in case MagicCompleter fails to be defined, so we don't crash.
1612 in case MagicCompleter fails to be defined, so we don't crash.
1587
1613
1588 2004-07-13 Fernando Perez <fperez@colorado.edu>
1614 2004-07-13 Fernando Perez <fperez@colorado.edu>
1589
1615
1590 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1616 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1591 of EPS if the requested filename ends in '.eps'.
1617 of EPS if the requested filename ends in '.eps'.
1592
1618
1593 2004-07-04 Fernando Perez <fperez@colorado.edu>
1619 2004-07-04 Fernando Perez <fperez@colorado.edu>
1594
1620
1595 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1621 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1596 escaping of quotes when calling the shell.
1622 escaping of quotes when calling the shell.
1597
1623
1598 2004-07-02 Fernando Perez <fperez@colorado.edu>
1624 2004-07-02 Fernando Perez <fperez@colorado.edu>
1599
1625
1600 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1626 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1601 gettext not working because we were clobbering '_'. Fixes
1627 gettext not working because we were clobbering '_'. Fixes
1602 http://www.scipy.net/roundup/ipython/issue6.
1628 http://www.scipy.net/roundup/ipython/issue6.
1603
1629
1604 2004-07-01 Fernando Perez <fperez@colorado.edu>
1630 2004-07-01 Fernando Perez <fperez@colorado.edu>
1605
1631
1606 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1632 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1607 into @cd. Patch by Ville.
1633 into @cd. Patch by Ville.
1608
1634
1609 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1635 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1610 new function to store things after ipmaker runs. Patch by Ville.
1636 new function to store things after ipmaker runs. Patch by Ville.
1611 Eventually this will go away once ipmaker is removed and the class
1637 Eventually this will go away once ipmaker is removed and the class
1612 gets cleaned up, but for now it's ok. Key functionality here is
1638 gets cleaned up, but for now it's ok. Key functionality here is
1613 the addition of the persistent storage mechanism, a dict for
1639 the addition of the persistent storage mechanism, a dict for
1614 keeping data across sessions (for now just bookmarks, but more can
1640 keeping data across sessions (for now just bookmarks, but more can
1615 be implemented later).
1641 be implemented later).
1616
1642
1617 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1643 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1618 persistent across sections. Patch by Ville, I modified it
1644 persistent across sections. Patch by Ville, I modified it
1619 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1645 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1620 added a '-l' option to list all bookmarks.
1646 added a '-l' option to list all bookmarks.
1621
1647
1622 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1648 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1623 center for cleanup. Registered with atexit.register(). I moved
1649 center for cleanup. Registered with atexit.register(). I moved
1624 here the old exit_cleanup(). After a patch by Ville.
1650 here the old exit_cleanup(). After a patch by Ville.
1625
1651
1626 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1652 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1627 characters in the hacked shlex_split for python 2.2.
1653 characters in the hacked shlex_split for python 2.2.
1628
1654
1629 * IPython/iplib.py (file_matches): more fixes to filenames with
1655 * IPython/iplib.py (file_matches): more fixes to filenames with
1630 whitespace in them. It's not perfect, but limitations in python's
1656 whitespace in them. It's not perfect, but limitations in python's
1631 readline make it impossible to go further.
1657 readline make it impossible to go further.
1632
1658
1633 2004-06-29 Fernando Perez <fperez@colorado.edu>
1659 2004-06-29 Fernando Perez <fperez@colorado.edu>
1634
1660
1635 * IPython/iplib.py (file_matches): escape whitespace correctly in
1661 * IPython/iplib.py (file_matches): escape whitespace correctly in
1636 filename completions. Bug reported by Ville.
1662 filename completions. Bug reported by Ville.
1637
1663
1638 2004-06-28 Fernando Perez <fperez@colorado.edu>
1664 2004-06-28 Fernando Perez <fperez@colorado.edu>
1639
1665
1640 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1666 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1641 the history file will be called 'history-PROFNAME' (or just
1667 the history file will be called 'history-PROFNAME' (or just
1642 'history' if no profile is loaded). I was getting annoyed at
1668 'history' if no profile is loaded). I was getting annoyed at
1643 getting my Numerical work history clobbered by pysh sessions.
1669 getting my Numerical work history clobbered by pysh sessions.
1644
1670
1645 * IPython/iplib.py (InteractiveShell.__init__): Internal
1671 * IPython/iplib.py (InteractiveShell.__init__): Internal
1646 getoutputerror() function so that we can honor the system_verbose
1672 getoutputerror() function so that we can honor the system_verbose
1647 flag for _all_ system calls. I also added escaping of #
1673 flag for _all_ system calls. I also added escaping of #
1648 characters here to avoid confusing Itpl.
1674 characters here to avoid confusing Itpl.
1649
1675
1650 * IPython/Magic.py (shlex_split): removed call to shell in
1676 * IPython/Magic.py (shlex_split): removed call to shell in
1651 parse_options and replaced it with shlex.split(). The annoying
1677 parse_options and replaced it with shlex.split(). The annoying
1652 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1678 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1653 to backport it from 2.3, with several frail hacks (the shlex
1679 to backport it from 2.3, with several frail hacks (the shlex
1654 module is rather limited in 2.2). Thanks to a suggestion by Ville
1680 module is rather limited in 2.2). Thanks to a suggestion by Ville
1655 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1681 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1656 problem.
1682 problem.
1657
1683
1658 (Magic.magic_system_verbose): new toggle to print the actual
1684 (Magic.magic_system_verbose): new toggle to print the actual
1659 system calls made by ipython. Mainly for debugging purposes.
1685 system calls made by ipython. Mainly for debugging purposes.
1660
1686
1661 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1687 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1662 doesn't support persistence. Reported (and fix suggested) by
1688 doesn't support persistence. Reported (and fix suggested) by
1663 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1689 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1664
1690
1665 2004-06-26 Fernando Perez <fperez@colorado.edu>
1691 2004-06-26 Fernando Perez <fperez@colorado.edu>
1666
1692
1667 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1693 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1668 continue prompts.
1694 continue prompts.
1669
1695
1670 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1696 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1671 function (basically a big docstring) and a few more things here to
1697 function (basically a big docstring) and a few more things here to
1672 speedup startup. pysh.py is now very lightweight. We want because
1698 speedup startup. pysh.py is now very lightweight. We want because
1673 it gets execfile'd, while InterpreterExec gets imported, so
1699 it gets execfile'd, while InterpreterExec gets imported, so
1674 byte-compilation saves time.
1700 byte-compilation saves time.
1675
1701
1676 2004-06-25 Fernando Perez <fperez@colorado.edu>
1702 2004-06-25 Fernando Perez <fperez@colorado.edu>
1677
1703
1678 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1704 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1679 -NUM', which was recently broken.
1705 -NUM', which was recently broken.
1680
1706
1681 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1707 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1682 in multi-line input (but not !!, which doesn't make sense there).
1708 in multi-line input (but not !!, which doesn't make sense there).
1683
1709
1684 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1710 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1685 It's just too useful, and people can turn it off in the less
1711 It's just too useful, and people can turn it off in the less
1686 common cases where it's a problem.
1712 common cases where it's a problem.
1687
1713
1688 2004-06-24 Fernando Perez <fperez@colorado.edu>
1714 2004-06-24 Fernando Perez <fperez@colorado.edu>
1689
1715
1690 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1716 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1691 special syntaxes (like alias calling) is now allied in multi-line
1717 special syntaxes (like alias calling) is now allied in multi-line
1692 input. This is still _very_ experimental, but it's necessary for
1718 input. This is still _very_ experimental, but it's necessary for
1693 efficient shell usage combining python looping syntax with system
1719 efficient shell usage combining python looping syntax with system
1694 calls. For now it's restricted to aliases, I don't think it
1720 calls. For now it's restricted to aliases, I don't think it
1695 really even makes sense to have this for magics.
1721 really even makes sense to have this for magics.
1696
1722
1697 2004-06-23 Fernando Perez <fperez@colorado.edu>
1723 2004-06-23 Fernando Perez <fperez@colorado.edu>
1698
1724
1699 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1725 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1700 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1726 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1701
1727
1702 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1728 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1703 extensions under Windows (after code sent by Gary Bishop). The
1729 extensions under Windows (after code sent by Gary Bishop). The
1704 extensions considered 'executable' are stored in IPython's rc
1730 extensions considered 'executable' are stored in IPython's rc
1705 structure as win_exec_ext.
1731 structure as win_exec_ext.
1706
1732
1707 * IPython/genutils.py (shell): new function, like system() but
1733 * IPython/genutils.py (shell): new function, like system() but
1708 without return value. Very useful for interactive shell work.
1734 without return value. Very useful for interactive shell work.
1709
1735
1710 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1736 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1711 delete aliases.
1737 delete aliases.
1712
1738
1713 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1739 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1714 sure that the alias table doesn't contain python keywords.
1740 sure that the alias table doesn't contain python keywords.
1715
1741
1716 2004-06-21 Fernando Perez <fperez@colorado.edu>
1742 2004-06-21 Fernando Perez <fperez@colorado.edu>
1717
1743
1718 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1744 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1719 non-existent items are found in $PATH. Reported by Thorsten.
1745 non-existent items are found in $PATH. Reported by Thorsten.
1720
1746
1721 2004-06-20 Fernando Perez <fperez@colorado.edu>
1747 2004-06-20 Fernando Perez <fperez@colorado.edu>
1722
1748
1723 * IPython/iplib.py (complete): modified the completer so that the
1749 * IPython/iplib.py (complete): modified the completer so that the
1724 order of priorities can be easily changed at runtime.
1750 order of priorities can be easily changed at runtime.
1725
1751
1726 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1752 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1727 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1753 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1728
1754
1729 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1755 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1730 expand Python variables prepended with $ in all system calls. The
1756 expand Python variables prepended with $ in all system calls. The
1731 same was done to InteractiveShell.handle_shell_escape. Now all
1757 same was done to InteractiveShell.handle_shell_escape. Now all
1732 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1758 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1733 expansion of python variables and expressions according to the
1759 expansion of python variables and expressions according to the
1734 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1760 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1735
1761
1736 Though PEP-215 has been rejected, a similar (but simpler) one
1762 Though PEP-215 has been rejected, a similar (but simpler) one
1737 seems like it will go into Python 2.4, PEP-292 -
1763 seems like it will go into Python 2.4, PEP-292 -
1738 http://www.python.org/peps/pep-0292.html.
1764 http://www.python.org/peps/pep-0292.html.
1739
1765
1740 I'll keep the full syntax of PEP-215, since IPython has since the
1766 I'll keep the full syntax of PEP-215, since IPython has since the
1741 start used Ka-Ping Yee's reference implementation discussed there
1767 start used Ka-Ping Yee's reference implementation discussed there
1742 (Itpl), and I actually like the powerful semantics it offers.
1768 (Itpl), and I actually like the powerful semantics it offers.
1743
1769
1744 In order to access normal shell variables, the $ has to be escaped
1770 In order to access normal shell variables, the $ has to be escaped
1745 via an extra $. For example:
1771 via an extra $. For example:
1746
1772
1747 In [7]: PATH='a python variable'
1773 In [7]: PATH='a python variable'
1748
1774
1749 In [8]: !echo $PATH
1775 In [8]: !echo $PATH
1750 a python variable
1776 a python variable
1751
1777
1752 In [9]: !echo $$PATH
1778 In [9]: !echo $$PATH
1753 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1779 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1754
1780
1755 (Magic.parse_options): escape $ so the shell doesn't evaluate
1781 (Magic.parse_options): escape $ so the shell doesn't evaluate
1756 things prematurely.
1782 things prematurely.
1757
1783
1758 * IPython/iplib.py (InteractiveShell.call_alias): added the
1784 * IPython/iplib.py (InteractiveShell.call_alias): added the
1759 ability for aliases to expand python variables via $.
1785 ability for aliases to expand python variables via $.
1760
1786
1761 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1787 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1762 system, now there's a @rehash/@rehashx pair of magics. These work
1788 system, now there's a @rehash/@rehashx pair of magics. These work
1763 like the csh rehash command, and can be invoked at any time. They
1789 like the csh rehash command, and can be invoked at any time. They
1764 build a table of aliases to everything in the user's $PATH
1790 build a table of aliases to everything in the user's $PATH
1765 (@rehash uses everything, @rehashx is slower but only adds
1791 (@rehash uses everything, @rehashx is slower but only adds
1766 executable files). With this, the pysh.py-based shell profile can
1792 executable files). With this, the pysh.py-based shell profile can
1767 now simply call rehash upon startup, and full access to all
1793 now simply call rehash upon startup, and full access to all
1768 programs in the user's path is obtained.
1794 programs in the user's path is obtained.
1769
1795
1770 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1796 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1771 functionality is now fully in place. I removed the old dynamic
1797 functionality is now fully in place. I removed the old dynamic
1772 code generation based approach, in favor of a much lighter one
1798 code generation based approach, in favor of a much lighter one
1773 based on a simple dict. The advantage is that this allows me to
1799 based on a simple dict. The advantage is that this allows me to
1774 now have thousands of aliases with negligible cost (unthinkable
1800 now have thousands of aliases with negligible cost (unthinkable
1775 with the old system).
1801 with the old system).
1776
1802
1777 2004-06-19 Fernando Perez <fperez@colorado.edu>
1803 2004-06-19 Fernando Perez <fperez@colorado.edu>
1778
1804
1779 * IPython/iplib.py (__init__): extended MagicCompleter class to
1805 * IPython/iplib.py (__init__): extended MagicCompleter class to
1780 also complete (last in priority) on user aliases.
1806 also complete (last in priority) on user aliases.
1781
1807
1782 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1808 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1783 call to eval.
1809 call to eval.
1784 (ItplNS.__init__): Added a new class which functions like Itpl,
1810 (ItplNS.__init__): Added a new class which functions like Itpl,
1785 but allows configuring the namespace for the evaluation to occur
1811 but allows configuring the namespace for the evaluation to occur
1786 in.
1812 in.
1787
1813
1788 2004-06-18 Fernando Perez <fperez@colorado.edu>
1814 2004-06-18 Fernando Perez <fperez@colorado.edu>
1789
1815
1790 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1816 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1791 better message when 'exit' or 'quit' are typed (a common newbie
1817 better message when 'exit' or 'quit' are typed (a common newbie
1792 confusion).
1818 confusion).
1793
1819
1794 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1820 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1795 check for Windows users.
1821 check for Windows users.
1796
1822
1797 * IPython/iplib.py (InteractiveShell.user_setup): removed
1823 * IPython/iplib.py (InteractiveShell.user_setup): removed
1798 disabling of colors for Windows. I'll test at runtime and issue a
1824 disabling of colors for Windows. I'll test at runtime and issue a
1799 warning if Gary's readline isn't found, as to nudge users to
1825 warning if Gary's readline isn't found, as to nudge users to
1800 download it.
1826 download it.
1801
1827
1802 2004-06-16 Fernando Perez <fperez@colorado.edu>
1828 2004-06-16 Fernando Perez <fperez@colorado.edu>
1803
1829
1804 * IPython/genutils.py (Stream.__init__): changed to print errors
1830 * IPython/genutils.py (Stream.__init__): changed to print errors
1805 to sys.stderr. I had a circular dependency here. Now it's
1831 to sys.stderr. I had a circular dependency here. Now it's
1806 possible to run ipython as IDLE's shell (consider this pre-alpha,
1832 possible to run ipython as IDLE's shell (consider this pre-alpha,
1807 since true stdout things end up in the starting terminal instead
1833 since true stdout things end up in the starting terminal instead
1808 of IDLE's out).
1834 of IDLE's out).
1809
1835
1810 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1836 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1811 users who haven't # updated their prompt_in2 definitions. Remove
1837 users who haven't # updated their prompt_in2 definitions. Remove
1812 eventually.
1838 eventually.
1813 (multiple_replace): added credit to original ASPN recipe.
1839 (multiple_replace): added credit to original ASPN recipe.
1814
1840
1815 2004-06-15 Fernando Perez <fperez@colorado.edu>
1841 2004-06-15 Fernando Perez <fperez@colorado.edu>
1816
1842
1817 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1843 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1818 list of auto-defined aliases.
1844 list of auto-defined aliases.
1819
1845
1820 2004-06-13 Fernando Perez <fperez@colorado.edu>
1846 2004-06-13 Fernando Perez <fperez@colorado.edu>
1821
1847
1822 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1848 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1823 install was really requested (so setup.py can be used for other
1849 install was really requested (so setup.py can be used for other
1824 things under Windows).
1850 things under Windows).
1825
1851
1826 2004-06-10 Fernando Perez <fperez@colorado.edu>
1852 2004-06-10 Fernando Perez <fperez@colorado.edu>
1827
1853
1828 * IPython/Logger.py (Logger.create_log): Manually remove any old
1854 * IPython/Logger.py (Logger.create_log): Manually remove any old
1829 backup, since os.remove may fail under Windows. Fixes bug
1855 backup, since os.remove may fail under Windows. Fixes bug
1830 reported by Thorsten.
1856 reported by Thorsten.
1831
1857
1832 2004-06-09 Fernando Perez <fperez@colorado.edu>
1858 2004-06-09 Fernando Perez <fperez@colorado.edu>
1833
1859
1834 * examples/example-embed.py: fixed all references to %n (replaced
1860 * examples/example-embed.py: fixed all references to %n (replaced
1835 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1861 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1836 for all examples and the manual as well.
1862 for all examples and the manual as well.
1837
1863
1838 2004-06-08 Fernando Perez <fperez@colorado.edu>
1864 2004-06-08 Fernando Perez <fperez@colorado.edu>
1839
1865
1840 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1866 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1841 alignment and color management. All 3 prompt subsystems now
1867 alignment and color management. All 3 prompt subsystems now
1842 inherit from BasePrompt.
1868 inherit from BasePrompt.
1843
1869
1844 * tools/release: updates for windows installer build and tag rpms
1870 * tools/release: updates for windows installer build and tag rpms
1845 with python version (since paths are fixed).
1871 with python version (since paths are fixed).
1846
1872
1847 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1873 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1848 which will become eventually obsolete. Also fixed the default
1874 which will become eventually obsolete. Also fixed the default
1849 prompt_in2 to use \D, so at least new users start with the correct
1875 prompt_in2 to use \D, so at least new users start with the correct
1850 defaults.
1876 defaults.
1851 WARNING: Users with existing ipythonrc files will need to apply
1877 WARNING: Users with existing ipythonrc files will need to apply
1852 this fix manually!
1878 this fix manually!
1853
1879
1854 * setup.py: make windows installer (.exe). This is finally the
1880 * setup.py: make windows installer (.exe). This is finally the
1855 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1881 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1856 which I hadn't included because it required Python 2.3 (or recent
1882 which I hadn't included because it required Python 2.3 (or recent
1857 distutils).
1883 distutils).
1858
1884
1859 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1885 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1860 usage of new '\D' escape.
1886 usage of new '\D' escape.
1861
1887
1862 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1888 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1863 lacks os.getuid())
1889 lacks os.getuid())
1864 (CachedOutput.set_colors): Added the ability to turn coloring
1890 (CachedOutput.set_colors): Added the ability to turn coloring
1865 on/off with @colors even for manually defined prompt colors. It
1891 on/off with @colors even for manually defined prompt colors. It
1866 uses a nasty global, but it works safely and via the generic color
1892 uses a nasty global, but it works safely and via the generic color
1867 handling mechanism.
1893 handling mechanism.
1868 (Prompt2.__init__): Introduced new escape '\D' for continuation
1894 (Prompt2.__init__): Introduced new escape '\D' for continuation
1869 prompts. It represents the counter ('\#') as dots.
1895 prompts. It represents the counter ('\#') as dots.
1870 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1896 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1871 need to update their ipythonrc files and replace '%n' with '\D' in
1897 need to update their ipythonrc files and replace '%n' with '\D' in
1872 their prompt_in2 settings everywhere. Sorry, but there's
1898 their prompt_in2 settings everywhere. Sorry, but there's
1873 otherwise no clean way to get all prompts to properly align. The
1899 otherwise no clean way to get all prompts to properly align. The
1874 ipythonrc shipped with IPython has been updated.
1900 ipythonrc shipped with IPython has been updated.
1875
1901
1876 2004-06-07 Fernando Perez <fperez@colorado.edu>
1902 2004-06-07 Fernando Perez <fperez@colorado.edu>
1877
1903
1878 * setup.py (isfile): Pass local_icons option to latex2html, so the
1904 * setup.py (isfile): Pass local_icons option to latex2html, so the
1879 resulting HTML file is self-contained. Thanks to
1905 resulting HTML file is self-contained. Thanks to
1880 dryice-AT-liu.com.cn for the tip.
1906 dryice-AT-liu.com.cn for the tip.
1881
1907
1882 * pysh.py: I created a new profile 'shell', which implements a
1908 * pysh.py: I created a new profile 'shell', which implements a
1883 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1909 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1884 system shell, nor will it become one anytime soon. It's mainly
1910 system shell, nor will it become one anytime soon. It's mainly
1885 meant to illustrate the use of the new flexible bash-like prompts.
1911 meant to illustrate the use of the new flexible bash-like prompts.
1886 I guess it could be used by hardy souls for true shell management,
1912 I guess it could be used by hardy souls for true shell management,
1887 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1913 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1888 profile. This uses the InterpreterExec extension provided by
1914 profile. This uses the InterpreterExec extension provided by
1889 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1915 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1890
1916
1891 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1917 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1892 auto-align itself with the length of the previous input prompt
1918 auto-align itself with the length of the previous input prompt
1893 (taking into account the invisible color escapes).
1919 (taking into account the invisible color escapes).
1894 (CachedOutput.__init__): Large restructuring of this class. Now
1920 (CachedOutput.__init__): Large restructuring of this class. Now
1895 all three prompts (primary1, primary2, output) are proper objects,
1921 all three prompts (primary1, primary2, output) are proper objects,
1896 managed by the 'parent' CachedOutput class. The code is still a
1922 managed by the 'parent' CachedOutput class. The code is still a
1897 bit hackish (all prompts share state via a pointer to the cache),
1923 bit hackish (all prompts share state via a pointer to the cache),
1898 but it's overall far cleaner than before.
1924 but it's overall far cleaner than before.
1899
1925
1900 * IPython/genutils.py (getoutputerror): modified to add verbose,
1926 * IPython/genutils.py (getoutputerror): modified to add verbose,
1901 debug and header options. This makes the interface of all getout*
1927 debug and header options. This makes the interface of all getout*
1902 functions uniform.
1928 functions uniform.
1903 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1929 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1904
1930
1905 * IPython/Magic.py (Magic.default_option): added a function to
1931 * IPython/Magic.py (Magic.default_option): added a function to
1906 allow registering default options for any magic command. This
1932 allow registering default options for any magic command. This
1907 makes it easy to have profiles which customize the magics globally
1933 makes it easy to have profiles which customize the magics globally
1908 for a certain use. The values set through this function are
1934 for a certain use. The values set through this function are
1909 picked up by the parse_options() method, which all magics should
1935 picked up by the parse_options() method, which all magics should
1910 use to parse their options.
1936 use to parse their options.
1911
1937
1912 * IPython/genutils.py (warn): modified the warnings framework to
1938 * IPython/genutils.py (warn): modified the warnings framework to
1913 use the Term I/O class. I'm trying to slowly unify all of
1939 use the Term I/O class. I'm trying to slowly unify all of
1914 IPython's I/O operations to pass through Term.
1940 IPython's I/O operations to pass through Term.
1915
1941
1916 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1942 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1917 the secondary prompt to correctly match the length of the primary
1943 the secondary prompt to correctly match the length of the primary
1918 one for any prompt. Now multi-line code will properly line up
1944 one for any prompt. Now multi-line code will properly line up
1919 even for path dependent prompts, such as the new ones available
1945 even for path dependent prompts, such as the new ones available
1920 via the prompt_specials.
1946 via the prompt_specials.
1921
1947
1922 2004-06-06 Fernando Perez <fperez@colorado.edu>
1948 2004-06-06 Fernando Perez <fperez@colorado.edu>
1923
1949
1924 * IPython/Prompts.py (prompt_specials): Added the ability to have
1950 * IPython/Prompts.py (prompt_specials): Added the ability to have
1925 bash-like special sequences in the prompts, which get
1951 bash-like special sequences in the prompts, which get
1926 automatically expanded. Things like hostname, current working
1952 automatically expanded. Things like hostname, current working
1927 directory and username are implemented already, but it's easy to
1953 directory and username are implemented already, but it's easy to
1928 add more in the future. Thanks to a patch by W.J. van der Laan
1954 add more in the future. Thanks to a patch by W.J. van der Laan
1929 <gnufnork-AT-hetdigitalegat.nl>
1955 <gnufnork-AT-hetdigitalegat.nl>
1930 (prompt_specials): Added color support for prompt strings, so
1956 (prompt_specials): Added color support for prompt strings, so
1931 users can define arbitrary color setups for their prompts.
1957 users can define arbitrary color setups for their prompts.
1932
1958
1933 2004-06-05 Fernando Perez <fperez@colorado.edu>
1959 2004-06-05 Fernando Perez <fperez@colorado.edu>
1934
1960
1935 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1961 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1936 code to load Gary Bishop's readline and configure it
1962 code to load Gary Bishop's readline and configure it
1937 automatically. Thanks to Gary for help on this.
1963 automatically. Thanks to Gary for help on this.
1938
1964
1939 2004-06-01 Fernando Perez <fperez@colorado.edu>
1965 2004-06-01 Fernando Perez <fperez@colorado.edu>
1940
1966
1941 * IPython/Logger.py (Logger.create_log): fix bug for logging
1967 * IPython/Logger.py (Logger.create_log): fix bug for logging
1942 with no filename (previous fix was incomplete).
1968 with no filename (previous fix was incomplete).
1943
1969
1944 2004-05-25 Fernando Perez <fperez@colorado.edu>
1970 2004-05-25 Fernando Perez <fperez@colorado.edu>
1945
1971
1946 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1972 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1947 parens would get passed to the shell.
1973 parens would get passed to the shell.
1948
1974
1949 2004-05-20 Fernando Perez <fperez@colorado.edu>
1975 2004-05-20 Fernando Perez <fperez@colorado.edu>
1950
1976
1951 * IPython/Magic.py (Magic.magic_prun): changed default profile
1977 * IPython/Magic.py (Magic.magic_prun): changed default profile
1952 sort order to 'time' (the more common profiling need).
1978 sort order to 'time' (the more common profiling need).
1953
1979
1954 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1980 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1955 so that source code shown is guaranteed in sync with the file on
1981 so that source code shown is guaranteed in sync with the file on
1956 disk (also changed in psource). Similar fix to the one for
1982 disk (also changed in psource). Similar fix to the one for
1957 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1983 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1958 <yann.ledu-AT-noos.fr>.
1984 <yann.ledu-AT-noos.fr>.
1959
1985
1960 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1986 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1961 with a single option would not be correctly parsed. Closes
1987 with a single option would not be correctly parsed. Closes
1962 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1988 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1963 introduced in 0.6.0 (on 2004-05-06).
1989 introduced in 0.6.0 (on 2004-05-06).
1964
1990
1965 2004-05-13 *** Released version 0.6.0
1991 2004-05-13 *** Released version 0.6.0
1966
1992
1967 2004-05-13 Fernando Perez <fperez@colorado.edu>
1993 2004-05-13 Fernando Perez <fperez@colorado.edu>
1968
1994
1969 * debian/: Added debian/ directory to CVS, so that debian support
1995 * debian/: Added debian/ directory to CVS, so that debian support
1970 is publicly accessible. The debian package is maintained by Jack
1996 is publicly accessible. The debian package is maintained by Jack
1971 Moffit <jack-AT-xiph.org>.
1997 Moffit <jack-AT-xiph.org>.
1972
1998
1973 * Documentation: included the notes about an ipython-based system
1999 * Documentation: included the notes about an ipython-based system
1974 shell (the hypothetical 'pysh') into the new_design.pdf document,
2000 shell (the hypothetical 'pysh') into the new_design.pdf document,
1975 so that these ideas get distributed to users along with the
2001 so that these ideas get distributed to users along with the
1976 official documentation.
2002 official documentation.
1977
2003
1978 2004-05-10 Fernando Perez <fperez@colorado.edu>
2004 2004-05-10 Fernando Perez <fperez@colorado.edu>
1979
2005
1980 * IPython/Logger.py (Logger.create_log): fix recently introduced
2006 * IPython/Logger.py (Logger.create_log): fix recently introduced
1981 bug (misindented line) where logstart would fail when not given an
2007 bug (misindented line) where logstart would fail when not given an
1982 explicit filename.
2008 explicit filename.
1983
2009
1984 2004-05-09 Fernando Perez <fperez@colorado.edu>
2010 2004-05-09 Fernando Perez <fperez@colorado.edu>
1985
2011
1986 * IPython/Magic.py (Magic.parse_options): skip system call when
2012 * IPython/Magic.py (Magic.parse_options): skip system call when
1987 there are no options to look for. Faster, cleaner for the common
2013 there are no options to look for. Faster, cleaner for the common
1988 case.
2014 case.
1989
2015
1990 * Documentation: many updates to the manual: describing Windows
2016 * Documentation: many updates to the manual: describing Windows
1991 support better, Gnuplot updates, credits, misc small stuff. Also
2017 support better, Gnuplot updates, credits, misc small stuff. Also
1992 updated the new_design doc a bit.
2018 updated the new_design doc a bit.
1993
2019
1994 2004-05-06 *** Released version 0.6.0.rc1
2020 2004-05-06 *** Released version 0.6.0.rc1
1995
2021
1996 2004-05-06 Fernando Perez <fperez@colorado.edu>
2022 2004-05-06 Fernando Perez <fperez@colorado.edu>
1997
2023
1998 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2024 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1999 operations to use the vastly more efficient list/''.join() method.
2025 operations to use the vastly more efficient list/''.join() method.
2000 (FormattedTB.text): Fix
2026 (FormattedTB.text): Fix
2001 http://www.scipy.net/roundup/ipython/issue12 - exception source
2027 http://www.scipy.net/roundup/ipython/issue12 - exception source
2002 extract not updated after reload. Thanks to Mike Salib
2028 extract not updated after reload. Thanks to Mike Salib
2003 <msalib-AT-mit.edu> for pinning the source of the problem.
2029 <msalib-AT-mit.edu> for pinning the source of the problem.
2004 Fortunately, the solution works inside ipython and doesn't require
2030 Fortunately, the solution works inside ipython and doesn't require
2005 any changes to python proper.
2031 any changes to python proper.
2006
2032
2007 * IPython/Magic.py (Magic.parse_options): Improved to process the
2033 * IPython/Magic.py (Magic.parse_options): Improved to process the
2008 argument list as a true shell would (by actually using the
2034 argument list as a true shell would (by actually using the
2009 underlying system shell). This way, all @magics automatically get
2035 underlying system shell). This way, all @magics automatically get
2010 shell expansion for variables. Thanks to a comment by Alex
2036 shell expansion for variables. Thanks to a comment by Alex
2011 Schmolck.
2037 Schmolck.
2012
2038
2013 2004-04-04 Fernando Perez <fperez@colorado.edu>
2039 2004-04-04 Fernando Perez <fperez@colorado.edu>
2014
2040
2015 * IPython/iplib.py (InteractiveShell.interact): Added a special
2041 * IPython/iplib.py (InteractiveShell.interact): Added a special
2016 trap for a debugger quit exception, which is basically impossible
2042 trap for a debugger quit exception, which is basically impossible
2017 to handle by normal mechanisms, given what pdb does to the stack.
2043 to handle by normal mechanisms, given what pdb does to the stack.
2018 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2044 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2019
2045
2020 2004-04-03 Fernando Perez <fperez@colorado.edu>
2046 2004-04-03 Fernando Perez <fperez@colorado.edu>
2021
2047
2022 * IPython/genutils.py (Term): Standardized the names of the Term
2048 * IPython/genutils.py (Term): Standardized the names of the Term
2023 class streams to cin/cout/cerr, following C++ naming conventions
2049 class streams to cin/cout/cerr, following C++ naming conventions
2024 (I can't use in/out/err because 'in' is not a valid attribute
2050 (I can't use in/out/err because 'in' is not a valid attribute
2025 name).
2051 name).
2026
2052
2027 * IPython/iplib.py (InteractiveShell.interact): don't increment
2053 * IPython/iplib.py (InteractiveShell.interact): don't increment
2028 the prompt if there's no user input. By Daniel 'Dang' Griffith
2054 the prompt if there's no user input. By Daniel 'Dang' Griffith
2029 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2055 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2030 Francois Pinard.
2056 Francois Pinard.
2031
2057
2032 2004-04-02 Fernando Perez <fperez@colorado.edu>
2058 2004-04-02 Fernando Perez <fperez@colorado.edu>
2033
2059
2034 * IPython/genutils.py (Stream.__init__): Modified to survive at
2060 * IPython/genutils.py (Stream.__init__): Modified to survive at
2035 least importing in contexts where stdin/out/err aren't true file
2061 least importing in contexts where stdin/out/err aren't true file
2036 objects, such as PyCrust (they lack fileno() and mode). However,
2062 objects, such as PyCrust (they lack fileno() and mode). However,
2037 the recovery facilities which rely on these things existing will
2063 the recovery facilities which rely on these things existing will
2038 not work.
2064 not work.
2039
2065
2040 2004-04-01 Fernando Perez <fperez@colorado.edu>
2066 2004-04-01 Fernando Perez <fperez@colorado.edu>
2041
2067
2042 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2068 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2043 use the new getoutputerror() function, so it properly
2069 use the new getoutputerror() function, so it properly
2044 distinguishes stdout/err.
2070 distinguishes stdout/err.
2045
2071
2046 * IPython/genutils.py (getoutputerror): added a function to
2072 * IPython/genutils.py (getoutputerror): added a function to
2047 capture separately the standard output and error of a command.
2073 capture separately the standard output and error of a command.
2048 After a comment from dang on the mailing lists. This code is
2074 After a comment from dang on the mailing lists. This code is
2049 basically a modified version of commands.getstatusoutput(), from
2075 basically a modified version of commands.getstatusoutput(), from
2050 the standard library.
2076 the standard library.
2051
2077
2052 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2078 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2053 '!!' as a special syntax (shorthand) to access @sx.
2079 '!!' as a special syntax (shorthand) to access @sx.
2054
2080
2055 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2081 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2056 command and return its output as a list split on '\n'.
2082 command and return its output as a list split on '\n'.
2057
2083
2058 2004-03-31 Fernando Perez <fperez@colorado.edu>
2084 2004-03-31 Fernando Perez <fperez@colorado.edu>
2059
2085
2060 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2086 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2061 method to dictionaries used as FakeModule instances if they lack
2087 method to dictionaries used as FakeModule instances if they lack
2062 it. At least pydoc in python2.3 breaks for runtime-defined
2088 it. At least pydoc in python2.3 breaks for runtime-defined
2063 functions without this hack. At some point I need to _really_
2089 functions without this hack. At some point I need to _really_
2064 understand what FakeModule is doing, because it's a gross hack.
2090 understand what FakeModule is doing, because it's a gross hack.
2065 But it solves Arnd's problem for now...
2091 But it solves Arnd's problem for now...
2066
2092
2067 2004-02-27 Fernando Perez <fperez@colorado.edu>
2093 2004-02-27 Fernando Perez <fperez@colorado.edu>
2068
2094
2069 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2095 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2070 mode would behave erratically. Also increased the number of
2096 mode would behave erratically. Also increased the number of
2071 possible logs in rotate mod to 999. Thanks to Rod Holland
2097 possible logs in rotate mod to 999. Thanks to Rod Holland
2072 <rhh@StructureLABS.com> for the report and fixes.
2098 <rhh@StructureLABS.com> for the report and fixes.
2073
2099
2074 2004-02-26 Fernando Perez <fperez@colorado.edu>
2100 2004-02-26 Fernando Perez <fperez@colorado.edu>
2075
2101
2076 * IPython/genutils.py (page): Check that the curses module really
2102 * IPython/genutils.py (page): Check that the curses module really
2077 has the initscr attribute before trying to use it. For some
2103 has the initscr attribute before trying to use it. For some
2078 reason, the Solaris curses module is missing this. I think this
2104 reason, the Solaris curses module is missing this. I think this
2079 should be considered a Solaris python bug, but I'm not sure.
2105 should be considered a Solaris python bug, but I'm not sure.
2080
2106
2081 2004-01-17 Fernando Perez <fperez@colorado.edu>
2107 2004-01-17 Fernando Perez <fperez@colorado.edu>
2082
2108
2083 * IPython/genutils.py (Stream.__init__): Changes to try to make
2109 * IPython/genutils.py (Stream.__init__): Changes to try to make
2084 ipython robust against stdin/out/err being closed by the user.
2110 ipython robust against stdin/out/err being closed by the user.
2085 This is 'user error' (and blocks a normal python session, at least
2111 This is 'user error' (and blocks a normal python session, at least
2086 the stdout case). However, Ipython should be able to survive such
2112 the stdout case). However, Ipython should be able to survive such
2087 instances of abuse as gracefully as possible. To simplify the
2113 instances of abuse as gracefully as possible. To simplify the
2088 coding and maintain compatibility with Gary Bishop's Term
2114 coding and maintain compatibility with Gary Bishop's Term
2089 contributions, I've made use of classmethods for this. I think
2115 contributions, I've made use of classmethods for this. I think
2090 this introduces a dependency on python 2.2.
2116 this introduces a dependency on python 2.2.
2091
2117
2092 2004-01-13 Fernando Perez <fperez@colorado.edu>
2118 2004-01-13 Fernando Perez <fperez@colorado.edu>
2093
2119
2094 * IPython/numutils.py (exp_safe): simplified the code a bit and
2120 * IPython/numutils.py (exp_safe): simplified the code a bit and
2095 removed the need for importing the kinds module altogether.
2121 removed the need for importing the kinds module altogether.
2096
2122
2097 2004-01-06 Fernando Perez <fperez@colorado.edu>
2123 2004-01-06 Fernando Perez <fperez@colorado.edu>
2098
2124
2099 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2125 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2100 a magic function instead, after some community feedback. No
2126 a magic function instead, after some community feedback. No
2101 special syntax will exist for it, but its name is deliberately
2127 special syntax will exist for it, but its name is deliberately
2102 very short.
2128 very short.
2103
2129
2104 2003-12-20 Fernando Perez <fperez@colorado.edu>
2130 2003-12-20 Fernando Perez <fperez@colorado.edu>
2105
2131
2106 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2132 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2107 new functionality, to automagically assign the result of a shell
2133 new functionality, to automagically assign the result of a shell
2108 command to a variable. I'll solicit some community feedback on
2134 command to a variable. I'll solicit some community feedback on
2109 this before making it permanent.
2135 this before making it permanent.
2110
2136
2111 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2137 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2112 requested about callables for which inspect couldn't obtain a
2138 requested about callables for which inspect couldn't obtain a
2113 proper argspec. Thanks to a crash report sent by Etienne
2139 proper argspec. Thanks to a crash report sent by Etienne
2114 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2140 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2115
2141
2116 2003-12-09 Fernando Perez <fperez@colorado.edu>
2142 2003-12-09 Fernando Perez <fperez@colorado.edu>
2117
2143
2118 * IPython/genutils.py (page): patch for the pager to work across
2144 * IPython/genutils.py (page): patch for the pager to work across
2119 various versions of Windows. By Gary Bishop.
2145 various versions of Windows. By Gary Bishop.
2120
2146
2121 2003-12-04 Fernando Perez <fperez@colorado.edu>
2147 2003-12-04 Fernando Perez <fperez@colorado.edu>
2122
2148
2123 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2149 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2124 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2150 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2125 While I tested this and it looks ok, there may still be corner
2151 While I tested this and it looks ok, there may still be corner
2126 cases I've missed.
2152 cases I've missed.
2127
2153
2128 2003-12-01 Fernando Perez <fperez@colorado.edu>
2154 2003-12-01 Fernando Perez <fperez@colorado.edu>
2129
2155
2130 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2156 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2131 where a line like 'p,q=1,2' would fail because the automagic
2157 where a line like 'p,q=1,2' would fail because the automagic
2132 system would be triggered for @p.
2158 system would be triggered for @p.
2133
2159
2134 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2160 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2135 cleanups, code unmodified.
2161 cleanups, code unmodified.
2136
2162
2137 * IPython/genutils.py (Term): added a class for IPython to handle
2163 * IPython/genutils.py (Term): added a class for IPython to handle
2138 output. In most cases it will just be a proxy for stdout/err, but
2164 output. In most cases it will just be a proxy for stdout/err, but
2139 having this allows modifications to be made for some platforms,
2165 having this allows modifications to be made for some platforms,
2140 such as handling color escapes under Windows. All of this code
2166 such as handling color escapes under Windows. All of this code
2141 was contributed by Gary Bishop, with minor modifications by me.
2167 was contributed by Gary Bishop, with minor modifications by me.
2142 The actual changes affect many files.
2168 The actual changes affect many files.
2143
2169
2144 2003-11-30 Fernando Perez <fperez@colorado.edu>
2170 2003-11-30 Fernando Perez <fperez@colorado.edu>
2145
2171
2146 * IPython/iplib.py (file_matches): new completion code, courtesy
2172 * IPython/iplib.py (file_matches): new completion code, courtesy
2147 of Jeff Collins. This enables filename completion again under
2173 of Jeff Collins. This enables filename completion again under
2148 python 2.3, which disabled it at the C level.
2174 python 2.3, which disabled it at the C level.
2149
2175
2150 2003-11-11 Fernando Perez <fperez@colorado.edu>
2176 2003-11-11 Fernando Perez <fperez@colorado.edu>
2151
2177
2152 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2178 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2153 for Numeric.array(map(...)), but often convenient.
2179 for Numeric.array(map(...)), but often convenient.
2154
2180
2155 2003-11-05 Fernando Perez <fperez@colorado.edu>
2181 2003-11-05 Fernando Perez <fperez@colorado.edu>
2156
2182
2157 * IPython/numutils.py (frange): Changed a call from int() to
2183 * IPython/numutils.py (frange): Changed a call from int() to
2158 int(round()) to prevent a problem reported with arange() in the
2184 int(round()) to prevent a problem reported with arange() in the
2159 numpy list.
2185 numpy list.
2160
2186
2161 2003-10-06 Fernando Perez <fperez@colorado.edu>
2187 2003-10-06 Fernando Perez <fperez@colorado.edu>
2162
2188
2163 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2189 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2164 prevent crashes if sys lacks an argv attribute (it happens with
2190 prevent crashes if sys lacks an argv attribute (it happens with
2165 embedded interpreters which build a bare-bones sys module).
2191 embedded interpreters which build a bare-bones sys module).
2166 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2192 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2167
2193
2168 2003-09-24 Fernando Perez <fperez@colorado.edu>
2194 2003-09-24 Fernando Perez <fperez@colorado.edu>
2169
2195
2170 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2196 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2171 to protect against poorly written user objects where __getattr__
2197 to protect against poorly written user objects where __getattr__
2172 raises exceptions other than AttributeError. Thanks to a bug
2198 raises exceptions other than AttributeError. Thanks to a bug
2173 report by Oliver Sander <osander-AT-gmx.de>.
2199 report by Oliver Sander <osander-AT-gmx.de>.
2174
2200
2175 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2201 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2176 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2202 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2177
2203
2178 2003-09-09 Fernando Perez <fperez@colorado.edu>
2204 2003-09-09 Fernando Perez <fperez@colorado.edu>
2179
2205
2180 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2206 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2181 unpacking a list whith a callable as first element would
2207 unpacking a list whith a callable as first element would
2182 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2208 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2183 Collins.
2209 Collins.
2184
2210
2185 2003-08-25 *** Released version 0.5.0
2211 2003-08-25 *** Released version 0.5.0
2186
2212
2187 2003-08-22 Fernando Perez <fperez@colorado.edu>
2213 2003-08-22 Fernando Perez <fperez@colorado.edu>
2188
2214
2189 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2215 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2190 improperly defined user exceptions. Thanks to feedback from Mark
2216 improperly defined user exceptions. Thanks to feedback from Mark
2191 Russell <mrussell-AT-verio.net>.
2217 Russell <mrussell-AT-verio.net>.
2192
2218
2193 2003-08-20 Fernando Perez <fperez@colorado.edu>
2219 2003-08-20 Fernando Perez <fperez@colorado.edu>
2194
2220
2195 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2221 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2196 printing so that it would print multi-line string forms starting
2222 printing so that it would print multi-line string forms starting
2197 with a new line. This way the formatting is better respected for
2223 with a new line. This way the formatting is better respected for
2198 objects which work hard to make nice string forms.
2224 objects which work hard to make nice string forms.
2199
2225
2200 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2226 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2201 autocall would overtake data access for objects with both
2227 autocall would overtake data access for objects with both
2202 __getitem__ and __call__.
2228 __getitem__ and __call__.
2203
2229
2204 2003-08-19 *** Released version 0.5.0-rc1
2230 2003-08-19 *** Released version 0.5.0-rc1
2205
2231
2206 2003-08-19 Fernando Perez <fperez@colorado.edu>
2232 2003-08-19 Fernando Perez <fperez@colorado.edu>
2207
2233
2208 * IPython/deep_reload.py (load_tail): single tiny change here
2234 * IPython/deep_reload.py (load_tail): single tiny change here
2209 seems to fix the long-standing bug of dreload() failing to work
2235 seems to fix the long-standing bug of dreload() failing to work
2210 for dotted names. But this module is pretty tricky, so I may have
2236 for dotted names. But this module is pretty tricky, so I may have
2211 missed some subtlety. Needs more testing!.
2237 missed some subtlety. Needs more testing!.
2212
2238
2213 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2239 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2214 exceptions which have badly implemented __str__ methods.
2240 exceptions which have badly implemented __str__ methods.
2215 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2241 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2216 which I've been getting reports about from Python 2.3 users. I
2242 which I've been getting reports about from Python 2.3 users. I
2217 wish I had a simple test case to reproduce the problem, so I could
2243 wish I had a simple test case to reproduce the problem, so I could
2218 either write a cleaner workaround or file a bug report if
2244 either write a cleaner workaround or file a bug report if
2219 necessary.
2245 necessary.
2220
2246
2221 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2247 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2222 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2248 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2223 a bug report by Tjabo Kloppenburg.
2249 a bug report by Tjabo Kloppenburg.
2224
2250
2225 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2251 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2226 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2252 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2227 seems rather unstable. Thanks to a bug report by Tjabo
2253 seems rather unstable. Thanks to a bug report by Tjabo
2228 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2254 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2229
2255
2230 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2256 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2231 this out soon because of the critical fixes in the inner loop for
2257 this out soon because of the critical fixes in the inner loop for
2232 generators.
2258 generators.
2233
2259
2234 * IPython/Magic.py (Magic.getargspec): removed. This (and
2260 * IPython/Magic.py (Magic.getargspec): removed. This (and
2235 _get_def) have been obsoleted by OInspect for a long time, I
2261 _get_def) have been obsoleted by OInspect for a long time, I
2236 hadn't noticed that they were dead code.
2262 hadn't noticed that they were dead code.
2237 (Magic._ofind): restored _ofind functionality for a few literals
2263 (Magic._ofind): restored _ofind functionality for a few literals
2238 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2264 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2239 for things like "hello".capitalize?, since that would require a
2265 for things like "hello".capitalize?, since that would require a
2240 potentially dangerous eval() again.
2266 potentially dangerous eval() again.
2241
2267
2242 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2268 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2243 logic a bit more to clean up the escapes handling and minimize the
2269 logic a bit more to clean up the escapes handling and minimize the
2244 use of _ofind to only necessary cases. The interactive 'feel' of
2270 use of _ofind to only necessary cases. The interactive 'feel' of
2245 IPython should have improved quite a bit with the changes in
2271 IPython should have improved quite a bit with the changes in
2246 _prefilter and _ofind (besides being far safer than before).
2272 _prefilter and _ofind (besides being far safer than before).
2247
2273
2248 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2274 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2249 obscure, never reported). Edit would fail to find the object to
2275 obscure, never reported). Edit would fail to find the object to
2250 edit under some circumstances.
2276 edit under some circumstances.
2251 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2277 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2252 which were causing double-calling of generators. Those eval calls
2278 which were causing double-calling of generators. Those eval calls
2253 were _very_ dangerous, since code with side effects could be
2279 were _very_ dangerous, since code with side effects could be
2254 triggered. As they say, 'eval is evil'... These were the
2280 triggered. As they say, 'eval is evil'... These were the
2255 nastiest evals in IPython. Besides, _ofind is now far simpler,
2281 nastiest evals in IPython. Besides, _ofind is now far simpler,
2256 and it should also be quite a bit faster. Its use of inspect is
2282 and it should also be quite a bit faster. Its use of inspect is
2257 also safer, so perhaps some of the inspect-related crashes I've
2283 also safer, so perhaps some of the inspect-related crashes I've
2258 seen lately with Python 2.3 might be taken care of. That will
2284 seen lately with Python 2.3 might be taken care of. That will
2259 need more testing.
2285 need more testing.
2260
2286
2261 2003-08-17 Fernando Perez <fperez@colorado.edu>
2287 2003-08-17 Fernando Perez <fperez@colorado.edu>
2262
2288
2263 * IPython/iplib.py (InteractiveShell._prefilter): significant
2289 * IPython/iplib.py (InteractiveShell._prefilter): significant
2264 simplifications to the logic for handling user escapes. Faster
2290 simplifications to the logic for handling user escapes. Faster
2265 and simpler code.
2291 and simpler code.
2266
2292
2267 2003-08-14 Fernando Perez <fperez@colorado.edu>
2293 2003-08-14 Fernando Perez <fperez@colorado.edu>
2268
2294
2269 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2295 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2270 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2296 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2271 but it should be quite a bit faster. And the recursive version
2297 but it should be quite a bit faster. And the recursive version
2272 generated O(log N) intermediate storage for all rank>1 arrays,
2298 generated O(log N) intermediate storage for all rank>1 arrays,
2273 even if they were contiguous.
2299 even if they were contiguous.
2274 (l1norm): Added this function.
2300 (l1norm): Added this function.
2275 (norm): Added this function for arbitrary norms (including
2301 (norm): Added this function for arbitrary norms (including
2276 l-infinity). l1 and l2 are still special cases for convenience
2302 l-infinity). l1 and l2 are still special cases for convenience
2277 and speed.
2303 and speed.
2278
2304
2279 2003-08-03 Fernando Perez <fperez@colorado.edu>
2305 2003-08-03 Fernando Perez <fperez@colorado.edu>
2280
2306
2281 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2307 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2282 exceptions, which now raise PendingDeprecationWarnings in Python
2308 exceptions, which now raise PendingDeprecationWarnings in Python
2283 2.3. There were some in Magic and some in Gnuplot2.
2309 2.3. There were some in Magic and some in Gnuplot2.
2284
2310
2285 2003-06-30 Fernando Perez <fperez@colorado.edu>
2311 2003-06-30 Fernando Perez <fperez@colorado.edu>
2286
2312
2287 * IPython/genutils.py (page): modified to call curses only for
2313 * IPython/genutils.py (page): modified to call curses only for
2288 terminals where TERM=='xterm'. After problems under many other
2314 terminals where TERM=='xterm'. After problems under many other
2289 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2315 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2290
2316
2291 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2317 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2292 would be triggered when readline was absent. This was just an old
2318 would be triggered when readline was absent. This was just an old
2293 debugging statement I'd forgotten to take out.
2319 debugging statement I'd forgotten to take out.
2294
2320
2295 2003-06-20 Fernando Perez <fperez@colorado.edu>
2321 2003-06-20 Fernando Perez <fperez@colorado.edu>
2296
2322
2297 * IPython/genutils.py (clock): modified to return only user time
2323 * IPython/genutils.py (clock): modified to return only user time
2298 (not counting system time), after a discussion on scipy. While
2324 (not counting system time), after a discussion on scipy. While
2299 system time may be a useful quantity occasionally, it may much
2325 system time may be a useful quantity occasionally, it may much
2300 more easily be skewed by occasional swapping or other similar
2326 more easily be skewed by occasional swapping or other similar
2301 activity.
2327 activity.
2302
2328
2303 2003-06-05 Fernando Perez <fperez@colorado.edu>
2329 2003-06-05 Fernando Perez <fperez@colorado.edu>
2304
2330
2305 * IPython/numutils.py (identity): new function, for building
2331 * IPython/numutils.py (identity): new function, for building
2306 arbitrary rank Kronecker deltas (mostly backwards compatible with
2332 arbitrary rank Kronecker deltas (mostly backwards compatible with
2307 Numeric.identity)
2333 Numeric.identity)
2308
2334
2309 2003-06-03 Fernando Perez <fperez@colorado.edu>
2335 2003-06-03 Fernando Perez <fperez@colorado.edu>
2310
2336
2311 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2337 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2312 arguments passed to magics with spaces, to allow trailing '\' to
2338 arguments passed to magics with spaces, to allow trailing '\' to
2313 work normally (mainly for Windows users).
2339 work normally (mainly for Windows users).
2314
2340
2315 2003-05-29 Fernando Perez <fperez@colorado.edu>
2341 2003-05-29 Fernando Perez <fperez@colorado.edu>
2316
2342
2317 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2343 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2318 instead of pydoc.help. This fixes a bizarre behavior where
2344 instead of pydoc.help. This fixes a bizarre behavior where
2319 printing '%s' % locals() would trigger the help system. Now
2345 printing '%s' % locals() would trigger the help system. Now
2320 ipython behaves like normal python does.
2346 ipython behaves like normal python does.
2321
2347
2322 Note that if one does 'from pydoc import help', the bizarre
2348 Note that if one does 'from pydoc import help', the bizarre
2323 behavior returns, but this will also happen in normal python, so
2349 behavior returns, but this will also happen in normal python, so
2324 it's not an ipython bug anymore (it has to do with how pydoc.help
2350 it's not an ipython bug anymore (it has to do with how pydoc.help
2325 is implemented).
2351 is implemented).
2326
2352
2327 2003-05-22 Fernando Perez <fperez@colorado.edu>
2353 2003-05-22 Fernando Perez <fperez@colorado.edu>
2328
2354
2329 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2355 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2330 return [] instead of None when nothing matches, also match to end
2356 return [] instead of None when nothing matches, also match to end
2331 of line. Patch by Gary Bishop.
2357 of line. Patch by Gary Bishop.
2332
2358
2333 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2359 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2334 protection as before, for files passed on the command line. This
2360 protection as before, for files passed on the command line. This
2335 prevents the CrashHandler from kicking in if user files call into
2361 prevents the CrashHandler from kicking in if user files call into
2336 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2362 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2337 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2363 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2338
2364
2339 2003-05-20 *** Released version 0.4.0
2365 2003-05-20 *** Released version 0.4.0
2340
2366
2341 2003-05-20 Fernando Perez <fperez@colorado.edu>
2367 2003-05-20 Fernando Perez <fperez@colorado.edu>
2342
2368
2343 * setup.py: added support for manpages. It's a bit hackish b/c of
2369 * setup.py: added support for manpages. It's a bit hackish b/c of
2344 a bug in the way the bdist_rpm distutils target handles gzipped
2370 a bug in the way the bdist_rpm distutils target handles gzipped
2345 manpages, but it works. After a patch by Jack.
2371 manpages, but it works. After a patch by Jack.
2346
2372
2347 2003-05-19 Fernando Perez <fperez@colorado.edu>
2373 2003-05-19 Fernando Perez <fperez@colorado.edu>
2348
2374
2349 * IPython/numutils.py: added a mockup of the kinds module, since
2375 * IPython/numutils.py: added a mockup of the kinds module, since
2350 it was recently removed from Numeric. This way, numutils will
2376 it was recently removed from Numeric. This way, numutils will
2351 work for all users even if they are missing kinds.
2377 work for all users even if they are missing kinds.
2352
2378
2353 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2379 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2354 failure, which can occur with SWIG-wrapped extensions. After a
2380 failure, which can occur with SWIG-wrapped extensions. After a
2355 crash report from Prabhu.
2381 crash report from Prabhu.
2356
2382
2357 2003-05-16 Fernando Perez <fperez@colorado.edu>
2383 2003-05-16 Fernando Perez <fperez@colorado.edu>
2358
2384
2359 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2385 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2360 protect ipython from user code which may call directly
2386 protect ipython from user code which may call directly
2361 sys.excepthook (this looks like an ipython crash to the user, even
2387 sys.excepthook (this looks like an ipython crash to the user, even
2362 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2388 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2363 This is especially important to help users of WxWindows, but may
2389 This is especially important to help users of WxWindows, but may
2364 also be useful in other cases.
2390 also be useful in other cases.
2365
2391
2366 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2392 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2367 an optional tb_offset to be specified, and to preserve exception
2393 an optional tb_offset to be specified, and to preserve exception
2368 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2394 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2369
2395
2370 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2396 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2371
2397
2372 2003-05-15 Fernando Perez <fperez@colorado.edu>
2398 2003-05-15 Fernando Perez <fperez@colorado.edu>
2373
2399
2374 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2400 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2375 installing for a new user under Windows.
2401 installing for a new user under Windows.
2376
2402
2377 2003-05-12 Fernando Perez <fperez@colorado.edu>
2403 2003-05-12 Fernando Perez <fperez@colorado.edu>
2378
2404
2379 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2405 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2380 handler for Emacs comint-based lines. Currently it doesn't do
2406 handler for Emacs comint-based lines. Currently it doesn't do
2381 much (but importantly, it doesn't update the history cache). In
2407 much (but importantly, it doesn't update the history cache). In
2382 the future it may be expanded if Alex needs more functionality
2408 the future it may be expanded if Alex needs more functionality
2383 there.
2409 there.
2384
2410
2385 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2411 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2386 info to crash reports.
2412 info to crash reports.
2387
2413
2388 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2414 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2389 just like Python's -c. Also fixed crash with invalid -color
2415 just like Python's -c. Also fixed crash with invalid -color
2390 option value at startup. Thanks to Will French
2416 option value at startup. Thanks to Will French
2391 <wfrench-AT-bestweb.net> for the bug report.
2417 <wfrench-AT-bestweb.net> for the bug report.
2392
2418
2393 2003-05-09 Fernando Perez <fperez@colorado.edu>
2419 2003-05-09 Fernando Perez <fperez@colorado.edu>
2394
2420
2395 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2421 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2396 to EvalDict (it's a mapping, after all) and simplified its code
2422 to EvalDict (it's a mapping, after all) and simplified its code
2397 quite a bit, after a nice discussion on c.l.py where Gustavo
2423 quite a bit, after a nice discussion on c.l.py where Gustavo
2398 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2424 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2399
2425
2400 2003-04-30 Fernando Perez <fperez@colorado.edu>
2426 2003-04-30 Fernando Perez <fperez@colorado.edu>
2401
2427
2402 * IPython/genutils.py (timings_out): modified it to reduce its
2428 * IPython/genutils.py (timings_out): modified it to reduce its
2403 overhead in the common reps==1 case.
2429 overhead in the common reps==1 case.
2404
2430
2405 2003-04-29 Fernando Perez <fperez@colorado.edu>
2431 2003-04-29 Fernando Perez <fperez@colorado.edu>
2406
2432
2407 * IPython/genutils.py (timings_out): Modified to use the resource
2433 * IPython/genutils.py (timings_out): Modified to use the resource
2408 module, which avoids the wraparound problems of time.clock().
2434 module, which avoids the wraparound problems of time.clock().
2409
2435
2410 2003-04-17 *** Released version 0.2.15pre4
2436 2003-04-17 *** Released version 0.2.15pre4
2411
2437
2412 2003-04-17 Fernando Perez <fperez@colorado.edu>
2438 2003-04-17 Fernando Perez <fperez@colorado.edu>
2413
2439
2414 * setup.py (scriptfiles): Split windows-specific stuff over to a
2440 * setup.py (scriptfiles): Split windows-specific stuff over to a
2415 separate file, in an attempt to have a Windows GUI installer.
2441 separate file, in an attempt to have a Windows GUI installer.
2416 That didn't work, but part of the groundwork is done.
2442 That didn't work, but part of the groundwork is done.
2417
2443
2418 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2444 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2419 indent/unindent with 4 spaces. Particularly useful in combination
2445 indent/unindent with 4 spaces. Particularly useful in combination
2420 with the new auto-indent option.
2446 with the new auto-indent option.
2421
2447
2422 2003-04-16 Fernando Perez <fperez@colorado.edu>
2448 2003-04-16 Fernando Perez <fperez@colorado.edu>
2423
2449
2424 * IPython/Magic.py: various replacements of self.rc for
2450 * IPython/Magic.py: various replacements of self.rc for
2425 self.shell.rc. A lot more remains to be done to fully disentangle
2451 self.shell.rc. A lot more remains to be done to fully disentangle
2426 this class from the main Shell class.
2452 this class from the main Shell class.
2427
2453
2428 * IPython/GnuplotRuntime.py: added checks for mouse support so
2454 * IPython/GnuplotRuntime.py: added checks for mouse support so
2429 that we don't try to enable it if the current gnuplot doesn't
2455 that we don't try to enable it if the current gnuplot doesn't
2430 really support it. Also added checks so that we don't try to
2456 really support it. Also added checks so that we don't try to
2431 enable persist under Windows (where Gnuplot doesn't recognize the
2457 enable persist under Windows (where Gnuplot doesn't recognize the
2432 option).
2458 option).
2433
2459
2434 * IPython/iplib.py (InteractiveShell.interact): Added optional
2460 * IPython/iplib.py (InteractiveShell.interact): Added optional
2435 auto-indenting code, after a patch by King C. Shu
2461 auto-indenting code, after a patch by King C. Shu
2436 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2462 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2437 get along well with pasting indented code. If I ever figure out
2463 get along well with pasting indented code. If I ever figure out
2438 how to make that part go well, it will become on by default.
2464 how to make that part go well, it will become on by default.
2439
2465
2440 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2466 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2441 crash ipython if there was an unmatched '%' in the user's prompt
2467 crash ipython if there was an unmatched '%' in the user's prompt
2442 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2468 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2443
2469
2444 * IPython/iplib.py (InteractiveShell.interact): removed the
2470 * IPython/iplib.py (InteractiveShell.interact): removed the
2445 ability to ask the user whether he wants to crash or not at the
2471 ability to ask the user whether he wants to crash or not at the
2446 'last line' exception handler. Calling functions at that point
2472 'last line' exception handler. Calling functions at that point
2447 changes the stack, and the error reports would have incorrect
2473 changes the stack, and the error reports would have incorrect
2448 tracebacks.
2474 tracebacks.
2449
2475
2450 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2476 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2451 pass through a peger a pretty-printed form of any object. After a
2477 pass through a peger a pretty-printed form of any object. After a
2452 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2478 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2453
2479
2454 2003-04-14 Fernando Perez <fperez@colorado.edu>
2480 2003-04-14 Fernando Perez <fperez@colorado.edu>
2455
2481
2456 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2482 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2457 all files in ~ would be modified at first install (instead of
2483 all files in ~ would be modified at first install (instead of
2458 ~/.ipython). This could be potentially disastrous, as the
2484 ~/.ipython). This could be potentially disastrous, as the
2459 modification (make line-endings native) could damage binary files.
2485 modification (make line-endings native) could damage binary files.
2460
2486
2461 2003-04-10 Fernando Perez <fperez@colorado.edu>
2487 2003-04-10 Fernando Perez <fperez@colorado.edu>
2462
2488
2463 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2489 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2464 handle only lines which are invalid python. This now means that
2490 handle only lines which are invalid python. This now means that
2465 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2491 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2466 for the bug report.
2492 for the bug report.
2467
2493
2468 2003-04-01 Fernando Perez <fperez@colorado.edu>
2494 2003-04-01 Fernando Perez <fperez@colorado.edu>
2469
2495
2470 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2496 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2471 where failing to set sys.last_traceback would crash pdb.pm().
2497 where failing to set sys.last_traceback would crash pdb.pm().
2472 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2498 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2473 report.
2499 report.
2474
2500
2475 2003-03-25 Fernando Perez <fperez@colorado.edu>
2501 2003-03-25 Fernando Perez <fperez@colorado.edu>
2476
2502
2477 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2503 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2478 before printing it (it had a lot of spurious blank lines at the
2504 before printing it (it had a lot of spurious blank lines at the
2479 end).
2505 end).
2480
2506
2481 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2507 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2482 output would be sent 21 times! Obviously people don't use this
2508 output would be sent 21 times! Obviously people don't use this
2483 too often, or I would have heard about it.
2509 too often, or I would have heard about it.
2484
2510
2485 2003-03-24 Fernando Perez <fperez@colorado.edu>
2511 2003-03-24 Fernando Perez <fperez@colorado.edu>
2486
2512
2487 * setup.py (scriptfiles): renamed the data_files parameter from
2513 * setup.py (scriptfiles): renamed the data_files parameter from
2488 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2514 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2489 for the patch.
2515 for the patch.
2490
2516
2491 2003-03-20 Fernando Perez <fperez@colorado.edu>
2517 2003-03-20 Fernando Perez <fperez@colorado.edu>
2492
2518
2493 * IPython/genutils.py (error): added error() and fatal()
2519 * IPython/genutils.py (error): added error() and fatal()
2494 functions.
2520 functions.
2495
2521
2496 2003-03-18 *** Released version 0.2.15pre3
2522 2003-03-18 *** Released version 0.2.15pre3
2497
2523
2498 2003-03-18 Fernando Perez <fperez@colorado.edu>
2524 2003-03-18 Fernando Perez <fperez@colorado.edu>
2499
2525
2500 * setupext/install_data_ext.py
2526 * setupext/install_data_ext.py
2501 (install_data_ext.initialize_options): Class contributed by Jack
2527 (install_data_ext.initialize_options): Class contributed by Jack
2502 Moffit for fixing the old distutils hack. He is sending this to
2528 Moffit for fixing the old distutils hack. He is sending this to
2503 the distutils folks so in the future we may not need it as a
2529 the distutils folks so in the future we may not need it as a
2504 private fix.
2530 private fix.
2505
2531
2506 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2532 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2507 changes for Debian packaging. See his patch for full details.
2533 changes for Debian packaging. See his patch for full details.
2508 The old distutils hack of making the ipythonrc* files carry a
2534 The old distutils hack of making the ipythonrc* files carry a
2509 bogus .py extension is gone, at last. Examples were moved to a
2535 bogus .py extension is gone, at last. Examples were moved to a
2510 separate subdir under doc/, and the separate executable scripts
2536 separate subdir under doc/, and the separate executable scripts
2511 now live in their own directory. Overall a great cleanup. The
2537 now live in their own directory. Overall a great cleanup. The
2512 manual was updated to use the new files, and setup.py has been
2538 manual was updated to use the new files, and setup.py has been
2513 fixed for this setup.
2539 fixed for this setup.
2514
2540
2515 * IPython/PyColorize.py (Parser.usage): made non-executable and
2541 * IPython/PyColorize.py (Parser.usage): made non-executable and
2516 created a pycolor wrapper around it to be included as a script.
2542 created a pycolor wrapper around it to be included as a script.
2517
2543
2518 2003-03-12 *** Released version 0.2.15pre2
2544 2003-03-12 *** Released version 0.2.15pre2
2519
2545
2520 2003-03-12 Fernando Perez <fperez@colorado.edu>
2546 2003-03-12 Fernando Perez <fperez@colorado.edu>
2521
2547
2522 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2548 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2523 long-standing problem with garbage characters in some terminals.
2549 long-standing problem with garbage characters in some terminals.
2524 The issue was really that the \001 and \002 escapes must _only_ be
2550 The issue was really that the \001 and \002 escapes must _only_ be
2525 passed to input prompts (which call readline), but _never_ to
2551 passed to input prompts (which call readline), but _never_ to
2526 normal text to be printed on screen. I changed ColorANSI to have
2552 normal text to be printed on screen. I changed ColorANSI to have
2527 two classes: TermColors and InputTermColors, each with the
2553 two classes: TermColors and InputTermColors, each with the
2528 appropriate escapes for input prompts or normal text. The code in
2554 appropriate escapes for input prompts or normal text. The code in
2529 Prompts.py got slightly more complicated, but this very old and
2555 Prompts.py got slightly more complicated, but this very old and
2530 annoying bug is finally fixed.
2556 annoying bug is finally fixed.
2531
2557
2532 All the credit for nailing down the real origin of this problem
2558 All the credit for nailing down the real origin of this problem
2533 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2559 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2534 *Many* thanks to him for spending quite a bit of effort on this.
2560 *Many* thanks to him for spending quite a bit of effort on this.
2535
2561
2536 2003-03-05 *** Released version 0.2.15pre1
2562 2003-03-05 *** Released version 0.2.15pre1
2537
2563
2538 2003-03-03 Fernando Perez <fperez@colorado.edu>
2564 2003-03-03 Fernando Perez <fperez@colorado.edu>
2539
2565
2540 * IPython/FakeModule.py: Moved the former _FakeModule to a
2566 * IPython/FakeModule.py: Moved the former _FakeModule to a
2541 separate file, because it's also needed by Magic (to fix a similar
2567 separate file, because it's also needed by Magic (to fix a similar
2542 pickle-related issue in @run).
2568 pickle-related issue in @run).
2543
2569
2544 2003-03-02 Fernando Perez <fperez@colorado.edu>
2570 2003-03-02 Fernando Perez <fperez@colorado.edu>
2545
2571
2546 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2572 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2547 the autocall option at runtime.
2573 the autocall option at runtime.
2548 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2574 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2549 across Magic.py to start separating Magic from InteractiveShell.
2575 across Magic.py to start separating Magic from InteractiveShell.
2550 (Magic._ofind): Fixed to return proper namespace for dotted
2576 (Magic._ofind): Fixed to return proper namespace for dotted
2551 names. Before, a dotted name would always return 'not currently
2577 names. Before, a dotted name would always return 'not currently
2552 defined', because it would find the 'parent'. s.x would be found,
2578 defined', because it would find the 'parent'. s.x would be found,
2553 but since 'x' isn't defined by itself, it would get confused.
2579 but since 'x' isn't defined by itself, it would get confused.
2554 (Magic.magic_run): Fixed pickling problems reported by Ralf
2580 (Magic.magic_run): Fixed pickling problems reported by Ralf
2555 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2581 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2556 that I'd used when Mike Heeter reported similar issues at the
2582 that I'd used when Mike Heeter reported similar issues at the
2557 top-level, but now for @run. It boils down to injecting the
2583 top-level, but now for @run. It boils down to injecting the
2558 namespace where code is being executed with something that looks
2584 namespace where code is being executed with something that looks
2559 enough like a module to fool pickle.dump(). Since a pickle stores
2585 enough like a module to fool pickle.dump(). Since a pickle stores
2560 a named reference to the importing module, we need this for
2586 a named reference to the importing module, we need this for
2561 pickles to save something sensible.
2587 pickles to save something sensible.
2562
2588
2563 * IPython/ipmaker.py (make_IPython): added an autocall option.
2589 * IPython/ipmaker.py (make_IPython): added an autocall option.
2564
2590
2565 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2591 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2566 the auto-eval code. Now autocalling is an option, and the code is
2592 the auto-eval code. Now autocalling is an option, and the code is
2567 also vastly safer. There is no more eval() involved at all.
2593 also vastly safer. There is no more eval() involved at all.
2568
2594
2569 2003-03-01 Fernando Perez <fperez@colorado.edu>
2595 2003-03-01 Fernando Perez <fperez@colorado.edu>
2570
2596
2571 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2597 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2572 dict with named keys instead of a tuple.
2598 dict with named keys instead of a tuple.
2573
2599
2574 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2600 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2575
2601
2576 * setup.py (make_shortcut): Fixed message about directories
2602 * setup.py (make_shortcut): Fixed message about directories
2577 created during Windows installation (the directories were ok, just
2603 created during Windows installation (the directories were ok, just
2578 the printed message was misleading). Thanks to Chris Liechti
2604 the printed message was misleading). Thanks to Chris Liechti
2579 <cliechti-AT-gmx.net> for the heads up.
2605 <cliechti-AT-gmx.net> for the heads up.
2580
2606
2581 2003-02-21 Fernando Perez <fperez@colorado.edu>
2607 2003-02-21 Fernando Perez <fperez@colorado.edu>
2582
2608
2583 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2609 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2584 of ValueError exception when checking for auto-execution. This
2610 of ValueError exception when checking for auto-execution. This
2585 one is raised by things like Numeric arrays arr.flat when the
2611 one is raised by things like Numeric arrays arr.flat when the
2586 array is non-contiguous.
2612 array is non-contiguous.
2587
2613
2588 2003-01-31 Fernando Perez <fperez@colorado.edu>
2614 2003-01-31 Fernando Perez <fperez@colorado.edu>
2589
2615
2590 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2616 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2591 not return any value at all (even though the command would get
2617 not return any value at all (even though the command would get
2592 executed).
2618 executed).
2593 (xsys): Flush stdout right after printing the command to ensure
2619 (xsys): Flush stdout right after printing the command to ensure
2594 proper ordering of commands and command output in the total
2620 proper ordering of commands and command output in the total
2595 output.
2621 output.
2596 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2622 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2597 system/getoutput as defaults. The old ones are kept for
2623 system/getoutput as defaults. The old ones are kept for
2598 compatibility reasons, so no code which uses this library needs
2624 compatibility reasons, so no code which uses this library needs
2599 changing.
2625 changing.
2600
2626
2601 2003-01-27 *** Released version 0.2.14
2627 2003-01-27 *** Released version 0.2.14
2602
2628
2603 2003-01-25 Fernando Perez <fperez@colorado.edu>
2629 2003-01-25 Fernando Perez <fperez@colorado.edu>
2604
2630
2605 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2631 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2606 functions defined in previous edit sessions could not be re-edited
2632 functions defined in previous edit sessions could not be re-edited
2607 (because the temp files were immediately removed). Now temp files
2633 (because the temp files were immediately removed). Now temp files
2608 are removed only at IPython's exit.
2634 are removed only at IPython's exit.
2609 (Magic.magic_run): Improved @run to perform shell-like expansions
2635 (Magic.magic_run): Improved @run to perform shell-like expansions
2610 on its arguments (~users and $VARS). With this, @run becomes more
2636 on its arguments (~users and $VARS). With this, @run becomes more
2611 like a normal command-line.
2637 like a normal command-line.
2612
2638
2613 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2639 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2614 bugs related to embedding and cleaned up that code. A fairly
2640 bugs related to embedding and cleaned up that code. A fairly
2615 important one was the impossibility to access the global namespace
2641 important one was the impossibility to access the global namespace
2616 through the embedded IPython (only local variables were visible).
2642 through the embedded IPython (only local variables were visible).
2617
2643
2618 2003-01-14 Fernando Perez <fperez@colorado.edu>
2644 2003-01-14 Fernando Perez <fperez@colorado.edu>
2619
2645
2620 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2646 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2621 auto-calling to be a bit more conservative. Now it doesn't get
2647 auto-calling to be a bit more conservative. Now it doesn't get
2622 triggered if any of '!=()<>' are in the rest of the input line, to
2648 triggered if any of '!=()<>' are in the rest of the input line, to
2623 allow comparing callables. Thanks to Alex for the heads up.
2649 allow comparing callables. Thanks to Alex for the heads up.
2624
2650
2625 2003-01-07 Fernando Perez <fperez@colorado.edu>
2651 2003-01-07 Fernando Perez <fperez@colorado.edu>
2626
2652
2627 * IPython/genutils.py (page): fixed estimation of the number of
2653 * IPython/genutils.py (page): fixed estimation of the number of
2628 lines in a string to be paged to simply count newlines. This
2654 lines in a string to be paged to simply count newlines. This
2629 prevents over-guessing due to embedded escape sequences. A better
2655 prevents over-guessing due to embedded escape sequences. A better
2630 long-term solution would involve stripping out the control chars
2656 long-term solution would involve stripping out the control chars
2631 for the count, but it's potentially so expensive I just don't
2657 for the count, but it's potentially so expensive I just don't
2632 think it's worth doing.
2658 think it's worth doing.
2633
2659
2634 2002-12-19 *** Released version 0.2.14pre50
2660 2002-12-19 *** Released version 0.2.14pre50
2635
2661
2636 2002-12-19 Fernando Perez <fperez@colorado.edu>
2662 2002-12-19 Fernando Perez <fperez@colorado.edu>
2637
2663
2638 * tools/release (version): Changed release scripts to inform
2664 * tools/release (version): Changed release scripts to inform
2639 Andrea and build a NEWS file with a list of recent changes.
2665 Andrea and build a NEWS file with a list of recent changes.
2640
2666
2641 * IPython/ColorANSI.py (__all__): changed terminal detection
2667 * IPython/ColorANSI.py (__all__): changed terminal detection
2642 code. Seems to work better for xterms without breaking
2668 code. Seems to work better for xterms without breaking
2643 konsole. Will need more testing to determine if WinXP and Mac OSX
2669 konsole. Will need more testing to determine if WinXP and Mac OSX
2644 also work ok.
2670 also work ok.
2645
2671
2646 2002-12-18 *** Released version 0.2.14pre49
2672 2002-12-18 *** Released version 0.2.14pre49
2647
2673
2648 2002-12-18 Fernando Perez <fperez@colorado.edu>
2674 2002-12-18 Fernando Perez <fperez@colorado.edu>
2649
2675
2650 * Docs: added new info about Mac OSX, from Andrea.
2676 * Docs: added new info about Mac OSX, from Andrea.
2651
2677
2652 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2678 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2653 allow direct plotting of python strings whose format is the same
2679 allow direct plotting of python strings whose format is the same
2654 of gnuplot data files.
2680 of gnuplot data files.
2655
2681
2656 2002-12-16 Fernando Perez <fperez@colorado.edu>
2682 2002-12-16 Fernando Perez <fperez@colorado.edu>
2657
2683
2658 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2684 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2659 value of exit question to be acknowledged.
2685 value of exit question to be acknowledged.
2660
2686
2661 2002-12-03 Fernando Perez <fperez@colorado.edu>
2687 2002-12-03 Fernando Perez <fperez@colorado.edu>
2662
2688
2663 * IPython/ipmaker.py: removed generators, which had been added
2689 * IPython/ipmaker.py: removed generators, which had been added
2664 by mistake in an earlier debugging run. This was causing trouble
2690 by mistake in an earlier debugging run. This was causing trouble
2665 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2691 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2666 for pointing this out.
2692 for pointing this out.
2667
2693
2668 2002-11-17 Fernando Perez <fperez@colorado.edu>
2694 2002-11-17 Fernando Perez <fperez@colorado.edu>
2669
2695
2670 * Manual: updated the Gnuplot section.
2696 * Manual: updated the Gnuplot section.
2671
2697
2672 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2698 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2673 a much better split of what goes in Runtime and what goes in
2699 a much better split of what goes in Runtime and what goes in
2674 Interactive.
2700 Interactive.
2675
2701
2676 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2702 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2677 being imported from iplib.
2703 being imported from iplib.
2678
2704
2679 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2705 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2680 for command-passing. Now the global Gnuplot instance is called
2706 for command-passing. Now the global Gnuplot instance is called
2681 'gp' instead of 'g', which was really a far too fragile and
2707 'gp' instead of 'g', which was really a far too fragile and
2682 common name.
2708 common name.
2683
2709
2684 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2710 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2685 bounding boxes generated by Gnuplot for square plots.
2711 bounding boxes generated by Gnuplot for square plots.
2686
2712
2687 * IPython/genutils.py (popkey): new function added. I should
2713 * IPython/genutils.py (popkey): new function added. I should
2688 suggest this on c.l.py as a dict method, it seems useful.
2714 suggest this on c.l.py as a dict method, it seems useful.
2689
2715
2690 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2716 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2691 to transparently handle PostScript generation. MUCH better than
2717 to transparently handle PostScript generation. MUCH better than
2692 the previous plot_eps/replot_eps (which I removed now). The code
2718 the previous plot_eps/replot_eps (which I removed now). The code
2693 is also fairly clean and well documented now (including
2719 is also fairly clean and well documented now (including
2694 docstrings).
2720 docstrings).
2695
2721
2696 2002-11-13 Fernando Perez <fperez@colorado.edu>
2722 2002-11-13 Fernando Perez <fperez@colorado.edu>
2697
2723
2698 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2724 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2699 (inconsistent with options).
2725 (inconsistent with options).
2700
2726
2701 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2727 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2702 manually disabled, I don't know why. Fixed it.
2728 manually disabled, I don't know why. Fixed it.
2703 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2729 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2704 eps output.
2730 eps output.
2705
2731
2706 2002-11-12 Fernando Perez <fperez@colorado.edu>
2732 2002-11-12 Fernando Perez <fperez@colorado.edu>
2707
2733
2708 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2734 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2709 don't propagate up to caller. Fixes crash reported by François
2735 don't propagate up to caller. Fixes crash reported by François
2710 Pinard.
2736 Pinard.
2711
2737
2712 2002-11-09 Fernando Perez <fperez@colorado.edu>
2738 2002-11-09 Fernando Perez <fperez@colorado.edu>
2713
2739
2714 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2740 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2715 history file for new users.
2741 history file for new users.
2716 (make_IPython): fixed bug where initial install would leave the
2742 (make_IPython): fixed bug where initial install would leave the
2717 user running in the .ipython dir.
2743 user running in the .ipython dir.
2718 (make_IPython): fixed bug where config dir .ipython would be
2744 (make_IPython): fixed bug where config dir .ipython would be
2719 created regardless of the given -ipythondir option. Thanks to Cory
2745 created regardless of the given -ipythondir option. Thanks to Cory
2720 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2746 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2721
2747
2722 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2748 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2723 type confirmations. Will need to use it in all of IPython's code
2749 type confirmations. Will need to use it in all of IPython's code
2724 consistently.
2750 consistently.
2725
2751
2726 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2752 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2727 context to print 31 lines instead of the default 5. This will make
2753 context to print 31 lines instead of the default 5. This will make
2728 the crash reports extremely detailed in case the problem is in
2754 the crash reports extremely detailed in case the problem is in
2729 libraries I don't have access to.
2755 libraries I don't have access to.
2730
2756
2731 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2757 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2732 line of defense' code to still crash, but giving users fair
2758 line of defense' code to still crash, but giving users fair
2733 warning. I don't want internal errors to go unreported: if there's
2759 warning. I don't want internal errors to go unreported: if there's
2734 an internal problem, IPython should crash and generate a full
2760 an internal problem, IPython should crash and generate a full
2735 report.
2761 report.
2736
2762
2737 2002-11-08 Fernando Perez <fperez@colorado.edu>
2763 2002-11-08 Fernando Perez <fperez@colorado.edu>
2738
2764
2739 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2765 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2740 otherwise uncaught exceptions which can appear if people set
2766 otherwise uncaught exceptions which can appear if people set
2741 sys.stdout to something badly broken. Thanks to a crash report
2767 sys.stdout to something badly broken. Thanks to a crash report
2742 from henni-AT-mail.brainbot.com.
2768 from henni-AT-mail.brainbot.com.
2743
2769
2744 2002-11-04 Fernando Perez <fperez@colorado.edu>
2770 2002-11-04 Fernando Perez <fperez@colorado.edu>
2745
2771
2746 * IPython/iplib.py (InteractiveShell.interact): added
2772 * IPython/iplib.py (InteractiveShell.interact): added
2747 __IPYTHON__active to the builtins. It's a flag which goes on when
2773 __IPYTHON__active to the builtins. It's a flag which goes on when
2748 the interaction starts and goes off again when it stops. This
2774 the interaction starts and goes off again when it stops. This
2749 allows embedding code to detect being inside IPython. Before this
2775 allows embedding code to detect being inside IPython. Before this
2750 was done via __IPYTHON__, but that only shows that an IPython
2776 was done via __IPYTHON__, but that only shows that an IPython
2751 instance has been created.
2777 instance has been created.
2752
2778
2753 * IPython/Magic.py (Magic.magic_env): I realized that in a
2779 * IPython/Magic.py (Magic.magic_env): I realized that in a
2754 UserDict, instance.data holds the data as a normal dict. So I
2780 UserDict, instance.data holds the data as a normal dict. So I
2755 modified @env to return os.environ.data instead of rebuilding a
2781 modified @env to return os.environ.data instead of rebuilding a
2756 dict by hand.
2782 dict by hand.
2757
2783
2758 2002-11-02 Fernando Perez <fperez@colorado.edu>
2784 2002-11-02 Fernando Perez <fperez@colorado.edu>
2759
2785
2760 * IPython/genutils.py (warn): changed so that level 1 prints no
2786 * IPython/genutils.py (warn): changed so that level 1 prints no
2761 header. Level 2 is now the default (with 'WARNING' header, as
2787 header. Level 2 is now the default (with 'WARNING' header, as
2762 before). I think I tracked all places where changes were needed in
2788 before). I think I tracked all places where changes were needed in
2763 IPython, but outside code using the old level numbering may have
2789 IPython, but outside code using the old level numbering may have
2764 broken.
2790 broken.
2765
2791
2766 * IPython/iplib.py (InteractiveShell.runcode): added this to
2792 * IPython/iplib.py (InteractiveShell.runcode): added this to
2767 handle the tracebacks in SystemExit traps correctly. The previous
2793 handle the tracebacks in SystemExit traps correctly. The previous
2768 code (through interact) was printing more of the stack than
2794 code (through interact) was printing more of the stack than
2769 necessary, showing IPython internal code to the user.
2795 necessary, showing IPython internal code to the user.
2770
2796
2771 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2797 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2772 default. Now that the default at the confirmation prompt is yes,
2798 default. Now that the default at the confirmation prompt is yes,
2773 it's not so intrusive. François' argument that ipython sessions
2799 it's not so intrusive. François' argument that ipython sessions
2774 tend to be complex enough not to lose them from an accidental C-d,
2800 tend to be complex enough not to lose them from an accidental C-d,
2775 is a valid one.
2801 is a valid one.
2776
2802
2777 * IPython/iplib.py (InteractiveShell.interact): added a
2803 * IPython/iplib.py (InteractiveShell.interact): added a
2778 showtraceback() call to the SystemExit trap, and modified the exit
2804 showtraceback() call to the SystemExit trap, and modified the exit
2779 confirmation to have yes as the default.
2805 confirmation to have yes as the default.
2780
2806
2781 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2807 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2782 this file. It's been gone from the code for a long time, this was
2808 this file. It's been gone from the code for a long time, this was
2783 simply leftover junk.
2809 simply leftover junk.
2784
2810
2785 2002-11-01 Fernando Perez <fperez@colorado.edu>
2811 2002-11-01 Fernando Perez <fperez@colorado.edu>
2786
2812
2787 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2813 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2788 added. If set, IPython now traps EOF and asks for
2814 added. If set, IPython now traps EOF and asks for
2789 confirmation. After a request by François Pinard.
2815 confirmation. After a request by François Pinard.
2790
2816
2791 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2817 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2792 of @abort, and with a new (better) mechanism for handling the
2818 of @abort, and with a new (better) mechanism for handling the
2793 exceptions.
2819 exceptions.
2794
2820
2795 2002-10-27 Fernando Perez <fperez@colorado.edu>
2821 2002-10-27 Fernando Perez <fperez@colorado.edu>
2796
2822
2797 * IPython/usage.py (__doc__): updated the --help information and
2823 * IPython/usage.py (__doc__): updated the --help information and
2798 the ipythonrc file to indicate that -log generates
2824 the ipythonrc file to indicate that -log generates
2799 ./ipython.log. Also fixed the corresponding info in @logstart.
2825 ./ipython.log. Also fixed the corresponding info in @logstart.
2800 This and several other fixes in the manuals thanks to reports by
2826 This and several other fixes in the manuals thanks to reports by
2801 François Pinard <pinard-AT-iro.umontreal.ca>.
2827 François Pinard <pinard-AT-iro.umontreal.ca>.
2802
2828
2803 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2829 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2804 refer to @logstart (instead of @log, which doesn't exist).
2830 refer to @logstart (instead of @log, which doesn't exist).
2805
2831
2806 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2832 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2807 AttributeError crash. Thanks to Christopher Armstrong
2833 AttributeError crash. Thanks to Christopher Armstrong
2808 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2834 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2809 introduced recently (in 0.2.14pre37) with the fix to the eval
2835 introduced recently (in 0.2.14pre37) with the fix to the eval
2810 problem mentioned below.
2836 problem mentioned below.
2811
2837
2812 2002-10-17 Fernando Perez <fperez@colorado.edu>
2838 2002-10-17 Fernando Perez <fperez@colorado.edu>
2813
2839
2814 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2840 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2815 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2841 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2816
2842
2817 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2843 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2818 this function to fix a problem reported by Alex Schmolck. He saw
2844 this function to fix a problem reported by Alex Schmolck. He saw
2819 it with list comprehensions and generators, which were getting
2845 it with list comprehensions and generators, which were getting
2820 called twice. The real problem was an 'eval' call in testing for
2846 called twice. The real problem was an 'eval' call in testing for
2821 automagic which was evaluating the input line silently.
2847 automagic which was evaluating the input line silently.
2822
2848
2823 This is a potentially very nasty bug, if the input has side
2849 This is a potentially very nasty bug, if the input has side
2824 effects which must not be repeated. The code is much cleaner now,
2850 effects which must not be repeated. The code is much cleaner now,
2825 without any blanket 'except' left and with a regexp test for
2851 without any blanket 'except' left and with a regexp test for
2826 actual function names.
2852 actual function names.
2827
2853
2828 But an eval remains, which I'm not fully comfortable with. I just
2854 But an eval remains, which I'm not fully comfortable with. I just
2829 don't know how to find out if an expression could be a callable in
2855 don't know how to find out if an expression could be a callable in
2830 the user's namespace without doing an eval on the string. However
2856 the user's namespace without doing an eval on the string. However
2831 that string is now much more strictly checked so that no code
2857 that string is now much more strictly checked so that no code
2832 slips by, so the eval should only happen for things that can
2858 slips by, so the eval should only happen for things that can
2833 really be only function/method names.
2859 really be only function/method names.
2834
2860
2835 2002-10-15 Fernando Perez <fperez@colorado.edu>
2861 2002-10-15 Fernando Perez <fperez@colorado.edu>
2836
2862
2837 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2863 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2838 OSX information to main manual, removed README_Mac_OSX file from
2864 OSX information to main manual, removed README_Mac_OSX file from
2839 distribution. Also updated credits for recent additions.
2865 distribution. Also updated credits for recent additions.
2840
2866
2841 2002-10-10 Fernando Perez <fperez@colorado.edu>
2867 2002-10-10 Fernando Perez <fperez@colorado.edu>
2842
2868
2843 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2869 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2844 terminal-related issues. Many thanks to Andrea Riciputi
2870 terminal-related issues. Many thanks to Andrea Riciputi
2845 <andrea.riciputi-AT-libero.it> for writing it.
2871 <andrea.riciputi-AT-libero.it> for writing it.
2846
2872
2847 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2873 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2848 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2874 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2849
2875
2850 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2876 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2851 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2877 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2852 <syver-en-AT-online.no> who both submitted patches for this problem.
2878 <syver-en-AT-online.no> who both submitted patches for this problem.
2853
2879
2854 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2880 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2855 global embedding to make sure that things don't overwrite user
2881 global embedding to make sure that things don't overwrite user
2856 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2882 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2857
2883
2858 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2884 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2859 compatibility. Thanks to Hayden Callow
2885 compatibility. Thanks to Hayden Callow
2860 <h.callow-AT-elec.canterbury.ac.nz>
2886 <h.callow-AT-elec.canterbury.ac.nz>
2861
2887
2862 2002-10-04 Fernando Perez <fperez@colorado.edu>
2888 2002-10-04 Fernando Perez <fperez@colorado.edu>
2863
2889
2864 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2890 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2865 Gnuplot.File objects.
2891 Gnuplot.File objects.
2866
2892
2867 2002-07-23 Fernando Perez <fperez@colorado.edu>
2893 2002-07-23 Fernando Perez <fperez@colorado.edu>
2868
2894
2869 * IPython/genutils.py (timing): Added timings() and timing() for
2895 * IPython/genutils.py (timing): Added timings() and timing() for
2870 quick access to the most commonly needed data, the execution
2896 quick access to the most commonly needed data, the execution
2871 times. Old timing() renamed to timings_out().
2897 times. Old timing() renamed to timings_out().
2872
2898
2873 2002-07-18 Fernando Perez <fperez@colorado.edu>
2899 2002-07-18 Fernando Perez <fperez@colorado.edu>
2874
2900
2875 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2901 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2876 bug with nested instances disrupting the parent's tab completion.
2902 bug with nested instances disrupting the parent's tab completion.
2877
2903
2878 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2904 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2879 all_completions code to begin the emacs integration.
2905 all_completions code to begin the emacs integration.
2880
2906
2881 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2907 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2882 argument to allow titling individual arrays when plotting.
2908 argument to allow titling individual arrays when plotting.
2883
2909
2884 2002-07-15 Fernando Perez <fperez@colorado.edu>
2910 2002-07-15 Fernando Perez <fperez@colorado.edu>
2885
2911
2886 * setup.py (make_shortcut): changed to retrieve the value of
2912 * setup.py (make_shortcut): changed to retrieve the value of
2887 'Program Files' directory from the registry (this value changes in
2913 'Program Files' directory from the registry (this value changes in
2888 non-english versions of Windows). Thanks to Thomas Fanslau
2914 non-english versions of Windows). Thanks to Thomas Fanslau
2889 <tfanslau-AT-gmx.de> for the report.
2915 <tfanslau-AT-gmx.de> for the report.
2890
2916
2891 2002-07-10 Fernando Perez <fperez@colorado.edu>
2917 2002-07-10 Fernando Perez <fperez@colorado.edu>
2892
2918
2893 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2919 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2894 a bug in pdb, which crashes if a line with only whitespace is
2920 a bug in pdb, which crashes if a line with only whitespace is
2895 entered. Bug report submitted to sourceforge.
2921 entered. Bug report submitted to sourceforge.
2896
2922
2897 2002-07-09 Fernando Perez <fperez@colorado.edu>
2923 2002-07-09 Fernando Perez <fperez@colorado.edu>
2898
2924
2899 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2925 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2900 reporting exceptions (it's a bug in inspect.py, I just set a
2926 reporting exceptions (it's a bug in inspect.py, I just set a
2901 workaround).
2927 workaround).
2902
2928
2903 2002-07-08 Fernando Perez <fperez@colorado.edu>
2929 2002-07-08 Fernando Perez <fperez@colorado.edu>
2904
2930
2905 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2931 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2906 __IPYTHON__ in __builtins__ to show up in user_ns.
2932 __IPYTHON__ in __builtins__ to show up in user_ns.
2907
2933
2908 2002-07-03 Fernando Perez <fperez@colorado.edu>
2934 2002-07-03 Fernando Perez <fperez@colorado.edu>
2909
2935
2910 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2936 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2911 name from @gp_set_instance to @gp_set_default.
2937 name from @gp_set_instance to @gp_set_default.
2912
2938
2913 * IPython/ipmaker.py (make_IPython): default editor value set to
2939 * IPython/ipmaker.py (make_IPython): default editor value set to
2914 '0' (a string), to match the rc file. Otherwise will crash when
2940 '0' (a string), to match the rc file. Otherwise will crash when
2915 .strip() is called on it.
2941 .strip() is called on it.
2916
2942
2917
2943
2918 2002-06-28 Fernando Perez <fperez@colorado.edu>
2944 2002-06-28 Fernando Perez <fperez@colorado.edu>
2919
2945
2920 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2946 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2921 of files in current directory when a file is executed via
2947 of files in current directory when a file is executed via
2922 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2948 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2923
2949
2924 * setup.py (manfiles): fix for rpm builds, submitted by RA
2950 * setup.py (manfiles): fix for rpm builds, submitted by RA
2925 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2951 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2926
2952
2927 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2953 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2928 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2954 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2929 string!). A. Schmolck caught this one.
2955 string!). A. Schmolck caught this one.
2930
2956
2931 2002-06-27 Fernando Perez <fperez@colorado.edu>
2957 2002-06-27 Fernando Perez <fperez@colorado.edu>
2932
2958
2933 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2959 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2934 defined files at the cmd line. __name__ wasn't being set to
2960 defined files at the cmd line. __name__ wasn't being set to
2935 __main__.
2961 __main__.
2936
2962
2937 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2963 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2938 regular lists and tuples besides Numeric arrays.
2964 regular lists and tuples besides Numeric arrays.
2939
2965
2940 * IPython/Prompts.py (CachedOutput.__call__): Added output
2966 * IPython/Prompts.py (CachedOutput.__call__): Added output
2941 supression for input ending with ';'. Similar to Mathematica and
2967 supression for input ending with ';'. Similar to Mathematica and
2942 Matlab. The _* vars and Out[] list are still updated, just like
2968 Matlab. The _* vars and Out[] list are still updated, just like
2943 Mathematica behaves.
2969 Mathematica behaves.
2944
2970
2945 2002-06-25 Fernando Perez <fperez@colorado.edu>
2971 2002-06-25 Fernando Perez <fperez@colorado.edu>
2946
2972
2947 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2973 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2948 .ini extensions for profiels under Windows.
2974 .ini extensions for profiels under Windows.
2949
2975
2950 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2976 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2951 string form. Fix contributed by Alexander Schmolck
2977 string form. Fix contributed by Alexander Schmolck
2952 <a.schmolck-AT-gmx.net>
2978 <a.schmolck-AT-gmx.net>
2953
2979
2954 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2980 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2955 pre-configured Gnuplot instance.
2981 pre-configured Gnuplot instance.
2956
2982
2957 2002-06-21 Fernando Perez <fperez@colorado.edu>
2983 2002-06-21 Fernando Perez <fperez@colorado.edu>
2958
2984
2959 * IPython/numutils.py (exp_safe): new function, works around the
2985 * IPython/numutils.py (exp_safe): new function, works around the
2960 underflow problems in Numeric.
2986 underflow problems in Numeric.
2961 (log2): New fn. Safe log in base 2: returns exact integer answer
2987 (log2): New fn. Safe log in base 2: returns exact integer answer
2962 for exact integer powers of 2.
2988 for exact integer powers of 2.
2963
2989
2964 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2990 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2965 properly.
2991 properly.
2966
2992
2967 2002-06-20 Fernando Perez <fperez@colorado.edu>
2993 2002-06-20 Fernando Perez <fperez@colorado.edu>
2968
2994
2969 * IPython/genutils.py (timing): new function like
2995 * IPython/genutils.py (timing): new function like
2970 Mathematica's. Similar to time_test, but returns more info.
2996 Mathematica's. Similar to time_test, but returns more info.
2971
2997
2972 2002-06-18 Fernando Perez <fperez@colorado.edu>
2998 2002-06-18 Fernando Perez <fperez@colorado.edu>
2973
2999
2974 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3000 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2975 according to Mike Heeter's suggestions.
3001 according to Mike Heeter's suggestions.
2976
3002
2977 2002-06-16 Fernando Perez <fperez@colorado.edu>
3003 2002-06-16 Fernando Perez <fperez@colorado.edu>
2978
3004
2979 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3005 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2980 system. GnuplotMagic is gone as a user-directory option. New files
3006 system. GnuplotMagic is gone as a user-directory option. New files
2981 make it easier to use all the gnuplot stuff both from external
3007 make it easier to use all the gnuplot stuff both from external
2982 programs as well as from IPython. Had to rewrite part of
3008 programs as well as from IPython. Had to rewrite part of
2983 hardcopy() b/c of a strange bug: often the ps files simply don't
3009 hardcopy() b/c of a strange bug: often the ps files simply don't
2984 get created, and require a repeat of the command (often several
3010 get created, and require a repeat of the command (often several
2985 times).
3011 times).
2986
3012
2987 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3013 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2988 resolve output channel at call time, so that if sys.stderr has
3014 resolve output channel at call time, so that if sys.stderr has
2989 been redirected by user this gets honored.
3015 been redirected by user this gets honored.
2990
3016
2991 2002-06-13 Fernando Perez <fperez@colorado.edu>
3017 2002-06-13 Fernando Perez <fperez@colorado.edu>
2992
3018
2993 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3019 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2994 IPShell. Kept a copy with the old names to avoid breaking people's
3020 IPShell. Kept a copy with the old names to avoid breaking people's
2995 embedded code.
3021 embedded code.
2996
3022
2997 * IPython/ipython: simplified it to the bare minimum after
3023 * IPython/ipython: simplified it to the bare minimum after
2998 Holger's suggestions. Added info about how to use it in
3024 Holger's suggestions. Added info about how to use it in
2999 PYTHONSTARTUP.
3025 PYTHONSTARTUP.
3000
3026
3001 * IPython/Shell.py (IPythonShell): changed the options passing
3027 * IPython/Shell.py (IPythonShell): changed the options passing
3002 from a string with funky %s replacements to a straight list. Maybe
3028 from a string with funky %s replacements to a straight list. Maybe
3003 a bit more typing, but it follows sys.argv conventions, so there's
3029 a bit more typing, but it follows sys.argv conventions, so there's
3004 less special-casing to remember.
3030 less special-casing to remember.
3005
3031
3006 2002-06-12 Fernando Perez <fperez@colorado.edu>
3032 2002-06-12 Fernando Perez <fperez@colorado.edu>
3007
3033
3008 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3034 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3009 command. Thanks to a suggestion by Mike Heeter.
3035 command. Thanks to a suggestion by Mike Heeter.
3010 (Magic.magic_pfile): added behavior to look at filenames if given
3036 (Magic.magic_pfile): added behavior to look at filenames if given
3011 arg is not a defined object.
3037 arg is not a defined object.
3012 (Magic.magic_save): New @save function to save code snippets. Also
3038 (Magic.magic_save): New @save function to save code snippets. Also
3013 a Mike Heeter idea.
3039 a Mike Heeter idea.
3014
3040
3015 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3041 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3016 plot() and replot(). Much more convenient now, especially for
3042 plot() and replot(). Much more convenient now, especially for
3017 interactive use.
3043 interactive use.
3018
3044
3019 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3045 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3020 filenames.
3046 filenames.
3021
3047
3022 2002-06-02 Fernando Perez <fperez@colorado.edu>
3048 2002-06-02 Fernando Perez <fperez@colorado.edu>
3023
3049
3024 * IPython/Struct.py (Struct.__init__): modified to admit
3050 * IPython/Struct.py (Struct.__init__): modified to admit
3025 initialization via another struct.
3051 initialization via another struct.
3026
3052
3027 * IPython/genutils.py (SystemExec.__init__): New stateful
3053 * IPython/genutils.py (SystemExec.__init__): New stateful
3028 interface to xsys and bq. Useful for writing system scripts.
3054 interface to xsys and bq. Useful for writing system scripts.
3029
3055
3030 2002-05-30 Fernando Perez <fperez@colorado.edu>
3056 2002-05-30 Fernando Perez <fperez@colorado.edu>
3031
3057
3032 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3058 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3033 documents. This will make the user download smaller (it's getting
3059 documents. This will make the user download smaller (it's getting
3034 too big).
3060 too big).
3035
3061
3036 2002-05-29 Fernando Perez <fperez@colorado.edu>
3062 2002-05-29 Fernando Perez <fperez@colorado.edu>
3037
3063
3038 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3064 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3039 fix problems with shelve and pickle. Seems to work, but I don't
3065 fix problems with shelve and pickle. Seems to work, but I don't
3040 know if corner cases break it. Thanks to Mike Heeter
3066 know if corner cases break it. Thanks to Mike Heeter
3041 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3067 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3042
3068
3043 2002-05-24 Fernando Perez <fperez@colorado.edu>
3069 2002-05-24 Fernando Perez <fperez@colorado.edu>
3044
3070
3045 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3071 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3046 macros having broken.
3072 macros having broken.
3047
3073
3048 2002-05-21 Fernando Perez <fperez@colorado.edu>
3074 2002-05-21 Fernando Perez <fperez@colorado.edu>
3049
3075
3050 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3076 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3051 introduced logging bug: all history before logging started was
3077 introduced logging bug: all history before logging started was
3052 being written one character per line! This came from the redesign
3078 being written one character per line! This came from the redesign
3053 of the input history as a special list which slices to strings,
3079 of the input history as a special list which slices to strings,
3054 not to lists.
3080 not to lists.
3055
3081
3056 2002-05-20 Fernando Perez <fperez@colorado.edu>
3082 2002-05-20 Fernando Perez <fperez@colorado.edu>
3057
3083
3058 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3084 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3059 be an attribute of all classes in this module. The design of these
3085 be an attribute of all classes in this module. The design of these
3060 classes needs some serious overhauling.
3086 classes needs some serious overhauling.
3061
3087
3062 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3088 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3063 which was ignoring '_' in option names.
3089 which was ignoring '_' in option names.
3064
3090
3065 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3091 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3066 'Verbose_novars' to 'Context' and made it the new default. It's a
3092 'Verbose_novars' to 'Context' and made it the new default. It's a
3067 bit more readable and also safer than verbose.
3093 bit more readable and also safer than verbose.
3068
3094
3069 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3095 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3070 triple-quoted strings.
3096 triple-quoted strings.
3071
3097
3072 * IPython/OInspect.py (__all__): new module exposing the object
3098 * IPython/OInspect.py (__all__): new module exposing the object
3073 introspection facilities. Now the corresponding magics are dummy
3099 introspection facilities. Now the corresponding magics are dummy
3074 wrappers around this. Having this module will make it much easier
3100 wrappers around this. Having this module will make it much easier
3075 to put these functions into our modified pdb.
3101 to put these functions into our modified pdb.
3076 This new object inspector system uses the new colorizing module,
3102 This new object inspector system uses the new colorizing module,
3077 so source code and other things are nicely syntax highlighted.
3103 so source code and other things are nicely syntax highlighted.
3078
3104
3079 2002-05-18 Fernando Perez <fperez@colorado.edu>
3105 2002-05-18 Fernando Perez <fperez@colorado.edu>
3080
3106
3081 * IPython/ColorANSI.py: Split the coloring tools into a separate
3107 * IPython/ColorANSI.py: Split the coloring tools into a separate
3082 module so I can use them in other code easier (they were part of
3108 module so I can use them in other code easier (they were part of
3083 ultraTB).
3109 ultraTB).
3084
3110
3085 2002-05-17 Fernando Perez <fperez@colorado.edu>
3111 2002-05-17 Fernando Perez <fperez@colorado.edu>
3086
3112
3087 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3113 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3088 fixed it to set the global 'g' also to the called instance, as
3114 fixed it to set the global 'g' also to the called instance, as
3089 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3115 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3090 user's 'g' variables).
3116 user's 'g' variables).
3091
3117
3092 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3118 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3093 global variables (aliases to _ih,_oh) so that users which expect
3119 global variables (aliases to _ih,_oh) so that users which expect
3094 In[5] or Out[7] to work aren't unpleasantly surprised.
3120 In[5] or Out[7] to work aren't unpleasantly surprised.
3095 (InputList.__getslice__): new class to allow executing slices of
3121 (InputList.__getslice__): new class to allow executing slices of
3096 input history directly. Very simple class, complements the use of
3122 input history directly. Very simple class, complements the use of
3097 macros.
3123 macros.
3098
3124
3099 2002-05-16 Fernando Perez <fperez@colorado.edu>
3125 2002-05-16 Fernando Perez <fperez@colorado.edu>
3100
3126
3101 * setup.py (docdirbase): make doc directory be just doc/IPython
3127 * setup.py (docdirbase): make doc directory be just doc/IPython
3102 without version numbers, it will reduce clutter for users.
3128 without version numbers, it will reduce clutter for users.
3103
3129
3104 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3130 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3105 execfile call to prevent possible memory leak. See for details:
3131 execfile call to prevent possible memory leak. See for details:
3106 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3132 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3107
3133
3108 2002-05-15 Fernando Perez <fperez@colorado.edu>
3134 2002-05-15 Fernando Perez <fperez@colorado.edu>
3109
3135
3110 * IPython/Magic.py (Magic.magic_psource): made the object
3136 * IPython/Magic.py (Magic.magic_psource): made the object
3111 introspection names be more standard: pdoc, pdef, pfile and
3137 introspection names be more standard: pdoc, pdef, pfile and
3112 psource. They all print/page their output, and it makes
3138 psource. They all print/page their output, and it makes
3113 remembering them easier. Kept old names for compatibility as
3139 remembering them easier. Kept old names for compatibility as
3114 aliases.
3140 aliases.
3115
3141
3116 2002-05-14 Fernando Perez <fperez@colorado.edu>
3142 2002-05-14 Fernando Perez <fperez@colorado.edu>
3117
3143
3118 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3144 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3119 what the mouse problem was. The trick is to use gnuplot with temp
3145 what the mouse problem was. The trick is to use gnuplot with temp
3120 files and NOT with pipes (for data communication), because having
3146 files and NOT with pipes (for data communication), because having
3121 both pipes and the mouse on is bad news.
3147 both pipes and the mouse on is bad news.
3122
3148
3123 2002-05-13 Fernando Perez <fperez@colorado.edu>
3149 2002-05-13 Fernando Perez <fperez@colorado.edu>
3124
3150
3125 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3151 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3126 bug. Information would be reported about builtins even when
3152 bug. Information would be reported about builtins even when
3127 user-defined functions overrode them.
3153 user-defined functions overrode them.
3128
3154
3129 2002-05-11 Fernando Perez <fperez@colorado.edu>
3155 2002-05-11 Fernando Perez <fperez@colorado.edu>
3130
3156
3131 * IPython/__init__.py (__all__): removed FlexCompleter from
3157 * IPython/__init__.py (__all__): removed FlexCompleter from
3132 __all__ so that things don't fail in platforms without readline.
3158 __all__ so that things don't fail in platforms without readline.
3133
3159
3134 2002-05-10 Fernando Perez <fperez@colorado.edu>
3160 2002-05-10 Fernando Perez <fperez@colorado.edu>
3135
3161
3136 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3162 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3137 it requires Numeric, effectively making Numeric a dependency for
3163 it requires Numeric, effectively making Numeric a dependency for
3138 IPython.
3164 IPython.
3139
3165
3140 * Released 0.2.13
3166 * Released 0.2.13
3141
3167
3142 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3168 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3143 profiler interface. Now all the major options from the profiler
3169 profiler interface. Now all the major options from the profiler
3144 module are directly supported in IPython, both for single
3170 module are directly supported in IPython, both for single
3145 expressions (@prun) and for full programs (@run -p).
3171 expressions (@prun) and for full programs (@run -p).
3146
3172
3147 2002-05-09 Fernando Perez <fperez@colorado.edu>
3173 2002-05-09 Fernando Perez <fperez@colorado.edu>
3148
3174
3149 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3175 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3150 magic properly formatted for screen.
3176 magic properly formatted for screen.
3151
3177
3152 * setup.py (make_shortcut): Changed things to put pdf version in
3178 * setup.py (make_shortcut): Changed things to put pdf version in
3153 doc/ instead of doc/manual (had to change lyxport a bit).
3179 doc/ instead of doc/manual (had to change lyxport a bit).
3154
3180
3155 * IPython/Magic.py (Profile.string_stats): made profile runs go
3181 * IPython/Magic.py (Profile.string_stats): made profile runs go
3156 through pager (they are long and a pager allows searching, saving,
3182 through pager (they are long and a pager allows searching, saving,
3157 etc.)
3183 etc.)
3158
3184
3159 2002-05-08 Fernando Perez <fperez@colorado.edu>
3185 2002-05-08 Fernando Perez <fperez@colorado.edu>
3160
3186
3161 * Released 0.2.12
3187 * Released 0.2.12
3162
3188
3163 2002-05-06 Fernando Perez <fperez@colorado.edu>
3189 2002-05-06 Fernando Perez <fperez@colorado.edu>
3164
3190
3165 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3191 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3166 introduced); 'hist n1 n2' was broken.
3192 introduced); 'hist n1 n2' was broken.
3167 (Magic.magic_pdb): added optional on/off arguments to @pdb
3193 (Magic.magic_pdb): added optional on/off arguments to @pdb
3168 (Magic.magic_run): added option -i to @run, which executes code in
3194 (Magic.magic_run): added option -i to @run, which executes code in
3169 the IPython namespace instead of a clean one. Also added @irun as
3195 the IPython namespace instead of a clean one. Also added @irun as
3170 an alias to @run -i.
3196 an alias to @run -i.
3171
3197
3172 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3198 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3173 fixed (it didn't really do anything, the namespaces were wrong).
3199 fixed (it didn't really do anything, the namespaces were wrong).
3174
3200
3175 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3201 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3176
3202
3177 * IPython/__init__.py (__all__): Fixed package namespace, now
3203 * IPython/__init__.py (__all__): Fixed package namespace, now
3178 'import IPython' does give access to IPython.<all> as
3204 'import IPython' does give access to IPython.<all> as
3179 expected. Also renamed __release__ to Release.
3205 expected. Also renamed __release__ to Release.
3180
3206
3181 * IPython/Debugger.py (__license__): created new Pdb class which
3207 * IPython/Debugger.py (__license__): created new Pdb class which
3182 functions like a drop-in for the normal pdb.Pdb but does NOT
3208 functions like a drop-in for the normal pdb.Pdb but does NOT
3183 import readline by default. This way it doesn't muck up IPython's
3209 import readline by default. This way it doesn't muck up IPython's
3184 readline handling, and now tab-completion finally works in the
3210 readline handling, and now tab-completion finally works in the
3185 debugger -- sort of. It completes things globally visible, but the
3211 debugger -- sort of. It completes things globally visible, but the
3186 completer doesn't track the stack as pdb walks it. That's a bit
3212 completer doesn't track the stack as pdb walks it. That's a bit
3187 tricky, and I'll have to implement it later.
3213 tricky, and I'll have to implement it later.
3188
3214
3189 2002-05-05 Fernando Perez <fperez@colorado.edu>
3215 2002-05-05 Fernando Perez <fperez@colorado.edu>
3190
3216
3191 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3217 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3192 magic docstrings when printed via ? (explicit \'s were being
3218 magic docstrings when printed via ? (explicit \'s were being
3193 printed).
3219 printed).
3194
3220
3195 * IPython/ipmaker.py (make_IPython): fixed namespace
3221 * IPython/ipmaker.py (make_IPython): fixed namespace
3196 identification bug. Now variables loaded via logs or command-line
3222 identification bug. Now variables loaded via logs or command-line
3197 files are recognized in the interactive namespace by @who.
3223 files are recognized in the interactive namespace by @who.
3198
3224
3199 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3225 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3200 log replay system stemming from the string form of Structs.
3226 log replay system stemming from the string form of Structs.
3201
3227
3202 * IPython/Magic.py (Macro.__init__): improved macros to properly
3228 * IPython/Magic.py (Macro.__init__): improved macros to properly
3203 handle magic commands in them.
3229 handle magic commands in them.
3204 (Magic.magic_logstart): usernames are now expanded so 'logstart
3230 (Magic.magic_logstart): usernames are now expanded so 'logstart
3205 ~/mylog' now works.
3231 ~/mylog' now works.
3206
3232
3207 * IPython/iplib.py (complete): fixed bug where paths starting with
3233 * IPython/iplib.py (complete): fixed bug where paths starting with
3208 '/' would be completed as magic names.
3234 '/' would be completed as magic names.
3209
3235
3210 2002-05-04 Fernando Perez <fperez@colorado.edu>
3236 2002-05-04 Fernando Perez <fperez@colorado.edu>
3211
3237
3212 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3238 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3213 allow running full programs under the profiler's control.
3239 allow running full programs under the profiler's control.
3214
3240
3215 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3241 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3216 mode to report exceptions verbosely but without formatting
3242 mode to report exceptions verbosely but without formatting
3217 variables. This addresses the issue of ipython 'freezing' (it's
3243 variables. This addresses the issue of ipython 'freezing' (it's
3218 not frozen, but caught in an expensive formatting loop) when huge
3244 not frozen, but caught in an expensive formatting loop) when huge
3219 variables are in the context of an exception.
3245 variables are in the context of an exception.
3220 (VerboseTB.text): Added '--->' markers at line where exception was
3246 (VerboseTB.text): Added '--->' markers at line where exception was
3221 triggered. Much clearer to read, especially in NoColor modes.
3247 triggered. Much clearer to read, especially in NoColor modes.
3222
3248
3223 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3249 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3224 implemented in reverse when changing to the new parse_options().
3250 implemented in reverse when changing to the new parse_options().
3225
3251
3226 2002-05-03 Fernando Perez <fperez@colorado.edu>
3252 2002-05-03 Fernando Perez <fperez@colorado.edu>
3227
3253
3228 * IPython/Magic.py (Magic.parse_options): new function so that
3254 * IPython/Magic.py (Magic.parse_options): new function so that
3229 magics can parse options easier.
3255 magics can parse options easier.
3230 (Magic.magic_prun): new function similar to profile.run(),
3256 (Magic.magic_prun): new function similar to profile.run(),
3231 suggested by Chris Hart.
3257 suggested by Chris Hart.
3232 (Magic.magic_cd): fixed behavior so that it only changes if
3258 (Magic.magic_cd): fixed behavior so that it only changes if
3233 directory actually is in history.
3259 directory actually is in history.
3234
3260
3235 * IPython/usage.py (__doc__): added information about potential
3261 * IPython/usage.py (__doc__): added information about potential
3236 slowness of Verbose exception mode when there are huge data
3262 slowness of Verbose exception mode when there are huge data
3237 structures to be formatted (thanks to Archie Paulson).
3263 structures to be formatted (thanks to Archie Paulson).
3238
3264
3239 * IPython/ipmaker.py (make_IPython): Changed default logging
3265 * IPython/ipmaker.py (make_IPython): Changed default logging
3240 (when simply called with -log) to use curr_dir/ipython.log in
3266 (when simply called with -log) to use curr_dir/ipython.log in
3241 rotate mode. Fixed crash which was occuring with -log before
3267 rotate mode. Fixed crash which was occuring with -log before
3242 (thanks to Jim Boyle).
3268 (thanks to Jim Boyle).
3243
3269
3244 2002-05-01 Fernando Perez <fperez@colorado.edu>
3270 2002-05-01 Fernando Perez <fperez@colorado.edu>
3245
3271
3246 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3272 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3247 was nasty -- though somewhat of a corner case).
3273 was nasty -- though somewhat of a corner case).
3248
3274
3249 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3275 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3250 text (was a bug).
3276 text (was a bug).
3251
3277
3252 2002-04-30 Fernando Perez <fperez@colorado.edu>
3278 2002-04-30 Fernando Perez <fperez@colorado.edu>
3253
3279
3254 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3280 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3255 a print after ^D or ^C from the user so that the In[] prompt
3281 a print after ^D or ^C from the user so that the In[] prompt
3256 doesn't over-run the gnuplot one.
3282 doesn't over-run the gnuplot one.
3257
3283
3258 2002-04-29 Fernando Perez <fperez@colorado.edu>
3284 2002-04-29 Fernando Perez <fperez@colorado.edu>
3259
3285
3260 * Released 0.2.10
3286 * Released 0.2.10
3261
3287
3262 * IPython/__release__.py (version): get date dynamically.
3288 * IPython/__release__.py (version): get date dynamically.
3263
3289
3264 * Misc. documentation updates thanks to Arnd's comments. Also ran
3290 * Misc. documentation updates thanks to Arnd's comments. Also ran
3265 a full spellcheck on the manual (hadn't been done in a while).
3291 a full spellcheck on the manual (hadn't been done in a while).
3266
3292
3267 2002-04-27 Fernando Perez <fperez@colorado.edu>
3293 2002-04-27 Fernando Perez <fperez@colorado.edu>
3268
3294
3269 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3295 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3270 starting a log in mid-session would reset the input history list.
3296 starting a log in mid-session would reset the input history list.
3271
3297
3272 2002-04-26 Fernando Perez <fperez@colorado.edu>
3298 2002-04-26 Fernando Perez <fperez@colorado.edu>
3273
3299
3274 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3300 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3275 all files were being included in an update. Now anything in
3301 all files were being included in an update. Now anything in
3276 UserConfig that matches [A-Za-z]*.py will go (this excludes
3302 UserConfig that matches [A-Za-z]*.py will go (this excludes
3277 __init__.py)
3303 __init__.py)
3278
3304
3279 2002-04-25 Fernando Perez <fperez@colorado.edu>
3305 2002-04-25 Fernando Perez <fperez@colorado.edu>
3280
3306
3281 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3307 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3282 to __builtins__ so that any form of embedded or imported code can
3308 to __builtins__ so that any form of embedded or imported code can
3283 test for being inside IPython.
3309 test for being inside IPython.
3284
3310
3285 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3311 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3286 changed to GnuplotMagic because it's now an importable module,
3312 changed to GnuplotMagic because it's now an importable module,
3287 this makes the name follow that of the standard Gnuplot module.
3313 this makes the name follow that of the standard Gnuplot module.
3288 GnuplotMagic can now be loaded at any time in mid-session.
3314 GnuplotMagic can now be loaded at any time in mid-session.
3289
3315
3290 2002-04-24 Fernando Perez <fperez@colorado.edu>
3316 2002-04-24 Fernando Perez <fperez@colorado.edu>
3291
3317
3292 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3318 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3293 the globals (IPython has its own namespace) and the
3319 the globals (IPython has its own namespace) and the
3294 PhysicalQuantity stuff is much better anyway.
3320 PhysicalQuantity stuff is much better anyway.
3295
3321
3296 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3322 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3297 embedding example to standard user directory for
3323 embedding example to standard user directory for
3298 distribution. Also put it in the manual.
3324 distribution. Also put it in the manual.
3299
3325
3300 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3326 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3301 instance as first argument (so it doesn't rely on some obscure
3327 instance as first argument (so it doesn't rely on some obscure
3302 hidden global).
3328 hidden global).
3303
3329
3304 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3330 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3305 delimiters. While it prevents ().TAB from working, it allows
3331 delimiters. While it prevents ().TAB from working, it allows
3306 completions in open (... expressions. This is by far a more common
3332 completions in open (... expressions. This is by far a more common
3307 case.
3333 case.
3308
3334
3309 2002-04-23 Fernando Perez <fperez@colorado.edu>
3335 2002-04-23 Fernando Perez <fperez@colorado.edu>
3310
3336
3311 * IPython/Extensions/InterpreterPasteInput.py: new
3337 * IPython/Extensions/InterpreterPasteInput.py: new
3312 syntax-processing module for pasting lines with >>> or ... at the
3338 syntax-processing module for pasting lines with >>> or ... at the
3313 start.
3339 start.
3314
3340
3315 * IPython/Extensions/PhysicalQ_Interactive.py
3341 * IPython/Extensions/PhysicalQ_Interactive.py
3316 (PhysicalQuantityInteractive.__int__): fixed to work with either
3342 (PhysicalQuantityInteractive.__int__): fixed to work with either
3317 Numeric or math.
3343 Numeric or math.
3318
3344
3319 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3345 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3320 provided profiles. Now we have:
3346 provided profiles. Now we have:
3321 -math -> math module as * and cmath with its own namespace.
3347 -math -> math module as * and cmath with its own namespace.
3322 -numeric -> Numeric as *, plus gnuplot & grace
3348 -numeric -> Numeric as *, plus gnuplot & grace
3323 -physics -> same as before
3349 -physics -> same as before
3324
3350
3325 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3351 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3326 user-defined magics wouldn't be found by @magic if they were
3352 user-defined magics wouldn't be found by @magic if they were
3327 defined as class methods. Also cleaned up the namespace search
3353 defined as class methods. Also cleaned up the namespace search
3328 logic and the string building (to use %s instead of many repeated
3354 logic and the string building (to use %s instead of many repeated
3329 string adds).
3355 string adds).
3330
3356
3331 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3357 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3332 of user-defined magics to operate with class methods (cleaner, in
3358 of user-defined magics to operate with class methods (cleaner, in
3333 line with the gnuplot code).
3359 line with the gnuplot code).
3334
3360
3335 2002-04-22 Fernando Perez <fperez@colorado.edu>
3361 2002-04-22 Fernando Perez <fperez@colorado.edu>
3336
3362
3337 * setup.py: updated dependency list so that manual is updated when
3363 * setup.py: updated dependency list so that manual is updated when
3338 all included files change.
3364 all included files change.
3339
3365
3340 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3366 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3341 the delimiter removal option (the fix is ugly right now).
3367 the delimiter removal option (the fix is ugly right now).
3342
3368
3343 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3369 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3344 all of the math profile (quicker loading, no conflict between
3370 all of the math profile (quicker loading, no conflict between
3345 g-9.8 and g-gnuplot).
3371 g-9.8 and g-gnuplot).
3346
3372
3347 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3373 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3348 name of post-mortem files to IPython_crash_report.txt.
3374 name of post-mortem files to IPython_crash_report.txt.
3349
3375
3350 * Cleanup/update of the docs. Added all the new readline info and
3376 * Cleanup/update of the docs. Added all the new readline info and
3351 formatted all lists as 'real lists'.
3377 formatted all lists as 'real lists'.
3352
3378
3353 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3379 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3354 tab-completion options, since the full readline parse_and_bind is
3380 tab-completion options, since the full readline parse_and_bind is
3355 now accessible.
3381 now accessible.
3356
3382
3357 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3383 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3358 handling of readline options. Now users can specify any string to
3384 handling of readline options. Now users can specify any string to
3359 be passed to parse_and_bind(), as well as the delimiters to be
3385 be passed to parse_and_bind(), as well as the delimiters to be
3360 removed.
3386 removed.
3361 (InteractiveShell.__init__): Added __name__ to the global
3387 (InteractiveShell.__init__): Added __name__ to the global
3362 namespace so that things like Itpl which rely on its existence
3388 namespace so that things like Itpl which rely on its existence
3363 don't crash.
3389 don't crash.
3364 (InteractiveShell._prefilter): Defined the default with a _ so
3390 (InteractiveShell._prefilter): Defined the default with a _ so
3365 that prefilter() is easier to override, while the default one
3391 that prefilter() is easier to override, while the default one
3366 remains available.
3392 remains available.
3367
3393
3368 2002-04-18 Fernando Perez <fperez@colorado.edu>
3394 2002-04-18 Fernando Perez <fperez@colorado.edu>
3369
3395
3370 * Added information about pdb in the docs.
3396 * Added information about pdb in the docs.
3371
3397
3372 2002-04-17 Fernando Perez <fperez@colorado.edu>
3398 2002-04-17 Fernando Perez <fperez@colorado.edu>
3373
3399
3374 * IPython/ipmaker.py (make_IPython): added rc_override option to
3400 * IPython/ipmaker.py (make_IPython): added rc_override option to
3375 allow passing config options at creation time which may override
3401 allow passing config options at creation time which may override
3376 anything set in the config files or command line. This is
3402 anything set in the config files or command line. This is
3377 particularly useful for configuring embedded instances.
3403 particularly useful for configuring embedded instances.
3378
3404
3379 2002-04-15 Fernando Perez <fperez@colorado.edu>
3405 2002-04-15 Fernando Perez <fperez@colorado.edu>
3380
3406
3381 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3407 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3382 crash embedded instances because of the input cache falling out of
3408 crash embedded instances because of the input cache falling out of
3383 sync with the output counter.
3409 sync with the output counter.
3384
3410
3385 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3411 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3386 mode which calls pdb after an uncaught exception in IPython itself.
3412 mode which calls pdb after an uncaught exception in IPython itself.
3387
3413
3388 2002-04-14 Fernando Perez <fperez@colorado.edu>
3414 2002-04-14 Fernando Perez <fperez@colorado.edu>
3389
3415
3390 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3416 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3391 readline, fix it back after each call.
3417 readline, fix it back after each call.
3392
3418
3393 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3419 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3394 method to force all access via __call__(), which guarantees that
3420 method to force all access via __call__(), which guarantees that
3395 traceback references are properly deleted.
3421 traceback references are properly deleted.
3396
3422
3397 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3423 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3398 improve printing when pprint is in use.
3424 improve printing when pprint is in use.
3399
3425
3400 2002-04-13 Fernando Perez <fperez@colorado.edu>
3426 2002-04-13 Fernando Perez <fperez@colorado.edu>
3401
3427
3402 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3428 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3403 exceptions aren't caught anymore. If the user triggers one, he
3429 exceptions aren't caught anymore. If the user triggers one, he
3404 should know why he's doing it and it should go all the way up,
3430 should know why he's doing it and it should go all the way up,
3405 just like any other exception. So now @abort will fully kill the
3431 just like any other exception. So now @abort will fully kill the
3406 embedded interpreter and the embedding code (unless that happens
3432 embedded interpreter and the embedding code (unless that happens
3407 to catch SystemExit).
3433 to catch SystemExit).
3408
3434
3409 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3435 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3410 and a debugger() method to invoke the interactive pdb debugger
3436 and a debugger() method to invoke the interactive pdb debugger
3411 after printing exception information. Also added the corresponding
3437 after printing exception information. Also added the corresponding
3412 -pdb option and @pdb magic to control this feature, and updated
3438 -pdb option and @pdb magic to control this feature, and updated
3413 the docs. After a suggestion from Christopher Hart
3439 the docs. After a suggestion from Christopher Hart
3414 (hart-AT-caltech.edu).
3440 (hart-AT-caltech.edu).
3415
3441
3416 2002-04-12 Fernando Perez <fperez@colorado.edu>
3442 2002-04-12 Fernando Perez <fperez@colorado.edu>
3417
3443
3418 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3444 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3419 the exception handlers defined by the user (not the CrashHandler)
3445 the exception handlers defined by the user (not the CrashHandler)
3420 so that user exceptions don't trigger an ipython bug report.
3446 so that user exceptions don't trigger an ipython bug report.
3421
3447
3422 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3448 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3423 configurable (it should have always been so).
3449 configurable (it should have always been so).
3424
3450
3425 2002-03-26 Fernando Perez <fperez@colorado.edu>
3451 2002-03-26 Fernando Perez <fperez@colorado.edu>
3426
3452
3427 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3453 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3428 and there to fix embedding namespace issues. This should all be
3454 and there to fix embedding namespace issues. This should all be
3429 done in a more elegant way.
3455 done in a more elegant way.
3430
3456
3431 2002-03-25 Fernando Perez <fperez@colorado.edu>
3457 2002-03-25 Fernando Perez <fperez@colorado.edu>
3432
3458
3433 * IPython/genutils.py (get_home_dir): Try to make it work under
3459 * IPython/genutils.py (get_home_dir): Try to make it work under
3434 win9x also.
3460 win9x also.
3435
3461
3436 2002-03-20 Fernando Perez <fperez@colorado.edu>
3462 2002-03-20 Fernando Perez <fperez@colorado.edu>
3437
3463
3438 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3464 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3439 sys.displayhook untouched upon __init__.
3465 sys.displayhook untouched upon __init__.
3440
3466
3441 2002-03-19 Fernando Perez <fperez@colorado.edu>
3467 2002-03-19 Fernando Perez <fperez@colorado.edu>
3442
3468
3443 * Released 0.2.9 (for embedding bug, basically).
3469 * Released 0.2.9 (for embedding bug, basically).
3444
3470
3445 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3471 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3446 exceptions so that enclosing shell's state can be restored.
3472 exceptions so that enclosing shell's state can be restored.
3447
3473
3448 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3474 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3449 naming conventions in the .ipython/ dir.
3475 naming conventions in the .ipython/ dir.
3450
3476
3451 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3477 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3452 from delimiters list so filenames with - in them get expanded.
3478 from delimiters list so filenames with - in them get expanded.
3453
3479
3454 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3480 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3455 sys.displayhook not being properly restored after an embedded call.
3481 sys.displayhook not being properly restored after an embedded call.
3456
3482
3457 2002-03-18 Fernando Perez <fperez@colorado.edu>
3483 2002-03-18 Fernando Perez <fperez@colorado.edu>
3458
3484
3459 * Released 0.2.8
3485 * Released 0.2.8
3460
3486
3461 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3487 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3462 some files weren't being included in a -upgrade.
3488 some files weren't being included in a -upgrade.
3463 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3489 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3464 on' so that the first tab completes.
3490 on' so that the first tab completes.
3465 (InteractiveShell.handle_magic): fixed bug with spaces around
3491 (InteractiveShell.handle_magic): fixed bug with spaces around
3466 quotes breaking many magic commands.
3492 quotes breaking many magic commands.
3467
3493
3468 * setup.py: added note about ignoring the syntax error messages at
3494 * setup.py: added note about ignoring the syntax error messages at
3469 installation.
3495 installation.
3470
3496
3471 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3497 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3472 streamlining the gnuplot interface, now there's only one magic @gp.
3498 streamlining the gnuplot interface, now there's only one magic @gp.
3473
3499
3474 2002-03-17 Fernando Perez <fperez@colorado.edu>
3500 2002-03-17 Fernando Perez <fperez@colorado.edu>
3475
3501
3476 * IPython/UserConfig/magic_gnuplot.py: new name for the
3502 * IPython/UserConfig/magic_gnuplot.py: new name for the
3477 example-magic_pm.py file. Much enhanced system, now with a shell
3503 example-magic_pm.py file. Much enhanced system, now with a shell
3478 for communicating directly with gnuplot, one command at a time.
3504 for communicating directly with gnuplot, one command at a time.
3479
3505
3480 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3506 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3481 setting __name__=='__main__'.
3507 setting __name__=='__main__'.
3482
3508
3483 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3509 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3484 mini-shell for accessing gnuplot from inside ipython. Should
3510 mini-shell for accessing gnuplot from inside ipython. Should
3485 extend it later for grace access too. Inspired by Arnd's
3511 extend it later for grace access too. Inspired by Arnd's
3486 suggestion.
3512 suggestion.
3487
3513
3488 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3514 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3489 calling magic functions with () in their arguments. Thanks to Arnd
3515 calling magic functions with () in their arguments. Thanks to Arnd
3490 Baecker for pointing this to me.
3516 Baecker for pointing this to me.
3491
3517
3492 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3518 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3493 infinitely for integer or complex arrays (only worked with floats).
3519 infinitely for integer or complex arrays (only worked with floats).
3494
3520
3495 2002-03-16 Fernando Perez <fperez@colorado.edu>
3521 2002-03-16 Fernando Perez <fperez@colorado.edu>
3496
3522
3497 * setup.py: Merged setup and setup_windows into a single script
3523 * setup.py: Merged setup and setup_windows into a single script
3498 which properly handles things for windows users.
3524 which properly handles things for windows users.
3499
3525
3500 2002-03-15 Fernando Perez <fperez@colorado.edu>
3526 2002-03-15 Fernando Perez <fperez@colorado.edu>
3501
3527
3502 * Big change to the manual: now the magics are all automatically
3528 * Big change to the manual: now the magics are all automatically
3503 documented. This information is generated from their docstrings
3529 documented. This information is generated from their docstrings
3504 and put in a latex file included by the manual lyx file. This way
3530 and put in a latex file included by the manual lyx file. This way
3505 we get always up to date information for the magics. The manual
3531 we get always up to date information for the magics. The manual
3506 now also has proper version information, also auto-synced.
3532 now also has proper version information, also auto-synced.
3507
3533
3508 For this to work, an undocumented --magic_docstrings option was added.
3534 For this to work, an undocumented --magic_docstrings option was added.
3509
3535
3510 2002-03-13 Fernando Perez <fperez@colorado.edu>
3536 2002-03-13 Fernando Perez <fperez@colorado.edu>
3511
3537
3512 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3538 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3513 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3539 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3514
3540
3515 2002-03-12 Fernando Perez <fperez@colorado.edu>
3541 2002-03-12 Fernando Perez <fperez@colorado.edu>
3516
3542
3517 * IPython/ultraTB.py (TermColors): changed color escapes again to
3543 * IPython/ultraTB.py (TermColors): changed color escapes again to
3518 fix the (old, reintroduced) line-wrapping bug. Basically, if
3544 fix the (old, reintroduced) line-wrapping bug. Basically, if
3519 \001..\002 aren't given in the color escapes, lines get wrapped
3545 \001..\002 aren't given in the color escapes, lines get wrapped
3520 weirdly. But giving those screws up old xterms and emacs terms. So
3546 weirdly. But giving those screws up old xterms and emacs terms. So
3521 I added some logic for emacs terms to be ok, but I can't identify old
3547 I added some logic for emacs terms to be ok, but I can't identify old
3522 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3548 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3523
3549
3524 2002-03-10 Fernando Perez <fperez@colorado.edu>
3550 2002-03-10 Fernando Perez <fperez@colorado.edu>
3525
3551
3526 * IPython/usage.py (__doc__): Various documentation cleanups and
3552 * IPython/usage.py (__doc__): Various documentation cleanups and
3527 updates, both in usage docstrings and in the manual.
3553 updates, both in usage docstrings and in the manual.
3528
3554
3529 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3555 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3530 handling of caching. Set minimum acceptabe value for having a
3556 handling of caching. Set minimum acceptabe value for having a
3531 cache at 20 values.
3557 cache at 20 values.
3532
3558
3533 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3559 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3534 install_first_time function to a method, renamed it and added an
3560 install_first_time function to a method, renamed it and added an
3535 'upgrade' mode. Now people can update their config directory with
3561 'upgrade' mode. Now people can update their config directory with
3536 a simple command line switch (-upgrade, also new).
3562 a simple command line switch (-upgrade, also new).
3537
3563
3538 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3564 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3539 @file (convenient for automagic users under Python >= 2.2).
3565 @file (convenient for automagic users under Python >= 2.2).
3540 Removed @files (it seemed more like a plural than an abbrev. of
3566 Removed @files (it seemed more like a plural than an abbrev. of
3541 'file show').
3567 'file show').
3542
3568
3543 * IPython/iplib.py (install_first_time): Fixed crash if there were
3569 * IPython/iplib.py (install_first_time): Fixed crash if there were
3544 backup files ('~') in .ipython/ install directory.
3570 backup files ('~') in .ipython/ install directory.
3545
3571
3546 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3572 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3547 system. Things look fine, but these changes are fairly
3573 system. Things look fine, but these changes are fairly
3548 intrusive. Test them for a few days.
3574 intrusive. Test them for a few days.
3549
3575
3550 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3576 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3551 the prompts system. Now all in/out prompt strings are user
3577 the prompts system. Now all in/out prompt strings are user
3552 controllable. This is particularly useful for embedding, as one
3578 controllable. This is particularly useful for embedding, as one
3553 can tag embedded instances with particular prompts.
3579 can tag embedded instances with particular prompts.
3554
3580
3555 Also removed global use of sys.ps1/2, which now allows nested
3581 Also removed global use of sys.ps1/2, which now allows nested
3556 embeddings without any problems. Added command-line options for
3582 embeddings without any problems. Added command-line options for
3557 the prompt strings.
3583 the prompt strings.
3558
3584
3559 2002-03-08 Fernando Perez <fperez@colorado.edu>
3585 2002-03-08 Fernando Perez <fperez@colorado.edu>
3560
3586
3561 * IPython/UserConfig/example-embed-short.py (ipshell): added
3587 * IPython/UserConfig/example-embed-short.py (ipshell): added
3562 example file with the bare minimum code for embedding.
3588 example file with the bare minimum code for embedding.
3563
3589
3564 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3590 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3565 functionality for the embeddable shell to be activated/deactivated
3591 functionality for the embeddable shell to be activated/deactivated
3566 either globally or at each call.
3592 either globally or at each call.
3567
3593
3568 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3594 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3569 rewriting the prompt with '--->' for auto-inputs with proper
3595 rewriting the prompt with '--->' for auto-inputs with proper
3570 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3596 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3571 this is handled by the prompts class itself, as it should.
3597 this is handled by the prompts class itself, as it should.
3572
3598
3573 2002-03-05 Fernando Perez <fperez@colorado.edu>
3599 2002-03-05 Fernando Perez <fperez@colorado.edu>
3574
3600
3575 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3601 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3576 @logstart to avoid name clashes with the math log function.
3602 @logstart to avoid name clashes with the math log function.
3577
3603
3578 * Big updates to X/Emacs section of the manual.
3604 * Big updates to X/Emacs section of the manual.
3579
3605
3580 * Removed ipython_emacs. Milan explained to me how to pass
3606 * Removed ipython_emacs. Milan explained to me how to pass
3581 arguments to ipython through Emacs. Some day I'm going to end up
3607 arguments to ipython through Emacs. Some day I'm going to end up
3582 learning some lisp...
3608 learning some lisp...
3583
3609
3584 2002-03-04 Fernando Perez <fperez@colorado.edu>
3610 2002-03-04 Fernando Perez <fperez@colorado.edu>
3585
3611
3586 * IPython/ipython_emacs: Created script to be used as the
3612 * IPython/ipython_emacs: Created script to be used as the
3587 py-python-command Emacs variable so we can pass IPython
3613 py-python-command Emacs variable so we can pass IPython
3588 parameters. I can't figure out how to tell Emacs directly to pass
3614 parameters. I can't figure out how to tell Emacs directly to pass
3589 parameters to IPython, so a dummy shell script will do it.
3615 parameters to IPython, so a dummy shell script will do it.
3590
3616
3591 Other enhancements made for things to work better under Emacs'
3617 Other enhancements made for things to work better under Emacs'
3592 various types of terminals. Many thanks to Milan Zamazal
3618 various types of terminals. Many thanks to Milan Zamazal
3593 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3619 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3594
3620
3595 2002-03-01 Fernando Perez <fperez@colorado.edu>
3621 2002-03-01 Fernando Perez <fperez@colorado.edu>
3596
3622
3597 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3623 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3598 that loading of readline is now optional. This gives better
3624 that loading of readline is now optional. This gives better
3599 control to emacs users.
3625 control to emacs users.
3600
3626
3601 * IPython/ultraTB.py (__date__): Modified color escape sequences
3627 * IPython/ultraTB.py (__date__): Modified color escape sequences
3602 and now things work fine under xterm and in Emacs' term buffers
3628 and now things work fine under xterm and in Emacs' term buffers
3603 (though not shell ones). Well, in emacs you get colors, but all
3629 (though not shell ones). Well, in emacs you get colors, but all
3604 seem to be 'light' colors (no difference between dark and light
3630 seem to be 'light' colors (no difference between dark and light
3605 ones). But the garbage chars are gone, and also in xterms. It
3631 ones). But the garbage chars are gone, and also in xterms. It
3606 seems that now I'm using 'cleaner' ansi sequences.
3632 seems that now I'm using 'cleaner' ansi sequences.
3607
3633
3608 2002-02-21 Fernando Perez <fperez@colorado.edu>
3634 2002-02-21 Fernando Perez <fperez@colorado.edu>
3609
3635
3610 * Released 0.2.7 (mainly to publish the scoping fix).
3636 * Released 0.2.7 (mainly to publish the scoping fix).
3611
3637
3612 * IPython/Logger.py (Logger.logstate): added. A corresponding
3638 * IPython/Logger.py (Logger.logstate): added. A corresponding
3613 @logstate magic was created.
3639 @logstate magic was created.
3614
3640
3615 * IPython/Magic.py: fixed nested scoping problem under Python
3641 * IPython/Magic.py: fixed nested scoping problem under Python
3616 2.1.x (automagic wasn't working).
3642 2.1.x (automagic wasn't working).
3617
3643
3618 2002-02-20 Fernando Perez <fperez@colorado.edu>
3644 2002-02-20 Fernando Perez <fperez@colorado.edu>
3619
3645
3620 * Released 0.2.6.
3646 * Released 0.2.6.
3621
3647
3622 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3648 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3623 option so that logs can come out without any headers at all.
3649 option so that logs can come out without any headers at all.
3624
3650
3625 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3651 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3626 SciPy.
3652 SciPy.
3627
3653
3628 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3654 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3629 that embedded IPython calls don't require vars() to be explicitly
3655 that embedded IPython calls don't require vars() to be explicitly
3630 passed. Now they are extracted from the caller's frame (code
3656 passed. Now they are extracted from the caller's frame (code
3631 snatched from Eric Jones' weave). Added better documentation to
3657 snatched from Eric Jones' weave). Added better documentation to
3632 the section on embedding and the example file.
3658 the section on embedding and the example file.
3633
3659
3634 * IPython/genutils.py (page): Changed so that under emacs, it just
3660 * IPython/genutils.py (page): Changed so that under emacs, it just
3635 prints the string. You can then page up and down in the emacs
3661 prints the string. You can then page up and down in the emacs
3636 buffer itself. This is how the builtin help() works.
3662 buffer itself. This is how the builtin help() works.
3637
3663
3638 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3664 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3639 macro scoping: macros need to be executed in the user's namespace
3665 macro scoping: macros need to be executed in the user's namespace
3640 to work as if they had been typed by the user.
3666 to work as if they had been typed by the user.
3641
3667
3642 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3668 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3643 execute automatically (no need to type 'exec...'). They then
3669 execute automatically (no need to type 'exec...'). They then
3644 behave like 'true macros'. The printing system was also modified
3670 behave like 'true macros'. The printing system was also modified
3645 for this to work.
3671 for this to work.
3646
3672
3647 2002-02-19 Fernando Perez <fperez@colorado.edu>
3673 2002-02-19 Fernando Perez <fperez@colorado.edu>
3648
3674
3649 * IPython/genutils.py (page_file): new function for paging files
3675 * IPython/genutils.py (page_file): new function for paging files
3650 in an OS-independent way. Also necessary for file viewing to work
3676 in an OS-independent way. Also necessary for file viewing to work
3651 well inside Emacs buffers.
3677 well inside Emacs buffers.
3652 (page): Added checks for being in an emacs buffer.
3678 (page): Added checks for being in an emacs buffer.
3653 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3679 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3654 same bug in iplib.
3680 same bug in iplib.
3655
3681
3656 2002-02-18 Fernando Perez <fperez@colorado.edu>
3682 2002-02-18 Fernando Perez <fperez@colorado.edu>
3657
3683
3658 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3684 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3659 of readline so that IPython can work inside an Emacs buffer.
3685 of readline so that IPython can work inside an Emacs buffer.
3660
3686
3661 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3687 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3662 method signatures (they weren't really bugs, but it looks cleaner
3688 method signatures (they weren't really bugs, but it looks cleaner
3663 and keeps PyChecker happy).
3689 and keeps PyChecker happy).
3664
3690
3665 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3691 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3666 for implementing various user-defined hooks. Currently only
3692 for implementing various user-defined hooks. Currently only
3667 display is done.
3693 display is done.
3668
3694
3669 * IPython/Prompts.py (CachedOutput._display): changed display
3695 * IPython/Prompts.py (CachedOutput._display): changed display
3670 functions so that they can be dynamically changed by users easily.
3696 functions so that they can be dynamically changed by users easily.
3671
3697
3672 * IPython/Extensions/numeric_formats.py (num_display): added an
3698 * IPython/Extensions/numeric_formats.py (num_display): added an
3673 extension for printing NumPy arrays in flexible manners. It
3699 extension for printing NumPy arrays in flexible manners. It
3674 doesn't do anything yet, but all the structure is in
3700 doesn't do anything yet, but all the structure is in
3675 place. Ultimately the plan is to implement output format control
3701 place. Ultimately the plan is to implement output format control
3676 like in Octave.
3702 like in Octave.
3677
3703
3678 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3704 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3679 methods are found at run-time by all the automatic machinery.
3705 methods are found at run-time by all the automatic machinery.
3680
3706
3681 2002-02-17 Fernando Perez <fperez@colorado.edu>
3707 2002-02-17 Fernando Perez <fperez@colorado.edu>
3682
3708
3683 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3709 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3684 whole file a little.
3710 whole file a little.
3685
3711
3686 * ToDo: closed this document. Now there's a new_design.lyx
3712 * ToDo: closed this document. Now there's a new_design.lyx
3687 document for all new ideas. Added making a pdf of it for the
3713 document for all new ideas. Added making a pdf of it for the
3688 end-user distro.
3714 end-user distro.
3689
3715
3690 * IPython/Logger.py (Logger.switch_log): Created this to replace
3716 * IPython/Logger.py (Logger.switch_log): Created this to replace
3691 logon() and logoff(). It also fixes a nasty crash reported by
3717 logon() and logoff(). It also fixes a nasty crash reported by
3692 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3718 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3693
3719
3694 * IPython/iplib.py (complete): got auto-completion to work with
3720 * IPython/iplib.py (complete): got auto-completion to work with
3695 automagic (I had wanted this for a long time).
3721 automagic (I had wanted this for a long time).
3696
3722
3697 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3723 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3698 to @file, since file() is now a builtin and clashes with automagic
3724 to @file, since file() is now a builtin and clashes with automagic
3699 for @file.
3725 for @file.
3700
3726
3701 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3727 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3702 of this was previously in iplib, which had grown to more than 2000
3728 of this was previously in iplib, which had grown to more than 2000
3703 lines, way too long. No new functionality, but it makes managing
3729 lines, way too long. No new functionality, but it makes managing
3704 the code a bit easier.
3730 the code a bit easier.
3705
3731
3706 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3732 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3707 information to crash reports.
3733 information to crash reports.
3708
3734
3709 2002-02-12 Fernando Perez <fperez@colorado.edu>
3735 2002-02-12 Fernando Perez <fperez@colorado.edu>
3710
3736
3711 * Released 0.2.5.
3737 * Released 0.2.5.
3712
3738
3713 2002-02-11 Fernando Perez <fperez@colorado.edu>
3739 2002-02-11 Fernando Perez <fperez@colorado.edu>
3714
3740
3715 * Wrote a relatively complete Windows installer. It puts
3741 * Wrote a relatively complete Windows installer. It puts
3716 everything in place, creates Start Menu entries and fixes the
3742 everything in place, creates Start Menu entries and fixes the
3717 color issues. Nothing fancy, but it works.
3743 color issues. Nothing fancy, but it works.
3718
3744
3719 2002-02-10 Fernando Perez <fperez@colorado.edu>
3745 2002-02-10 Fernando Perez <fperez@colorado.edu>
3720
3746
3721 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3747 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3722 os.path.expanduser() call so that we can type @run ~/myfile.py and
3748 os.path.expanduser() call so that we can type @run ~/myfile.py and
3723 have thigs work as expected.
3749 have thigs work as expected.
3724
3750
3725 * IPython/genutils.py (page): fixed exception handling so things
3751 * IPython/genutils.py (page): fixed exception handling so things
3726 work both in Unix and Windows correctly. Quitting a pager triggers
3752 work both in Unix and Windows correctly. Quitting a pager triggers
3727 an IOError/broken pipe in Unix, and in windows not finding a pager
3753 an IOError/broken pipe in Unix, and in windows not finding a pager
3728 is also an IOError, so I had to actually look at the return value
3754 is also an IOError, so I had to actually look at the return value
3729 of the exception, not just the exception itself. Should be ok now.
3755 of the exception, not just the exception itself. Should be ok now.
3730
3756
3731 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3757 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3732 modified to allow case-insensitive color scheme changes.
3758 modified to allow case-insensitive color scheme changes.
3733
3759
3734 2002-02-09 Fernando Perez <fperez@colorado.edu>
3760 2002-02-09 Fernando Perez <fperez@colorado.edu>
3735
3761
3736 * IPython/genutils.py (native_line_ends): new function to leave
3762 * IPython/genutils.py (native_line_ends): new function to leave
3737 user config files with os-native line-endings.
3763 user config files with os-native line-endings.
3738
3764
3739 * README and manual updates.
3765 * README and manual updates.
3740
3766
3741 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3767 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3742 instead of StringType to catch Unicode strings.
3768 instead of StringType to catch Unicode strings.
3743
3769
3744 * IPython/genutils.py (filefind): fixed bug for paths with
3770 * IPython/genutils.py (filefind): fixed bug for paths with
3745 embedded spaces (very common in Windows).
3771 embedded spaces (very common in Windows).
3746
3772
3747 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3773 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3748 files under Windows, so that they get automatically associated
3774 files under Windows, so that they get automatically associated
3749 with a text editor. Windows makes it a pain to handle
3775 with a text editor. Windows makes it a pain to handle
3750 extension-less files.
3776 extension-less files.
3751
3777
3752 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3778 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3753 warning about readline only occur for Posix. In Windows there's no
3779 warning about readline only occur for Posix. In Windows there's no
3754 way to get readline, so why bother with the warning.
3780 way to get readline, so why bother with the warning.
3755
3781
3756 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3782 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3757 for __str__ instead of dir(self), since dir() changed in 2.2.
3783 for __str__ instead of dir(self), since dir() changed in 2.2.
3758
3784
3759 * Ported to Windows! Tested on XP, I suspect it should work fine
3785 * Ported to Windows! Tested on XP, I suspect it should work fine
3760 on NT/2000, but I don't think it will work on 98 et al. That
3786 on NT/2000, but I don't think it will work on 98 et al. That
3761 series of Windows is such a piece of junk anyway that I won't try
3787 series of Windows is such a piece of junk anyway that I won't try
3762 porting it there. The XP port was straightforward, showed a few
3788 porting it there. The XP port was straightforward, showed a few
3763 bugs here and there (fixed all), in particular some string
3789 bugs here and there (fixed all), in particular some string
3764 handling stuff which required considering Unicode strings (which
3790 handling stuff which required considering Unicode strings (which
3765 Windows uses). This is good, but hasn't been too tested :) No
3791 Windows uses). This is good, but hasn't been too tested :) No
3766 fancy installer yet, I'll put a note in the manual so people at
3792 fancy installer yet, I'll put a note in the manual so people at
3767 least make manually a shortcut.
3793 least make manually a shortcut.
3768
3794
3769 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3795 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3770 into a single one, "colors". This now controls both prompt and
3796 into a single one, "colors". This now controls both prompt and
3771 exception color schemes, and can be changed both at startup
3797 exception color schemes, and can be changed both at startup
3772 (either via command-line switches or via ipythonrc files) and at
3798 (either via command-line switches or via ipythonrc files) and at
3773 runtime, with @colors.
3799 runtime, with @colors.
3774 (Magic.magic_run): renamed @prun to @run and removed the old
3800 (Magic.magic_run): renamed @prun to @run and removed the old
3775 @run. The two were too similar to warrant keeping both.
3801 @run. The two were too similar to warrant keeping both.
3776
3802
3777 2002-02-03 Fernando Perez <fperez@colorado.edu>
3803 2002-02-03 Fernando Perez <fperez@colorado.edu>
3778
3804
3779 * IPython/iplib.py (install_first_time): Added comment on how to
3805 * IPython/iplib.py (install_first_time): Added comment on how to
3780 configure the color options for first-time users. Put a <return>
3806 configure the color options for first-time users. Put a <return>
3781 request at the end so that small-terminal users get a chance to
3807 request at the end so that small-terminal users get a chance to
3782 read the startup info.
3808 read the startup info.
3783
3809
3784 2002-01-23 Fernando Perez <fperez@colorado.edu>
3810 2002-01-23 Fernando Perez <fperez@colorado.edu>
3785
3811
3786 * IPython/iplib.py (CachedOutput.update): Changed output memory
3812 * IPython/iplib.py (CachedOutput.update): Changed output memory
3787 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3813 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3788 input history we still use _i. Did this b/c these variable are
3814 input history we still use _i. Did this b/c these variable are
3789 very commonly used in interactive work, so the less we need to
3815 very commonly used in interactive work, so the less we need to
3790 type the better off we are.
3816 type the better off we are.
3791 (Magic.magic_prun): updated @prun to better handle the namespaces
3817 (Magic.magic_prun): updated @prun to better handle the namespaces
3792 the file will run in, including a fix for __name__ not being set
3818 the file will run in, including a fix for __name__ not being set
3793 before.
3819 before.
3794
3820
3795 2002-01-20 Fernando Perez <fperez@colorado.edu>
3821 2002-01-20 Fernando Perez <fperez@colorado.edu>
3796
3822
3797 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3823 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3798 extra garbage for Python 2.2. Need to look more carefully into
3824 extra garbage for Python 2.2. Need to look more carefully into
3799 this later.
3825 this later.
3800
3826
3801 2002-01-19 Fernando Perez <fperez@colorado.edu>
3827 2002-01-19 Fernando Perez <fperez@colorado.edu>
3802
3828
3803 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3829 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3804 display SyntaxError exceptions properly formatted when they occur
3830 display SyntaxError exceptions properly formatted when they occur
3805 (they can be triggered by imported code).
3831 (they can be triggered by imported code).
3806
3832
3807 2002-01-18 Fernando Perez <fperez@colorado.edu>
3833 2002-01-18 Fernando Perez <fperez@colorado.edu>
3808
3834
3809 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3835 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3810 SyntaxError exceptions are reported nicely formatted, instead of
3836 SyntaxError exceptions are reported nicely formatted, instead of
3811 spitting out only offset information as before.
3837 spitting out only offset information as before.
3812 (Magic.magic_prun): Added the @prun function for executing
3838 (Magic.magic_prun): Added the @prun function for executing
3813 programs with command line args inside IPython.
3839 programs with command line args inside IPython.
3814
3840
3815 2002-01-16 Fernando Perez <fperez@colorado.edu>
3841 2002-01-16 Fernando Perez <fperez@colorado.edu>
3816
3842
3817 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3843 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3818 to *not* include the last item given in a range. This brings their
3844 to *not* include the last item given in a range. This brings their
3819 behavior in line with Python's slicing:
3845 behavior in line with Python's slicing:
3820 a[n1:n2] -> a[n1]...a[n2-1]
3846 a[n1:n2] -> a[n1]...a[n2-1]
3821 It may be a bit less convenient, but I prefer to stick to Python's
3847 It may be a bit less convenient, but I prefer to stick to Python's
3822 conventions *everywhere*, so users never have to wonder.
3848 conventions *everywhere*, so users never have to wonder.
3823 (Magic.magic_macro): Added @macro function to ease the creation of
3849 (Magic.magic_macro): Added @macro function to ease the creation of
3824 macros.
3850 macros.
3825
3851
3826 2002-01-05 Fernando Perez <fperez@colorado.edu>
3852 2002-01-05 Fernando Perez <fperez@colorado.edu>
3827
3853
3828 * Released 0.2.4.
3854 * Released 0.2.4.
3829
3855
3830 * IPython/iplib.py (Magic.magic_pdef):
3856 * IPython/iplib.py (Magic.magic_pdef):
3831 (InteractiveShell.safe_execfile): report magic lines and error
3857 (InteractiveShell.safe_execfile): report magic lines and error
3832 lines without line numbers so one can easily copy/paste them for
3858 lines without line numbers so one can easily copy/paste them for
3833 re-execution.
3859 re-execution.
3834
3860
3835 * Updated manual with recent changes.
3861 * Updated manual with recent changes.
3836
3862
3837 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3863 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3838 docstring printing when class? is called. Very handy for knowing
3864 docstring printing when class? is called. Very handy for knowing
3839 how to create class instances (as long as __init__ is well
3865 how to create class instances (as long as __init__ is well
3840 documented, of course :)
3866 documented, of course :)
3841 (Magic.magic_doc): print both class and constructor docstrings.
3867 (Magic.magic_doc): print both class and constructor docstrings.
3842 (Magic.magic_pdef): give constructor info if passed a class and
3868 (Magic.magic_pdef): give constructor info if passed a class and
3843 __call__ info for callable object instances.
3869 __call__ info for callable object instances.
3844
3870
3845 2002-01-04 Fernando Perez <fperez@colorado.edu>
3871 2002-01-04 Fernando Perez <fperez@colorado.edu>
3846
3872
3847 * Made deep_reload() off by default. It doesn't always work
3873 * Made deep_reload() off by default. It doesn't always work
3848 exactly as intended, so it's probably safer to have it off. It's
3874 exactly as intended, so it's probably safer to have it off. It's
3849 still available as dreload() anyway, so nothing is lost.
3875 still available as dreload() anyway, so nothing is lost.
3850
3876
3851 2002-01-02 Fernando Perez <fperez@colorado.edu>
3877 2002-01-02 Fernando Perez <fperez@colorado.edu>
3852
3878
3853 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3879 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3854 so I wanted an updated release).
3880 so I wanted an updated release).
3855
3881
3856 2001-12-27 Fernando Perez <fperez@colorado.edu>
3882 2001-12-27 Fernando Perez <fperez@colorado.edu>
3857
3883
3858 * IPython/iplib.py (InteractiveShell.interact): Added the original
3884 * IPython/iplib.py (InteractiveShell.interact): Added the original
3859 code from 'code.py' for this module in order to change the
3885 code from 'code.py' for this module in order to change the
3860 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3886 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3861 the history cache would break when the user hit Ctrl-C, and
3887 the history cache would break when the user hit Ctrl-C, and
3862 interact() offers no way to add any hooks to it.
3888 interact() offers no way to add any hooks to it.
3863
3889
3864 2001-12-23 Fernando Perez <fperez@colorado.edu>
3890 2001-12-23 Fernando Perez <fperez@colorado.edu>
3865
3891
3866 * setup.py: added check for 'MANIFEST' before trying to remove
3892 * setup.py: added check for 'MANIFEST' before trying to remove
3867 it. Thanks to Sean Reifschneider.
3893 it. Thanks to Sean Reifschneider.
3868
3894
3869 2001-12-22 Fernando Perez <fperez@colorado.edu>
3895 2001-12-22 Fernando Perez <fperez@colorado.edu>
3870
3896
3871 * Released 0.2.2.
3897 * Released 0.2.2.
3872
3898
3873 * Finished (reasonably) writing the manual. Later will add the
3899 * Finished (reasonably) writing the manual. Later will add the
3874 python-standard navigation stylesheets, but for the time being
3900 python-standard navigation stylesheets, but for the time being
3875 it's fairly complete. Distribution will include html and pdf
3901 it's fairly complete. Distribution will include html and pdf
3876 versions.
3902 versions.
3877
3903
3878 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3904 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3879 (MayaVi author).
3905 (MayaVi author).
3880
3906
3881 2001-12-21 Fernando Perez <fperez@colorado.edu>
3907 2001-12-21 Fernando Perez <fperez@colorado.edu>
3882
3908
3883 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3909 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3884 good public release, I think (with the manual and the distutils
3910 good public release, I think (with the manual and the distutils
3885 installer). The manual can use some work, but that can go
3911 installer). The manual can use some work, but that can go
3886 slowly. Otherwise I think it's quite nice for end users. Next
3912 slowly. Otherwise I think it's quite nice for end users. Next
3887 summer, rewrite the guts of it...
3913 summer, rewrite the guts of it...
3888
3914
3889 * Changed format of ipythonrc files to use whitespace as the
3915 * Changed format of ipythonrc files to use whitespace as the
3890 separator instead of an explicit '='. Cleaner.
3916 separator instead of an explicit '='. Cleaner.
3891
3917
3892 2001-12-20 Fernando Perez <fperez@colorado.edu>
3918 2001-12-20 Fernando Perez <fperez@colorado.edu>
3893
3919
3894 * Started a manual in LyX. For now it's just a quick merge of the
3920 * Started a manual in LyX. For now it's just a quick merge of the
3895 various internal docstrings and READMEs. Later it may grow into a
3921 various internal docstrings and READMEs. Later it may grow into a
3896 nice, full-blown manual.
3922 nice, full-blown manual.
3897
3923
3898 * Set up a distutils based installer. Installation should now be
3924 * Set up a distutils based installer. Installation should now be
3899 trivially simple for end-users.
3925 trivially simple for end-users.
3900
3926
3901 2001-12-11 Fernando Perez <fperez@colorado.edu>
3927 2001-12-11 Fernando Perez <fperez@colorado.edu>
3902
3928
3903 * Released 0.2.0. First public release, announced it at
3929 * Released 0.2.0. First public release, announced it at
3904 comp.lang.python. From now on, just bugfixes...
3930 comp.lang.python. From now on, just bugfixes...
3905
3931
3906 * Went through all the files, set copyright/license notices and
3932 * Went through all the files, set copyright/license notices and
3907 cleaned up things. Ready for release.
3933 cleaned up things. Ready for release.
3908
3934
3909 2001-12-10 Fernando Perez <fperez@colorado.edu>
3935 2001-12-10 Fernando Perez <fperez@colorado.edu>
3910
3936
3911 * Changed the first-time installer not to use tarfiles. It's more
3937 * Changed the first-time installer not to use tarfiles. It's more
3912 robust now and less unix-dependent. Also makes it easier for
3938 robust now and less unix-dependent. Also makes it easier for
3913 people to later upgrade versions.
3939 people to later upgrade versions.
3914
3940
3915 * Changed @exit to @abort to reflect the fact that it's pretty
3941 * Changed @exit to @abort to reflect the fact that it's pretty
3916 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3942 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3917 becomes significant only when IPyhton is embedded: in that case,
3943 becomes significant only when IPyhton is embedded: in that case,
3918 C-D closes IPython only, but @abort kills the enclosing program
3944 C-D closes IPython only, but @abort kills the enclosing program
3919 too (unless it had called IPython inside a try catching
3945 too (unless it had called IPython inside a try catching
3920 SystemExit).
3946 SystemExit).
3921
3947
3922 * Created Shell module which exposes the actuall IPython Shell
3948 * Created Shell module which exposes the actuall IPython Shell
3923 classes, currently the normal and the embeddable one. This at
3949 classes, currently the normal and the embeddable one. This at
3924 least offers a stable interface we won't need to change when
3950 least offers a stable interface we won't need to change when
3925 (later) the internals are rewritten. That rewrite will be confined
3951 (later) the internals are rewritten. That rewrite will be confined
3926 to iplib and ipmaker, but the Shell interface should remain as is.
3952 to iplib and ipmaker, but the Shell interface should remain as is.
3927
3953
3928 * Added embed module which offers an embeddable IPShell object,
3954 * Added embed module which offers an embeddable IPShell object,
3929 useful to fire up IPython *inside* a running program. Great for
3955 useful to fire up IPython *inside* a running program. Great for
3930 debugging or dynamical data analysis.
3956 debugging or dynamical data analysis.
3931
3957
3932 2001-12-08 Fernando Perez <fperez@colorado.edu>
3958 2001-12-08 Fernando Perez <fperez@colorado.edu>
3933
3959
3934 * Fixed small bug preventing seeing info from methods of defined
3960 * Fixed small bug preventing seeing info from methods of defined
3935 objects (incorrect namespace in _ofind()).
3961 objects (incorrect namespace in _ofind()).
3936
3962
3937 * Documentation cleanup. Moved the main usage docstrings to a
3963 * Documentation cleanup. Moved the main usage docstrings to a
3938 separate file, usage.py (cleaner to maintain, and hopefully in the
3964 separate file, usage.py (cleaner to maintain, and hopefully in the
3939 future some perlpod-like way of producing interactive, man and
3965 future some perlpod-like way of producing interactive, man and
3940 html docs out of it will be found).
3966 html docs out of it will be found).
3941
3967
3942 * Added @profile to see your profile at any time.
3968 * Added @profile to see your profile at any time.
3943
3969
3944 * Added @p as an alias for 'print'. It's especially convenient if
3970 * Added @p as an alias for 'print'. It's especially convenient if
3945 using automagic ('p x' prints x).
3971 using automagic ('p x' prints x).
3946
3972
3947 * Small cleanups and fixes after a pychecker run.
3973 * Small cleanups and fixes after a pychecker run.
3948
3974
3949 * Changed the @cd command to handle @cd - and @cd -<n> for
3975 * Changed the @cd command to handle @cd - and @cd -<n> for
3950 visiting any directory in _dh.
3976 visiting any directory in _dh.
3951
3977
3952 * Introduced _dh, a history of visited directories. @dhist prints
3978 * Introduced _dh, a history of visited directories. @dhist prints
3953 it out with numbers.
3979 it out with numbers.
3954
3980
3955 2001-12-07 Fernando Perez <fperez@colorado.edu>
3981 2001-12-07 Fernando Perez <fperez@colorado.edu>
3956
3982
3957 * Released 0.1.22
3983 * Released 0.1.22
3958
3984
3959 * Made initialization a bit more robust against invalid color
3985 * Made initialization a bit more robust against invalid color
3960 options in user input (exit, not traceback-crash).
3986 options in user input (exit, not traceback-crash).
3961
3987
3962 * Changed the bug crash reporter to write the report only in the
3988 * Changed the bug crash reporter to write the report only in the
3963 user's .ipython directory. That way IPython won't litter people's
3989 user's .ipython directory. That way IPython won't litter people's
3964 hard disks with crash files all over the place. Also print on
3990 hard disks with crash files all over the place. Also print on
3965 screen the necessary mail command.
3991 screen the necessary mail command.
3966
3992
3967 * With the new ultraTB, implemented LightBG color scheme for light
3993 * With the new ultraTB, implemented LightBG color scheme for light
3968 background terminals. A lot of people like white backgrounds, so I
3994 background terminals. A lot of people like white backgrounds, so I
3969 guess we should at least give them something readable.
3995 guess we should at least give them something readable.
3970
3996
3971 2001-12-06 Fernando Perez <fperez@colorado.edu>
3997 2001-12-06 Fernando Perez <fperez@colorado.edu>
3972
3998
3973 * Modified the structure of ultraTB. Now there's a proper class
3999 * Modified the structure of ultraTB. Now there's a proper class
3974 for tables of color schemes which allow adding schemes easily and
4000 for tables of color schemes which allow adding schemes easily and
3975 switching the active scheme without creating a new instance every
4001 switching the active scheme without creating a new instance every
3976 time (which was ridiculous). The syntax for creating new schemes
4002 time (which was ridiculous). The syntax for creating new schemes
3977 is also cleaner. I think ultraTB is finally done, with a clean
4003 is also cleaner. I think ultraTB is finally done, with a clean
3978 class structure. Names are also much cleaner (now there's proper
4004 class structure. Names are also much cleaner (now there's proper
3979 color tables, no need for every variable to also have 'color' in
4005 color tables, no need for every variable to also have 'color' in
3980 its name).
4006 its name).
3981
4007
3982 * Broke down genutils into separate files. Now genutils only
4008 * Broke down genutils into separate files. Now genutils only
3983 contains utility functions, and classes have been moved to their
4009 contains utility functions, and classes have been moved to their
3984 own files (they had enough independent functionality to warrant
4010 own files (they had enough independent functionality to warrant
3985 it): ConfigLoader, OutputTrap, Struct.
4011 it): ConfigLoader, OutputTrap, Struct.
3986
4012
3987 2001-12-05 Fernando Perez <fperez@colorado.edu>
4013 2001-12-05 Fernando Perez <fperez@colorado.edu>
3988
4014
3989 * IPython turns 21! Released version 0.1.21, as a candidate for
4015 * IPython turns 21! Released version 0.1.21, as a candidate for
3990 public consumption. If all goes well, release in a few days.
4016 public consumption. If all goes well, release in a few days.
3991
4017
3992 * Fixed path bug (files in Extensions/ directory wouldn't be found
4018 * Fixed path bug (files in Extensions/ directory wouldn't be found
3993 unless IPython/ was explicitly in sys.path).
4019 unless IPython/ was explicitly in sys.path).
3994
4020
3995 * Extended the FlexCompleter class as MagicCompleter to allow
4021 * Extended the FlexCompleter class as MagicCompleter to allow
3996 completion of @-starting lines.
4022 completion of @-starting lines.
3997
4023
3998 * Created __release__.py file as a central repository for release
4024 * Created __release__.py file as a central repository for release
3999 info that other files can read from.
4025 info that other files can read from.
4000
4026
4001 * Fixed small bug in logging: when logging was turned on in
4027 * Fixed small bug in logging: when logging was turned on in
4002 mid-session, old lines with special meanings (!@?) were being
4028 mid-session, old lines with special meanings (!@?) were being
4003 logged without the prepended comment, which is necessary since
4029 logged without the prepended comment, which is necessary since
4004 they are not truly valid python syntax. This should make session
4030 they are not truly valid python syntax. This should make session
4005 restores produce less errors.
4031 restores produce less errors.
4006
4032
4007 * The namespace cleanup forced me to make a FlexCompleter class
4033 * The namespace cleanup forced me to make a FlexCompleter class
4008 which is nothing but a ripoff of rlcompleter, but with selectable
4034 which is nothing but a ripoff of rlcompleter, but with selectable
4009 namespace (rlcompleter only works in __main__.__dict__). I'll try
4035 namespace (rlcompleter only works in __main__.__dict__). I'll try
4010 to submit a note to the authors to see if this change can be
4036 to submit a note to the authors to see if this change can be
4011 incorporated in future rlcompleter releases (Dec.6: done)
4037 incorporated in future rlcompleter releases (Dec.6: done)
4012
4038
4013 * More fixes to namespace handling. It was a mess! Now all
4039 * More fixes to namespace handling. It was a mess! Now all
4014 explicit references to __main__.__dict__ are gone (except when
4040 explicit references to __main__.__dict__ are gone (except when
4015 really needed) and everything is handled through the namespace
4041 really needed) and everything is handled through the namespace
4016 dicts in the IPython instance. We seem to be getting somewhere
4042 dicts in the IPython instance. We seem to be getting somewhere
4017 with this, finally...
4043 with this, finally...
4018
4044
4019 * Small documentation updates.
4045 * Small documentation updates.
4020
4046
4021 * Created the Extensions directory under IPython (with an
4047 * Created the Extensions directory under IPython (with an
4022 __init__.py). Put the PhysicalQ stuff there. This directory should
4048 __init__.py). Put the PhysicalQ stuff there. This directory should
4023 be used for all special-purpose extensions.
4049 be used for all special-purpose extensions.
4024
4050
4025 * File renaming:
4051 * File renaming:
4026 ipythonlib --> ipmaker
4052 ipythonlib --> ipmaker
4027 ipplib --> iplib
4053 ipplib --> iplib
4028 This makes a bit more sense in terms of what these files actually do.
4054 This makes a bit more sense in terms of what these files actually do.
4029
4055
4030 * Moved all the classes and functions in ipythonlib to ipplib, so
4056 * Moved all the classes and functions in ipythonlib to ipplib, so
4031 now ipythonlib only has make_IPython(). This will ease up its
4057 now ipythonlib only has make_IPython(). This will ease up its
4032 splitting in smaller functional chunks later.
4058 splitting in smaller functional chunks later.
4033
4059
4034 * Cleaned up (done, I think) output of @whos. Better column
4060 * Cleaned up (done, I think) output of @whos. Better column
4035 formatting, and now shows str(var) for as much as it can, which is
4061 formatting, and now shows str(var) for as much as it can, which is
4036 typically what one gets with a 'print var'.
4062 typically what one gets with a 'print var'.
4037
4063
4038 2001-12-04 Fernando Perez <fperez@colorado.edu>
4064 2001-12-04 Fernando Perez <fperez@colorado.edu>
4039
4065
4040 * Fixed namespace problems. Now builtin/IPyhton/user names get
4066 * Fixed namespace problems. Now builtin/IPyhton/user names get
4041 properly reported in their namespace. Internal namespace handling
4067 properly reported in their namespace. Internal namespace handling
4042 is finally getting decent (not perfect yet, but much better than
4068 is finally getting decent (not perfect yet, but much better than
4043 the ad-hoc mess we had).
4069 the ad-hoc mess we had).
4044
4070
4045 * Removed -exit option. If people just want to run a python
4071 * Removed -exit option. If people just want to run a python
4046 script, that's what the normal interpreter is for. Less
4072 script, that's what the normal interpreter is for. Less
4047 unnecessary options, less chances for bugs.
4073 unnecessary options, less chances for bugs.
4048
4074
4049 * Added a crash handler which generates a complete post-mortem if
4075 * Added a crash handler which generates a complete post-mortem if
4050 IPython crashes. This will help a lot in tracking bugs down the
4076 IPython crashes. This will help a lot in tracking bugs down the
4051 road.
4077 road.
4052
4078
4053 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4079 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4054 which were boud to functions being reassigned would bypass the
4080 which were boud to functions being reassigned would bypass the
4055 logger, breaking the sync of _il with the prompt counter. This
4081 logger, breaking the sync of _il with the prompt counter. This
4056 would then crash IPython later when a new line was logged.
4082 would then crash IPython later when a new line was logged.
4057
4083
4058 2001-12-02 Fernando Perez <fperez@colorado.edu>
4084 2001-12-02 Fernando Perez <fperez@colorado.edu>
4059
4085
4060 * Made IPython a package. This means people don't have to clutter
4086 * Made IPython a package. This means people don't have to clutter
4061 their sys.path with yet another directory. Changed the INSTALL
4087 their sys.path with yet another directory. Changed the INSTALL
4062 file accordingly.
4088 file accordingly.
4063
4089
4064 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4090 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4065 sorts its output (so @who shows it sorted) and @whos formats the
4091 sorts its output (so @who shows it sorted) and @whos formats the
4066 table according to the width of the first column. Nicer, easier to
4092 table according to the width of the first column. Nicer, easier to
4067 read. Todo: write a generic table_format() which takes a list of
4093 read. Todo: write a generic table_format() which takes a list of
4068 lists and prints it nicely formatted, with optional row/column
4094 lists and prints it nicely formatted, with optional row/column
4069 separators and proper padding and justification.
4095 separators and proper padding and justification.
4070
4096
4071 * Released 0.1.20
4097 * Released 0.1.20
4072
4098
4073 * Fixed bug in @log which would reverse the inputcache list (a
4099 * Fixed bug in @log which would reverse the inputcache list (a
4074 copy operation was missing).
4100 copy operation was missing).
4075
4101
4076 * Code cleanup. @config was changed to use page(). Better, since
4102 * Code cleanup. @config was changed to use page(). Better, since
4077 its output is always quite long.
4103 its output is always quite long.
4078
4104
4079 * Itpl is back as a dependency. I was having too many problems
4105 * Itpl is back as a dependency. I was having too many problems
4080 getting the parametric aliases to work reliably, and it's just
4106 getting the parametric aliases to work reliably, and it's just
4081 easier to code weird string operations with it than playing %()s
4107 easier to code weird string operations with it than playing %()s
4082 games. It's only ~6k, so I don't think it's too big a deal.
4108 games. It's only ~6k, so I don't think it's too big a deal.
4083
4109
4084 * Found (and fixed) a very nasty bug with history. !lines weren't
4110 * Found (and fixed) a very nasty bug with history. !lines weren't
4085 getting cached, and the out of sync caches would crash
4111 getting cached, and the out of sync caches would crash
4086 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4112 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4087 division of labor a bit better. Bug fixed, cleaner structure.
4113 division of labor a bit better. Bug fixed, cleaner structure.
4088
4114
4089 2001-12-01 Fernando Perez <fperez@colorado.edu>
4115 2001-12-01 Fernando Perez <fperez@colorado.edu>
4090
4116
4091 * Released 0.1.19
4117 * Released 0.1.19
4092
4118
4093 * Added option -n to @hist to prevent line number printing. Much
4119 * Added option -n to @hist to prevent line number printing. Much
4094 easier to copy/paste code this way.
4120 easier to copy/paste code this way.
4095
4121
4096 * Created global _il to hold the input list. Allows easy
4122 * Created global _il to hold the input list. Allows easy
4097 re-execution of blocks of code by slicing it (inspired by Janko's
4123 re-execution of blocks of code by slicing it (inspired by Janko's
4098 comment on 'macros').
4124 comment on 'macros').
4099
4125
4100 * Small fixes and doc updates.
4126 * Small fixes and doc updates.
4101
4127
4102 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4128 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4103 much too fragile with automagic. Handles properly multi-line
4129 much too fragile with automagic. Handles properly multi-line
4104 statements and takes parameters.
4130 statements and takes parameters.
4105
4131
4106 2001-11-30 Fernando Perez <fperez@colorado.edu>
4132 2001-11-30 Fernando Perez <fperez@colorado.edu>
4107
4133
4108 * Version 0.1.18 released.
4134 * Version 0.1.18 released.
4109
4135
4110 * Fixed nasty namespace bug in initial module imports.
4136 * Fixed nasty namespace bug in initial module imports.
4111
4137
4112 * Added copyright/license notes to all code files (except
4138 * Added copyright/license notes to all code files (except
4113 DPyGetOpt). For the time being, LGPL. That could change.
4139 DPyGetOpt). For the time being, LGPL. That could change.
4114
4140
4115 * Rewrote a much nicer README, updated INSTALL, cleaned up
4141 * Rewrote a much nicer README, updated INSTALL, cleaned up
4116 ipythonrc-* samples.
4142 ipythonrc-* samples.
4117
4143
4118 * Overall code/documentation cleanup. Basically ready for
4144 * Overall code/documentation cleanup. Basically ready for
4119 release. Only remaining thing: licence decision (LGPL?).
4145 release. Only remaining thing: licence decision (LGPL?).
4120
4146
4121 * Converted load_config to a class, ConfigLoader. Now recursion
4147 * Converted load_config to a class, ConfigLoader. Now recursion
4122 control is better organized. Doesn't include the same file twice.
4148 control is better organized. Doesn't include the same file twice.
4123
4149
4124 2001-11-29 Fernando Perez <fperez@colorado.edu>
4150 2001-11-29 Fernando Perez <fperez@colorado.edu>
4125
4151
4126 * Got input history working. Changed output history variables from
4152 * Got input history working. Changed output history variables from
4127 _p to _o so that _i is for input and _o for output. Just cleaner
4153 _p to _o so that _i is for input and _o for output. Just cleaner
4128 convention.
4154 convention.
4129
4155
4130 * Implemented parametric aliases. This pretty much allows the
4156 * Implemented parametric aliases. This pretty much allows the
4131 alias system to offer full-blown shell convenience, I think.
4157 alias system to offer full-blown shell convenience, I think.
4132
4158
4133 * Version 0.1.17 released, 0.1.18 opened.
4159 * Version 0.1.17 released, 0.1.18 opened.
4134
4160
4135 * dot_ipython/ipythonrc (alias): added documentation.
4161 * dot_ipython/ipythonrc (alias): added documentation.
4136 (xcolor): Fixed small bug (xcolors -> xcolor)
4162 (xcolor): Fixed small bug (xcolors -> xcolor)
4137
4163
4138 * Changed the alias system. Now alias is a magic command to define
4164 * Changed the alias system. Now alias is a magic command to define
4139 aliases just like the shell. Rationale: the builtin magics should
4165 aliases just like the shell. Rationale: the builtin magics should
4140 be there for things deeply connected to IPython's
4166 be there for things deeply connected to IPython's
4141 architecture. And this is a much lighter system for what I think
4167 architecture. And this is a much lighter system for what I think
4142 is the really important feature: allowing users to define quickly
4168 is the really important feature: allowing users to define quickly
4143 magics that will do shell things for them, so they can customize
4169 magics that will do shell things for them, so they can customize
4144 IPython easily to match their work habits. If someone is really
4170 IPython easily to match their work habits. If someone is really
4145 desperate to have another name for a builtin alias, they can
4171 desperate to have another name for a builtin alias, they can
4146 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4172 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4147 works.
4173 works.
4148
4174
4149 2001-11-28 Fernando Perez <fperez@colorado.edu>
4175 2001-11-28 Fernando Perez <fperez@colorado.edu>
4150
4176
4151 * Changed @file so that it opens the source file at the proper
4177 * Changed @file so that it opens the source file at the proper
4152 line. Since it uses less, if your EDITOR environment is
4178 line. Since it uses less, if your EDITOR environment is
4153 configured, typing v will immediately open your editor of choice
4179 configured, typing v will immediately open your editor of choice
4154 right at the line where the object is defined. Not as quick as
4180 right at the line where the object is defined. Not as quick as
4155 having a direct @edit command, but for all intents and purposes it
4181 having a direct @edit command, but for all intents and purposes it
4156 works. And I don't have to worry about writing @edit to deal with
4182 works. And I don't have to worry about writing @edit to deal with
4157 all the editors, less does that.
4183 all the editors, less does that.
4158
4184
4159 * Version 0.1.16 released, 0.1.17 opened.
4185 * Version 0.1.16 released, 0.1.17 opened.
4160
4186
4161 * Fixed some nasty bugs in the page/page_dumb combo that could
4187 * Fixed some nasty bugs in the page/page_dumb combo that could
4162 crash IPython.
4188 crash IPython.
4163
4189
4164 2001-11-27 Fernando Perez <fperez@colorado.edu>
4190 2001-11-27 Fernando Perez <fperez@colorado.edu>
4165
4191
4166 * Version 0.1.15 released, 0.1.16 opened.
4192 * Version 0.1.15 released, 0.1.16 opened.
4167
4193
4168 * Finally got ? and ?? to work for undefined things: now it's
4194 * Finally got ? and ?? to work for undefined things: now it's
4169 possible to type {}.get? and get information about the get method
4195 possible to type {}.get? and get information about the get method
4170 of dicts, or os.path? even if only os is defined (so technically
4196 of dicts, or os.path? even if only os is defined (so technically
4171 os.path isn't). Works at any level. For example, after import os,
4197 os.path isn't). Works at any level. For example, after import os,
4172 os?, os.path?, os.path.abspath? all work. This is great, took some
4198 os?, os.path?, os.path.abspath? all work. This is great, took some
4173 work in _ofind.
4199 work in _ofind.
4174
4200
4175 * Fixed more bugs with logging. The sanest way to do it was to add
4201 * Fixed more bugs with logging. The sanest way to do it was to add
4176 to @log a 'mode' parameter. Killed two in one shot (this mode
4202 to @log a 'mode' parameter. Killed two in one shot (this mode
4177 option was a request of Janko's). I think it's finally clean
4203 option was a request of Janko's). I think it's finally clean
4178 (famous last words).
4204 (famous last words).
4179
4205
4180 * Added a page_dumb() pager which does a decent job of paging on
4206 * Added a page_dumb() pager which does a decent job of paging on
4181 screen, if better things (like less) aren't available. One less
4207 screen, if better things (like less) aren't available. One less
4182 unix dependency (someday maybe somebody will port this to
4208 unix dependency (someday maybe somebody will port this to
4183 windows).
4209 windows).
4184
4210
4185 * Fixed problem in magic_log: would lock of logging out if log
4211 * Fixed problem in magic_log: would lock of logging out if log
4186 creation failed (because it would still think it had succeeded).
4212 creation failed (because it would still think it had succeeded).
4187
4213
4188 * Improved the page() function using curses to auto-detect screen
4214 * Improved the page() function using curses to auto-detect screen
4189 size. Now it can make a much better decision on whether to print
4215 size. Now it can make a much better decision on whether to print
4190 or page a string. Option screen_length was modified: a value 0
4216 or page a string. Option screen_length was modified: a value 0
4191 means auto-detect, and that's the default now.
4217 means auto-detect, and that's the default now.
4192
4218
4193 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4219 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4194 go out. I'll test it for a few days, then talk to Janko about
4220 go out. I'll test it for a few days, then talk to Janko about
4195 licences and announce it.
4221 licences and announce it.
4196
4222
4197 * Fixed the length of the auto-generated ---> prompt which appears
4223 * Fixed the length of the auto-generated ---> prompt which appears
4198 for auto-parens and auto-quotes. Getting this right isn't trivial,
4224 for auto-parens and auto-quotes. Getting this right isn't trivial,
4199 with all the color escapes, different prompt types and optional
4225 with all the color escapes, different prompt types and optional
4200 separators. But it seems to be working in all the combinations.
4226 separators. But it seems to be working in all the combinations.
4201
4227
4202 2001-11-26 Fernando Perez <fperez@colorado.edu>
4228 2001-11-26 Fernando Perez <fperez@colorado.edu>
4203
4229
4204 * Wrote a regexp filter to get option types from the option names
4230 * Wrote a regexp filter to get option types from the option names
4205 string. This eliminates the need to manually keep two duplicate
4231 string. This eliminates the need to manually keep two duplicate
4206 lists.
4232 lists.
4207
4233
4208 * Removed the unneeded check_option_names. Now options are handled
4234 * Removed the unneeded check_option_names. Now options are handled
4209 in a much saner manner and it's easy to visually check that things
4235 in a much saner manner and it's easy to visually check that things
4210 are ok.
4236 are ok.
4211
4237
4212 * Updated version numbers on all files I modified to carry a
4238 * Updated version numbers on all files I modified to carry a
4213 notice so Janko and Nathan have clear version markers.
4239 notice so Janko and Nathan have clear version markers.
4214
4240
4215 * Updated docstring for ultraTB with my changes. I should send
4241 * Updated docstring for ultraTB with my changes. I should send
4216 this to Nathan.
4242 this to Nathan.
4217
4243
4218 * Lots of small fixes. Ran everything through pychecker again.
4244 * Lots of small fixes. Ran everything through pychecker again.
4219
4245
4220 * Made loading of deep_reload an cmd line option. If it's not too
4246 * Made loading of deep_reload an cmd line option. If it's not too
4221 kosher, now people can just disable it. With -nodeep_reload it's
4247 kosher, now people can just disable it. With -nodeep_reload it's
4222 still available as dreload(), it just won't overwrite reload().
4248 still available as dreload(), it just won't overwrite reload().
4223
4249
4224 * Moved many options to the no| form (-opt and -noopt
4250 * Moved many options to the no| form (-opt and -noopt
4225 accepted). Cleaner.
4251 accepted). Cleaner.
4226
4252
4227 * Changed magic_log so that if called with no parameters, it uses
4253 * Changed magic_log so that if called with no parameters, it uses
4228 'rotate' mode. That way auto-generated logs aren't automatically
4254 'rotate' mode. That way auto-generated logs aren't automatically
4229 over-written. For normal logs, now a backup is made if it exists
4255 over-written. For normal logs, now a backup is made if it exists
4230 (only 1 level of backups). A new 'backup' mode was added to the
4256 (only 1 level of backups). A new 'backup' mode was added to the
4231 Logger class to support this. This was a request by Janko.
4257 Logger class to support this. This was a request by Janko.
4232
4258
4233 * Added @logoff/@logon to stop/restart an active log.
4259 * Added @logoff/@logon to stop/restart an active log.
4234
4260
4235 * Fixed a lot of bugs in log saving/replay. It was pretty
4261 * Fixed a lot of bugs in log saving/replay. It was pretty
4236 broken. Now special lines (!@,/) appear properly in the command
4262 broken. Now special lines (!@,/) appear properly in the command
4237 history after a log replay.
4263 history after a log replay.
4238
4264
4239 * Tried and failed to implement full session saving via pickle. My
4265 * Tried and failed to implement full session saving via pickle. My
4240 idea was to pickle __main__.__dict__, but modules can't be
4266 idea was to pickle __main__.__dict__, but modules can't be
4241 pickled. This would be a better alternative to replaying logs, but
4267 pickled. This would be a better alternative to replaying logs, but
4242 seems quite tricky to get to work. Changed -session to be called
4268 seems quite tricky to get to work. Changed -session to be called
4243 -logplay, which more accurately reflects what it does. And if we
4269 -logplay, which more accurately reflects what it does. And if we
4244 ever get real session saving working, -session is now available.
4270 ever get real session saving working, -session is now available.
4245
4271
4246 * Implemented color schemes for prompts also. As for tracebacks,
4272 * Implemented color schemes for prompts also. As for tracebacks,
4247 currently only NoColor and Linux are supported. But now the
4273 currently only NoColor and Linux are supported. But now the
4248 infrastructure is in place, based on a generic ColorScheme
4274 infrastructure is in place, based on a generic ColorScheme
4249 class. So writing and activating new schemes both for the prompts
4275 class. So writing and activating new schemes both for the prompts
4250 and the tracebacks should be straightforward.
4276 and the tracebacks should be straightforward.
4251
4277
4252 * Version 0.1.13 released, 0.1.14 opened.
4278 * Version 0.1.13 released, 0.1.14 opened.
4253
4279
4254 * Changed handling of options for output cache. Now counter is
4280 * Changed handling of options for output cache. Now counter is
4255 hardwired starting at 1 and one specifies the maximum number of
4281 hardwired starting at 1 and one specifies the maximum number of
4256 entries *in the outcache* (not the max prompt counter). This is
4282 entries *in the outcache* (not the max prompt counter). This is
4257 much better, since many statements won't increase the cache
4283 much better, since many statements won't increase the cache
4258 count. It also eliminated some confusing options, now there's only
4284 count. It also eliminated some confusing options, now there's only
4259 one: cache_size.
4285 one: cache_size.
4260
4286
4261 * Added 'alias' magic function and magic_alias option in the
4287 * Added 'alias' magic function and magic_alias option in the
4262 ipythonrc file. Now the user can easily define whatever names he
4288 ipythonrc file. Now the user can easily define whatever names he
4263 wants for the magic functions without having to play weird
4289 wants for the magic functions without having to play weird
4264 namespace games. This gives IPython a real shell-like feel.
4290 namespace games. This gives IPython a real shell-like feel.
4265
4291
4266 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4292 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4267 @ or not).
4293 @ or not).
4268
4294
4269 This was one of the last remaining 'visible' bugs (that I know
4295 This was one of the last remaining 'visible' bugs (that I know
4270 of). I think if I can clean up the session loading so it works
4296 of). I think if I can clean up the session loading so it works
4271 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4297 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4272 about licensing).
4298 about licensing).
4273
4299
4274 2001-11-25 Fernando Perez <fperez@colorado.edu>
4300 2001-11-25 Fernando Perez <fperez@colorado.edu>
4275
4301
4276 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4302 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4277 there's a cleaner distinction between what ? and ?? show.
4303 there's a cleaner distinction between what ? and ?? show.
4278
4304
4279 * Added screen_length option. Now the user can define his own
4305 * Added screen_length option. Now the user can define his own
4280 screen size for page() operations.
4306 screen size for page() operations.
4281
4307
4282 * Implemented magic shell-like functions with automatic code
4308 * Implemented magic shell-like functions with automatic code
4283 generation. Now adding another function is just a matter of adding
4309 generation. Now adding another function is just a matter of adding
4284 an entry to a dict, and the function is dynamically generated at
4310 an entry to a dict, and the function is dynamically generated at
4285 run-time. Python has some really cool features!
4311 run-time. Python has some really cool features!
4286
4312
4287 * Renamed many options to cleanup conventions a little. Now all
4313 * Renamed many options to cleanup conventions a little. Now all
4288 are lowercase, and only underscores where needed. Also in the code
4314 are lowercase, and only underscores where needed. Also in the code
4289 option name tables are clearer.
4315 option name tables are clearer.
4290
4316
4291 * Changed prompts a little. Now input is 'In [n]:' instead of
4317 * Changed prompts a little. Now input is 'In [n]:' instead of
4292 'In[n]:='. This allows it the numbers to be aligned with the
4318 'In[n]:='. This allows it the numbers to be aligned with the
4293 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4319 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4294 Python (it was a Mathematica thing). The '...' continuation prompt
4320 Python (it was a Mathematica thing). The '...' continuation prompt
4295 was also changed a little to align better.
4321 was also changed a little to align better.
4296
4322
4297 * Fixed bug when flushing output cache. Not all _p<n> variables
4323 * Fixed bug when flushing output cache. Not all _p<n> variables
4298 exist, so their deletion needs to be wrapped in a try:
4324 exist, so their deletion needs to be wrapped in a try:
4299
4325
4300 * Figured out how to properly use inspect.formatargspec() (it
4326 * Figured out how to properly use inspect.formatargspec() (it
4301 requires the args preceded by *). So I removed all the code from
4327 requires the args preceded by *). So I removed all the code from
4302 _get_pdef in Magic, which was just replicating that.
4328 _get_pdef in Magic, which was just replicating that.
4303
4329
4304 * Added test to prefilter to allow redefining magic function names
4330 * Added test to prefilter to allow redefining magic function names
4305 as variables. This is ok, since the @ form is always available,
4331 as variables. This is ok, since the @ form is always available,
4306 but whe should allow the user to define a variable called 'ls' if
4332 but whe should allow the user to define a variable called 'ls' if
4307 he needs it.
4333 he needs it.
4308
4334
4309 * Moved the ToDo information from README into a separate ToDo.
4335 * Moved the ToDo information from README into a separate ToDo.
4310
4336
4311 * General code cleanup and small bugfixes. I think it's close to a
4337 * General code cleanup and small bugfixes. I think it's close to a
4312 state where it can be released, obviously with a big 'beta'
4338 state where it can be released, obviously with a big 'beta'
4313 warning on it.
4339 warning on it.
4314
4340
4315 * Got the magic function split to work. Now all magics are defined
4341 * Got the magic function split to work. Now all magics are defined
4316 in a separate class. It just organizes things a bit, and now
4342 in a separate class. It just organizes things a bit, and now
4317 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4343 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4318 was too long).
4344 was too long).
4319
4345
4320 * Changed @clear to @reset to avoid potential confusions with
4346 * Changed @clear to @reset to avoid potential confusions with
4321 the shell command clear. Also renamed @cl to @clear, which does
4347 the shell command clear. Also renamed @cl to @clear, which does
4322 exactly what people expect it to from their shell experience.
4348 exactly what people expect it to from their shell experience.
4323
4349
4324 Added a check to the @reset command (since it's so
4350 Added a check to the @reset command (since it's so
4325 destructive, it's probably a good idea to ask for confirmation).
4351 destructive, it's probably a good idea to ask for confirmation).
4326 But now reset only works for full namespace resetting. Since the
4352 But now reset only works for full namespace resetting. Since the
4327 del keyword is already there for deleting a few specific
4353 del keyword is already there for deleting a few specific
4328 variables, I don't see the point of having a redundant magic
4354 variables, I don't see the point of having a redundant magic
4329 function for the same task.
4355 function for the same task.
4330
4356
4331 2001-11-24 Fernando Perez <fperez@colorado.edu>
4357 2001-11-24 Fernando Perez <fperez@colorado.edu>
4332
4358
4333 * Updated the builtin docs (esp. the ? ones).
4359 * Updated the builtin docs (esp. the ? ones).
4334
4360
4335 * Ran all the code through pychecker. Not terribly impressed with
4361 * Ran all the code through pychecker. Not terribly impressed with
4336 it: lots of spurious warnings and didn't really find anything of
4362 it: lots of spurious warnings and didn't really find anything of
4337 substance (just a few modules being imported and not used).
4363 substance (just a few modules being imported and not used).
4338
4364
4339 * Implemented the new ultraTB functionality into IPython. New
4365 * Implemented the new ultraTB functionality into IPython. New
4340 option: xcolors. This chooses color scheme. xmode now only selects
4366 option: xcolors. This chooses color scheme. xmode now only selects
4341 between Plain and Verbose. Better orthogonality.
4367 between Plain and Verbose. Better orthogonality.
4342
4368
4343 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4369 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4344 mode and color scheme for the exception handlers. Now it's
4370 mode and color scheme for the exception handlers. Now it's
4345 possible to have the verbose traceback with no coloring.
4371 possible to have the verbose traceback with no coloring.
4346
4372
4347 2001-11-23 Fernando Perez <fperez@colorado.edu>
4373 2001-11-23 Fernando Perez <fperez@colorado.edu>
4348
4374
4349 * Version 0.1.12 released, 0.1.13 opened.
4375 * Version 0.1.12 released, 0.1.13 opened.
4350
4376
4351 * Removed option to set auto-quote and auto-paren escapes by
4377 * Removed option to set auto-quote and auto-paren escapes by
4352 user. The chances of breaking valid syntax are just too high. If
4378 user. The chances of breaking valid syntax are just too high. If
4353 someone *really* wants, they can always dig into the code.
4379 someone *really* wants, they can always dig into the code.
4354
4380
4355 * Made prompt separators configurable.
4381 * Made prompt separators configurable.
4356
4382
4357 2001-11-22 Fernando Perez <fperez@colorado.edu>
4383 2001-11-22 Fernando Perez <fperez@colorado.edu>
4358
4384
4359 * Small bugfixes in many places.
4385 * Small bugfixes in many places.
4360
4386
4361 * Removed the MyCompleter class from ipplib. It seemed redundant
4387 * Removed the MyCompleter class from ipplib. It seemed redundant
4362 with the C-p,C-n history search functionality. Less code to
4388 with the C-p,C-n history search functionality. Less code to
4363 maintain.
4389 maintain.
4364
4390
4365 * Moved all the original ipython.py code into ipythonlib.py. Right
4391 * Moved all the original ipython.py code into ipythonlib.py. Right
4366 now it's just one big dump into a function called make_IPython, so
4392 now it's just one big dump into a function called make_IPython, so
4367 no real modularity has been gained. But at least it makes the
4393 no real modularity has been gained. But at least it makes the
4368 wrapper script tiny, and since ipythonlib is a module, it gets
4394 wrapper script tiny, and since ipythonlib is a module, it gets
4369 compiled and startup is much faster.
4395 compiled and startup is much faster.
4370
4396
4371 This is a reasobably 'deep' change, so we should test it for a
4397 This is a reasobably 'deep' change, so we should test it for a
4372 while without messing too much more with the code.
4398 while without messing too much more with the code.
4373
4399
4374 2001-11-21 Fernando Perez <fperez@colorado.edu>
4400 2001-11-21 Fernando Perez <fperez@colorado.edu>
4375
4401
4376 * Version 0.1.11 released, 0.1.12 opened for further work.
4402 * Version 0.1.11 released, 0.1.12 opened for further work.
4377
4403
4378 * Removed dependency on Itpl. It was only needed in one place. It
4404 * Removed dependency on Itpl. It was only needed in one place. It
4379 would be nice if this became part of python, though. It makes life
4405 would be nice if this became part of python, though. It makes life
4380 *a lot* easier in some cases.
4406 *a lot* easier in some cases.
4381
4407
4382 * Simplified the prefilter code a bit. Now all handlers are
4408 * Simplified the prefilter code a bit. Now all handlers are
4383 expected to explicitly return a value (at least a blank string).
4409 expected to explicitly return a value (at least a blank string).
4384
4410
4385 * Heavy edits in ipplib. Removed the help system altogether. Now
4411 * Heavy edits in ipplib. Removed the help system altogether. Now
4386 obj?/?? is used for inspecting objects, a magic @doc prints
4412 obj?/?? is used for inspecting objects, a magic @doc prints
4387 docstrings, and full-blown Python help is accessed via the 'help'
4413 docstrings, and full-blown Python help is accessed via the 'help'
4388 keyword. This cleans up a lot of code (less to maintain) and does
4414 keyword. This cleans up a lot of code (less to maintain) and does
4389 the job. Since 'help' is now a standard Python component, might as
4415 the job. Since 'help' is now a standard Python component, might as
4390 well use it and remove duplicate functionality.
4416 well use it and remove duplicate functionality.
4391
4417
4392 Also removed the option to use ipplib as a standalone program. By
4418 Also removed the option to use ipplib as a standalone program. By
4393 now it's too dependent on other parts of IPython to function alone.
4419 now it's too dependent on other parts of IPython to function alone.
4394
4420
4395 * Fixed bug in genutils.pager. It would crash if the pager was
4421 * Fixed bug in genutils.pager. It would crash if the pager was
4396 exited immediately after opening (broken pipe).
4422 exited immediately after opening (broken pipe).
4397
4423
4398 * Trimmed down the VerboseTB reporting a little. The header is
4424 * Trimmed down the VerboseTB reporting a little. The header is
4399 much shorter now and the repeated exception arguments at the end
4425 much shorter now and the repeated exception arguments at the end
4400 have been removed. For interactive use the old header seemed a bit
4426 have been removed. For interactive use the old header seemed a bit
4401 excessive.
4427 excessive.
4402
4428
4403 * Fixed small bug in output of @whos for variables with multi-word
4429 * Fixed small bug in output of @whos for variables with multi-word
4404 types (only first word was displayed).
4430 types (only first word was displayed).
4405
4431
4406 2001-11-17 Fernando Perez <fperez@colorado.edu>
4432 2001-11-17 Fernando Perez <fperez@colorado.edu>
4407
4433
4408 * Version 0.1.10 released, 0.1.11 opened for further work.
4434 * Version 0.1.10 released, 0.1.11 opened for further work.
4409
4435
4410 * Modified dirs and friends. dirs now *returns* the stack (not
4436 * Modified dirs and friends. dirs now *returns* the stack (not
4411 prints), so one can manipulate it as a variable. Convenient to
4437 prints), so one can manipulate it as a variable. Convenient to
4412 travel along many directories.
4438 travel along many directories.
4413
4439
4414 * Fixed bug in magic_pdef: would only work with functions with
4440 * Fixed bug in magic_pdef: would only work with functions with
4415 arguments with default values.
4441 arguments with default values.
4416
4442
4417 2001-11-14 Fernando Perez <fperez@colorado.edu>
4443 2001-11-14 Fernando Perez <fperez@colorado.edu>
4418
4444
4419 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4445 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4420 example with IPython. Various other minor fixes and cleanups.
4446 example with IPython. Various other minor fixes and cleanups.
4421
4447
4422 * Version 0.1.9 released, 0.1.10 opened for further work.
4448 * Version 0.1.9 released, 0.1.10 opened for further work.
4423
4449
4424 * Added sys.path to the list of directories searched in the
4450 * Added sys.path to the list of directories searched in the
4425 execfile= option. It used to be the current directory and the
4451 execfile= option. It used to be the current directory and the
4426 user's IPYTHONDIR only.
4452 user's IPYTHONDIR only.
4427
4453
4428 2001-11-13 Fernando Perez <fperez@colorado.edu>
4454 2001-11-13 Fernando Perez <fperez@colorado.edu>
4429
4455
4430 * Reinstated the raw_input/prefilter separation that Janko had
4456 * Reinstated the raw_input/prefilter separation that Janko had
4431 initially. This gives a more convenient setup for extending the
4457 initially. This gives a more convenient setup for extending the
4432 pre-processor from the outside: raw_input always gets a string,
4458 pre-processor from the outside: raw_input always gets a string,
4433 and prefilter has to process it. We can then redefine prefilter
4459 and prefilter has to process it. We can then redefine prefilter
4434 from the outside and implement extensions for special
4460 from the outside and implement extensions for special
4435 purposes.
4461 purposes.
4436
4462
4437 Today I got one for inputting PhysicalQuantity objects
4463 Today I got one for inputting PhysicalQuantity objects
4438 (from Scientific) without needing any function calls at
4464 (from Scientific) without needing any function calls at
4439 all. Extremely convenient, and it's all done as a user-level
4465 all. Extremely convenient, and it's all done as a user-level
4440 extension (no IPython code was touched). Now instead of:
4466 extension (no IPython code was touched). Now instead of:
4441 a = PhysicalQuantity(4.2,'m/s**2')
4467 a = PhysicalQuantity(4.2,'m/s**2')
4442 one can simply say
4468 one can simply say
4443 a = 4.2 m/s**2
4469 a = 4.2 m/s**2
4444 or even
4470 or even
4445 a = 4.2 m/s^2
4471 a = 4.2 m/s^2
4446
4472
4447 I use this, but it's also a proof of concept: IPython really is
4473 I use this, but it's also a proof of concept: IPython really is
4448 fully user-extensible, even at the level of the parsing of the
4474 fully user-extensible, even at the level of the parsing of the
4449 command line. It's not trivial, but it's perfectly doable.
4475 command line. It's not trivial, but it's perfectly doable.
4450
4476
4451 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4477 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4452 the problem of modules being loaded in the inverse order in which
4478 the problem of modules being loaded in the inverse order in which
4453 they were defined in
4479 they were defined in
4454
4480
4455 * Version 0.1.8 released, 0.1.9 opened for further work.
4481 * Version 0.1.8 released, 0.1.9 opened for further work.
4456
4482
4457 * Added magics pdef, source and file. They respectively show the
4483 * Added magics pdef, source and file. They respectively show the
4458 definition line ('prototype' in C), source code and full python
4484 definition line ('prototype' in C), source code and full python
4459 file for any callable object. The object inspector oinfo uses
4485 file for any callable object. The object inspector oinfo uses
4460 these to show the same information.
4486 these to show the same information.
4461
4487
4462 * Version 0.1.7 released, 0.1.8 opened for further work.
4488 * Version 0.1.7 released, 0.1.8 opened for further work.
4463
4489
4464 * Separated all the magic functions into a class called Magic. The
4490 * Separated all the magic functions into a class called Magic. The
4465 InteractiveShell class was becoming too big for Xemacs to handle
4491 InteractiveShell class was becoming too big for Xemacs to handle
4466 (de-indenting a line would lock it up for 10 seconds while it
4492 (de-indenting a line would lock it up for 10 seconds while it
4467 backtracked on the whole class!)
4493 backtracked on the whole class!)
4468
4494
4469 FIXME: didn't work. It can be done, but right now namespaces are
4495 FIXME: didn't work. It can be done, but right now namespaces are
4470 all messed up. Do it later (reverted it for now, so at least
4496 all messed up. Do it later (reverted it for now, so at least
4471 everything works as before).
4497 everything works as before).
4472
4498
4473 * Got the object introspection system (magic_oinfo) working! I
4499 * Got the object introspection system (magic_oinfo) working! I
4474 think this is pretty much ready for release to Janko, so he can
4500 think this is pretty much ready for release to Janko, so he can
4475 test it for a while and then announce it. Pretty much 100% of what
4501 test it for a while and then announce it. Pretty much 100% of what
4476 I wanted for the 'phase 1' release is ready. Happy, tired.
4502 I wanted for the 'phase 1' release is ready. Happy, tired.
4477
4503
4478 2001-11-12 Fernando Perez <fperez@colorado.edu>
4504 2001-11-12 Fernando Perez <fperez@colorado.edu>
4479
4505
4480 * Version 0.1.6 released, 0.1.7 opened for further work.
4506 * Version 0.1.6 released, 0.1.7 opened for further work.
4481
4507
4482 * Fixed bug in printing: it used to test for truth before
4508 * Fixed bug in printing: it used to test for truth before
4483 printing, so 0 wouldn't print. Now checks for None.
4509 printing, so 0 wouldn't print. Now checks for None.
4484
4510
4485 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4511 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4486 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4512 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4487 reaches by hand into the outputcache. Think of a better way to do
4513 reaches by hand into the outputcache. Think of a better way to do
4488 this later.
4514 this later.
4489
4515
4490 * Various small fixes thanks to Nathan's comments.
4516 * Various small fixes thanks to Nathan's comments.
4491
4517
4492 * Changed magic_pprint to magic_Pprint. This way it doesn't
4518 * Changed magic_pprint to magic_Pprint. This way it doesn't
4493 collide with pprint() and the name is consistent with the command
4519 collide with pprint() and the name is consistent with the command
4494 line option.
4520 line option.
4495
4521
4496 * Changed prompt counter behavior to be fully like
4522 * Changed prompt counter behavior to be fully like
4497 Mathematica's. That is, even input that doesn't return a result
4523 Mathematica's. That is, even input that doesn't return a result
4498 raises the prompt counter. The old behavior was kind of confusing
4524 raises the prompt counter. The old behavior was kind of confusing
4499 (getting the same prompt number several times if the operation
4525 (getting the same prompt number several times if the operation
4500 didn't return a result).
4526 didn't return a result).
4501
4527
4502 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4528 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4503
4529
4504 * Fixed -Classic mode (wasn't working anymore).
4530 * Fixed -Classic mode (wasn't working anymore).
4505
4531
4506 * Added colored prompts using Nathan's new code. Colors are
4532 * Added colored prompts using Nathan's new code. Colors are
4507 currently hardwired, they can be user-configurable. For
4533 currently hardwired, they can be user-configurable. For
4508 developers, they can be chosen in file ipythonlib.py, at the
4534 developers, they can be chosen in file ipythonlib.py, at the
4509 beginning of the CachedOutput class def.
4535 beginning of the CachedOutput class def.
4510
4536
4511 2001-11-11 Fernando Perez <fperez@colorado.edu>
4537 2001-11-11 Fernando Perez <fperez@colorado.edu>
4512
4538
4513 * Version 0.1.5 released, 0.1.6 opened for further work.
4539 * Version 0.1.5 released, 0.1.6 opened for further work.
4514
4540
4515 * Changed magic_env to *return* the environment as a dict (not to
4541 * Changed magic_env to *return* the environment as a dict (not to
4516 print it). This way it prints, but it can also be processed.
4542 print it). This way it prints, but it can also be processed.
4517
4543
4518 * Added Verbose exception reporting to interactive
4544 * Added Verbose exception reporting to interactive
4519 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4545 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4520 traceback. Had to make some changes to the ultraTB file. This is
4546 traceback. Had to make some changes to the ultraTB file. This is
4521 probably the last 'big' thing in my mental todo list. This ties
4547 probably the last 'big' thing in my mental todo list. This ties
4522 in with the next entry:
4548 in with the next entry:
4523
4549
4524 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4550 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4525 has to specify is Plain, Color or Verbose for all exception
4551 has to specify is Plain, Color or Verbose for all exception
4526 handling.
4552 handling.
4527
4553
4528 * Removed ShellServices option. All this can really be done via
4554 * Removed ShellServices option. All this can really be done via
4529 the magic system. It's easier to extend, cleaner and has automatic
4555 the magic system. It's easier to extend, cleaner and has automatic
4530 namespace protection and documentation.
4556 namespace protection and documentation.
4531
4557
4532 2001-11-09 Fernando Perez <fperez@colorado.edu>
4558 2001-11-09 Fernando Perez <fperez@colorado.edu>
4533
4559
4534 * Fixed bug in output cache flushing (missing parameter to
4560 * Fixed bug in output cache flushing (missing parameter to
4535 __init__). Other small bugs fixed (found using pychecker).
4561 __init__). Other small bugs fixed (found using pychecker).
4536
4562
4537 * Version 0.1.4 opened for bugfixing.
4563 * Version 0.1.4 opened for bugfixing.
4538
4564
4539 2001-11-07 Fernando Perez <fperez@colorado.edu>
4565 2001-11-07 Fernando Perez <fperez@colorado.edu>
4540
4566
4541 * Version 0.1.3 released, mainly because of the raw_input bug.
4567 * Version 0.1.3 released, mainly because of the raw_input bug.
4542
4568
4543 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4569 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4544 and when testing for whether things were callable, a call could
4570 and when testing for whether things were callable, a call could
4545 actually be made to certain functions. They would get called again
4571 actually be made to certain functions. They would get called again
4546 once 'really' executed, with a resulting double call. A disaster
4572 once 'really' executed, with a resulting double call. A disaster
4547 in many cases (list.reverse() would never work!).
4573 in many cases (list.reverse() would never work!).
4548
4574
4549 * Removed prefilter() function, moved its code to raw_input (which
4575 * Removed prefilter() function, moved its code to raw_input (which
4550 after all was just a near-empty caller for prefilter). This saves
4576 after all was just a near-empty caller for prefilter). This saves
4551 a function call on every prompt, and simplifies the class a tiny bit.
4577 a function call on every prompt, and simplifies the class a tiny bit.
4552
4578
4553 * Fix _ip to __ip name in magic example file.
4579 * Fix _ip to __ip name in magic example file.
4554
4580
4555 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4581 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4556 work with non-gnu versions of tar.
4582 work with non-gnu versions of tar.
4557
4583
4558 2001-11-06 Fernando Perez <fperez@colorado.edu>
4584 2001-11-06 Fernando Perez <fperez@colorado.edu>
4559
4585
4560 * Version 0.1.2. Just to keep track of the recent changes.
4586 * Version 0.1.2. Just to keep track of the recent changes.
4561
4587
4562 * Fixed nasty bug in output prompt routine. It used to check 'if
4588 * Fixed nasty bug in output prompt routine. It used to check 'if
4563 arg != None...'. Problem is, this fails if arg implements a
4589 arg != None...'. Problem is, this fails if arg implements a
4564 special comparison (__cmp__) which disallows comparing to
4590 special comparison (__cmp__) which disallows comparing to
4565 None. Found it when trying to use the PhysicalQuantity module from
4591 None. Found it when trying to use the PhysicalQuantity module from
4566 ScientificPython.
4592 ScientificPython.
4567
4593
4568 2001-11-05 Fernando Perez <fperez@colorado.edu>
4594 2001-11-05 Fernando Perez <fperez@colorado.edu>
4569
4595
4570 * Also added dirs. Now the pushd/popd/dirs family functions
4596 * Also added dirs. Now the pushd/popd/dirs family functions
4571 basically like the shell, with the added convenience of going home
4597 basically like the shell, with the added convenience of going home
4572 when called with no args.
4598 when called with no args.
4573
4599
4574 * pushd/popd slightly modified to mimic shell behavior more
4600 * pushd/popd slightly modified to mimic shell behavior more
4575 closely.
4601 closely.
4576
4602
4577 * Added env,pushd,popd from ShellServices as magic functions. I
4603 * Added env,pushd,popd from ShellServices as magic functions. I
4578 think the cleanest will be to port all desired functions from
4604 think the cleanest will be to port all desired functions from
4579 ShellServices as magics and remove ShellServices altogether. This
4605 ShellServices as magics and remove ShellServices altogether. This
4580 will provide a single, clean way of adding functionality
4606 will provide a single, clean way of adding functionality
4581 (shell-type or otherwise) to IP.
4607 (shell-type or otherwise) to IP.
4582
4608
4583 2001-11-04 Fernando Perez <fperez@colorado.edu>
4609 2001-11-04 Fernando Perez <fperez@colorado.edu>
4584
4610
4585 * Added .ipython/ directory to sys.path. This way users can keep
4611 * Added .ipython/ directory to sys.path. This way users can keep
4586 customizations there and access them via import.
4612 customizations there and access them via import.
4587
4613
4588 2001-11-03 Fernando Perez <fperez@colorado.edu>
4614 2001-11-03 Fernando Perez <fperez@colorado.edu>
4589
4615
4590 * Opened version 0.1.1 for new changes.
4616 * Opened version 0.1.1 for new changes.
4591
4617
4592 * Changed version number to 0.1.0: first 'public' release, sent to
4618 * Changed version number to 0.1.0: first 'public' release, sent to
4593 Nathan and Janko.
4619 Nathan and Janko.
4594
4620
4595 * Lots of small fixes and tweaks.
4621 * Lots of small fixes and tweaks.
4596
4622
4597 * Minor changes to whos format. Now strings are shown, snipped if
4623 * Minor changes to whos format. Now strings are shown, snipped if
4598 too long.
4624 too long.
4599
4625
4600 * Changed ShellServices to work on __main__ so they show up in @who
4626 * Changed ShellServices to work on __main__ so they show up in @who
4601
4627
4602 * Help also works with ? at the end of a line:
4628 * Help also works with ? at the end of a line:
4603 ?sin and sin?
4629 ?sin and sin?
4604 both produce the same effect. This is nice, as often I use the
4630 both produce the same effect. This is nice, as often I use the
4605 tab-complete to find the name of a method, but I used to then have
4631 tab-complete to find the name of a method, but I used to then have
4606 to go to the beginning of the line to put a ? if I wanted more
4632 to go to the beginning of the line to put a ? if I wanted more
4607 info. Now I can just add the ? and hit return. Convenient.
4633 info. Now I can just add the ? and hit return. Convenient.
4608
4634
4609 2001-11-02 Fernando Perez <fperez@colorado.edu>
4635 2001-11-02 Fernando Perez <fperez@colorado.edu>
4610
4636
4611 * Python version check (>=2.1) added.
4637 * Python version check (>=2.1) added.
4612
4638
4613 * Added LazyPython documentation. At this point the docs are quite
4639 * Added LazyPython documentation. At this point the docs are quite
4614 a mess. A cleanup is in order.
4640 a mess. A cleanup is in order.
4615
4641
4616 * Auto-installer created. For some bizarre reason, the zipfiles
4642 * Auto-installer created. For some bizarre reason, the zipfiles
4617 module isn't working on my system. So I made a tar version
4643 module isn't working on my system. So I made a tar version
4618 (hopefully the command line options in various systems won't kill
4644 (hopefully the command line options in various systems won't kill
4619 me).
4645 me).
4620
4646
4621 * Fixes to Struct in genutils. Now all dictionary-like methods are
4647 * Fixes to Struct in genutils. Now all dictionary-like methods are
4622 protected (reasonably).
4648 protected (reasonably).
4623
4649
4624 * Added pager function to genutils and changed ? to print usage
4650 * Added pager function to genutils and changed ? to print usage
4625 note through it (it was too long).
4651 note through it (it was too long).
4626
4652
4627 * Added the LazyPython functionality. Works great! I changed the
4653 * Added the LazyPython functionality. Works great! I changed the
4628 auto-quote escape to ';', it's on home row and next to '. But
4654 auto-quote escape to ';', it's on home row and next to '. But
4629 both auto-quote and auto-paren (still /) escapes are command-line
4655 both auto-quote and auto-paren (still /) escapes are command-line
4630 parameters.
4656 parameters.
4631
4657
4632
4658
4633 2001-11-01 Fernando Perez <fperez@colorado.edu>
4659 2001-11-01 Fernando Perez <fperez@colorado.edu>
4634
4660
4635 * Version changed to 0.0.7. Fairly large change: configuration now
4661 * Version changed to 0.0.7. Fairly large change: configuration now
4636 is all stored in a directory, by default .ipython. There, all
4662 is all stored in a directory, by default .ipython. There, all
4637 config files have normal looking names (not .names)
4663 config files have normal looking names (not .names)
4638
4664
4639 * Version 0.0.6 Released first to Lucas and Archie as a test
4665 * Version 0.0.6 Released first to Lucas and Archie as a test
4640 run. Since it's the first 'semi-public' release, change version to
4666 run. Since it's the first 'semi-public' release, change version to
4641 > 0.0.6 for any changes now.
4667 > 0.0.6 for any changes now.
4642
4668
4643 * Stuff I had put in the ipplib.py changelog:
4669 * Stuff I had put in the ipplib.py changelog:
4644
4670
4645 Changes to InteractiveShell:
4671 Changes to InteractiveShell:
4646
4672
4647 - Made the usage message a parameter.
4673 - Made the usage message a parameter.
4648
4674
4649 - Require the name of the shell variable to be given. It's a bit
4675 - Require the name of the shell variable to be given. It's a bit
4650 of a hack, but allows the name 'shell' not to be hardwire in the
4676 of a hack, but allows the name 'shell' not to be hardwire in the
4651 magic (@) handler, which is problematic b/c it requires
4677 magic (@) handler, which is problematic b/c it requires
4652 polluting the global namespace with 'shell'. This in turn is
4678 polluting the global namespace with 'shell'. This in turn is
4653 fragile: if a user redefines a variable called shell, things
4679 fragile: if a user redefines a variable called shell, things
4654 break.
4680 break.
4655
4681
4656 - magic @: all functions available through @ need to be defined
4682 - magic @: all functions available through @ need to be defined
4657 as magic_<name>, even though they can be called simply as
4683 as magic_<name>, even though they can be called simply as
4658 @<name>. This allows the special command @magic to gather
4684 @<name>. This allows the special command @magic to gather
4659 information automatically about all existing magic functions,
4685 information automatically about all existing magic functions,
4660 even if they are run-time user extensions, by parsing the shell
4686 even if they are run-time user extensions, by parsing the shell
4661 instance __dict__ looking for special magic_ names.
4687 instance __dict__ looking for special magic_ names.
4662
4688
4663 - mainloop: added *two* local namespace parameters. This allows
4689 - mainloop: added *two* local namespace parameters. This allows
4664 the class to differentiate between parameters which were there
4690 the class to differentiate between parameters which were there
4665 before and after command line initialization was processed. This
4691 before and after command line initialization was processed. This
4666 way, later @who can show things loaded at startup by the
4692 way, later @who can show things loaded at startup by the
4667 user. This trick was necessary to make session saving/reloading
4693 user. This trick was necessary to make session saving/reloading
4668 really work: ideally after saving/exiting/reloading a session,
4694 really work: ideally after saving/exiting/reloading a session,
4669 *everythin* should look the same, including the output of @who. I
4695 *everythin* should look the same, including the output of @who. I
4670 was only able to make this work with this double namespace
4696 was only able to make this work with this double namespace
4671 trick.
4697 trick.
4672
4698
4673 - added a header to the logfile which allows (almost) full
4699 - added a header to the logfile which allows (almost) full
4674 session restoring.
4700 session restoring.
4675
4701
4676 - prepend lines beginning with @ or !, with a and log
4702 - prepend lines beginning with @ or !, with a and log
4677 them. Why? !lines: may be useful to know what you did @lines:
4703 them. Why? !lines: may be useful to know what you did @lines:
4678 they may affect session state. So when restoring a session, at
4704 they may affect session state. So when restoring a session, at
4679 least inform the user of their presence. I couldn't quite get
4705 least inform the user of their presence. I couldn't quite get
4680 them to properly re-execute, but at least the user is warned.
4706 them to properly re-execute, but at least the user is warned.
4681
4707
4682 * Started ChangeLog.
4708 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now