##// END OF EJS Templates
Merged 1071-1076 from banches/0.7.1
vivainio -
Show More
@@ -1,233 +1,234 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 994 2006-01-08 08:29:44Z fperez $
5 $Id: Logger.py 1077 2006-01-24 18:15:27Z vivainio $
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-2006 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2006 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 try:
175 try:
176 input_hist = self.shell.user_ns['_ih']
176 input_hist = self.shell.user_ns['_ih']
177 except:
177 except:
178 print 'userns:',self.shell.user_ns.keys()
178 print 'userns:',self.shell.user_ns.keys()
179 return
179 return
180
180
181 if not continuation and line:
181 if not continuation and line:
182 self._iii = self._ii
182 self._iii = self._ii
183 self._ii = self._i
183 self._ii = self._i
184 self._i = self._i00
184 self._i = self._i00
185 # put back the final \n of every input line
185 # put back the final \n of every input line
186 self._i00 = line+'\n'
186 self._i00 = line+'\n'
187 #print 'Logging input:<%s>' % line # dbg
187 #print 'Logging input:<%s>' % line # dbg
188 input_hist.append(self._i00)
188 input_hist.append(self._i00)
189 #print '---[%s]' % (len(input_hist)-1,) # dbg
189 #print '---[%s]' % (len(input_hist)-1,) # dbg
190
190
191 # hackish access to top-level namespace to create _i1,_i2... dynamically
191 # hackish access to top-level namespace to create _i1,_i2... dynamically
192 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
192 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
193 if self.shell.outputcache.do_full_cache:
193 if self.shell.outputcache.do_full_cache:
194 in_num = self.shell.outputcache.prompt_count
194 in_num = self.shell.outputcache.prompt_count
195 # add blank lines if the input cache fell out of sync. This can
195 # add blank lines if the input cache fell out of sync. This can
196 # happen for embedded instances which get killed via C-D and then
196 # happen for embedded instances which get killed via C-D and then
197 # get resumed.
197 # get resumed.
198 while in_num >= len(input_hist):
198 while in_num >= len(input_hist):
199 input_hist.append('\n')
199 input_hist.append('\n')
200 # but if the opposite is true (a macro can produce multiple inputs
200 # but if the opposite is true (a macro can produce multiple inputs
201 # with no output display called), then bring the output counter in
201 # with no output display called), then bring the output counter in
202 # sync:
202 # sync:
203 last_num = len(input_hist)-1
203 last_num = len(input_hist)-1
204 if in_num != last_num:
204 if in_num != last_num:
205 in_num = self.shell.outputcache.prompt_count = last_num
205 in_num = self.shell.outputcache.prompt_count = last_num
206 new_i = '_i%s' % in_num
206 new_i = '_i%s' % in_num
207 if continuation:
207 if continuation:
208 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line)
208 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line)
209 input_hist[in_num] = self._i00
209 input_hist[in_num] = self._i00
210 to_main[new_i] = self._i00
210 to_main[new_i] = self._i00
211 self.shell.user_ns.update(to_main)
211 self.shell.user_ns.update(to_main)
212 self.log_write(line)
212 self.log_write(line)
213
213
214 def log_write(self,data,kind='input'):
214 def log_write(self,data,kind='input'):
215 """Write data to the log file, if active"""
215 """Write data to the log file, if active"""
216
216
217 #print 'data: %r' % data # dbg
217 if self.log_active and data:
218 if self.log_active and data:
218 write = self.logfile.write
219 write = self.logfile.write
219 if kind=='input':
220 if kind=='input':
220 if self.timestamp:
221 if self.timestamp:
221 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
222 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
222 time.localtime()))
223 time.localtime()))
223 write('%s\n' % data)
224 write('%s\n' % data)
224 elif kind=='output' and self.log_output:
225 elif kind=='output' and self.log_output:
225 odata = '\n'.join(['#[Out]# %s' % s
226 odata = '\n'.join(['#[Out]# %s' % s
226 for s in data.split('\n')])
227 for s in data.split('\n')])
227 write('%s\n' % odata)
228 write('%s\n' % odata)
228 self.logfile.flush()
229 self.logfile.flush()
229
230
230 def close_log(self):
231 def close_log(self):
231 self.logfile.close()
232 self.logfile.close()
232 self.logfile = None
233 self.logfile = None
233 self.logfname = ''
234 self.logfname = ''
@@ -1,2809 +1,2824 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 1076 2006-01-24 17:27:05Z vivainio $"""
4 $Id: Magic.py 1077 2006-01-24 18:15:27Z vivainio $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt
36 from getopt import getopt
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38
38
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 from IPython import Debugger, OInspect, wildcard
46 from IPython import Debugger, OInspect, wildcard
47 from IPython.FakeModule import FakeModule
47 from IPython.FakeModule import FakeModule
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.PyColorize import Parser
49 from IPython.PyColorize import Parser
50 from IPython.ipstruct import Struct
50 from IPython.ipstruct import Struct
51 from IPython.macro import Macro
51 from IPython.macro import Macro
52 from IPython.genutils import *
52 from IPython.genutils import *
53 from IPython import platutils
53 from IPython import platutils
54
54
55 #***************************************************************************
55 #***************************************************************************
56 # Utility functions
56 # Utility functions
57 def on_off(tag):
57 def on_off(tag):
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 return ['OFF','ON'][tag]
59 return ['OFF','ON'][tag]
60
60
61 class Bunch: pass
61 class Bunch: pass
62
62
63 #***************************************************************************
63 #***************************************************************************
64 # Main class implementing Magic functionality
64 # Main class implementing Magic functionality
65 class Magic:
65 class Magic:
66 """Magic functions for InteractiveShell.
66 """Magic functions for InteractiveShell.
67
67
68 Shell functions which can be reached as %function_name. All magic
68 Shell functions which can be reached as %function_name. All magic
69 functions should accept a string, which they can parse for their own
69 functions should accept a string, which they can parse for their own
70 needs. This can make some functions easier to type, eg `%cd ../`
70 needs. This can make some functions easier to type, eg `%cd ../`
71 vs. `%cd("../")`
71 vs. `%cd("../")`
72
72
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 at the command line, but it is is needed in the definition. """
74 at the command line, but it is is needed in the definition. """
75
75
76 # class globals
76 # class globals
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 'Automagic is ON, % prefix NOT needed for magic functions.']
78 'Automagic is ON, % prefix NOT needed for magic functions.']
79
79
80 #......................................................................
80 #......................................................................
81 # some utility functions
81 # some utility functions
82
82
83 def __init__(self,shell):
83 def __init__(self,shell):
84
84
85 self.options_table = {}
85 self.options_table = {}
86 if profile is None:
86 if profile is None:
87 self.magic_prun = self.profile_missing_notice
87 self.magic_prun = self.profile_missing_notice
88 self.shell = shell
88 self.shell = shell
89
89
90 # namespace for holding state we may need
90 # namespace for holding state we may need
91 self._magic_state = Bunch()
91 self._magic_state = Bunch()
92
92
93 def profile_missing_notice(self, *args, **kwargs):
93 def profile_missing_notice(self, *args, **kwargs):
94 error("""\
94 error("""\
95 The profile module could not be found. If you are a Debian user,
95 The profile module could not be found. If you are a Debian user,
96 it has been removed from the standard Debian package because of its non-free
96 it has been removed from the standard Debian package because of its non-free
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98
98
99 def default_option(self,fn,optstr):
99 def default_option(self,fn,optstr):
100 """Make an entry in the options_table for fn, with value optstr"""
100 """Make an entry in the options_table for fn, with value optstr"""
101
101
102 if fn not in self.lsmagic():
102 if fn not in self.lsmagic():
103 error("%s is not a magic function" % fn)
103 error("%s is not a magic function" % fn)
104 self.options_table[fn] = optstr
104 self.options_table[fn] = optstr
105
105
106 def lsmagic(self):
106 def lsmagic(self):
107 """Return a list of currently available magic functions.
107 """Return a list of currently available magic functions.
108
108
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 ['magic_ls','magic_cd',...]"""
110 ['magic_ls','magic_cd',...]"""
111
111
112 # FIXME. This needs a cleanup, in the way the magics list is built.
112 # FIXME. This needs a cleanup, in the way the magics list is built.
113
113
114 # magics in class definition
114 # magics in class definition
115 class_magic = lambda fn: fn.startswith('magic_') and \
115 class_magic = lambda fn: fn.startswith('magic_') and \
116 callable(Magic.__dict__[fn])
116 callable(Magic.__dict__[fn])
117 # in instance namespace (run-time user additions)
117 # in instance namespace (run-time user additions)
118 inst_magic = lambda fn: fn.startswith('magic_') and \
118 inst_magic = lambda fn: fn.startswith('magic_') and \
119 callable(self.__dict__[fn])
119 callable(self.__dict__[fn])
120 # and bound magics by user (so they can access self):
120 # and bound magics by user (so they can access self):
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 callable(self.__class__.__dict__[fn])
122 callable(self.__class__.__dict__[fn])
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 out = []
126 out = []
127 for fn in magics:
127 for fn in magics:
128 out.append(fn.replace('magic_','',1))
128 out.append(fn.replace('magic_','',1))
129 out.sort()
129 out.sort()
130 return out
130 return out
131
131
132 def extract_input_slices(self,slices):
132 def extract_input_slices(self,slices):
133 """Return as a string a set of input history slices.
133 """Return as a string a set of input history slices.
134
134
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
136 since this function is for use by magic functions which get their
136 since this function is for use by magic functions which get their
137 arguments as strings.
137 arguments as strings.
138
138
139 Note that slices can be called with two notations:
139 Note that slices can be called with two notations:
140
140
141 N:M -> standard python form, means including items N...(M-1).
141 N:M -> standard python form, means including items N...(M-1).
142
142
143 N-M -> include items N..M (closed endpoint)."""
143 N-M -> include items N..M (closed endpoint)."""
144
144
145 cmds = []
145 cmds = []
146 for chunk in slices:
146 for chunk in slices:
147 if ':' in chunk:
147 if ':' in chunk:
148 ini,fin = map(int,chunk.split(':'))
148 ini,fin = map(int,chunk.split(':'))
149 elif '-' in chunk:
149 elif '-' in chunk:
150 ini,fin = map(int,chunk.split('-'))
150 ini,fin = map(int,chunk.split('-'))
151 fin += 1
151 fin += 1
152 else:
152 else:
153 ini = int(chunk)
153 ini = int(chunk)
154 fin = ini+1
154 fin = ini+1
155 cmds.append(self.shell.input_hist[ini:fin])
155 cmds.append(self.shell.input_hist[ini:fin])
156 return cmds
156 return cmds
157
157
158 def _ofind(self,oname):
158 def _ofind(self,oname):
159 """Find an object in the available namespaces.
159 """Find an object in the available namespaces.
160
160
161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
162
162
163 Has special code to detect magic functions.
163 Has special code to detect magic functions.
164 """
164 """
165
165
166 oname = oname.strip()
166 oname = oname.strip()
167
167
168 # Namespaces to search in:
168 # Namespaces to search in:
169 user_ns = self.shell.user_ns
169 user_ns = self.shell.user_ns
170 internal_ns = self.shell.internal_ns
170 internal_ns = self.shell.internal_ns
171 builtin_ns = __builtin__.__dict__
171 builtin_ns = __builtin__.__dict__
172 alias_ns = self.shell.alias_table
172 alias_ns = self.shell.alias_table
173
173
174 # Put them in a list. The order is important so that we find things in
174 # Put them in a list. The order is important so that we find things in
175 # the same order that Python finds them.
175 # the same order that Python finds them.
176 namespaces = [ ('Interactive',user_ns),
176 namespaces = [ ('Interactive',user_ns),
177 ('IPython internal',internal_ns),
177 ('IPython internal',internal_ns),
178 ('Python builtin',builtin_ns),
178 ('Python builtin',builtin_ns),
179 ('Alias',alias_ns),
179 ('Alias',alias_ns),
180 ]
180 ]
181
181
182 # initialize results to 'null'
182 # initialize results to 'null'
183 found = 0; obj = None; ospace = None; ds = None;
183 found = 0; obj = None; ospace = None; ds = None;
184 ismagic = 0; isalias = 0
184 ismagic = 0; isalias = 0
185
185
186 # Look for the given name by splitting it in parts. If the head is
186 # Look for the given name by splitting it in parts. If the head is
187 # found, then we look for all the remaining parts as members, and only
187 # found, then we look for all the remaining parts as members, and only
188 # declare success if we can find them all.
188 # declare success if we can find them all.
189 oname_parts = oname.split('.')
189 oname_parts = oname.split('.')
190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
191 for nsname,ns in namespaces:
191 for nsname,ns in namespaces:
192 try:
192 try:
193 obj = ns[oname_head]
193 obj = ns[oname_head]
194 except KeyError:
194 except KeyError:
195 continue
195 continue
196 else:
196 else:
197 for part in oname_rest:
197 for part in oname_rest:
198 try:
198 try:
199 obj = getattr(obj,part)
199 obj = getattr(obj,part)
200 except:
200 except:
201 # Blanket except b/c some badly implemented objects
201 # Blanket except b/c some badly implemented objects
202 # allow __getattr__ to raise exceptions other than
202 # allow __getattr__ to raise exceptions other than
203 # AttributeError, which then crashes IPython.
203 # AttributeError, which then crashes IPython.
204 break
204 break
205 else:
205 else:
206 # If we finish the for loop (no break), we got all members
206 # If we finish the for loop (no break), we got all members
207 found = 1
207 found = 1
208 ospace = nsname
208 ospace = nsname
209 if ns == alias_ns:
209 if ns == alias_ns:
210 isalias = 1
210 isalias = 1
211 break # namespace loop
211 break # namespace loop
212
212
213 # Try to see if it's magic
213 # Try to see if it's magic
214 if not found:
214 if not found:
215 if oname.startswith(self.shell.ESC_MAGIC):
215 if oname.startswith(self.shell.ESC_MAGIC):
216 oname = oname[1:]
216 oname = oname[1:]
217 obj = getattr(self,'magic_'+oname,None)
217 obj = getattr(self,'magic_'+oname,None)
218 if obj is not None:
218 if obj is not None:
219 found = 1
219 found = 1
220 ospace = 'IPython internal'
220 ospace = 'IPython internal'
221 ismagic = 1
221 ismagic = 1
222
222
223 # Last try: special-case some literals like '', [], {}, etc:
223 # Last try: special-case some literals like '', [], {}, etc:
224 if not found and oname_head in ["''",'""','[]','{}','()']:
224 if not found and oname_head in ["''",'""','[]','{}','()']:
225 obj = eval(oname_head)
225 obj = eval(oname_head)
226 found = 1
226 found = 1
227 ospace = 'Interactive'
227 ospace = 'Interactive'
228
228
229 return {'found':found, 'obj':obj, 'namespace':ospace,
229 return {'found':found, 'obj':obj, 'namespace':ospace,
230 'ismagic':ismagic, 'isalias':isalias}
230 'ismagic':ismagic, 'isalias':isalias}
231
231
232 def arg_err(self,func):
232 def arg_err(self,func):
233 """Print docstring if incorrect arguments were passed"""
233 """Print docstring if incorrect arguments were passed"""
234 print 'Error in arguments:'
234 print 'Error in arguments:'
235 print OInspect.getdoc(func)
235 print OInspect.getdoc(func)
236
236
237 def format_latex(self,strng):
237 def format_latex(self,strng):
238 """Format a string for latex inclusion."""
238 """Format a string for latex inclusion."""
239
239
240 # Characters that need to be escaped for latex:
240 # Characters that need to be escaped for latex:
241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
242 # Magic command names as headers:
242 # Magic command names as headers:
243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
244 re.MULTILINE)
244 re.MULTILINE)
245 # Magic commands
245 # Magic commands
246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
247 re.MULTILINE)
247 re.MULTILINE)
248 # Paragraph continue
248 # Paragraph continue
249 par_re = re.compile(r'\\$',re.MULTILINE)
249 par_re = re.compile(r'\\$',re.MULTILINE)
250
250
251 # The "\n" symbol
251 # The "\n" symbol
252 newline_re = re.compile(r'\\n')
252 newline_re = re.compile(r'\\n')
253
253
254 # Now build the string for output:
254 # Now build the string for output:
255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
257 strng)
257 strng)
258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
259 strng = par_re.sub(r'\\\\',strng)
259 strng = par_re.sub(r'\\\\',strng)
260 strng = escape_re.sub(r'\\\1',strng)
260 strng = escape_re.sub(r'\\\1',strng)
261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
262 return strng
262 return strng
263
263
264 def format_screen(self,strng):
264 def format_screen(self,strng):
265 """Format a string for screen printing.
265 """Format a string for screen printing.
266
266
267 This removes some latex-type format codes."""
267 This removes some latex-type format codes."""
268 # Paragraph continue
268 # Paragraph continue
269 par_re = re.compile(r'\\$',re.MULTILINE)
269 par_re = re.compile(r'\\$',re.MULTILINE)
270 strng = par_re.sub('',strng)
270 strng = par_re.sub('',strng)
271 return strng
271 return strng
272
272
273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
274 """Parse options passed to an argument string.
274 """Parse options passed to an argument string.
275
275
276 The interface is similar to that of getopt(), but it returns back a
276 The interface is similar to that of getopt(), but it returns back a
277 Struct with the options as keys and the stripped argument string still
277 Struct with the options as keys and the stripped argument string still
278 as a string.
278 as a string.
279
279
280 arg_str is quoted as a true sys.argv vector by using shlex.split.
280 arg_str is quoted as a true sys.argv vector by using shlex.split.
281 This allows us to easily expand variables, glob files, quote
281 This allows us to easily expand variables, glob files, quote
282 arguments, etc.
282 arguments, etc.
283
283
284 Options:
284 Options:
285 -mode: default 'string'. If given as 'list', the argument string is
285 -mode: default 'string'. If given as 'list', the argument string is
286 returned as a list (split on whitespace) instead of a string.
286 returned as a list (split on whitespace) instead of a string.
287
287
288 -list_all: put all option values in lists. Normally only options
288 -list_all: put all option values in lists. Normally only options
289 appearing more than once are put in a list."""
289 appearing more than once are put in a list."""
290
290
291 # inject default options at the beginning of the input line
291 # inject default options at the beginning of the input line
292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
294
294
295 mode = kw.get('mode','string')
295 mode = kw.get('mode','string')
296 if mode not in ['string','list']:
296 if mode not in ['string','list']:
297 raise ValueError,'incorrect mode given: %s' % mode
297 raise ValueError,'incorrect mode given: %s' % mode
298 # Get options
298 # Get options
299 list_all = kw.get('list_all',0)
299 list_all = kw.get('list_all',0)
300
300
301 # Check if we have more than one argument to warrant extra processing:
301 # Check if we have more than one argument to warrant extra processing:
302 odict = {} # Dictionary with options
302 odict = {} # Dictionary with options
303 args = arg_str.split()
303 args = arg_str.split()
304 if len(args) >= 1:
304 if len(args) >= 1:
305 # If the list of inputs only has 0 or 1 thing in it, there's no
305 # If the list of inputs only has 0 or 1 thing in it, there's no
306 # need to look for options
306 # need to look for options
307 argv = shlex_split(arg_str)
307 argv = shlex_split(arg_str)
308 # Do regular option processing
308 # Do regular option processing
309 opts,args = getopt(argv,opt_str,*long_opts)
309 opts,args = getopt(argv,opt_str,*long_opts)
310 for o,a in opts:
310 for o,a in opts:
311 if o.startswith('--'):
311 if o.startswith('--'):
312 o = o[2:]
312 o = o[2:]
313 else:
313 else:
314 o = o[1:]
314 o = o[1:]
315 try:
315 try:
316 odict[o].append(a)
316 odict[o].append(a)
317 except AttributeError:
317 except AttributeError:
318 odict[o] = [odict[o],a]
318 odict[o] = [odict[o],a]
319 except KeyError:
319 except KeyError:
320 if list_all:
320 if list_all:
321 odict[o] = [a]
321 odict[o] = [a]
322 else:
322 else:
323 odict[o] = a
323 odict[o] = a
324
324
325 # Prepare opts,args for return
325 # Prepare opts,args for return
326 opts = Struct(odict)
326 opts = Struct(odict)
327 if mode == 'string':
327 if mode == 'string':
328 args = ' '.join(args)
328 args = ' '.join(args)
329
329
330 return opts,args
330 return opts,args
331
331
332 #......................................................................
332 #......................................................................
333 # And now the actual magic functions
333 # And now the actual magic functions
334
334
335 # Functions for IPython shell work (vars,funcs, config, etc)
335 # Functions for IPython shell work (vars,funcs, config, etc)
336 def magic_lsmagic(self, parameter_s = ''):
336 def magic_lsmagic(self, parameter_s = ''):
337 """List currently available magic functions."""
337 """List currently available magic functions."""
338 mesc = self.shell.ESC_MAGIC
338 mesc = self.shell.ESC_MAGIC
339 print 'Available magic functions:\n'+mesc+\
339 print 'Available magic functions:\n'+mesc+\
340 (' '+mesc).join(self.lsmagic())
340 (' '+mesc).join(self.lsmagic())
341 print '\n' + Magic.auto_status[self.shell.rc.automagic]
341 print '\n' + Magic.auto_status[self.shell.rc.automagic]
342 return None
342 return None
343
343
344 def magic_magic(self, parameter_s = ''):
344 def magic_magic(self, parameter_s = ''):
345 """Print information about the magic function system."""
345 """Print information about the magic function system."""
346
346
347 mode = ''
347 mode = ''
348 try:
348 try:
349 if parameter_s.split()[0] == '-latex':
349 if parameter_s.split()[0] == '-latex':
350 mode = 'latex'
350 mode = 'latex'
351 except:
351 except:
352 pass
352 pass
353
353
354 magic_docs = []
354 magic_docs = []
355 for fname in self.lsmagic():
355 for fname in self.lsmagic():
356 mname = 'magic_' + fname
356 mname = 'magic_' + fname
357 for space in (Magic,self,self.__class__):
357 for space in (Magic,self,self.__class__):
358 try:
358 try:
359 fn = space.__dict__[mname]
359 fn = space.__dict__[mname]
360 except KeyError:
360 except KeyError:
361 pass
361 pass
362 else:
362 else:
363 break
363 break
364 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
364 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
365 fname,fn.__doc__))
365 fname,fn.__doc__))
366 magic_docs = ''.join(magic_docs)
366 magic_docs = ''.join(magic_docs)
367
367
368 if mode == 'latex':
368 if mode == 'latex':
369 print self.format_latex(magic_docs)
369 print self.format_latex(magic_docs)
370 return
370 return
371 else:
371 else:
372 magic_docs = self.format_screen(magic_docs)
372 magic_docs = self.format_screen(magic_docs)
373
373
374 outmsg = """
374 outmsg = """
375 IPython's 'magic' functions
375 IPython's 'magic' functions
376 ===========================
376 ===========================
377
377
378 The magic function system provides a series of functions which allow you to
378 The magic function system provides a series of functions which allow you to
379 control the behavior of IPython itself, plus a lot of system-type
379 control the behavior of IPython itself, plus a lot of system-type
380 features. All these functions are prefixed with a % character, but parameters
380 features. All these functions are prefixed with a % character, but parameters
381 are given without parentheses or quotes.
381 are given without parentheses or quotes.
382
382
383 NOTE: If you have 'automagic' enabled (via the command line option or with the
383 NOTE: If you have 'automagic' enabled (via the command line option or with the
384 %automagic function), you don't need to type in the % explicitly. By default,
384 %automagic function), you don't need to type in the % explicitly. By default,
385 IPython ships with automagic on, so you should only rarely need the % escape.
385 IPython ships with automagic on, so you should only rarely need the % escape.
386
386
387 Example: typing '%cd mydir' (without the quotes) changes you working directory
387 Example: typing '%cd mydir' (without the quotes) changes you working directory
388 to 'mydir', if it exists.
388 to 'mydir', if it exists.
389
389
390 You can define your own magic functions to extend the system. See the supplied
390 You can define your own magic functions to extend the system. See the supplied
391 ipythonrc and example-magic.py files for details (in your ipython
391 ipythonrc and example-magic.py files for details (in your ipython
392 configuration directory, typically $HOME/.ipython/).
392 configuration directory, typically $HOME/.ipython/).
393
393
394 You can also define your own aliased names for magic functions. In your
394 You can also define your own aliased names for magic functions. In your
395 ipythonrc file, placing a line like:
395 ipythonrc file, placing a line like:
396
396
397 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
397 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
398
398
399 will define %pf as a new name for %profile.
399 will define %pf as a new name for %profile.
400
400
401 You can also call magics in code using the ipmagic() function, which IPython
401 You can also call magics in code using the ipmagic() function, which IPython
402 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
402 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
403
403
404 For a list of the available magic functions, use %lsmagic. For a description
404 For a list of the available magic functions, use %lsmagic. For a description
405 of any of them, type %magic_name?, e.g. '%cd?'.
405 of any of them, type %magic_name?, e.g. '%cd?'.
406
406
407 Currently the magic system has the following functions:\n"""
407 Currently the magic system has the following functions:\n"""
408
408
409 mesc = self.shell.ESC_MAGIC
409 mesc = self.shell.ESC_MAGIC
410 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
410 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
411 "\n\n%s%s\n\n%s" % (outmsg,
411 "\n\n%s%s\n\n%s" % (outmsg,
412 magic_docs,mesc,mesc,
412 magic_docs,mesc,mesc,
413 (' '+mesc).join(self.lsmagic()),
413 (' '+mesc).join(self.lsmagic()),
414 Magic.auto_status[self.shell.rc.automagic] ) )
414 Magic.auto_status[self.shell.rc.automagic] ) )
415
415
416 page(outmsg,screen_lines=self.shell.rc.screen_length)
416 page(outmsg,screen_lines=self.shell.rc.screen_length)
417
417
418 def magic_automagic(self, parameter_s = ''):
418 def magic_automagic(self, parameter_s = ''):
419 """Make magic functions callable without having to type the initial %.
419 """Make magic functions callable without having to type the initial %.
420
420
421 Toggles on/off (when off, you must call it as %automagic, of
421 Toggles on/off (when off, you must call it as %automagic, of
422 course). Note that magic functions have lowest priority, so if there's
422 course). Note that magic functions have lowest priority, so if there's
423 a variable whose name collides with that of a magic fn, automagic
423 a variable whose name collides with that of a magic fn, automagic
424 won't work for that function (you get the variable instead). However,
424 won't work for that function (you get the variable instead). However,
425 if you delete the variable (del var), the previously shadowed magic
425 if you delete the variable (del var), the previously shadowed magic
426 function becomes visible to automagic again."""
426 function becomes visible to automagic again."""
427
427
428 rc = self.shell.rc
428 rc = self.shell.rc
429 rc.automagic = not rc.automagic
429 rc.automagic = not rc.automagic
430 print '\n' + Magic.auto_status[rc.automagic]
430 print '\n' + Magic.auto_status[rc.automagic]
431
431
432 def magic_autocall(self, parameter_s = ''):
432 def magic_autocall(self, parameter_s = ''):
433 """Make functions callable without having to type parentheses.
433 """Make functions callable without having to type parentheses.
434
434
435 Usage:
435 Usage:
436
436
437 %autocall [mode]
437 %autocall [mode]
438
438
439 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
439 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
440 value is toggled on and off (remembering the previous state)."""
440 value is toggled on and off (remembering the previous state)."""
441
441
442 rc = self.shell.rc
442 rc = self.shell.rc
443
443
444 if parameter_s:
444 if parameter_s:
445 arg = int(parameter_s)
445 arg = int(parameter_s)
446 else:
446 else:
447 arg = 'toggle'
447 arg = 'toggle'
448
448
449 if not arg in (0,1,2,'toggle'):
449 if not arg in (0,1,2,'toggle'):
450 error('Valid modes: (0->Off, 1->Smart, 2->Full')
450 error('Valid modes: (0->Off, 1->Smart, 2->Full')
451 return
451 return
452
452
453 if arg in (0,1,2):
453 if arg in (0,1,2):
454 rc.autocall = arg
454 rc.autocall = arg
455 else: # toggle
455 else: # toggle
456 if rc.autocall:
456 if rc.autocall:
457 self._magic_state.autocall_save = rc.autocall
457 self._magic_state.autocall_save = rc.autocall
458 rc.autocall = 0
458 rc.autocall = 0
459 else:
459 else:
460 try:
460 try:
461 rc.autocall = self._magic_state.autocall_save
461 rc.autocall = self._magic_state.autocall_save
462 except AttributeError:
462 except AttributeError:
463 rc.autocall = self._magic_state.autocall_save = 1
463 rc.autocall = self._magic_state.autocall_save = 1
464
464
465 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
465 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
466
466
467 def magic_autoindent(self, parameter_s = ''):
467 def magic_autoindent(self, parameter_s = ''):
468 """Toggle autoindent on/off (if available)."""
468 """Toggle autoindent on/off (if available)."""
469
469
470 self.shell.set_autoindent()
470 self.shell.set_autoindent()
471 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
471 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
472
472
473 def magic_system_verbose(self, parameter_s = ''):
473 def magic_system_verbose(self, parameter_s = ''):
474 """Toggle verbose printing of system calls on/off."""
474 """Toggle verbose printing of system calls on/off."""
475
475
476 self.shell.rc_set_toggle('system_verbose')
476 self.shell.rc_set_toggle('system_verbose')
477 print "System verbose printing is:",\
477 print "System verbose printing is:",\
478 ['OFF','ON'][self.shell.rc.system_verbose]
478 ['OFF','ON'][self.shell.rc.system_verbose]
479
479
480 def magic_history(self, parameter_s = ''):
480 def magic_history(self, parameter_s = ''):
481 """Print input history (_i<n> variables), with most recent last.
481 """Print input history (_i<n> variables), with most recent last.
482
482
483 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
483 %history -> print at most 40 inputs (some may be multi-line)\\
484 %history [-n] n -> print at most n inputs\\
484 %history n -> print at most n inputs\\
485 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
485 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
486
486
487 Each input's number <n> is shown, and is accessible as the
487 Each input's number <n> is shown, and is accessible as the
488 automatically generated variable _i<n>. Multi-line statements are
488 automatically generated variable _i<n>. Multi-line statements are
489 printed starting at a new line for easy copy/paste.
489 printed starting at a new line for easy copy/paste.
490
491
492 Options:
490
493
491 If option -n is used, input numbers are not printed. This is useful if
494 -n: do NOT print line numbers. This is useful if you want to get a
492 you want to get a printout of many lines which can be directly pasted
495 printout of many lines which can be directly pasted into a text
493 into a text editor.
496 editor.
494
497
495 This feature is only available if numbered prompts are in use."""
498 This feature is only available if numbered prompts are in use.
499
500 -r: print the 'raw' history. IPython filters your input and
501 converts it all into valid Python source before executing it (things
502 like magics or aliases are turned into function calls, for
503 example). With this option, you'll see the unfiltered history
504 instead of the filtered version: '%cd /' will be seen as '%cd /'
505 instead of 'ipmagic("%cd /")'.
506 """
496
507
497 shell = self.shell
508 shell = self.shell
498 if not shell.outputcache.do_full_cache:
509 if not shell.outputcache.do_full_cache:
499 print 'This feature is only available if numbered prompts are in use.'
510 print 'This feature is only available if numbered prompts are in use.'
500 return
511 return
501 opts,args = self.parse_options(parameter_s,'n',mode='list')
512 opts,args = self.parse_options(parameter_s,'nr',mode='list')
513
514 if opts.has_key('r'):
515 input_hist = shell.input_hist_raw
516 else:
517 input_hist = shell.input_hist
502
518
503 input_hist = shell.input_hist
504 default_length = 40
519 default_length = 40
505 if len(args) == 0:
520 if len(args) == 0:
506 final = len(input_hist)
521 final = len(input_hist)
507 init = max(1,final-default_length)
522 init = max(1,final-default_length)
508 elif len(args) == 1:
523 elif len(args) == 1:
509 final = len(input_hist)
524 final = len(input_hist)
510 init = max(1,final-int(args[0]))
525 init = max(1,final-int(args[0]))
511 elif len(args) == 2:
526 elif len(args) == 2:
512 init,final = map(int,args)
527 init,final = map(int,args)
513 else:
528 else:
514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
529 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
515 print self.magic_hist.__doc__
530 print self.magic_hist.__doc__
516 return
531 return
517 width = len(str(final))
532 width = len(str(final))
518 line_sep = ['','\n']
533 line_sep = ['','\n']
519 print_nums = not opts.has_key('n')
534 print_nums = not opts.has_key('n')
520 for in_num in range(init,final):
535 for in_num in range(init,final):
521 inline = input_hist[in_num]
536 inline = input_hist[in_num]
522 multiline = int(inline.count('\n') > 1)
537 multiline = int(inline.count('\n') > 1)
523 if print_nums:
538 if print_nums:
524 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
539 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
525 print inline,
540 print inline,
526
541
527 def magic_hist(self, parameter_s=''):
542 def magic_hist(self, parameter_s=''):
528 """Alternate name for %history."""
543 """Alternate name for %history."""
529 return self.magic_history(parameter_s)
544 return self.magic_history(parameter_s)
530
545
531 def magic_p(self, parameter_s=''):
546 def magic_p(self, parameter_s=''):
532 """Just a short alias for Python's 'print'."""
547 """Just a short alias for Python's 'print'."""
533 exec 'print ' + parameter_s in self.shell.user_ns
548 exec 'print ' + parameter_s in self.shell.user_ns
534
549
535 def magic_r(self, parameter_s=''):
550 def magic_r(self, parameter_s=''):
536 """Repeat previous input.
551 """Repeat previous input.
537
552
538 If given an argument, repeats the previous command which starts with
553 If given an argument, repeats the previous command which starts with
539 the same string, otherwise it just repeats the previous input.
554 the same string, otherwise it just repeats the previous input.
540
555
541 Shell escaped commands (with ! as first character) are not recognized
556 Shell escaped commands (with ! as first character) are not recognized
542 by this system, only pure python code and magic commands.
557 by this system, only pure python code and magic commands.
543 """
558 """
544
559
545 start = parameter_s.strip()
560 start = parameter_s.strip()
546 esc_magic = self.shell.ESC_MAGIC
561 esc_magic = self.shell.ESC_MAGIC
547 # Identify magic commands even if automagic is on (which means
562 # Identify magic commands even if automagic is on (which means
548 # the in-memory version is different from that typed by the user).
563 # the in-memory version is different from that typed by the user).
549 if self.shell.rc.automagic:
564 if self.shell.rc.automagic:
550 start_magic = esc_magic+start
565 start_magic = esc_magic+start
551 else:
566 else:
552 start_magic = start
567 start_magic = start
553 # Look through the input history in reverse
568 # Look through the input history in reverse
554 for n in range(len(self.shell.input_hist)-2,0,-1):
569 for n in range(len(self.shell.input_hist)-2,0,-1):
555 input = self.shell.input_hist[n]
570 input = self.shell.input_hist[n]
556 # skip plain 'r' lines so we don't recurse to infinity
571 # skip plain 'r' lines so we don't recurse to infinity
557 if input != 'ipmagic("r")\n' and \
572 if input != 'ipmagic("r")\n' and \
558 (input.startswith(start) or input.startswith(start_magic)):
573 (input.startswith(start) or input.startswith(start_magic)):
559 #print 'match',`input` # dbg
574 #print 'match',`input` # dbg
560 print 'Executing:',input,
575 print 'Executing:',input,
561 self.shell.runlines(input)
576 self.shell.runlines(input)
562 return
577 return
563 print 'No previous input matching `%s` found.' % start
578 print 'No previous input matching `%s` found.' % start
564
579
565 def magic_page(self, parameter_s=''):
580 def magic_page(self, parameter_s=''):
566 """Pretty print the object and display it through a pager.
581 """Pretty print the object and display it through a pager.
567
582
568 If no parameter is given, use _ (last output)."""
583 If no parameter is given, use _ (last output)."""
569 # After a function contributed by Olivier Aubert, slightly modified.
584 # After a function contributed by Olivier Aubert, slightly modified.
570
585
571 oname = parameter_s and parameter_s or '_'
586 oname = parameter_s and parameter_s or '_'
572 info = self._ofind(oname)
587 info = self._ofind(oname)
573 if info['found']:
588 if info['found']:
574 page(pformat(info['obj']))
589 page(pformat(info['obj']))
575 else:
590 else:
576 print 'Object `%s` not found' % oname
591 print 'Object `%s` not found' % oname
577
592
578 def magic_profile(self, parameter_s=''):
593 def magic_profile(self, parameter_s=''):
579 """Print your currently active IPyhton profile."""
594 """Print your currently active IPyhton profile."""
580 if self.shell.rc.profile:
595 if self.shell.rc.profile:
581 printpl('Current IPython profile: $self.shell.rc.profile.')
596 printpl('Current IPython profile: $self.shell.rc.profile.')
582 else:
597 else:
583 print 'No profile active.'
598 print 'No profile active.'
584
599
585 def _inspect(self,meth,oname,**kw):
600 def _inspect(self,meth,oname,**kw):
586 """Generic interface to the inspector system.
601 """Generic interface to the inspector system.
587
602
588 This function is meant to be called by pdef, pdoc & friends."""
603 This function is meant to be called by pdef, pdoc & friends."""
589
604
590 oname = oname.strip()
605 oname = oname.strip()
591 info = Struct(self._ofind(oname))
606 info = Struct(self._ofind(oname))
592 if info.found:
607 if info.found:
593 pmethod = getattr(self.shell.inspector,meth)
608 pmethod = getattr(self.shell.inspector,meth)
594 formatter = info.ismagic and self.format_screen or None
609 formatter = info.ismagic and self.format_screen or None
595 if meth == 'pdoc':
610 if meth == 'pdoc':
596 pmethod(info.obj,oname,formatter)
611 pmethod(info.obj,oname,formatter)
597 elif meth == 'pinfo':
612 elif meth == 'pinfo':
598 pmethod(info.obj,oname,formatter,info,**kw)
613 pmethod(info.obj,oname,formatter,info,**kw)
599 else:
614 else:
600 pmethod(info.obj,oname)
615 pmethod(info.obj,oname)
601 else:
616 else:
602 print 'Object `%s` not found.' % oname
617 print 'Object `%s` not found.' % oname
603 return 'not found' # so callers can take other action
618 return 'not found' # so callers can take other action
604
619
605 def magic_pdef(self, parameter_s=''):
620 def magic_pdef(self, parameter_s=''):
606 """Print the definition header for any callable object.
621 """Print the definition header for any callable object.
607
622
608 If the object is a class, print the constructor information."""
623 If the object is a class, print the constructor information."""
609 self._inspect('pdef',parameter_s)
624 self._inspect('pdef',parameter_s)
610
625
611 def magic_pdoc(self, parameter_s=''):
626 def magic_pdoc(self, parameter_s=''):
612 """Print the docstring for an object.
627 """Print the docstring for an object.
613
628
614 If the given object is a class, it will print both the class and the
629 If the given object is a class, it will print both the class and the
615 constructor docstrings."""
630 constructor docstrings."""
616 self._inspect('pdoc',parameter_s)
631 self._inspect('pdoc',parameter_s)
617
632
618 def magic_psource(self, parameter_s=''):
633 def magic_psource(self, parameter_s=''):
619 """Print (or run through pager) the source code for an object."""
634 """Print (or run through pager) the source code for an object."""
620 self._inspect('psource',parameter_s)
635 self._inspect('psource',parameter_s)
621
636
622 def magic_pfile(self, parameter_s=''):
637 def magic_pfile(self, parameter_s=''):
623 """Print (or run through pager) the file where an object is defined.
638 """Print (or run through pager) the file where an object is defined.
624
639
625 The file opens at the line where the object definition begins. IPython
640 The file opens at the line where the object definition begins. IPython
626 will honor the environment variable PAGER if set, and otherwise will
641 will honor the environment variable PAGER if set, and otherwise will
627 do its best to print the file in a convenient form.
642 do its best to print the file in a convenient form.
628
643
629 If the given argument is not an object currently defined, IPython will
644 If the given argument is not an object currently defined, IPython will
630 try to interpret it as a filename (automatically adding a .py extension
645 try to interpret it as a filename (automatically adding a .py extension
631 if needed). You can thus use %pfile as a syntax highlighting code
646 if needed). You can thus use %pfile as a syntax highlighting code
632 viewer."""
647 viewer."""
633
648
634 # first interpret argument as an object name
649 # first interpret argument as an object name
635 out = self._inspect('pfile',parameter_s)
650 out = self._inspect('pfile',parameter_s)
636 # if not, try the input as a filename
651 # if not, try the input as a filename
637 if out == 'not found':
652 if out == 'not found':
638 try:
653 try:
639 filename = get_py_filename(parameter_s)
654 filename = get_py_filename(parameter_s)
640 except IOError,msg:
655 except IOError,msg:
641 print msg
656 print msg
642 return
657 return
643 page(self.shell.inspector.format(file(filename).read()))
658 page(self.shell.inspector.format(file(filename).read()))
644
659
645 def magic_pinfo(self, parameter_s=''):
660 def magic_pinfo(self, parameter_s=''):
646 """Provide detailed information about an object.
661 """Provide detailed information about an object.
647
662
648 '%pinfo object' is just a synonym for object? or ?object."""
663 '%pinfo object' is just a synonym for object? or ?object."""
649
664
650 #print 'pinfo par: <%s>' % parameter_s # dbg
665 #print 'pinfo par: <%s>' % parameter_s # dbg
651
666
652 # detail_level: 0 -> obj? , 1 -> obj??
667 # detail_level: 0 -> obj? , 1 -> obj??
653 detail_level = 0
668 detail_level = 0
654 # We need to detect if we got called as 'pinfo pinfo foo', which can
669 # We need to detect if we got called as 'pinfo pinfo foo', which can
655 # happen if the user types 'pinfo foo?' at the cmd line.
670 # happen if the user types 'pinfo foo?' at the cmd line.
656 pinfo,qmark1,oname,qmark2 = \
671 pinfo,qmark1,oname,qmark2 = \
657 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
672 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
658 if pinfo or qmark1 or qmark2:
673 if pinfo or qmark1 or qmark2:
659 detail_level = 1
674 detail_level = 1
660 if "*" in oname:
675 if "*" in oname:
661 self.magic_psearch(oname)
676 self.magic_psearch(oname)
662 else:
677 else:
663 self._inspect('pinfo',oname,detail_level=detail_level)
678 self._inspect('pinfo',oname,detail_level=detail_level)
664
679
665 def magic_psearch(self, parameter_s=''):
680 def magic_psearch(self, parameter_s=''):
666 """Search for object in namespaces by wildcard.
681 """Search for object in namespaces by wildcard.
667
682
668 %psearch [options] PATTERN [OBJECT TYPE]
683 %psearch [options] PATTERN [OBJECT TYPE]
669
684
670 Note: ? can be used as a synonym for %psearch, at the beginning or at
685 Note: ? can be used as a synonym for %psearch, at the beginning or at
671 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
686 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
672 rest of the command line must be unchanged (options come first), so
687 rest of the command line must be unchanged (options come first), so
673 for example the following forms are equivalent
688 for example the following forms are equivalent
674
689
675 %psearch -i a* function
690 %psearch -i a* function
676 -i a* function?
691 -i a* function?
677 ?-i a* function
692 ?-i a* function
678
693
679 Arguments:
694 Arguments:
680
695
681 PATTERN
696 PATTERN
682
697
683 where PATTERN is a string containing * as a wildcard similar to its
698 where PATTERN is a string containing * as a wildcard similar to its
684 use in a shell. The pattern is matched in all namespaces on the
699 use in a shell. The pattern is matched in all namespaces on the
685 search path. By default objects starting with a single _ are not
700 search path. By default objects starting with a single _ are not
686 matched, many IPython generated objects have a single
701 matched, many IPython generated objects have a single
687 underscore. The default is case insensitive matching. Matching is
702 underscore. The default is case insensitive matching. Matching is
688 also done on the attributes of objects and not only on the objects
703 also done on the attributes of objects and not only on the objects
689 in a module.
704 in a module.
690
705
691 [OBJECT TYPE]
706 [OBJECT TYPE]
692
707
693 Is the name of a python type from the types module. The name is
708 Is the name of a python type from the types module. The name is
694 given in lowercase without the ending type, ex. StringType is
709 given in lowercase without the ending type, ex. StringType is
695 written string. By adding a type here only objects matching the
710 written string. By adding a type here only objects matching the
696 given type are matched. Using all here makes the pattern match all
711 given type are matched. Using all here makes the pattern match all
697 types (this is the default).
712 types (this is the default).
698
713
699 Options:
714 Options:
700
715
701 -a: makes the pattern match even objects whose names start with a
716 -a: makes the pattern match even objects whose names start with a
702 single underscore. These names are normally ommitted from the
717 single underscore. These names are normally ommitted from the
703 search.
718 search.
704
719
705 -i/-c: make the pattern case insensitive/sensitive. If neither of
720 -i/-c: make the pattern case insensitive/sensitive. If neither of
706 these options is given, the default is read from your ipythonrc
721 these options is given, the default is read from your ipythonrc
707 file. The option name which sets this value is
722 file. The option name which sets this value is
708 'wildcards_case_sensitive'. If this option is not specified in your
723 'wildcards_case_sensitive'. If this option is not specified in your
709 ipythonrc file, IPython's internal default is to do a case sensitive
724 ipythonrc file, IPython's internal default is to do a case sensitive
710 search.
725 search.
711
726
712 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
727 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
713 specifiy can be searched in any of the following namespaces:
728 specifiy can be searched in any of the following namespaces:
714 'builtin', 'user', 'user_global','internal', 'alias', where
729 'builtin', 'user', 'user_global','internal', 'alias', where
715 'builtin' and 'user' are the search defaults. Note that you should
730 'builtin' and 'user' are the search defaults. Note that you should
716 not use quotes when specifying namespaces.
731 not use quotes when specifying namespaces.
717
732
718 'Builtin' contains the python module builtin, 'user' contains all
733 'Builtin' contains the python module builtin, 'user' contains all
719 user data, 'alias' only contain the shell aliases and no python
734 user data, 'alias' only contain the shell aliases and no python
720 objects, 'internal' contains objects used by IPython. The
735 objects, 'internal' contains objects used by IPython. The
721 'user_global' namespace is only used by embedded IPython instances,
736 'user_global' namespace is only used by embedded IPython instances,
722 and it contains module-level globals. You can add namespaces to the
737 and it contains module-level globals. You can add namespaces to the
723 search with -s or exclude them with -e (these options can be given
738 search with -s or exclude them with -e (these options can be given
724 more than once).
739 more than once).
725
740
726 Examples:
741 Examples:
727
742
728 %psearch a* -> objects beginning with an a
743 %psearch a* -> objects beginning with an a
729 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
744 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
730 %psearch a* function -> all functions beginning with an a
745 %psearch a* function -> all functions beginning with an a
731 %psearch re.e* -> objects beginning with an e in module re
746 %psearch re.e* -> objects beginning with an e in module re
732 %psearch r*.e* -> objects that start with e in modules starting in r
747 %psearch r*.e* -> objects that start with e in modules starting in r
733 %psearch r*.* string -> all strings in modules beginning with r
748 %psearch r*.* string -> all strings in modules beginning with r
734
749
735 Case sensitve search:
750 Case sensitve search:
736
751
737 %psearch -c a* list all object beginning with lower case a
752 %psearch -c a* list all object beginning with lower case a
738
753
739 Show objects beginning with a single _:
754 Show objects beginning with a single _:
740
755
741 %psearch -a _* list objects beginning with a single underscore"""
756 %psearch -a _* list objects beginning with a single underscore"""
742
757
743 # default namespaces to be searched
758 # default namespaces to be searched
744 def_search = ['user','builtin']
759 def_search = ['user','builtin']
745
760
746 # Process options/args
761 # Process options/args
747 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
762 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
748 opt = opts.get
763 opt = opts.get
749 shell = self.shell
764 shell = self.shell
750 psearch = shell.inspector.psearch
765 psearch = shell.inspector.psearch
751
766
752 # select case options
767 # select case options
753 if opts.has_key('i'):
768 if opts.has_key('i'):
754 ignore_case = True
769 ignore_case = True
755 elif opts.has_key('c'):
770 elif opts.has_key('c'):
756 ignore_case = False
771 ignore_case = False
757 else:
772 else:
758 ignore_case = not shell.rc.wildcards_case_sensitive
773 ignore_case = not shell.rc.wildcards_case_sensitive
759
774
760 # Build list of namespaces to search from user options
775 # Build list of namespaces to search from user options
761 def_search.extend(opt('s',[]))
776 def_search.extend(opt('s',[]))
762 ns_exclude = ns_exclude=opt('e',[])
777 ns_exclude = ns_exclude=opt('e',[])
763 ns_search = [nm for nm in def_search if nm not in ns_exclude]
778 ns_search = [nm for nm in def_search if nm not in ns_exclude]
764
779
765 # Call the actual search
780 # Call the actual search
766 try:
781 try:
767 psearch(args,shell.ns_table,ns_search,
782 psearch(args,shell.ns_table,ns_search,
768 show_all=opt('a'),ignore_case=ignore_case)
783 show_all=opt('a'),ignore_case=ignore_case)
769 except:
784 except:
770 shell.showtraceback()
785 shell.showtraceback()
771
786
772 def magic_who_ls(self, parameter_s=''):
787 def magic_who_ls(self, parameter_s=''):
773 """Return a sorted list of all interactive variables.
788 """Return a sorted list of all interactive variables.
774
789
775 If arguments are given, only variables of types matching these
790 If arguments are given, only variables of types matching these
776 arguments are returned."""
791 arguments are returned."""
777
792
778 user_ns = self.shell.user_ns
793 user_ns = self.shell.user_ns
779 internal_ns = self.shell.internal_ns
794 internal_ns = self.shell.internal_ns
780 user_config_ns = self.shell.user_config_ns
795 user_config_ns = self.shell.user_config_ns
781 out = []
796 out = []
782 typelist = parameter_s.split()
797 typelist = parameter_s.split()
783
798
784 for i in user_ns:
799 for i in user_ns:
785 if not (i.startswith('_') or i.startswith('_i')) \
800 if not (i.startswith('_') or i.startswith('_i')) \
786 and not (i in internal_ns or i in user_config_ns):
801 and not (i in internal_ns or i in user_config_ns):
787 if typelist:
802 if typelist:
788 if type(user_ns[i]).__name__ in typelist:
803 if type(user_ns[i]).__name__ in typelist:
789 out.append(i)
804 out.append(i)
790 else:
805 else:
791 out.append(i)
806 out.append(i)
792 out.sort()
807 out.sort()
793 return out
808 return out
794
809
795 def magic_who(self, parameter_s=''):
810 def magic_who(self, parameter_s=''):
796 """Print all interactive variables, with some minimal formatting.
811 """Print all interactive variables, with some minimal formatting.
797
812
798 If any arguments are given, only variables whose type matches one of
813 If any arguments are given, only variables whose type matches one of
799 these are printed. For example:
814 these are printed. For example:
800
815
801 %who function str
816 %who function str
802
817
803 will only list functions and strings, excluding all other types of
818 will only list functions and strings, excluding all other types of
804 variables. To find the proper type names, simply use type(var) at a
819 variables. To find the proper type names, simply use type(var) at a
805 command line to see how python prints type names. For example:
820 command line to see how python prints type names. For example:
806
821
807 In [1]: type('hello')\\
822 In [1]: type('hello')\\
808 Out[1]: <type 'str'>
823 Out[1]: <type 'str'>
809
824
810 indicates that the type name for strings is 'str'.
825 indicates that the type name for strings is 'str'.
811
826
812 %who always excludes executed names loaded through your configuration
827 %who always excludes executed names loaded through your configuration
813 file and things which are internal to IPython.
828 file and things which are internal to IPython.
814
829
815 This is deliberate, as typically you may load many modules and the
830 This is deliberate, as typically you may load many modules and the
816 purpose of %who is to show you only what you've manually defined."""
831 purpose of %who is to show you only what you've manually defined."""
817
832
818 varlist = self.magic_who_ls(parameter_s)
833 varlist = self.magic_who_ls(parameter_s)
819 if not varlist:
834 if not varlist:
820 print 'Interactive namespace is empty.'
835 print 'Interactive namespace is empty.'
821 return
836 return
822
837
823 # if we have variables, move on...
838 # if we have variables, move on...
824
839
825 # stupid flushing problem: when prompts have no separators, stdout is
840 # stupid flushing problem: when prompts have no separators, stdout is
826 # getting lost. I'm starting to think this is a python bug. I'm having
841 # getting lost. I'm starting to think this is a python bug. I'm having
827 # to force a flush with a print because even a sys.stdout.flush
842 # to force a flush with a print because even a sys.stdout.flush
828 # doesn't seem to do anything!
843 # doesn't seem to do anything!
829
844
830 count = 0
845 count = 0
831 for i in varlist:
846 for i in varlist:
832 print i+'\t',
847 print i+'\t',
833 count += 1
848 count += 1
834 if count > 8:
849 if count > 8:
835 count = 0
850 count = 0
836 print
851 print
837 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
852 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
838
853
839 print # well, this does force a flush at the expense of an extra \n
854 print # well, this does force a flush at the expense of an extra \n
840
855
841 def magic_whos(self, parameter_s=''):
856 def magic_whos(self, parameter_s=''):
842 """Like %who, but gives some extra information about each variable.
857 """Like %who, but gives some extra information about each variable.
843
858
844 The same type filtering of %who can be applied here.
859 The same type filtering of %who can be applied here.
845
860
846 For all variables, the type is printed. Additionally it prints:
861 For all variables, the type is printed. Additionally it prints:
847
862
848 - For {},[],(): their length.
863 - For {},[],(): their length.
849
864
850 - For Numeric arrays, a summary with shape, number of elements,
865 - For Numeric arrays, a summary with shape, number of elements,
851 typecode and size in memory.
866 typecode and size in memory.
852
867
853 - Everything else: a string representation, snipping their middle if
868 - Everything else: a string representation, snipping their middle if
854 too long."""
869 too long."""
855
870
856 varnames = self.magic_who_ls(parameter_s)
871 varnames = self.magic_who_ls(parameter_s)
857 if not varnames:
872 if not varnames:
858 print 'Interactive namespace is empty.'
873 print 'Interactive namespace is empty.'
859 return
874 return
860
875
861 # if we have variables, move on...
876 # if we have variables, move on...
862
877
863 # for these types, show len() instead of data:
878 # for these types, show len() instead of data:
864 seq_types = [types.DictType,types.ListType,types.TupleType]
879 seq_types = [types.DictType,types.ListType,types.TupleType]
865
880
866 # for Numeric arrays, display summary info
881 # for Numeric arrays, display summary info
867 try:
882 try:
868 import Numeric
883 import Numeric
869 except ImportError:
884 except ImportError:
870 array_type = None
885 array_type = None
871 else:
886 else:
872 array_type = Numeric.ArrayType.__name__
887 array_type = Numeric.ArrayType.__name__
873
888
874 # Find all variable names and types so we can figure out column sizes
889 # Find all variable names and types so we can figure out column sizes
875 get_vars = lambda i: self.shell.user_ns[i]
890 get_vars = lambda i: self.shell.user_ns[i]
876 type_name = lambda v: type(v).__name__
891 type_name = lambda v: type(v).__name__
877 varlist = map(get_vars,varnames)
892 varlist = map(get_vars,varnames)
878
893
879 typelist = []
894 typelist = []
880 for vv in varlist:
895 for vv in varlist:
881 tt = type_name(vv)
896 tt = type_name(vv)
882 if tt=='instance':
897 if tt=='instance':
883 typelist.append(str(vv.__class__))
898 typelist.append(str(vv.__class__))
884 else:
899 else:
885 typelist.append(tt)
900 typelist.append(tt)
886
901
887 # column labels and # of spaces as separator
902 # column labels and # of spaces as separator
888 varlabel = 'Variable'
903 varlabel = 'Variable'
889 typelabel = 'Type'
904 typelabel = 'Type'
890 datalabel = 'Data/Info'
905 datalabel = 'Data/Info'
891 colsep = 3
906 colsep = 3
892 # variable format strings
907 # variable format strings
893 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
908 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
894 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
909 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
895 aformat = "%s: %s elems, type `%s`, %s bytes"
910 aformat = "%s: %s elems, type `%s`, %s bytes"
896 # find the size of the columns to format the output nicely
911 # find the size of the columns to format the output nicely
897 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
912 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
898 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
913 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
899 # table header
914 # table header
900 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
915 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
901 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
916 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
902 # and the table itself
917 # and the table itself
903 kb = 1024
918 kb = 1024
904 Mb = 1048576 # kb**2
919 Mb = 1048576 # kb**2
905 for vname,var,vtype in zip(varnames,varlist,typelist):
920 for vname,var,vtype in zip(varnames,varlist,typelist):
906 print itpl(vformat),
921 print itpl(vformat),
907 if vtype in seq_types:
922 if vtype in seq_types:
908 print len(var)
923 print len(var)
909 elif vtype==array_type:
924 elif vtype==array_type:
910 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
925 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
911 vsize = Numeric.size(var)
926 vsize = Numeric.size(var)
912 vbytes = vsize*var.itemsize()
927 vbytes = vsize*var.itemsize()
913 if vbytes < 100000:
928 if vbytes < 100000:
914 print aformat % (vshape,vsize,var.typecode(),vbytes)
929 print aformat % (vshape,vsize,var.typecode(),vbytes)
915 else:
930 else:
916 print aformat % (vshape,vsize,var.typecode(),vbytes),
931 print aformat % (vshape,vsize,var.typecode(),vbytes),
917 if vbytes < Mb:
932 if vbytes < Mb:
918 print '(%s kb)' % (vbytes/kb,)
933 print '(%s kb)' % (vbytes/kb,)
919 else:
934 else:
920 print '(%s Mb)' % (vbytes/Mb,)
935 print '(%s Mb)' % (vbytes/Mb,)
921 else:
936 else:
922 vstr = str(var).replace('\n','\\n')
937 vstr = str(var).replace('\n','\\n')
923 if len(vstr) < 50:
938 if len(vstr) < 50:
924 print vstr
939 print vstr
925 else:
940 else:
926 printpl(vfmt_short)
941 printpl(vfmt_short)
927
942
928 def magic_reset(self, parameter_s=''):
943 def magic_reset(self, parameter_s=''):
929 """Resets the namespace by removing all names defined by the user.
944 """Resets the namespace by removing all names defined by the user.
930
945
931 Input/Output history are left around in case you need them."""
946 Input/Output history are left around in case you need them."""
932
947
933 ans = raw_input(
948 ans = raw_input(
934 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
949 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
935 if not ans.lower() == 'y':
950 if not ans.lower() == 'y':
936 print 'Nothing done.'
951 print 'Nothing done.'
937 return
952 return
938 user_ns = self.shell.user_ns
953 user_ns = self.shell.user_ns
939 for i in self.magic_who_ls():
954 for i in self.magic_who_ls():
940 del(user_ns[i])
955 del(user_ns[i])
941
956
942 def magic_config(self,parameter_s=''):
957 def magic_config(self,parameter_s=''):
943 """Show IPython's internal configuration."""
958 """Show IPython's internal configuration."""
944
959
945 page('Current configuration structure:\n'+
960 page('Current configuration structure:\n'+
946 pformat(self.shell.rc.dict()))
961 pformat(self.shell.rc.dict()))
947
962
948 def magic_logstart(self,parameter_s=''):
963 def magic_logstart(self,parameter_s=''):
949 """Start logging anywhere in a session.
964 """Start logging anywhere in a session.
950
965
951 %logstart [-o|-t] [log_name [log_mode]]
966 %logstart [-o|-t] [log_name [log_mode]]
952
967
953 If no name is given, it defaults to a file named 'ipython_log.py' in your
968 If no name is given, it defaults to a file named 'ipython_log.py' in your
954 current directory, in 'rotate' mode (see below).
969 current directory, in 'rotate' mode (see below).
955
970
956 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
971 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
957 history up to that point and then continues logging.
972 history up to that point and then continues logging.
958
973
959 %logstart takes a second optional parameter: logging mode. This can be one
974 %logstart takes a second optional parameter: logging mode. This can be one
960 of (note that the modes are given unquoted):\\
975 of (note that the modes are given unquoted):\\
961 append: well, that says it.\\
976 append: well, that says it.\\
962 backup: rename (if exists) to name~ and start name.\\
977 backup: rename (if exists) to name~ and start name.\\
963 global: single logfile in your home dir, appended to.\\
978 global: single logfile in your home dir, appended to.\\
964 over : overwrite existing log.\\
979 over : overwrite existing log.\\
965 rotate: create rotating logs name.1~, name.2~, etc.
980 rotate: create rotating logs name.1~, name.2~, etc.
966
981
967 Options:
982 Options:
968
983
969 -o: log also IPython's output. In this mode, all commands which
984 -o: log also IPython's output. In this mode, all commands which
970 generate an Out[NN] prompt are recorded to the logfile, right after
985 generate an Out[NN] prompt are recorded to the logfile, right after
971 their corresponding input line. The output lines are always
986 their corresponding input line. The output lines are always
972 prepended with a '#[Out]# ' marker, so that the log remains valid
987 prepended with a '#[Out]# ' marker, so that the log remains valid
973 Python code.
988 Python code.
974
989
975 Since this marker is always the same, filtering only the output from
990 Since this marker is always the same, filtering only the output from
976 a log is very easy, using for example a simple awk call:
991 a log is very easy, using for example a simple awk call:
977
992
978 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
993 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
979
994
980 -t: put timestamps before each input line logged (these are put in
995 -t: put timestamps before each input line logged (these are put in
981 comments)."""
996 comments)."""
982
997
983 opts,par = self.parse_options(parameter_s,'ot')
998 opts,par = self.parse_options(parameter_s,'ot')
984 log_output = 'o' in opts
999 log_output = 'o' in opts
985 timestamp = 't' in opts
1000 timestamp = 't' in opts
986
1001
987 rc = self.shell.rc
1002 rc = self.shell.rc
988 logger = self.shell.logger
1003 logger = self.shell.logger
989
1004
990 # if no args are given, the defaults set in the logger constructor by
1005 # if no args are given, the defaults set in the logger constructor by
991 # ipytohn remain valid
1006 # ipytohn remain valid
992 if par:
1007 if par:
993 try:
1008 try:
994 logfname,logmode = par.split()
1009 logfname,logmode = par.split()
995 except:
1010 except:
996 logfname = par
1011 logfname = par
997 logmode = 'backup'
1012 logmode = 'backup'
998 else:
1013 else:
999 logfname = logger.logfname
1014 logfname = logger.logfname
1000 logmode = logger.logmode
1015 logmode = logger.logmode
1001 # put logfname into rc struct as if it had been called on the command
1016 # put logfname into rc struct as if it had been called on the command
1002 # line, so it ends up saved in the log header Save it in case we need
1017 # line, so it ends up saved in the log header Save it in case we need
1003 # to restore it...
1018 # to restore it...
1004 old_logfile = rc.opts.get('logfile','')
1019 old_logfile = rc.opts.get('logfile','')
1005 if logfname:
1020 if logfname:
1006 logfname = os.path.expanduser(logfname)
1021 logfname = os.path.expanduser(logfname)
1007 rc.opts.logfile = logfname
1022 rc.opts.logfile = logfname
1008 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1023 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1009 try:
1024 try:
1010 started = logger.logstart(logfname,loghead,logmode,
1025 started = logger.logstart(logfname,loghead,logmode,
1011 log_output,timestamp)
1026 log_output,timestamp)
1012 except:
1027 except:
1013 rc.opts.logfile = old_logfile
1028 rc.opts.logfile = old_logfile
1014 warn("Couldn't start log: %s" % sys.exc_info()[1])
1029 warn("Couldn't start log: %s" % sys.exc_info()[1])
1015 else:
1030 else:
1016 # log input history up to this point, optionally interleaving
1031 # log input history up to this point, optionally interleaving
1017 # output if requested
1032 # output if requested
1018
1033
1019 if timestamp:
1034 if timestamp:
1020 # disable timestamping for the previous history, since we've
1035 # disable timestamping for the previous history, since we've
1021 # lost those already (no time machine here).
1036 # lost those already (no time machine here).
1022 logger.timestamp = False
1037 logger.timestamp = False
1023 if log_output:
1038 if log_output:
1024 log_write = logger.log_write
1039 log_write = logger.log_write
1025 input_hist = self.shell.input_hist
1040 input_hist = self.shell.input_hist
1026 output_hist = self.shell.output_hist
1041 output_hist = self.shell.output_hist
1027 for n in range(1,len(input_hist)-1):
1042 for n in range(1,len(input_hist)-1):
1028 log_write(input_hist[n].rstrip())
1043 log_write(input_hist[n].rstrip())
1029 if n in output_hist:
1044 if n in output_hist:
1030 log_write(repr(output_hist[n]),'output')
1045 log_write(repr(output_hist[n]),'output')
1031 else:
1046 else:
1032 logger.log_write(self.shell.input_hist[1:])
1047 logger.log_write(self.shell.input_hist[1:])
1033 if timestamp:
1048 if timestamp:
1034 # re-enable timestamping
1049 # re-enable timestamping
1035 logger.timestamp = True
1050 logger.timestamp = True
1036
1051
1037 print ('Activating auto-logging. '
1052 print ('Activating auto-logging. '
1038 'Current session state plus future input saved.')
1053 'Current session state plus future input saved.')
1039 logger.logstate()
1054 logger.logstate()
1040
1055
1041 def magic_logoff(self,parameter_s=''):
1056 def magic_logoff(self,parameter_s=''):
1042 """Temporarily stop logging.
1057 """Temporarily stop logging.
1043
1058
1044 You must have previously started logging."""
1059 You must have previously started logging."""
1045 self.shell.logger.switch_log(0)
1060 self.shell.logger.switch_log(0)
1046
1061
1047 def magic_logon(self,parameter_s=''):
1062 def magic_logon(self,parameter_s=''):
1048 """Restart logging.
1063 """Restart logging.
1049
1064
1050 This function is for restarting logging which you've temporarily
1065 This function is for restarting logging which you've temporarily
1051 stopped with %logoff. For starting logging for the first time, you
1066 stopped with %logoff. For starting logging for the first time, you
1052 must use the %logstart function, which allows you to specify an
1067 must use the %logstart function, which allows you to specify an
1053 optional log filename."""
1068 optional log filename."""
1054
1069
1055 self.shell.logger.switch_log(1)
1070 self.shell.logger.switch_log(1)
1056
1071
1057 def magic_logstate(self,parameter_s=''):
1072 def magic_logstate(self,parameter_s=''):
1058 """Print the status of the logging system."""
1073 """Print the status of the logging system."""
1059
1074
1060 self.shell.logger.logstate()
1075 self.shell.logger.logstate()
1061
1076
1062 def magic_pdb(self, parameter_s=''):
1077 def magic_pdb(self, parameter_s=''):
1063 """Control the calling of the pdb interactive debugger.
1078 """Control the calling of the pdb interactive debugger.
1064
1079
1065 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1080 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1066 argument it works as a toggle.
1081 argument it works as a toggle.
1067
1082
1068 When an exception is triggered, IPython can optionally call the
1083 When an exception is triggered, IPython can optionally call the
1069 interactive pdb debugger after the traceback printout. %pdb toggles
1084 interactive pdb debugger after the traceback printout. %pdb toggles
1070 this feature on and off."""
1085 this feature on and off."""
1071
1086
1072 par = parameter_s.strip().lower()
1087 par = parameter_s.strip().lower()
1073
1088
1074 if par:
1089 if par:
1075 try:
1090 try:
1076 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1091 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1077 except KeyError:
1092 except KeyError:
1078 print ('Incorrect argument. Use on/1, off/0, '
1093 print ('Incorrect argument. Use on/1, off/0, '
1079 'or nothing for a toggle.')
1094 'or nothing for a toggle.')
1080 return
1095 return
1081 else:
1096 else:
1082 # toggle
1097 # toggle
1083 new_pdb = not self.shell.InteractiveTB.call_pdb
1098 new_pdb = not self.shell.InteractiveTB.call_pdb
1084
1099
1085 # set on the shell
1100 # set on the shell
1086 self.shell.call_pdb = new_pdb
1101 self.shell.call_pdb = new_pdb
1087 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1102 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1088
1103
1089 def magic_prun(self, parameter_s ='',user_mode=1,
1104 def magic_prun(self, parameter_s ='',user_mode=1,
1090 opts=None,arg_lst=None,prog_ns=None):
1105 opts=None,arg_lst=None,prog_ns=None):
1091
1106
1092 """Run a statement through the python code profiler.
1107 """Run a statement through the python code profiler.
1093
1108
1094 Usage:\\
1109 Usage:\\
1095 %prun [options] statement
1110 %prun [options] statement
1096
1111
1097 The given statement (which doesn't require quote marks) is run via the
1112 The given statement (which doesn't require quote marks) is run via the
1098 python profiler in a manner similar to the profile.run() function.
1113 python profiler in a manner similar to the profile.run() function.
1099 Namespaces are internally managed to work correctly; profile.run
1114 Namespaces are internally managed to work correctly; profile.run
1100 cannot be used in IPython because it makes certain assumptions about
1115 cannot be used in IPython because it makes certain assumptions about
1101 namespaces which do not hold under IPython.
1116 namespaces which do not hold under IPython.
1102
1117
1103 Options:
1118 Options:
1104
1119
1105 -l <limit>: you can place restrictions on what or how much of the
1120 -l <limit>: you can place restrictions on what or how much of the
1106 profile gets printed. The limit value can be:
1121 profile gets printed. The limit value can be:
1107
1122
1108 * A string: only information for function names containing this string
1123 * A string: only information for function names containing this string
1109 is printed.
1124 is printed.
1110
1125
1111 * An integer: only these many lines are printed.
1126 * An integer: only these many lines are printed.
1112
1127
1113 * A float (between 0 and 1): this fraction of the report is printed
1128 * A float (between 0 and 1): this fraction of the report is printed
1114 (for example, use a limit of 0.4 to see the topmost 40% only).
1129 (for example, use a limit of 0.4 to see the topmost 40% only).
1115
1130
1116 You can combine several limits with repeated use of the option. For
1131 You can combine several limits with repeated use of the option. For
1117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1132 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1118 information about class constructors.
1133 information about class constructors.
1119
1134
1120 -r: return the pstats.Stats object generated by the profiling. This
1135 -r: return the pstats.Stats object generated by the profiling. This
1121 object has all the information about the profile in it, and you can
1136 object has all the information about the profile in it, and you can
1122 later use it for further analysis or in other functions.
1137 later use it for further analysis or in other functions.
1123
1138
1124 Since magic functions have a particular form of calling which prevents
1139 Since magic functions have a particular form of calling which prevents
1125 you from writing something like:\\
1140 you from writing something like:\\
1126 In [1]: p = %prun -r print 4 # invalid!\\
1141 In [1]: p = %prun -r print 4 # invalid!\\
1127 you must instead use IPython's automatic variables to assign this:\\
1142 you must instead use IPython's automatic variables to assign this:\\
1128 In [1]: %prun -r print 4 \\
1143 In [1]: %prun -r print 4 \\
1129 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1144 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1130 In [2]: stats = _
1145 In [2]: stats = _
1131
1146
1132 If you really need to assign this value via an explicit function call,
1147 If you really need to assign this value via an explicit function call,
1133 you can always tap directly into the true name of the magic function
1148 you can always tap directly into the true name of the magic function
1134 by using the ipmagic function (which IPython automatically adds to the
1149 by using the ipmagic function (which IPython automatically adds to the
1135 builtins):\\
1150 builtins):\\
1136 In [3]: stats = ipmagic('prun','-r print 4')
1151 In [3]: stats = ipmagic('prun','-r print 4')
1137
1152
1138 You can type ipmagic? for more details on ipmagic.
1153 You can type ipmagic? for more details on ipmagic.
1139
1154
1140 -s <key>: sort profile by given key. You can provide more than one key
1155 -s <key>: sort profile by given key. You can provide more than one key
1141 by using the option several times: '-s key1 -s key2 -s key3...'. The
1156 by using the option several times: '-s key1 -s key2 -s key3...'. The
1142 default sorting key is 'time'.
1157 default sorting key is 'time'.
1143
1158
1144 The following is copied verbatim from the profile documentation
1159 The following is copied verbatim from the profile documentation
1145 referenced below:
1160 referenced below:
1146
1161
1147 When more than one key is provided, additional keys are used as
1162 When more than one key is provided, additional keys are used as
1148 secondary criteria when the there is equality in all keys selected
1163 secondary criteria when the there is equality in all keys selected
1149 before them.
1164 before them.
1150
1165
1151 Abbreviations can be used for any key names, as long as the
1166 Abbreviations can be used for any key names, as long as the
1152 abbreviation is unambiguous. The following are the keys currently
1167 abbreviation is unambiguous. The following are the keys currently
1153 defined:
1168 defined:
1154
1169
1155 Valid Arg Meaning\\
1170 Valid Arg Meaning\\
1156 "calls" call count\\
1171 "calls" call count\\
1157 "cumulative" cumulative time\\
1172 "cumulative" cumulative time\\
1158 "file" file name\\
1173 "file" file name\\
1159 "module" file name\\
1174 "module" file name\\
1160 "pcalls" primitive call count\\
1175 "pcalls" primitive call count\\
1161 "line" line number\\
1176 "line" line number\\
1162 "name" function name\\
1177 "name" function name\\
1163 "nfl" name/file/line\\
1178 "nfl" name/file/line\\
1164 "stdname" standard name\\
1179 "stdname" standard name\\
1165 "time" internal time
1180 "time" internal time
1166
1181
1167 Note that all sorts on statistics are in descending order (placing
1182 Note that all sorts on statistics are in descending order (placing
1168 most time consuming items first), where as name, file, and line number
1183 most time consuming items first), where as name, file, and line number
1169 searches are in ascending order (i.e., alphabetical). The subtle
1184 searches are in ascending order (i.e., alphabetical). The subtle
1170 distinction between "nfl" and "stdname" is that the standard name is a
1185 distinction between "nfl" and "stdname" is that the standard name is a
1171 sort of the name as printed, which means that the embedded line
1186 sort of the name as printed, which means that the embedded line
1172 numbers get compared in an odd way. For example, lines 3, 20, and 40
1187 numbers get compared in an odd way. For example, lines 3, 20, and 40
1173 would (if the file names were the same) appear in the string order
1188 would (if the file names were the same) appear in the string order
1174 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1189 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1175 line numbers. In fact, sort_stats("nfl") is the same as
1190 line numbers. In fact, sort_stats("nfl") is the same as
1176 sort_stats("name", "file", "line").
1191 sort_stats("name", "file", "line").
1177
1192
1178 -T <filename>: save profile results as shown on screen to a text
1193 -T <filename>: save profile results as shown on screen to a text
1179 file. The profile is still shown on screen.
1194 file. The profile is still shown on screen.
1180
1195
1181 -D <filename>: save (via dump_stats) profile statistics to given
1196 -D <filename>: save (via dump_stats) profile statistics to given
1182 filename. This data is in a format understod by the pstats module, and
1197 filename. This data is in a format understod by the pstats module, and
1183 is generated by a call to the dump_stats() method of profile
1198 is generated by a call to the dump_stats() method of profile
1184 objects. The profile is still shown on screen.
1199 objects. The profile is still shown on screen.
1185
1200
1186 If you want to run complete programs under the profiler's control, use
1201 If you want to run complete programs under the profiler's control, use
1187 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1202 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1188 contains profiler specific options as described here.
1203 contains profiler specific options as described here.
1189
1204
1190 You can read the complete documentation for the profile module with:\\
1205 You can read the complete documentation for the profile module with:\\
1191 In [1]: import profile; profile.help() """
1206 In [1]: import profile; profile.help() """
1192
1207
1193 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1208 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1194 # protect user quote marks
1209 # protect user quote marks
1195 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1210 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1196
1211
1197 if user_mode: # regular user call
1212 if user_mode: # regular user call
1198 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1213 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1199 list_all=1)
1214 list_all=1)
1200 namespace = self.shell.user_ns
1215 namespace = self.shell.user_ns
1201 else: # called to run a program by %run -p
1216 else: # called to run a program by %run -p
1202 try:
1217 try:
1203 filename = get_py_filename(arg_lst[0])
1218 filename = get_py_filename(arg_lst[0])
1204 except IOError,msg:
1219 except IOError,msg:
1205 error(msg)
1220 error(msg)
1206 return
1221 return
1207
1222
1208 arg_str = 'execfile(filename,prog_ns)'
1223 arg_str = 'execfile(filename,prog_ns)'
1209 namespace = locals()
1224 namespace = locals()
1210
1225
1211 opts.merge(opts_def)
1226 opts.merge(opts_def)
1212
1227
1213 prof = profile.Profile()
1228 prof = profile.Profile()
1214 try:
1229 try:
1215 prof = prof.runctx(arg_str,namespace,namespace)
1230 prof = prof.runctx(arg_str,namespace,namespace)
1216 sys_exit = ''
1231 sys_exit = ''
1217 except SystemExit:
1232 except SystemExit:
1218 sys_exit = """*** SystemExit exception caught in code being profiled."""
1233 sys_exit = """*** SystemExit exception caught in code being profiled."""
1219
1234
1220 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1235 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1221
1236
1222 lims = opts.l
1237 lims = opts.l
1223 if lims:
1238 if lims:
1224 lims = [] # rebuild lims with ints/floats/strings
1239 lims = [] # rebuild lims with ints/floats/strings
1225 for lim in opts.l:
1240 for lim in opts.l:
1226 try:
1241 try:
1227 lims.append(int(lim))
1242 lims.append(int(lim))
1228 except ValueError:
1243 except ValueError:
1229 try:
1244 try:
1230 lims.append(float(lim))
1245 lims.append(float(lim))
1231 except ValueError:
1246 except ValueError:
1232 lims.append(lim)
1247 lims.append(lim)
1233
1248
1234 # trap output
1249 # trap output
1235 sys_stdout = sys.stdout
1250 sys_stdout = sys.stdout
1236 stdout_trap = StringIO()
1251 stdout_trap = StringIO()
1237 try:
1252 try:
1238 sys.stdout = stdout_trap
1253 sys.stdout = stdout_trap
1239 stats.print_stats(*lims)
1254 stats.print_stats(*lims)
1240 finally:
1255 finally:
1241 sys.stdout = sys_stdout
1256 sys.stdout = sys_stdout
1242 output = stdout_trap.getvalue()
1257 output = stdout_trap.getvalue()
1243 output = output.rstrip()
1258 output = output.rstrip()
1244
1259
1245 page(output,screen_lines=self.shell.rc.screen_length)
1260 page(output,screen_lines=self.shell.rc.screen_length)
1246 print sys_exit,
1261 print sys_exit,
1247
1262
1248 dump_file = opts.D[0]
1263 dump_file = opts.D[0]
1249 text_file = opts.T[0]
1264 text_file = opts.T[0]
1250 if dump_file:
1265 if dump_file:
1251 prof.dump_stats(dump_file)
1266 prof.dump_stats(dump_file)
1252 print '\n*** Profile stats marshalled to file',\
1267 print '\n*** Profile stats marshalled to file',\
1253 `dump_file`+'.',sys_exit
1268 `dump_file`+'.',sys_exit
1254 if text_file:
1269 if text_file:
1255 file(text_file,'w').write(output)
1270 file(text_file,'w').write(output)
1256 print '\n*** Profile printout saved to text file',\
1271 print '\n*** Profile printout saved to text file',\
1257 `text_file`+'.',sys_exit
1272 `text_file`+'.',sys_exit
1258
1273
1259 if opts.has_key('r'):
1274 if opts.has_key('r'):
1260 return stats
1275 return stats
1261 else:
1276 else:
1262 return None
1277 return None
1263
1278
1264 def magic_run(self, parameter_s ='',runner=None):
1279 def magic_run(self, parameter_s ='',runner=None):
1265 """Run the named file inside IPython as a program.
1280 """Run the named file inside IPython as a program.
1266
1281
1267 Usage:\\
1282 Usage:\\
1268 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1283 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1269
1284
1270 Parameters after the filename are passed as command-line arguments to
1285 Parameters after the filename are passed as command-line arguments to
1271 the program (put in sys.argv). Then, control returns to IPython's
1286 the program (put in sys.argv). Then, control returns to IPython's
1272 prompt.
1287 prompt.
1273
1288
1274 This is similar to running at a system prompt:\\
1289 This is similar to running at a system prompt:\\
1275 $ python file args\\
1290 $ python file args\\
1276 but with the advantage of giving you IPython's tracebacks, and of
1291 but with the advantage of giving you IPython's tracebacks, and of
1277 loading all variables into your interactive namespace for further use
1292 loading all variables into your interactive namespace for further use
1278 (unless -p is used, see below).
1293 (unless -p is used, see below).
1279
1294
1280 The file is executed in a namespace initially consisting only of
1295 The file is executed in a namespace initially consisting only of
1281 __name__=='__main__' and sys.argv constructed as indicated. It thus
1296 __name__=='__main__' and sys.argv constructed as indicated. It thus
1282 sees its environment as if it were being run as a stand-alone
1297 sees its environment as if it were being run as a stand-alone
1283 program. But after execution, the IPython interactive namespace gets
1298 program. But after execution, the IPython interactive namespace gets
1284 updated with all variables defined in the program (except for __name__
1299 updated with all variables defined in the program (except for __name__
1285 and sys.argv). This allows for very convenient loading of code for
1300 and sys.argv). This allows for very convenient loading of code for
1286 interactive work, while giving each program a 'clean sheet' to run in.
1301 interactive work, while giving each program a 'clean sheet' to run in.
1287
1302
1288 Options:
1303 Options:
1289
1304
1290 -n: __name__ is NOT set to '__main__', but to the running file's name
1305 -n: __name__ is NOT set to '__main__', but to the running file's name
1291 without extension (as python does under import). This allows running
1306 without extension (as python does under import). This allows running
1292 scripts and reloading the definitions in them without calling code
1307 scripts and reloading the definitions in them without calling code
1293 protected by an ' if __name__ == "__main__" ' clause.
1308 protected by an ' if __name__ == "__main__" ' clause.
1294
1309
1295 -i: run the file in IPython's namespace instead of an empty one. This
1310 -i: run the file in IPython's namespace instead of an empty one. This
1296 is useful if you are experimenting with code written in a text editor
1311 is useful if you are experimenting with code written in a text editor
1297 which depends on variables defined interactively.
1312 which depends on variables defined interactively.
1298
1313
1299 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1314 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1300 being run. This is particularly useful if IPython is being used to
1315 being run. This is particularly useful if IPython is being used to
1301 run unittests, which always exit with a sys.exit() call. In such
1316 run unittests, which always exit with a sys.exit() call. In such
1302 cases you are interested in the output of the test results, not in
1317 cases you are interested in the output of the test results, not in
1303 seeing a traceback of the unittest module.
1318 seeing a traceback of the unittest module.
1304
1319
1305 -t: print timing information at the end of the run. IPython will give
1320 -t: print timing information at the end of the run. IPython will give
1306 you an estimated CPU time consumption for your script, which under
1321 you an estimated CPU time consumption for your script, which under
1307 Unix uses the resource module to avoid the wraparound problems of
1322 Unix uses the resource module to avoid the wraparound problems of
1308 time.clock(). Under Unix, an estimate of time spent on system tasks
1323 time.clock(). Under Unix, an estimate of time spent on system tasks
1309 is also given (for Windows platforms this is reported as 0.0).
1324 is also given (for Windows platforms this is reported as 0.0).
1310
1325
1311 If -t is given, an additional -N<N> option can be given, where <N>
1326 If -t is given, an additional -N<N> option can be given, where <N>
1312 must be an integer indicating how many times you want the script to
1327 must be an integer indicating how many times you want the script to
1313 run. The final timing report will include total and per run results.
1328 run. The final timing report will include total and per run results.
1314
1329
1315 For example (testing the script uniq_stable.py):
1330 For example (testing the script uniq_stable.py):
1316
1331
1317 In [1]: run -t uniq_stable
1332 In [1]: run -t uniq_stable
1318
1333
1319 IPython CPU timings (estimated):\\
1334 IPython CPU timings (estimated):\\
1320 User : 0.19597 s.\\
1335 User : 0.19597 s.\\
1321 System: 0.0 s.\\
1336 System: 0.0 s.\\
1322
1337
1323 In [2]: run -t -N5 uniq_stable
1338 In [2]: run -t -N5 uniq_stable
1324
1339
1325 IPython CPU timings (estimated):\\
1340 IPython CPU timings (estimated):\\
1326 Total runs performed: 5\\
1341 Total runs performed: 5\\
1327 Times : Total Per run\\
1342 Times : Total Per run\\
1328 User : 0.910862 s, 0.1821724 s.\\
1343 User : 0.910862 s, 0.1821724 s.\\
1329 System: 0.0 s, 0.0 s.
1344 System: 0.0 s, 0.0 s.
1330
1345
1331 -d: run your program under the control of pdb, the Python debugger.
1346 -d: run your program under the control of pdb, the Python debugger.
1332 This allows you to execute your program step by step, watch variables,
1347 This allows you to execute your program step by step, watch variables,
1333 etc. Internally, what IPython does is similar to calling:
1348 etc. Internally, what IPython does is similar to calling:
1334
1349
1335 pdb.run('execfile("YOURFILENAME")')
1350 pdb.run('execfile("YOURFILENAME")')
1336
1351
1337 with a breakpoint set on line 1 of your file. You can change the line
1352 with a breakpoint set on line 1 of your file. You can change the line
1338 number for this automatic breakpoint to be <N> by using the -bN option
1353 number for this automatic breakpoint to be <N> by using the -bN option
1339 (where N must be an integer). For example:
1354 (where N must be an integer). For example:
1340
1355
1341 %run -d -b40 myscript
1356 %run -d -b40 myscript
1342
1357
1343 will set the first breakpoint at line 40 in myscript.py. Note that
1358 will set the first breakpoint at line 40 in myscript.py. Note that
1344 the first breakpoint must be set on a line which actually does
1359 the first breakpoint must be set on a line which actually does
1345 something (not a comment or docstring) for it to stop execution.
1360 something (not a comment or docstring) for it to stop execution.
1346
1361
1347 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1362 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1348 first enter 'c' (without qoutes) to start execution up to the first
1363 first enter 'c' (without qoutes) to start execution up to the first
1349 breakpoint.
1364 breakpoint.
1350
1365
1351 Entering 'help' gives information about the use of the debugger. You
1366 Entering 'help' gives information about the use of the debugger. You
1352 can easily see pdb's full documentation with "import pdb;pdb.help()"
1367 can easily see pdb's full documentation with "import pdb;pdb.help()"
1353 at a prompt.
1368 at a prompt.
1354
1369
1355 -p: run program under the control of the Python profiler module (which
1370 -p: run program under the control of the Python profiler module (which
1356 prints a detailed report of execution times, function calls, etc).
1371 prints a detailed report of execution times, function calls, etc).
1357
1372
1358 You can pass other options after -p which affect the behavior of the
1373 You can pass other options after -p which affect the behavior of the
1359 profiler itself. See the docs for %prun for details.
1374 profiler itself. See the docs for %prun for details.
1360
1375
1361 In this mode, the program's variables do NOT propagate back to the
1376 In this mode, the program's variables do NOT propagate back to the
1362 IPython interactive namespace (because they remain in the namespace
1377 IPython interactive namespace (because they remain in the namespace
1363 where the profiler executes them).
1378 where the profiler executes them).
1364
1379
1365 Internally this triggers a call to %prun, see its documentation for
1380 Internally this triggers a call to %prun, see its documentation for
1366 details on the options available specifically for profiling."""
1381 details on the options available specifically for profiling."""
1367
1382
1368 # get arguments and set sys.argv for program to be run.
1383 # get arguments and set sys.argv for program to be run.
1369 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1384 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1370 mode='list',list_all=1)
1385 mode='list',list_all=1)
1371
1386
1372 try:
1387 try:
1373 filename = get_py_filename(arg_lst[0])
1388 filename = get_py_filename(arg_lst[0])
1374 except IndexError:
1389 except IndexError:
1375 warn('you must provide at least a filename.')
1390 warn('you must provide at least a filename.')
1376 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1391 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1377 return
1392 return
1378 except IOError,msg:
1393 except IOError,msg:
1379 error(msg)
1394 error(msg)
1380 return
1395 return
1381
1396
1382 # Control the response to exit() calls made by the script being run
1397 # Control the response to exit() calls made by the script being run
1383 exit_ignore = opts.has_key('e')
1398 exit_ignore = opts.has_key('e')
1384
1399
1385 # Make sure that the running script gets a proper sys.argv as if it
1400 # Make sure that the running script gets a proper sys.argv as if it
1386 # were run from a system shell.
1401 # were run from a system shell.
1387 save_argv = sys.argv # save it for later restoring
1402 save_argv = sys.argv # save it for later restoring
1388 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1403 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1389
1404
1390 if opts.has_key('i'):
1405 if opts.has_key('i'):
1391 prog_ns = self.shell.user_ns
1406 prog_ns = self.shell.user_ns
1392 __name__save = self.shell.user_ns['__name__']
1407 __name__save = self.shell.user_ns['__name__']
1393 prog_ns['__name__'] = '__main__'
1408 prog_ns['__name__'] = '__main__'
1394 else:
1409 else:
1395 if opts.has_key('n'):
1410 if opts.has_key('n'):
1396 name = os.path.splitext(os.path.basename(filename))[0]
1411 name = os.path.splitext(os.path.basename(filename))[0]
1397 else:
1412 else:
1398 name = '__main__'
1413 name = '__main__'
1399 prog_ns = {'__name__':name}
1414 prog_ns = {'__name__':name}
1400
1415
1401 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1416 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1402 # set the __file__ global in the script's namespace
1417 # set the __file__ global in the script's namespace
1403 prog_ns['__file__'] = filename
1418 prog_ns['__file__'] = filename
1404
1419
1405 # pickle fix. See iplib for an explanation. But we need to make sure
1420 # pickle fix. See iplib for an explanation. But we need to make sure
1406 # that, if we overwrite __main__, we replace it at the end
1421 # that, if we overwrite __main__, we replace it at the end
1407 if prog_ns['__name__'] == '__main__':
1422 if prog_ns['__name__'] == '__main__':
1408 restore_main = sys.modules['__main__']
1423 restore_main = sys.modules['__main__']
1409 else:
1424 else:
1410 restore_main = False
1425 restore_main = False
1411
1426
1412 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1427 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1413
1428
1414 stats = None
1429 stats = None
1415 try:
1430 try:
1416 if opts.has_key('p'):
1431 if opts.has_key('p'):
1417 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1432 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1418 else:
1433 else:
1419 if opts.has_key('d'):
1434 if opts.has_key('d'):
1420 deb = Debugger.Pdb(self.shell.rc.colors)
1435 deb = Debugger.Pdb(self.shell.rc.colors)
1421 # reset Breakpoint state, which is moronically kept
1436 # reset Breakpoint state, which is moronically kept
1422 # in a class
1437 # in a class
1423 bdb.Breakpoint.next = 1
1438 bdb.Breakpoint.next = 1
1424 bdb.Breakpoint.bplist = {}
1439 bdb.Breakpoint.bplist = {}
1425 bdb.Breakpoint.bpbynumber = [None]
1440 bdb.Breakpoint.bpbynumber = [None]
1426 # Set an initial breakpoint to stop execution
1441 # Set an initial breakpoint to stop execution
1427 maxtries = 10
1442 maxtries = 10
1428 bp = int(opts.get('b',[1])[0])
1443 bp = int(opts.get('b',[1])[0])
1429 checkline = deb.checkline(filename,bp)
1444 checkline = deb.checkline(filename,bp)
1430 if not checkline:
1445 if not checkline:
1431 for bp in range(bp+1,bp+maxtries+1):
1446 for bp in range(bp+1,bp+maxtries+1):
1432 if deb.checkline(filename,bp):
1447 if deb.checkline(filename,bp):
1433 break
1448 break
1434 else:
1449 else:
1435 msg = ("\nI failed to find a valid line to set "
1450 msg = ("\nI failed to find a valid line to set "
1436 "a breakpoint\n"
1451 "a breakpoint\n"
1437 "after trying up to line: %s.\n"
1452 "after trying up to line: %s.\n"
1438 "Please set a valid breakpoint manually "
1453 "Please set a valid breakpoint manually "
1439 "with the -b option." % bp)
1454 "with the -b option." % bp)
1440 error(msg)
1455 error(msg)
1441 return
1456 return
1442 # if we find a good linenumber, set the breakpoint
1457 # if we find a good linenumber, set the breakpoint
1443 deb.do_break('%s:%s' % (filename,bp))
1458 deb.do_break('%s:%s' % (filename,bp))
1444 # Start file run
1459 # Start file run
1445 print "NOTE: Enter 'c' at the",
1460 print "NOTE: Enter 'c' at the",
1446 print "ipdb> prompt to start your script."
1461 print "ipdb> prompt to start your script."
1447 try:
1462 try:
1448 deb.run('execfile("%s")' % filename,prog_ns)
1463 deb.run('execfile("%s")' % filename,prog_ns)
1449 except:
1464 except:
1450 etype, value, tb = sys.exc_info()
1465 etype, value, tb = sys.exc_info()
1451 # Skip three frames in the traceback: the %run one,
1466 # Skip three frames in the traceback: the %run one,
1452 # one inside bdb.py, and the command-line typed by the
1467 # one inside bdb.py, and the command-line typed by the
1453 # user (run by exec in pdb itself).
1468 # user (run by exec in pdb itself).
1454 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1469 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1455 else:
1470 else:
1456 if runner is None:
1471 if runner is None:
1457 runner = self.shell.safe_execfile
1472 runner = self.shell.safe_execfile
1458 if opts.has_key('t'):
1473 if opts.has_key('t'):
1459 try:
1474 try:
1460 nruns = int(opts['N'][0])
1475 nruns = int(opts['N'][0])
1461 if nruns < 1:
1476 if nruns < 1:
1462 error('Number of runs must be >=1')
1477 error('Number of runs must be >=1')
1463 return
1478 return
1464 except (KeyError):
1479 except (KeyError):
1465 nruns = 1
1480 nruns = 1
1466 if nruns == 1:
1481 if nruns == 1:
1467 t0 = clock2()
1482 t0 = clock2()
1468 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1483 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1469 t1 = clock2()
1484 t1 = clock2()
1470 t_usr = t1[0]-t0[0]
1485 t_usr = t1[0]-t0[0]
1471 t_sys = t1[1]-t1[1]
1486 t_sys = t1[1]-t1[1]
1472 print "\nIPython CPU timings (estimated):"
1487 print "\nIPython CPU timings (estimated):"
1473 print " User : %10s s." % t_usr
1488 print " User : %10s s." % t_usr
1474 print " System: %10s s." % t_sys
1489 print " System: %10s s." % t_sys
1475 else:
1490 else:
1476 runs = range(nruns)
1491 runs = range(nruns)
1477 t0 = clock2()
1492 t0 = clock2()
1478 for nr in runs:
1493 for nr in runs:
1479 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1494 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1480 t1 = clock2()
1495 t1 = clock2()
1481 t_usr = t1[0]-t0[0]
1496 t_usr = t1[0]-t0[0]
1482 t_sys = t1[1]-t1[1]
1497 t_sys = t1[1]-t1[1]
1483 print "\nIPython CPU timings (estimated):"
1498 print "\nIPython CPU timings (estimated):"
1484 print "Total runs performed:",nruns
1499 print "Total runs performed:",nruns
1485 print " Times : %10s %10s" % ('Total','Per run')
1500 print " Times : %10s %10s" % ('Total','Per run')
1486 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1501 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1487 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1502 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1488
1503
1489 else:
1504 else:
1490 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1505 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1491 if opts.has_key('i'):
1506 if opts.has_key('i'):
1492 self.shell.user_ns['__name__'] = __name__save
1507 self.shell.user_ns['__name__'] = __name__save
1493 else:
1508 else:
1494 # update IPython interactive namespace
1509 # update IPython interactive namespace
1495 del prog_ns['__name__']
1510 del prog_ns['__name__']
1496 self.shell.user_ns.update(prog_ns)
1511 self.shell.user_ns.update(prog_ns)
1497 finally:
1512 finally:
1498 sys.argv = save_argv
1513 sys.argv = save_argv
1499 if restore_main:
1514 if restore_main:
1500 sys.modules['__main__'] = restore_main
1515 sys.modules['__main__'] = restore_main
1501 return stats
1516 return stats
1502
1517
1503 def magic_runlog(self, parameter_s =''):
1518 def magic_runlog(self, parameter_s =''):
1504 """Run files as logs.
1519 """Run files as logs.
1505
1520
1506 Usage:\\
1521 Usage:\\
1507 %runlog file1 file2 ...
1522 %runlog file1 file2 ...
1508
1523
1509 Run the named files (treating them as log files) in sequence inside
1524 Run the named files (treating them as log files) in sequence inside
1510 the interpreter, and return to the prompt. This is much slower than
1525 the interpreter, and return to the prompt. This is much slower than
1511 %run because each line is executed in a try/except block, but it
1526 %run because each line is executed in a try/except block, but it
1512 allows running files with syntax errors in them.
1527 allows running files with syntax errors in them.
1513
1528
1514 Normally IPython will guess when a file is one of its own logfiles, so
1529 Normally IPython will guess when a file is one of its own logfiles, so
1515 you can typically use %run even for logs. This shorthand allows you to
1530 you can typically use %run even for logs. This shorthand allows you to
1516 force any file to be treated as a log file."""
1531 force any file to be treated as a log file."""
1517
1532
1518 for f in parameter_s.split():
1533 for f in parameter_s.split():
1519 self.shell.safe_execfile(f,self.shell.user_ns,
1534 self.shell.safe_execfile(f,self.shell.user_ns,
1520 self.shell.user_ns,islog=1)
1535 self.shell.user_ns,islog=1)
1521
1536
1522 def magic_time(self,parameter_s = ''):
1537 def magic_time(self,parameter_s = ''):
1523 """Time execution of a Python statement or expression.
1538 """Time execution of a Python statement or expression.
1524
1539
1525 The CPU and wall clock times are printed, and the value of the
1540 The CPU and wall clock times are printed, and the value of the
1526 expression (if any) is returned. Note that under Win32, system time
1541 expression (if any) is returned. Note that under Win32, system time
1527 is always reported as 0, since it can not be measured.
1542 is always reported as 0, since it can not be measured.
1528
1543
1529 This function provides very basic timing functionality. In Python
1544 This function provides very basic timing functionality. In Python
1530 2.3, the timeit module offers more control and sophistication, but for
1545 2.3, the timeit module offers more control and sophistication, but for
1531 now IPython supports Python 2.2, so we can not rely on timeit being
1546 now IPython supports Python 2.2, so we can not rely on timeit being
1532 present.
1547 present.
1533
1548
1534 Some examples:
1549 Some examples:
1535
1550
1536 In [1]: time 2**128
1551 In [1]: time 2**128
1537 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1552 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1538 Wall time: 0.00
1553 Wall time: 0.00
1539 Out[1]: 340282366920938463463374607431768211456L
1554 Out[1]: 340282366920938463463374607431768211456L
1540
1555
1541 In [2]: n = 1000000
1556 In [2]: n = 1000000
1542
1557
1543 In [3]: time sum(range(n))
1558 In [3]: time sum(range(n))
1544 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1559 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1545 Wall time: 1.37
1560 Wall time: 1.37
1546 Out[3]: 499999500000L
1561 Out[3]: 499999500000L
1547
1562
1548 In [4]: time print 'hello world'
1563 In [4]: time print 'hello world'
1549 hello world
1564 hello world
1550 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1565 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1551 Wall time: 0.00
1566 Wall time: 0.00
1552 """
1567 """
1553
1568
1554 # fail immediately if the given expression can't be compiled
1569 # fail immediately if the given expression can't be compiled
1555 try:
1570 try:
1556 mode = 'eval'
1571 mode = 'eval'
1557 code = compile(parameter_s,'<timed eval>',mode)
1572 code = compile(parameter_s,'<timed eval>',mode)
1558 except SyntaxError:
1573 except SyntaxError:
1559 mode = 'exec'
1574 mode = 'exec'
1560 code = compile(parameter_s,'<timed exec>',mode)
1575 code = compile(parameter_s,'<timed exec>',mode)
1561 # skew measurement as little as possible
1576 # skew measurement as little as possible
1562 glob = self.shell.user_ns
1577 glob = self.shell.user_ns
1563 clk = clock2
1578 clk = clock2
1564 wtime = time.time
1579 wtime = time.time
1565 # time execution
1580 # time execution
1566 wall_st = wtime()
1581 wall_st = wtime()
1567 if mode=='eval':
1582 if mode=='eval':
1568 st = clk()
1583 st = clk()
1569 out = eval(code,glob)
1584 out = eval(code,glob)
1570 end = clk()
1585 end = clk()
1571 else:
1586 else:
1572 st = clk()
1587 st = clk()
1573 exec code in glob
1588 exec code in glob
1574 end = clk()
1589 end = clk()
1575 out = None
1590 out = None
1576 wall_end = wtime()
1591 wall_end = wtime()
1577 # Compute actual times and report
1592 # Compute actual times and report
1578 wall_time = wall_end-wall_st
1593 wall_time = wall_end-wall_st
1579 cpu_user = end[0]-st[0]
1594 cpu_user = end[0]-st[0]
1580 cpu_sys = end[1]-st[1]
1595 cpu_sys = end[1]-st[1]
1581 cpu_tot = cpu_user+cpu_sys
1596 cpu_tot = cpu_user+cpu_sys
1582 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1597 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1583 (cpu_user,cpu_sys,cpu_tot)
1598 (cpu_user,cpu_sys,cpu_tot)
1584 print "Wall time: %.2f" % wall_time
1599 print "Wall time: %.2f" % wall_time
1585 return out
1600 return out
1586
1601
1587 def magic_macro(self,parameter_s = ''):
1602 def magic_macro(self,parameter_s = ''):
1588 """Define a set of input lines as a macro for future re-execution.
1603 """Define a set of input lines as a macro for future re-execution.
1589
1604
1590 Usage:\\
1605 Usage:\\
1591 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1606 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1592
1607
1593 This will define a global variable called `name` which is a string
1608 This will define a global variable called `name` which is a string
1594 made of joining the slices and lines you specify (n1,n2,... numbers
1609 made of joining the slices and lines you specify (n1,n2,... numbers
1595 above) from your input history into a single string. This variable
1610 above) from your input history into a single string. This variable
1596 acts like an automatic function which re-executes those lines as if
1611 acts like an automatic function which re-executes those lines as if
1597 you had typed them. You just type 'name' at the prompt and the code
1612 you had typed them. You just type 'name' at the prompt and the code
1598 executes.
1613 executes.
1599
1614
1600 The notation for indicating number ranges is: n1-n2 means 'use line
1615 The notation for indicating number ranges is: n1-n2 means 'use line
1601 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1616 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1602 using the lines numbered 5,6 and 7.
1617 using the lines numbered 5,6 and 7.
1603
1618
1604 Note: as a 'hidden' feature, you can also use traditional python slice
1619 Note: as a 'hidden' feature, you can also use traditional python slice
1605 notation, where N:M means numbers N through M-1.
1620 notation, where N:M means numbers N through M-1.
1606
1621
1607 For example, if your history contains (%hist prints it):
1622 For example, if your history contains (%hist prints it):
1608
1623
1609 44: x=1\\
1624 44: x=1\\
1610 45: y=3\\
1625 45: y=3\\
1611 46: z=x+y\\
1626 46: z=x+y\\
1612 47: print x\\
1627 47: print x\\
1613 48: a=5\\
1628 48: a=5\\
1614 49: print 'x',x,'y',y\\
1629 49: print 'x',x,'y',y\\
1615
1630
1616 you can create a macro with lines 44 through 47 (included) and line 49
1631 you can create a macro with lines 44 through 47 (included) and line 49
1617 called my_macro with:
1632 called my_macro with:
1618
1633
1619 In [51]: %macro my_macro 44-47 49
1634 In [51]: %macro my_macro 44-47 49
1620
1635
1621 Now, typing `my_macro` (without quotes) will re-execute all this code
1636 Now, typing `my_macro` (without quotes) will re-execute all this code
1622 in one pass.
1637 in one pass.
1623
1638
1624 You don't need to give the line-numbers in order, and any given line
1639 You don't need to give the line-numbers in order, and any given line
1625 number can appear multiple times. You can assemble macros with any
1640 number can appear multiple times. You can assemble macros with any
1626 lines from your input history in any order.
1641 lines from your input history in any order.
1627
1642
1628 The macro is a simple object which holds its value in an attribute,
1643 The macro is a simple object which holds its value in an attribute,
1629 but IPython's display system checks for macros and executes them as
1644 but IPython's display system checks for macros and executes them as
1630 code instead of printing them when you type their name.
1645 code instead of printing them when you type their name.
1631
1646
1632 You can view a macro's contents by explicitly printing it with:
1647 You can view a macro's contents by explicitly printing it with:
1633
1648
1634 'print macro_name'.
1649 'print macro_name'.
1635
1650
1636 For one-off cases which DON'T contain magic function calls in them you
1651 For one-off cases which DON'T contain magic function calls in them you
1637 can obtain similar results by explicitly executing slices from your
1652 can obtain similar results by explicitly executing slices from your
1638 input history with:
1653 input history with:
1639
1654
1640 In [60]: exec In[44:48]+In[49]"""
1655 In [60]: exec In[44:48]+In[49]"""
1641
1656
1642 args = parameter_s.split()
1657 args = parameter_s.split()
1643 name,ranges = args[0], args[1:]
1658 name,ranges = args[0], args[1:]
1644 #print 'rng',ranges # dbg
1659 #print 'rng',ranges # dbg
1645 lines = self.extract_input_slices(ranges)
1660 lines = self.extract_input_slices(ranges)
1646 macro = Macro(lines)
1661 macro = Macro(lines)
1647 self.shell.user_ns.update({name:macro})
1662 self.shell.user_ns.update({name:macro})
1648 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1663 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1649 print 'Macro contents:'
1664 print 'Macro contents:'
1650 print macro,
1665 print macro,
1651
1666
1652 def magic_save(self,parameter_s = ''):
1667 def magic_save(self,parameter_s = ''):
1653 """Save a set of lines to a given filename.
1668 """Save a set of lines to a given filename.
1654
1669
1655 Usage:\\
1670 Usage:\\
1656 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1671 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1657
1672
1658 This function uses the same syntax as %macro for line extraction, but
1673 This function uses the same syntax as %macro for line extraction, but
1659 instead of creating a macro it saves the resulting string to the
1674 instead of creating a macro it saves the resulting string to the
1660 filename you specify.
1675 filename you specify.
1661
1676
1662 It adds a '.py' extension to the file if you don't do so yourself, and
1677 It adds a '.py' extension to the file if you don't do so yourself, and
1663 it asks for confirmation before overwriting existing files."""
1678 it asks for confirmation before overwriting existing files."""
1664
1679
1665 args = parameter_s.split()
1680 args = parameter_s.split()
1666 fname,ranges = args[0], args[1:]
1681 fname,ranges = args[0], args[1:]
1667 if not fname.endswith('.py'):
1682 if not fname.endswith('.py'):
1668 fname += '.py'
1683 fname += '.py'
1669 if os.path.isfile(fname):
1684 if os.path.isfile(fname):
1670 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1685 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1671 if ans.lower() not in ['y','yes']:
1686 if ans.lower() not in ['y','yes']:
1672 print 'Operation cancelled.'
1687 print 'Operation cancelled.'
1673 return
1688 return
1674 cmds = ''.join(self.extract_input_slices(ranges))
1689 cmds = ''.join(self.extract_input_slices(ranges))
1675 f = file(fname,'w')
1690 f = file(fname,'w')
1676 f.write(cmds)
1691 f.write(cmds)
1677 f.close()
1692 f.close()
1678 print 'The following commands were written to file `%s`:' % fname
1693 print 'The following commands were written to file `%s`:' % fname
1679 print cmds
1694 print cmds
1680
1695
1681 def _edit_macro(self,mname,macro):
1696 def _edit_macro(self,mname,macro):
1682 """open an editor with the macro data in a file"""
1697 """open an editor with the macro data in a file"""
1683 filename = self.shell.mktempfile(macro.value)
1698 filename = self.shell.mktempfile(macro.value)
1684 self.shell.hooks.editor(filename)
1699 self.shell.hooks.editor(filename)
1685
1700
1686 # and make a new macro object, to replace the old one
1701 # and make a new macro object, to replace the old one
1687 mfile = open(filename)
1702 mfile = open(filename)
1688 mvalue = mfile.read()
1703 mvalue = mfile.read()
1689 mfile.close()
1704 mfile.close()
1690 self.shell.user_ns[mname] = Macro(mvalue)
1705 self.shell.user_ns[mname] = Macro(mvalue)
1691
1706
1692 def magic_ed(self,parameter_s=''):
1707 def magic_ed(self,parameter_s=''):
1693 """Alias to %edit."""
1708 """Alias to %edit."""
1694 return self.magic_edit(parameter_s)
1709 return self.magic_edit(parameter_s)
1695
1710
1696 def magic_edit(self,parameter_s='',last_call=['','']):
1711 def magic_edit(self,parameter_s='',last_call=['','']):
1697 """Bring up an editor and execute the resulting code.
1712 """Bring up an editor and execute the resulting code.
1698
1713
1699 Usage:
1714 Usage:
1700 %edit [options] [args]
1715 %edit [options] [args]
1701
1716
1702 %edit runs IPython's editor hook. The default version of this hook is
1717 %edit runs IPython's editor hook. The default version of this hook is
1703 set to call the __IPYTHON__.rc.editor command. This is read from your
1718 set to call the __IPYTHON__.rc.editor command. This is read from your
1704 environment variable $EDITOR. If this isn't found, it will default to
1719 environment variable $EDITOR. If this isn't found, it will default to
1705 vi under Linux/Unix and to notepad under Windows. See the end of this
1720 vi under Linux/Unix and to notepad under Windows. See the end of this
1706 docstring for how to change the editor hook.
1721 docstring for how to change the editor hook.
1707
1722
1708 You can also set the value of this editor via the command line option
1723 You can also set the value of this editor via the command line option
1709 '-editor' or in your ipythonrc file. This is useful if you wish to use
1724 '-editor' or in your ipythonrc file. This is useful if you wish to use
1710 specifically for IPython an editor different from your typical default
1725 specifically for IPython an editor different from your typical default
1711 (and for Windows users who typically don't set environment variables).
1726 (and for Windows users who typically don't set environment variables).
1712
1727
1713 This command allows you to conveniently edit multi-line code right in
1728 This command allows you to conveniently edit multi-line code right in
1714 your IPython session.
1729 your IPython session.
1715
1730
1716 If called without arguments, %edit opens up an empty editor with a
1731 If called without arguments, %edit opens up an empty editor with a
1717 temporary file and will execute the contents of this file when you
1732 temporary file and will execute the contents of this file when you
1718 close it (don't forget to save it!).
1733 close it (don't forget to save it!).
1719
1734
1720
1735
1721 Options:
1736 Options:
1722
1737
1723 -p: this will call the editor with the same data as the previous time
1738 -p: this will call the editor with the same data as the previous time
1724 it was used, regardless of how long ago (in your current session) it
1739 it was used, regardless of how long ago (in your current session) it
1725 was.
1740 was.
1726
1741
1727 -x: do not execute the edited code immediately upon exit. This is
1742 -x: do not execute the edited code immediately upon exit. This is
1728 mainly useful if you are editing programs which need to be called with
1743 mainly useful if you are editing programs which need to be called with
1729 command line arguments, which you can then do using %run.
1744 command line arguments, which you can then do using %run.
1730
1745
1731
1746
1732 Arguments:
1747 Arguments:
1733
1748
1734 If arguments are given, the following possibilites exist:
1749 If arguments are given, the following possibilites exist:
1735
1750
1736 - The arguments are numbers or pairs of colon-separated numbers (like
1751 - The arguments are numbers or pairs of colon-separated numbers (like
1737 1 4:8 9). These are interpreted as lines of previous input to be
1752 1 4:8 9). These are interpreted as lines of previous input to be
1738 loaded into the editor. The syntax is the same of the %macro command.
1753 loaded into the editor. The syntax is the same of the %macro command.
1739
1754
1740 - If the argument doesn't start with a number, it is evaluated as a
1755 - If the argument doesn't start with a number, it is evaluated as a
1741 variable and its contents loaded into the editor. You can thus edit
1756 variable and its contents loaded into the editor. You can thus edit
1742 any string which contains python code (including the result of
1757 any string which contains python code (including the result of
1743 previous edits).
1758 previous edits).
1744
1759
1745 - If the argument is the name of an object (other than a string),
1760 - If the argument is the name of an object (other than a string),
1746 IPython will try to locate the file where it was defined and open the
1761 IPython will try to locate the file where it was defined and open the
1747 editor at the point where it is defined. You can use `%edit function`
1762 editor at the point where it is defined. You can use `%edit function`
1748 to load an editor exactly at the point where 'function' is defined,
1763 to load an editor exactly at the point where 'function' is defined,
1749 edit it and have the file be executed automatically.
1764 edit it and have the file be executed automatically.
1750
1765
1751 If the object is a macro (see %macro for details), this opens up your
1766 If the object is a macro (see %macro for details), this opens up your
1752 specified editor with a temporary file containing the macro's data.
1767 specified editor with a temporary file containing the macro's data.
1753 Upon exit, the macro is reloaded with the contents of the file.
1768 Upon exit, the macro is reloaded with the contents of the file.
1754
1769
1755 Note: opening at an exact line is only supported under Unix, and some
1770 Note: opening at an exact line is only supported under Unix, and some
1756 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1771 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1757 '+NUMBER' parameter necessary for this feature. Good editors like
1772 '+NUMBER' parameter necessary for this feature. Good editors like
1758 (X)Emacs, vi, jed, pico and joe all do.
1773 (X)Emacs, vi, jed, pico and joe all do.
1759
1774
1760 - If the argument is not found as a variable, IPython will look for a
1775 - If the argument is not found as a variable, IPython will look for a
1761 file with that name (adding .py if necessary) and load it into the
1776 file with that name (adding .py if necessary) and load it into the
1762 editor. It will execute its contents with execfile() when you exit,
1777 editor. It will execute its contents with execfile() when you exit,
1763 loading any code in the file into your interactive namespace.
1778 loading any code in the file into your interactive namespace.
1764
1779
1765 After executing your code, %edit will return as output the code you
1780 After executing your code, %edit will return as output the code you
1766 typed in the editor (except when it was an existing file). This way
1781 typed in the editor (except when it was an existing file). This way
1767 you can reload the code in further invocations of %edit as a variable,
1782 you can reload the code in further invocations of %edit as a variable,
1768 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1783 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1769 the output.
1784 the output.
1770
1785
1771 Note that %edit is also available through the alias %ed.
1786 Note that %edit is also available through the alias %ed.
1772
1787
1773 This is an example of creating a simple function inside the editor and
1788 This is an example of creating a simple function inside the editor and
1774 then modifying it. First, start up the editor:
1789 then modifying it. First, start up the editor:
1775
1790
1776 In [1]: ed\\
1791 In [1]: ed\\
1777 Editing... done. Executing edited code...\\
1792 Editing... done. Executing edited code...\\
1778 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1793 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1779
1794
1780 We can then call the function foo():
1795 We can then call the function foo():
1781
1796
1782 In [2]: foo()\\
1797 In [2]: foo()\\
1783 foo() was defined in an editing session
1798 foo() was defined in an editing session
1784
1799
1785 Now we edit foo. IPython automatically loads the editor with the
1800 Now we edit foo. IPython automatically loads the editor with the
1786 (temporary) file where foo() was previously defined:
1801 (temporary) file where foo() was previously defined:
1787
1802
1788 In [3]: ed foo\\
1803 In [3]: ed foo\\
1789 Editing... done. Executing edited code...
1804 Editing... done. Executing edited code...
1790
1805
1791 And if we call foo() again we get the modified version:
1806 And if we call foo() again we get the modified version:
1792
1807
1793 In [4]: foo()\\
1808 In [4]: foo()\\
1794 foo() has now been changed!
1809 foo() has now been changed!
1795
1810
1796 Here is an example of how to edit a code snippet successive
1811 Here is an example of how to edit a code snippet successive
1797 times. First we call the editor:
1812 times. First we call the editor:
1798
1813
1799 In [8]: ed\\
1814 In [8]: ed\\
1800 Editing... done. Executing edited code...\\
1815 Editing... done. Executing edited code...\\
1801 hello\\
1816 hello\\
1802 Out[8]: "print 'hello'\\n"
1817 Out[8]: "print 'hello'\\n"
1803
1818
1804 Now we call it again with the previous output (stored in _):
1819 Now we call it again with the previous output (stored in _):
1805
1820
1806 In [9]: ed _\\
1821 In [9]: ed _\\
1807 Editing... done. Executing edited code...\\
1822 Editing... done. Executing edited code...\\
1808 hello world\\
1823 hello world\\
1809 Out[9]: "print 'hello world'\\n"
1824 Out[9]: "print 'hello world'\\n"
1810
1825
1811 Now we call it with the output #8 (stored in _8, also as Out[8]):
1826 Now we call it with the output #8 (stored in _8, also as Out[8]):
1812
1827
1813 In [10]: ed _8\\
1828 In [10]: ed _8\\
1814 Editing... done. Executing edited code...\\
1829 Editing... done. Executing edited code...\\
1815 hello again\\
1830 hello again\\
1816 Out[10]: "print 'hello again'\\n"
1831 Out[10]: "print 'hello again'\\n"
1817
1832
1818
1833
1819 Changing the default editor hook:
1834 Changing the default editor hook:
1820
1835
1821 If you wish to write your own editor hook, you can put it in a
1836 If you wish to write your own editor hook, you can put it in a
1822 configuration file which you load at startup time. The default hook
1837 configuration file which you load at startup time. The default hook
1823 is defined in the IPython.hooks module, and you can use that as a
1838 is defined in the IPython.hooks module, and you can use that as a
1824 starting example for further modifications. That file also has
1839 starting example for further modifications. That file also has
1825 general instructions on how to set a new hook for use once you've
1840 general instructions on how to set a new hook for use once you've
1826 defined it."""
1841 defined it."""
1827
1842
1828 # FIXME: This function has become a convoluted mess. It needs a
1843 # FIXME: This function has become a convoluted mess. It needs a
1829 # ground-up rewrite with clean, simple logic.
1844 # ground-up rewrite with clean, simple logic.
1830
1845
1831 def make_filename(arg):
1846 def make_filename(arg):
1832 "Make a filename from the given args"
1847 "Make a filename from the given args"
1833 try:
1848 try:
1834 filename = get_py_filename(arg)
1849 filename = get_py_filename(arg)
1835 except IOError:
1850 except IOError:
1836 if args.endswith('.py'):
1851 if args.endswith('.py'):
1837 filename = arg
1852 filename = arg
1838 else:
1853 else:
1839 filename = None
1854 filename = None
1840 return filename
1855 return filename
1841
1856
1842 # custom exceptions
1857 # custom exceptions
1843 class DataIsObject(Exception): pass
1858 class DataIsObject(Exception): pass
1844
1859
1845 opts,args = self.parse_options(parameter_s,'px')
1860 opts,args = self.parse_options(parameter_s,'px')
1846
1861
1847 # Default line number value
1862 # Default line number value
1848 lineno = None
1863 lineno = None
1849 if opts.has_key('p'):
1864 if opts.has_key('p'):
1850 args = '_%s' % last_call[0]
1865 args = '_%s' % last_call[0]
1851 if not self.shell.user_ns.has_key(args):
1866 if not self.shell.user_ns.has_key(args):
1852 args = last_call[1]
1867 args = last_call[1]
1853
1868
1854 # use last_call to remember the state of the previous call, but don't
1869 # use last_call to remember the state of the previous call, but don't
1855 # let it be clobbered by successive '-p' calls.
1870 # let it be clobbered by successive '-p' calls.
1856 try:
1871 try:
1857 last_call[0] = self.shell.outputcache.prompt_count
1872 last_call[0] = self.shell.outputcache.prompt_count
1858 if not opts.has_key('p'):
1873 if not opts.has_key('p'):
1859 last_call[1] = parameter_s
1874 last_call[1] = parameter_s
1860 except:
1875 except:
1861 pass
1876 pass
1862
1877
1863 # by default this is done with temp files, except when the given
1878 # by default this is done with temp files, except when the given
1864 # arg is a filename
1879 # arg is a filename
1865 use_temp = 1
1880 use_temp = 1
1866
1881
1867 if re.match(r'\d',args):
1882 if re.match(r'\d',args):
1868 # Mode where user specifies ranges of lines, like in %macro.
1883 # Mode where user specifies ranges of lines, like in %macro.
1869 # This means that you can't edit files whose names begin with
1884 # This means that you can't edit files whose names begin with
1870 # numbers this way. Tough.
1885 # numbers this way. Tough.
1871 ranges = args.split()
1886 ranges = args.split()
1872 data = ''.join(self.extract_input_slices(ranges))
1887 data = ''.join(self.extract_input_slices(ranges))
1873 elif args.endswith('.py'):
1888 elif args.endswith('.py'):
1874 filename = make_filename(args)
1889 filename = make_filename(args)
1875 data = ''
1890 data = ''
1876 use_temp = 0
1891 use_temp = 0
1877 elif args:
1892 elif args:
1878 try:
1893 try:
1879 # Load the parameter given as a variable. If not a string,
1894 # Load the parameter given as a variable. If not a string,
1880 # process it as an object instead (below)
1895 # process it as an object instead (below)
1881
1896
1882 #print '*** args',args,'type',type(args) # dbg
1897 #print '*** args',args,'type',type(args) # dbg
1883 data = eval(args,self.shell.user_ns)
1898 data = eval(args,self.shell.user_ns)
1884 if not type(data) in StringTypes:
1899 if not type(data) in StringTypes:
1885 raise DataIsObject
1900 raise DataIsObject
1886
1901
1887 except (NameError,SyntaxError):
1902 except (NameError,SyntaxError):
1888 # given argument is not a variable, try as a filename
1903 # given argument is not a variable, try as a filename
1889 filename = make_filename(args)
1904 filename = make_filename(args)
1890 if filename is None:
1905 if filename is None:
1891 warn("Argument given (%s) can't be found as a variable "
1906 warn("Argument given (%s) can't be found as a variable "
1892 "or as a filename." % args)
1907 "or as a filename." % args)
1893 return
1908 return
1894
1909
1895 data = ''
1910 data = ''
1896 use_temp = 0
1911 use_temp = 0
1897 except DataIsObject:
1912 except DataIsObject:
1898
1913
1899 # macros have a special edit function
1914 # macros have a special edit function
1900 if isinstance(data,Macro):
1915 if isinstance(data,Macro):
1901 self._edit_macro(args,data)
1916 self._edit_macro(args,data)
1902 return
1917 return
1903
1918
1904 # For objects, try to edit the file where they are defined
1919 # For objects, try to edit the file where they are defined
1905 try:
1920 try:
1906 filename = inspect.getabsfile(data)
1921 filename = inspect.getabsfile(data)
1907 datafile = 1
1922 datafile = 1
1908 except TypeError:
1923 except TypeError:
1909 filename = make_filename(args)
1924 filename = make_filename(args)
1910 datafile = 1
1925 datafile = 1
1911 warn('Could not find file where `%s` is defined.\n'
1926 warn('Could not find file where `%s` is defined.\n'
1912 'Opening a file named `%s`' % (args,filename))
1927 'Opening a file named `%s`' % (args,filename))
1913 # Now, make sure we can actually read the source (if it was in
1928 # Now, make sure we can actually read the source (if it was in
1914 # a temp file it's gone by now).
1929 # a temp file it's gone by now).
1915 if datafile:
1930 if datafile:
1916 try:
1931 try:
1917 lineno = inspect.getsourcelines(data)[1]
1932 lineno = inspect.getsourcelines(data)[1]
1918 except IOError:
1933 except IOError:
1919 filename = make_filename(args)
1934 filename = make_filename(args)
1920 if filename is None:
1935 if filename is None:
1921 warn('The file `%s` where `%s` was defined cannot '
1936 warn('The file `%s` where `%s` was defined cannot '
1922 'be read.' % (filename,data))
1937 'be read.' % (filename,data))
1923 return
1938 return
1924 use_temp = 0
1939 use_temp = 0
1925 else:
1940 else:
1926 data = ''
1941 data = ''
1927
1942
1928 if use_temp:
1943 if use_temp:
1929 filename = self.shell.mktempfile(data)
1944 filename = self.shell.mktempfile(data)
1930 print 'IPython will make a temporary file named:',filename
1945 print 'IPython will make a temporary file named:',filename
1931
1946
1932 # do actual editing here
1947 # do actual editing here
1933 print 'Editing...',
1948 print 'Editing...',
1934 sys.stdout.flush()
1949 sys.stdout.flush()
1935 self.shell.hooks.editor(filename,lineno)
1950 self.shell.hooks.editor(filename,lineno)
1936 if opts.has_key('x'): # -x prevents actual execution
1951 if opts.has_key('x'): # -x prevents actual execution
1937 print
1952 print
1938 else:
1953 else:
1939 print 'done. Executing edited code...'
1954 print 'done. Executing edited code...'
1940 self.shell.safe_execfile(filename,self.shell.user_ns)
1955 self.shell.safe_execfile(filename,self.shell.user_ns)
1941 if use_temp:
1956 if use_temp:
1942 try:
1957 try:
1943 return open(filename).read()
1958 return open(filename).read()
1944 except IOError,msg:
1959 except IOError,msg:
1945 if msg.filename == filename:
1960 if msg.filename == filename:
1946 warn('File not found. Did you forget to save?')
1961 warn('File not found. Did you forget to save?')
1947 return
1962 return
1948 else:
1963 else:
1949 self.shell.showtraceback()
1964 self.shell.showtraceback()
1950
1965
1951 def magic_xmode(self,parameter_s = ''):
1966 def magic_xmode(self,parameter_s = ''):
1952 """Switch modes for the exception handlers.
1967 """Switch modes for the exception handlers.
1953
1968
1954 Valid modes: Plain, Context and Verbose.
1969 Valid modes: Plain, Context and Verbose.
1955
1970
1956 If called without arguments, acts as a toggle."""
1971 If called without arguments, acts as a toggle."""
1957
1972
1958 def xmode_switch_err(name):
1973 def xmode_switch_err(name):
1959 warn('Error changing %s exception modes.\n%s' %
1974 warn('Error changing %s exception modes.\n%s' %
1960 (name,sys.exc_info()[1]))
1975 (name,sys.exc_info()[1]))
1961
1976
1962 shell = self.shell
1977 shell = self.shell
1963 new_mode = parameter_s.strip().capitalize()
1978 new_mode = parameter_s.strip().capitalize()
1964 try:
1979 try:
1965 shell.InteractiveTB.set_mode(mode=new_mode)
1980 shell.InteractiveTB.set_mode(mode=new_mode)
1966 print 'Exception reporting mode:',shell.InteractiveTB.mode
1981 print 'Exception reporting mode:',shell.InteractiveTB.mode
1967 except:
1982 except:
1968 xmode_switch_err('user')
1983 xmode_switch_err('user')
1969
1984
1970 # threaded shells use a special handler in sys.excepthook
1985 # threaded shells use a special handler in sys.excepthook
1971 if shell.isthreaded:
1986 if shell.isthreaded:
1972 try:
1987 try:
1973 shell.sys_excepthook.set_mode(mode=new_mode)
1988 shell.sys_excepthook.set_mode(mode=new_mode)
1974 except:
1989 except:
1975 xmode_switch_err('threaded')
1990 xmode_switch_err('threaded')
1976
1991
1977 def magic_colors(self,parameter_s = ''):
1992 def magic_colors(self,parameter_s = ''):
1978 """Switch color scheme for prompts, info system and exception handlers.
1993 """Switch color scheme for prompts, info system and exception handlers.
1979
1994
1980 Currently implemented schemes: NoColor, Linux, LightBG.
1995 Currently implemented schemes: NoColor, Linux, LightBG.
1981
1996
1982 Color scheme names are not case-sensitive."""
1997 Color scheme names are not case-sensitive."""
1983
1998
1984 def color_switch_err(name):
1999 def color_switch_err(name):
1985 warn('Error changing %s color schemes.\n%s' %
2000 warn('Error changing %s color schemes.\n%s' %
1986 (name,sys.exc_info()[1]))
2001 (name,sys.exc_info()[1]))
1987
2002
1988
2003
1989 new_scheme = parameter_s.strip()
2004 new_scheme = parameter_s.strip()
1990 if not new_scheme:
2005 if not new_scheme:
1991 print 'You must specify a color scheme.'
2006 print 'You must specify a color scheme.'
1992 return
2007 return
1993 # Under Windows, check for Gary Bishop's readline, which is necessary
2008 # Under Windows, check for Gary Bishop's readline, which is necessary
1994 # for ANSI coloring
2009 # for ANSI coloring
1995 if os.name in ['nt','dos']:
2010 if os.name in ['nt','dos']:
1996 try:
2011 try:
1997 import readline
2012 import readline
1998 except ImportError:
2013 except ImportError:
1999 has_readline = 0
2014 has_readline = 0
2000 else:
2015 else:
2001 try:
2016 try:
2002 readline.GetOutputFile()
2017 readline.GetOutputFile()
2003 except AttributeError:
2018 except AttributeError:
2004 has_readline = 0
2019 has_readline = 0
2005 else:
2020 else:
2006 has_readline = 1
2021 has_readline = 1
2007 if not has_readline:
2022 if not has_readline:
2008 msg = """\
2023 msg = """\
2009 Proper color support under MS Windows requires Gary Bishop's readline library.
2024 Proper color support under MS Windows requires Gary Bishop's readline library.
2010 You can find it at:
2025 You can find it at:
2011 http://sourceforge.net/projects/uncpythontools
2026 http://sourceforge.net/projects/uncpythontools
2012 Gary's readline needs the ctypes module, from:
2027 Gary's readline needs the ctypes module, from:
2013 http://starship.python.net/crew/theller/ctypes
2028 http://starship.python.net/crew/theller/ctypes
2014
2029
2015 Defaulting color scheme to 'NoColor'"""
2030 Defaulting color scheme to 'NoColor'"""
2016 new_scheme = 'NoColor'
2031 new_scheme = 'NoColor'
2017 warn(msg)
2032 warn(msg)
2018 # local shortcut
2033 # local shortcut
2019 shell = self.shell
2034 shell = self.shell
2020
2035
2021 # Set prompt colors
2036 # Set prompt colors
2022 try:
2037 try:
2023 shell.outputcache.set_colors(new_scheme)
2038 shell.outputcache.set_colors(new_scheme)
2024 except:
2039 except:
2025 color_switch_err('prompt')
2040 color_switch_err('prompt')
2026 else:
2041 else:
2027 shell.rc.colors = \
2042 shell.rc.colors = \
2028 shell.outputcache.color_table.active_scheme_name
2043 shell.outputcache.color_table.active_scheme_name
2029 # Set exception colors
2044 # Set exception colors
2030 try:
2045 try:
2031 shell.InteractiveTB.set_colors(scheme = new_scheme)
2046 shell.InteractiveTB.set_colors(scheme = new_scheme)
2032 shell.SyntaxTB.set_colors(scheme = new_scheme)
2047 shell.SyntaxTB.set_colors(scheme = new_scheme)
2033 except:
2048 except:
2034 color_switch_err('exception')
2049 color_switch_err('exception')
2035
2050
2036 # threaded shells use a verbose traceback in sys.excepthook
2051 # threaded shells use a verbose traceback in sys.excepthook
2037 if shell.isthreaded:
2052 if shell.isthreaded:
2038 try:
2053 try:
2039 shell.sys_excepthook.set_colors(scheme=new_scheme)
2054 shell.sys_excepthook.set_colors(scheme=new_scheme)
2040 except:
2055 except:
2041 color_switch_err('system exception handler')
2056 color_switch_err('system exception handler')
2042
2057
2043 # Set info (for 'object?') colors
2058 # Set info (for 'object?') colors
2044 if shell.rc.color_info:
2059 if shell.rc.color_info:
2045 try:
2060 try:
2046 shell.inspector.set_active_scheme(new_scheme)
2061 shell.inspector.set_active_scheme(new_scheme)
2047 except:
2062 except:
2048 color_switch_err('object inspector')
2063 color_switch_err('object inspector')
2049 else:
2064 else:
2050 shell.inspector.set_active_scheme('NoColor')
2065 shell.inspector.set_active_scheme('NoColor')
2051
2066
2052 def magic_color_info(self,parameter_s = ''):
2067 def magic_color_info(self,parameter_s = ''):
2053 """Toggle color_info.
2068 """Toggle color_info.
2054
2069
2055 The color_info configuration parameter controls whether colors are
2070 The color_info configuration parameter controls whether colors are
2056 used for displaying object details (by things like %psource, %pfile or
2071 used for displaying object details (by things like %psource, %pfile or
2057 the '?' system). This function toggles this value with each call.
2072 the '?' system). This function toggles this value with each call.
2058
2073
2059 Note that unless you have a fairly recent pager (less works better
2074 Note that unless you have a fairly recent pager (less works better
2060 than more) in your system, using colored object information displays
2075 than more) in your system, using colored object information displays
2061 will not work properly. Test it and see."""
2076 will not work properly. Test it and see."""
2062
2077
2063 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2078 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2064 self.magic_colors(self.shell.rc.colors)
2079 self.magic_colors(self.shell.rc.colors)
2065 print 'Object introspection functions have now coloring:',
2080 print 'Object introspection functions have now coloring:',
2066 print ['OFF','ON'][self.shell.rc.color_info]
2081 print ['OFF','ON'][self.shell.rc.color_info]
2067
2082
2068 def magic_Pprint(self, parameter_s=''):
2083 def magic_Pprint(self, parameter_s=''):
2069 """Toggle pretty printing on/off."""
2084 """Toggle pretty printing on/off."""
2070
2085
2071 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2086 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2072 print 'Pretty printing has been turned', \
2087 print 'Pretty printing has been turned', \
2073 ['OFF','ON'][self.shell.outputcache.Pprint]
2088 ['OFF','ON'][self.shell.outputcache.Pprint]
2074
2089
2075 def magic_exit(self, parameter_s=''):
2090 def magic_exit(self, parameter_s=''):
2076 """Exit IPython, confirming if configured to do so.
2091 """Exit IPython, confirming if configured to do so.
2077
2092
2078 You can configure whether IPython asks for confirmation upon exit by
2093 You can configure whether IPython asks for confirmation upon exit by
2079 setting the confirm_exit flag in the ipythonrc file."""
2094 setting the confirm_exit flag in the ipythonrc file."""
2080
2095
2081 self.shell.exit()
2096 self.shell.exit()
2082
2097
2083 def magic_quit(self, parameter_s=''):
2098 def magic_quit(self, parameter_s=''):
2084 """Exit IPython, confirming if configured to do so (like %exit)"""
2099 """Exit IPython, confirming if configured to do so (like %exit)"""
2085
2100
2086 self.shell.exit()
2101 self.shell.exit()
2087
2102
2088 def magic_Exit(self, parameter_s=''):
2103 def magic_Exit(self, parameter_s=''):
2089 """Exit IPython without confirmation."""
2104 """Exit IPython without confirmation."""
2090
2105
2091 self.shell.exit_now = True
2106 self.shell.exit_now = True
2092
2107
2093 def magic_Quit(self, parameter_s=''):
2108 def magic_Quit(self, parameter_s=''):
2094 """Exit IPython without confirmation (like %Exit)."""
2109 """Exit IPython without confirmation (like %Exit)."""
2095
2110
2096 self.shell.exit_now = True
2111 self.shell.exit_now = True
2097
2112
2098 #......................................................................
2113 #......................................................................
2099 # Functions to implement unix shell-type things
2114 # Functions to implement unix shell-type things
2100
2115
2101 def magic_alias(self, parameter_s = ''):
2116 def magic_alias(self, parameter_s = ''):
2102 """Define an alias for a system command.
2117 """Define an alias for a system command.
2103
2118
2104 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2119 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2105
2120
2106 Then, typing 'alias_name params' will execute the system command 'cmd
2121 Then, typing 'alias_name params' will execute the system command 'cmd
2107 params' (from your underlying operating system).
2122 params' (from your underlying operating system).
2108
2123
2109 Aliases have lower precedence than magic functions and Python normal
2124 Aliases have lower precedence than magic functions and Python normal
2110 variables, so if 'foo' is both a Python variable and an alias, the
2125 variables, so if 'foo' is both a Python variable and an alias, the
2111 alias can not be executed until 'del foo' removes the Python variable.
2126 alias can not be executed until 'del foo' removes the Python variable.
2112
2127
2113 You can use the %l specifier in an alias definition to represent the
2128 You can use the %l specifier in an alias definition to represent the
2114 whole line when the alias is called. For example:
2129 whole line when the alias is called. For example:
2115
2130
2116 In [2]: alias all echo "Input in brackets: <%l>"\\
2131 In [2]: alias all echo "Input in brackets: <%l>"\\
2117 In [3]: all hello world\\
2132 In [3]: all hello world\\
2118 Input in brackets: <hello world>
2133 Input in brackets: <hello world>
2119
2134
2120 You can also define aliases with parameters using %s specifiers (one
2135 You can also define aliases with parameters using %s specifiers (one
2121 per parameter):
2136 per parameter):
2122
2137
2123 In [1]: alias parts echo first %s second %s\\
2138 In [1]: alias parts echo first %s second %s\\
2124 In [2]: %parts A B\\
2139 In [2]: %parts A B\\
2125 first A second B\\
2140 first A second B\\
2126 In [3]: %parts A\\
2141 In [3]: %parts A\\
2127 Incorrect number of arguments: 2 expected.\\
2142 Incorrect number of arguments: 2 expected.\\
2128 parts is an alias to: 'echo first %s second %s'
2143 parts is an alias to: 'echo first %s second %s'
2129
2144
2130 Note that %l and %s are mutually exclusive. You can only use one or
2145 Note that %l and %s are mutually exclusive. You can only use one or
2131 the other in your aliases.
2146 the other in your aliases.
2132
2147
2133 Aliases expand Python variables just like system calls using ! or !!
2148 Aliases expand Python variables just like system calls using ! or !!
2134 do: all expressions prefixed with '$' get expanded. For details of
2149 do: all expressions prefixed with '$' get expanded. For details of
2135 the semantic rules, see PEP-215:
2150 the semantic rules, see PEP-215:
2136 http://www.python.org/peps/pep-0215.html. This is the library used by
2151 http://www.python.org/peps/pep-0215.html. This is the library used by
2137 IPython for variable expansion. If you want to access a true shell
2152 IPython for variable expansion. If you want to access a true shell
2138 variable, an extra $ is necessary to prevent its expansion by IPython:
2153 variable, an extra $ is necessary to prevent its expansion by IPython:
2139
2154
2140 In [6]: alias show echo\\
2155 In [6]: alias show echo\\
2141 In [7]: PATH='A Python string'\\
2156 In [7]: PATH='A Python string'\\
2142 In [8]: show $PATH\\
2157 In [8]: show $PATH\\
2143 A Python string\\
2158 A Python string\\
2144 In [9]: show $$PATH\\
2159 In [9]: show $$PATH\\
2145 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2160 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2146
2161
2147 You can use the alias facility to acess all of $PATH. See the %rehash
2162 You can use the alias facility to acess all of $PATH. See the %rehash
2148 and %rehashx functions, which automatically create aliases for the
2163 and %rehashx functions, which automatically create aliases for the
2149 contents of your $PATH.
2164 contents of your $PATH.
2150
2165
2151 If called with no parameters, %alias prints the current alias table."""
2166 If called with no parameters, %alias prints the current alias table."""
2152
2167
2153 par = parameter_s.strip()
2168 par = parameter_s.strip()
2154 if not par:
2169 if not par:
2155 if self.shell.rc.automagic:
2170 if self.shell.rc.automagic:
2156 prechar = ''
2171 prechar = ''
2157 else:
2172 else:
2158 prechar = self.shell.ESC_MAGIC
2173 prechar = self.shell.ESC_MAGIC
2159 print 'Alias\t\tSystem Command\n'+'-'*30
2174 print 'Alias\t\tSystem Command\n'+'-'*30
2160 atab = self.shell.alias_table
2175 atab = self.shell.alias_table
2161 aliases = atab.keys()
2176 aliases = atab.keys()
2162 aliases.sort()
2177 aliases.sort()
2163 for alias in aliases:
2178 for alias in aliases:
2164 print prechar+alias+'\t\t'+atab[alias][1]
2179 print prechar+alias+'\t\t'+atab[alias][1]
2165 print '-'*30+'\nTotal number of aliases:',len(aliases)
2180 print '-'*30+'\nTotal number of aliases:',len(aliases)
2166 return
2181 return
2167 try:
2182 try:
2168 alias,cmd = par.split(None,1)
2183 alias,cmd = par.split(None,1)
2169 except:
2184 except:
2170 print OInspect.getdoc(self.magic_alias)
2185 print OInspect.getdoc(self.magic_alias)
2171 else:
2186 else:
2172 nargs = cmd.count('%s')
2187 nargs = cmd.count('%s')
2173 if nargs>0 and cmd.find('%l')>=0:
2188 if nargs>0 and cmd.find('%l')>=0:
2174 error('The %s and %l specifiers are mutually exclusive '
2189 error('The %s and %l specifiers are mutually exclusive '
2175 'in alias definitions.')
2190 'in alias definitions.')
2176 else: # all looks OK
2191 else: # all looks OK
2177 self.shell.alias_table[alias] = (nargs,cmd)
2192 self.shell.alias_table[alias] = (nargs,cmd)
2178 self.shell.alias_table_validate(verbose=1)
2193 self.shell.alias_table_validate(verbose=1)
2179 # end magic_alias
2194 # end magic_alias
2180
2195
2181 def magic_unalias(self, parameter_s = ''):
2196 def magic_unalias(self, parameter_s = ''):
2182 """Remove an alias"""
2197 """Remove an alias"""
2183
2198
2184 aname = parameter_s.strip()
2199 aname = parameter_s.strip()
2185 if aname in self.shell.alias_table:
2200 if aname in self.shell.alias_table:
2186 del self.shell.alias_table[aname]
2201 del self.shell.alias_table[aname]
2187
2202
2188 def magic_rehash(self, parameter_s = ''):
2203 def magic_rehash(self, parameter_s = ''):
2189 """Update the alias table with all entries in $PATH.
2204 """Update the alias table with all entries in $PATH.
2190
2205
2191 This version does no checks on execute permissions or whether the
2206 This version does no checks on execute permissions or whether the
2192 contents of $PATH are truly files (instead of directories or something
2207 contents of $PATH are truly files (instead of directories or something
2193 else). For such a safer (but slower) version, use %rehashx."""
2208 else). For such a safer (but slower) version, use %rehashx."""
2194
2209
2195 # This function (and rehashx) manipulate the alias_table directly
2210 # This function (and rehashx) manipulate the alias_table directly
2196 # rather than calling magic_alias, for speed reasons. A rehash on a
2211 # rather than calling magic_alias, for speed reasons. A rehash on a
2197 # typical Linux box involves several thousand entries, so efficiency
2212 # typical Linux box involves several thousand entries, so efficiency
2198 # here is a top concern.
2213 # here is a top concern.
2199
2214
2200 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2215 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2201 alias_table = self.shell.alias_table
2216 alias_table = self.shell.alias_table
2202 for pdir in path:
2217 for pdir in path:
2203 for ff in os.listdir(pdir):
2218 for ff in os.listdir(pdir):
2204 # each entry in the alias table must be (N,name), where
2219 # each entry in the alias table must be (N,name), where
2205 # N is the number of positional arguments of the alias.
2220 # N is the number of positional arguments of the alias.
2206 alias_table[ff] = (0,ff)
2221 alias_table[ff] = (0,ff)
2207 # Make sure the alias table doesn't contain keywords or builtins
2222 # Make sure the alias table doesn't contain keywords or builtins
2208 self.shell.alias_table_validate()
2223 self.shell.alias_table_validate()
2209 # Call again init_auto_alias() so we get 'rm -i' and other modified
2224 # Call again init_auto_alias() so we get 'rm -i' and other modified
2210 # aliases since %rehash will probably clobber them
2225 # aliases since %rehash will probably clobber them
2211 self.shell.init_auto_alias()
2226 self.shell.init_auto_alias()
2212
2227
2213 def magic_rehashx(self, parameter_s = ''):
2228 def magic_rehashx(self, parameter_s = ''):
2214 """Update the alias table with all executable files in $PATH.
2229 """Update the alias table with all executable files in $PATH.
2215
2230
2216 This version explicitly checks that every entry in $PATH is a file
2231 This version explicitly checks that every entry in $PATH is a file
2217 with execute access (os.X_OK), so it is much slower than %rehash.
2232 with execute access (os.X_OK), so it is much slower than %rehash.
2218
2233
2219 Under Windows, it checks executability as a match agains a
2234 Under Windows, it checks executability as a match agains a
2220 '|'-separated string of extensions, stored in the IPython config
2235 '|'-separated string of extensions, stored in the IPython config
2221 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2236 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2222
2237
2223 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2238 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2224 alias_table = self.shell.alias_table
2239 alias_table = self.shell.alias_table
2225
2240
2226 if os.name == 'posix':
2241 if os.name == 'posix':
2227 isexec = lambda fname:os.path.isfile(fname) and \
2242 isexec = lambda fname:os.path.isfile(fname) and \
2228 os.access(fname,os.X_OK)
2243 os.access(fname,os.X_OK)
2229 else:
2244 else:
2230
2245
2231 try:
2246 try:
2232 winext = os.environ['pathext'].replace(';','|').replace('.','')
2247 winext = os.environ['pathext'].replace(';','|').replace('.','')
2233 except KeyError:
2248 except KeyError:
2234 winext = 'exe|com|bat'
2249 winext = 'exe|com|bat'
2235
2250
2236 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2251 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2237 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2252 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2238 savedir = os.getcwd()
2253 savedir = os.getcwd()
2239 try:
2254 try:
2240 # write the whole loop for posix/Windows so we don't have an if in
2255 # write the whole loop for posix/Windows so we don't have an if in
2241 # the innermost part
2256 # the innermost part
2242 if os.name == 'posix':
2257 if os.name == 'posix':
2243 for pdir in path:
2258 for pdir in path:
2244 os.chdir(pdir)
2259 os.chdir(pdir)
2245 for ff in os.listdir(pdir):
2260 for ff in os.listdir(pdir):
2246 if isexec(ff):
2261 if isexec(ff):
2247 # each entry in the alias table must be (N,name),
2262 # each entry in the alias table must be (N,name),
2248 # where N is the number of positional arguments of the
2263 # where N is the number of positional arguments of the
2249 # alias.
2264 # alias.
2250 alias_table[ff] = (0,ff)
2265 alias_table[ff] = (0,ff)
2251 else:
2266 else:
2252 for pdir in path:
2267 for pdir in path:
2253 os.chdir(pdir)
2268 os.chdir(pdir)
2254 for ff in os.listdir(pdir):
2269 for ff in os.listdir(pdir):
2255 if isexec(ff):
2270 if isexec(ff):
2256 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2271 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2257 # Make sure the alias table doesn't contain keywords or builtins
2272 # Make sure the alias table doesn't contain keywords or builtins
2258 self.shell.alias_table_validate()
2273 self.shell.alias_table_validate()
2259 # Call again init_auto_alias() so we get 'rm -i' and other
2274 # Call again init_auto_alias() so we get 'rm -i' and other
2260 # modified aliases since %rehashx will probably clobber them
2275 # modified aliases since %rehashx will probably clobber them
2261 self.shell.init_auto_alias()
2276 self.shell.init_auto_alias()
2262 finally:
2277 finally:
2263 os.chdir(savedir)
2278 os.chdir(savedir)
2264
2279
2265 def magic_pwd(self, parameter_s = ''):
2280 def magic_pwd(self, parameter_s = ''):
2266 """Return the current working directory path."""
2281 """Return the current working directory path."""
2267 return os.getcwd()
2282 return os.getcwd()
2268
2283
2269 def magic_cd(self, parameter_s=''):
2284 def magic_cd(self, parameter_s=''):
2270 """Change the current working directory.
2285 """Change the current working directory.
2271
2286
2272 This command automatically maintains an internal list of directories
2287 This command automatically maintains an internal list of directories
2273 you visit during your IPython session, in the variable _dh. The
2288 you visit during your IPython session, in the variable _dh. The
2274 command %dhist shows this history nicely formatted.
2289 command %dhist shows this history nicely formatted.
2275
2290
2276 Usage:
2291 Usage:
2277
2292
2278 cd 'dir': changes to directory 'dir'.
2293 cd 'dir': changes to directory 'dir'.
2279
2294
2280 cd -: changes to the last visited directory.
2295 cd -: changes to the last visited directory.
2281
2296
2282 cd -<n>: changes to the n-th directory in the directory history.
2297 cd -<n>: changes to the n-th directory in the directory history.
2283
2298
2284 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2299 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2285 (note: cd <bookmark_name> is enough if there is no
2300 (note: cd <bookmark_name> is enough if there is no
2286 directory <bookmark_name>, but a bookmark with the name exists.)
2301 directory <bookmark_name>, but a bookmark with the name exists.)
2287
2302
2288 Options:
2303 Options:
2289
2304
2290 -q: quiet. Do not print the working directory after the cd command is
2305 -q: quiet. Do not print the working directory after the cd command is
2291 executed. By default IPython's cd command does print this directory,
2306 executed. By default IPython's cd command does print this directory,
2292 since the default prompts do not display path information.
2307 since the default prompts do not display path information.
2293
2308
2294 Note that !cd doesn't work for this purpose because the shell where
2309 Note that !cd doesn't work for this purpose because the shell where
2295 !command runs is immediately discarded after executing 'command'."""
2310 !command runs is immediately discarded after executing 'command'."""
2296
2311
2297 parameter_s = parameter_s.strip()
2312 parameter_s = parameter_s.strip()
2298 bkms = self.shell.persist.get("bookmarks",{})
2313 bkms = self.shell.persist.get("bookmarks",{})
2299
2314
2300 numcd = re.match(r'(-)(\d+)$',parameter_s)
2315 numcd = re.match(r'(-)(\d+)$',parameter_s)
2301 # jump in directory history by number
2316 # jump in directory history by number
2302 if numcd:
2317 if numcd:
2303 nn = int(numcd.group(2))
2318 nn = int(numcd.group(2))
2304 try:
2319 try:
2305 ps = self.shell.user_ns['_dh'][nn]
2320 ps = self.shell.user_ns['_dh'][nn]
2306 except IndexError:
2321 except IndexError:
2307 print 'The requested directory does not exist in history.'
2322 print 'The requested directory does not exist in history.'
2308 return
2323 return
2309 else:
2324 else:
2310 opts = {}
2325 opts = {}
2311 else:
2326 else:
2312 #turn all non-space-escaping backslashes to slashes,
2327 #turn all non-space-escaping backslashes to slashes,
2313 # for c:\windows\directory\names\
2328 # for c:\windows\directory\names\
2314 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2329 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2315 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2330 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2316 # jump to previous
2331 # jump to previous
2317 if ps == '-':
2332 if ps == '-':
2318 try:
2333 try:
2319 ps = self.shell.user_ns['_dh'][-2]
2334 ps = self.shell.user_ns['_dh'][-2]
2320 except IndexError:
2335 except IndexError:
2321 print 'No previous directory to change to.'
2336 print 'No previous directory to change to.'
2322 return
2337 return
2323 # jump to bookmark
2338 # jump to bookmark
2324 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2339 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2325 if bkms.has_key(ps):
2340 if bkms.has_key(ps):
2326 target = bkms[ps]
2341 target = bkms[ps]
2327 print '(bookmark:%s) -> %s' % (ps,target)
2342 print '(bookmark:%s) -> %s' % (ps,target)
2328 ps = target
2343 ps = target
2329 else:
2344 else:
2330 if bkms:
2345 if bkms:
2331 error("Bookmark '%s' not found. "
2346 error("Bookmark '%s' not found. "
2332 "Use '%%bookmark -l' to see your bookmarks." % ps)
2347 "Use '%%bookmark -l' to see your bookmarks." % ps)
2333 else:
2348 else:
2334 print "Bookmarks not set - use %bookmark <bookmarkname>"
2349 print "Bookmarks not set - use %bookmark <bookmarkname>"
2335 return
2350 return
2336
2351
2337 # at this point ps should point to the target dir
2352 # at this point ps should point to the target dir
2338 if ps:
2353 if ps:
2339 try:
2354 try:
2340 os.chdir(os.path.expanduser(ps))
2355 os.chdir(os.path.expanduser(ps))
2341 ttitle = ("IPy:" + (
2356 ttitle = ("IPy:" + (
2342 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2357 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2343 platutils.set_term_title(ttitle)
2358 platutils.set_term_title(ttitle)
2344 except OSError:
2359 except OSError:
2345 print sys.exc_info()[1]
2360 print sys.exc_info()[1]
2346 else:
2361 else:
2347 self.shell.user_ns['_dh'].append(os.getcwd())
2362 self.shell.user_ns['_dh'].append(os.getcwd())
2348 else:
2363 else:
2349 os.chdir(self.shell.home_dir)
2364 os.chdir(self.shell.home_dir)
2350 platutils.set_term_title("IPy:~")
2365 platutils.set_term_title("IPy:~")
2351 self.shell.user_ns['_dh'].append(os.getcwd())
2366 self.shell.user_ns['_dh'].append(os.getcwd())
2352 if not 'q' in opts:
2367 if not 'q' in opts:
2353 print self.shell.user_ns['_dh'][-1]
2368 print self.shell.user_ns['_dh'][-1]
2354
2369
2355 def magic_dhist(self, parameter_s=''):
2370 def magic_dhist(self, parameter_s=''):
2356 """Print your history of visited directories.
2371 """Print your history of visited directories.
2357
2372
2358 %dhist -> print full history\\
2373 %dhist -> print full history\\
2359 %dhist n -> print last n entries only\\
2374 %dhist n -> print last n entries only\\
2360 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2375 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2361
2376
2362 This history is automatically maintained by the %cd command, and
2377 This history is automatically maintained by the %cd command, and
2363 always available as the global list variable _dh. You can use %cd -<n>
2378 always available as the global list variable _dh. You can use %cd -<n>
2364 to go to directory number <n>."""
2379 to go to directory number <n>."""
2365
2380
2366 dh = self.shell.user_ns['_dh']
2381 dh = self.shell.user_ns['_dh']
2367 if parameter_s:
2382 if parameter_s:
2368 try:
2383 try:
2369 args = map(int,parameter_s.split())
2384 args = map(int,parameter_s.split())
2370 except:
2385 except:
2371 self.arg_err(Magic.magic_dhist)
2386 self.arg_err(Magic.magic_dhist)
2372 return
2387 return
2373 if len(args) == 1:
2388 if len(args) == 1:
2374 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2389 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2375 elif len(args) == 2:
2390 elif len(args) == 2:
2376 ini,fin = args
2391 ini,fin = args
2377 else:
2392 else:
2378 self.arg_err(Magic.magic_dhist)
2393 self.arg_err(Magic.magic_dhist)
2379 return
2394 return
2380 else:
2395 else:
2381 ini,fin = 0,len(dh)
2396 ini,fin = 0,len(dh)
2382 nlprint(dh,
2397 nlprint(dh,
2383 header = 'Directory history (kept in _dh)',
2398 header = 'Directory history (kept in _dh)',
2384 start=ini,stop=fin)
2399 start=ini,stop=fin)
2385
2400
2386 def magic_env(self, parameter_s=''):
2401 def magic_env(self, parameter_s=''):
2387 """List environment variables."""
2402 """List environment variables."""
2388
2403
2389 return os.environ.data
2404 return os.environ.data
2390
2405
2391 def magic_pushd(self, parameter_s=''):
2406 def magic_pushd(self, parameter_s=''):
2392 """Place the current dir on stack and change directory.
2407 """Place the current dir on stack and change directory.
2393
2408
2394 Usage:\\
2409 Usage:\\
2395 %pushd ['dirname']
2410 %pushd ['dirname']
2396
2411
2397 %pushd with no arguments does a %pushd to your home directory.
2412 %pushd with no arguments does a %pushd to your home directory.
2398 """
2413 """
2399 if parameter_s == '': parameter_s = '~'
2414 if parameter_s == '': parameter_s = '~'
2400 dir_s = self.shell.dir_stack
2415 dir_s = self.shell.dir_stack
2401 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2416 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2402 os.path.expanduser(self.shell.dir_stack[0]):
2417 os.path.expanduser(self.shell.dir_stack[0]):
2403 try:
2418 try:
2404 self.magic_cd(parameter_s)
2419 self.magic_cd(parameter_s)
2405 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2420 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2406 self.magic_dirs()
2421 self.magic_dirs()
2407 except:
2422 except:
2408 print 'Invalid directory'
2423 print 'Invalid directory'
2409 else:
2424 else:
2410 print 'You are already there!'
2425 print 'You are already there!'
2411
2426
2412 def magic_popd(self, parameter_s=''):
2427 def magic_popd(self, parameter_s=''):
2413 """Change to directory popped off the top of the stack.
2428 """Change to directory popped off the top of the stack.
2414 """
2429 """
2415 if len (self.shell.dir_stack) > 1:
2430 if len (self.shell.dir_stack) > 1:
2416 self.shell.dir_stack.pop(0)
2431 self.shell.dir_stack.pop(0)
2417 self.magic_cd(self.shell.dir_stack[0])
2432 self.magic_cd(self.shell.dir_stack[0])
2418 print self.shell.dir_stack[0]
2433 print self.shell.dir_stack[0]
2419 else:
2434 else:
2420 print "You can't remove the starting directory from the stack:",\
2435 print "You can't remove the starting directory from the stack:",\
2421 self.shell.dir_stack
2436 self.shell.dir_stack
2422
2437
2423 def magic_dirs(self, parameter_s=''):
2438 def magic_dirs(self, parameter_s=''):
2424 """Return the current directory stack."""
2439 """Return the current directory stack."""
2425
2440
2426 return self.shell.dir_stack[:]
2441 return self.shell.dir_stack[:]
2427
2442
2428 def magic_sc(self, parameter_s=''):
2443 def magic_sc(self, parameter_s=''):
2429 """Shell capture - execute a shell command and capture its output.
2444 """Shell capture - execute a shell command and capture its output.
2430
2445
2431 %sc [options] varname=command
2446 %sc [options] varname=command
2432
2447
2433 IPython will run the given command using commands.getoutput(), and
2448 IPython will run the given command using commands.getoutput(), and
2434 will then update the user's interactive namespace with a variable
2449 will then update the user's interactive namespace with a variable
2435 called varname, containing the value of the call. Your command can
2450 called varname, containing the value of the call. Your command can
2436 contain shell wildcards, pipes, etc.
2451 contain shell wildcards, pipes, etc.
2437
2452
2438 The '=' sign in the syntax is mandatory, and the variable name you
2453 The '=' sign in the syntax is mandatory, and the variable name you
2439 supply must follow Python's standard conventions for valid names.
2454 supply must follow Python's standard conventions for valid names.
2440
2455
2441 Options:
2456 Options:
2442
2457
2443 -l: list output. Split the output on newlines into a list before
2458 -l: list output. Split the output on newlines into a list before
2444 assigning it to the given variable. By default the output is stored
2459 assigning it to the given variable. By default the output is stored
2445 as a single string.
2460 as a single string.
2446
2461
2447 -v: verbose. Print the contents of the variable.
2462 -v: verbose. Print the contents of the variable.
2448
2463
2449 In most cases you should not need to split as a list, because the
2464 In most cases you should not need to split as a list, because the
2450 returned value is a special type of string which can automatically
2465 returned value is a special type of string which can automatically
2451 provide its contents either as a list (split on newlines) or as a
2466 provide its contents either as a list (split on newlines) or as a
2452 space-separated string. These are convenient, respectively, either
2467 space-separated string. These are convenient, respectively, either
2453 for sequential processing or to be passed to a shell command.
2468 for sequential processing or to be passed to a shell command.
2454
2469
2455 For example:
2470 For example:
2456
2471
2457 # Capture into variable a
2472 # Capture into variable a
2458 In [9]: sc a=ls *py
2473 In [9]: sc a=ls *py
2459
2474
2460 # a is a string with embedded newlines
2475 # a is a string with embedded newlines
2461 In [10]: a
2476 In [10]: a
2462 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2477 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2463
2478
2464 # which can be seen as a list:
2479 # which can be seen as a list:
2465 In [11]: a.l
2480 In [11]: a.l
2466 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2481 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2467
2482
2468 # or as a whitespace-separated string:
2483 # or as a whitespace-separated string:
2469 In [12]: a.s
2484 In [12]: a.s
2470 Out[12]: 'setup.py win32_manual_post_install.py'
2485 Out[12]: 'setup.py win32_manual_post_install.py'
2471
2486
2472 # a.s is useful to pass as a single command line:
2487 # a.s is useful to pass as a single command line:
2473 In [13]: !wc -l $a.s
2488 In [13]: !wc -l $a.s
2474 146 setup.py
2489 146 setup.py
2475 130 win32_manual_post_install.py
2490 130 win32_manual_post_install.py
2476 276 total
2491 276 total
2477
2492
2478 # while the list form is useful to loop over:
2493 # while the list form is useful to loop over:
2479 In [14]: for f in a.l:
2494 In [14]: for f in a.l:
2480 ....: !wc -l $f
2495 ....: !wc -l $f
2481 ....:
2496 ....:
2482 146 setup.py
2497 146 setup.py
2483 130 win32_manual_post_install.py
2498 130 win32_manual_post_install.py
2484
2499
2485 Similiarly, the lists returned by the -l option are also special, in
2500 Similiarly, the lists returned by the -l option are also special, in
2486 the sense that you can equally invoke the .s attribute on them to
2501 the sense that you can equally invoke the .s attribute on them to
2487 automatically get a whitespace-separated string from their contents:
2502 automatically get a whitespace-separated string from their contents:
2488
2503
2489 In [1]: sc -l b=ls *py
2504 In [1]: sc -l b=ls *py
2490
2505
2491 In [2]: b
2506 In [2]: b
2492 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2507 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2493
2508
2494 In [3]: b.s
2509 In [3]: b.s
2495 Out[3]: 'setup.py win32_manual_post_install.py'
2510 Out[3]: 'setup.py win32_manual_post_install.py'
2496
2511
2497 In summary, both the lists and strings used for ouptut capture have
2512 In summary, both the lists and strings used for ouptut capture have
2498 the following special attributes:
2513 the following special attributes:
2499
2514
2500 .l (or .list) : value as list.
2515 .l (or .list) : value as list.
2501 .n (or .nlstr): value as newline-separated string.
2516 .n (or .nlstr): value as newline-separated string.
2502 .s (or .spstr): value as space-separated string.
2517 .s (or .spstr): value as space-separated string.
2503 """
2518 """
2504
2519
2505 opts,args = self.parse_options(parameter_s,'lv')
2520 opts,args = self.parse_options(parameter_s,'lv')
2506 # Try to get a variable name and command to run
2521 # Try to get a variable name and command to run
2507 try:
2522 try:
2508 # the variable name must be obtained from the parse_options
2523 # the variable name must be obtained from the parse_options
2509 # output, which uses shlex.split to strip options out.
2524 # output, which uses shlex.split to strip options out.
2510 var,_ = args.split('=',1)
2525 var,_ = args.split('=',1)
2511 var = var.strip()
2526 var = var.strip()
2512 # But the the command has to be extracted from the original input
2527 # But the the command has to be extracted from the original input
2513 # parameter_s, not on what parse_options returns, to avoid the
2528 # parameter_s, not on what parse_options returns, to avoid the
2514 # quote stripping which shlex.split performs on it.
2529 # quote stripping which shlex.split performs on it.
2515 _,cmd = parameter_s.split('=',1)
2530 _,cmd = parameter_s.split('=',1)
2516 except ValueError:
2531 except ValueError:
2517 var,cmd = '',''
2532 var,cmd = '',''
2518 if not var:
2533 if not var:
2519 error('you must specify a variable to assign the command to.')
2534 error('you must specify a variable to assign the command to.')
2520 return
2535 return
2521 # If all looks ok, proceed
2536 # If all looks ok, proceed
2522 out,err = self.shell.getoutputerror(cmd)
2537 out,err = self.shell.getoutputerror(cmd)
2523 if err:
2538 if err:
2524 print >> Term.cerr,err
2539 print >> Term.cerr,err
2525 if opts.has_key('l'):
2540 if opts.has_key('l'):
2526 out = SList(out.split('\n'))
2541 out = SList(out.split('\n'))
2527 else:
2542 else:
2528 out = LSString(out)
2543 out = LSString(out)
2529 if opts.has_key('v'):
2544 if opts.has_key('v'):
2530 print '%s ==\n%s' % (var,pformat(out))
2545 print '%s ==\n%s' % (var,pformat(out))
2531 self.shell.user_ns.update({var:out})
2546 self.shell.user_ns.update({var:out})
2532
2547
2533 def magic_sx(self, parameter_s=''):
2548 def magic_sx(self, parameter_s=''):
2534 """Shell execute - run a shell command and capture its output.
2549 """Shell execute - run a shell command and capture its output.
2535
2550
2536 %sx command
2551 %sx command
2537
2552
2538 IPython will run the given command using commands.getoutput(), and
2553 IPython will run the given command using commands.getoutput(), and
2539 return the result formatted as a list (split on '\\n'). Since the
2554 return the result formatted as a list (split on '\\n'). Since the
2540 output is _returned_, it will be stored in ipython's regular output
2555 output is _returned_, it will be stored in ipython's regular output
2541 cache Out[N] and in the '_N' automatic variables.
2556 cache Out[N] and in the '_N' automatic variables.
2542
2557
2543 Notes:
2558 Notes:
2544
2559
2545 1) If an input line begins with '!!', then %sx is automatically
2560 1) If an input line begins with '!!', then %sx is automatically
2546 invoked. That is, while:
2561 invoked. That is, while:
2547 !ls
2562 !ls
2548 causes ipython to simply issue system('ls'), typing
2563 causes ipython to simply issue system('ls'), typing
2549 !!ls
2564 !!ls
2550 is a shorthand equivalent to:
2565 is a shorthand equivalent to:
2551 %sx ls
2566 %sx ls
2552
2567
2553 2) %sx differs from %sc in that %sx automatically splits into a list,
2568 2) %sx differs from %sc in that %sx automatically splits into a list,
2554 like '%sc -l'. The reason for this is to make it as easy as possible
2569 like '%sc -l'. The reason for this is to make it as easy as possible
2555 to process line-oriented shell output via further python commands.
2570 to process line-oriented shell output via further python commands.
2556 %sc is meant to provide much finer control, but requires more
2571 %sc is meant to provide much finer control, but requires more
2557 typing.
2572 typing.
2558
2573
2559 3) Just like %sc -l, this is a list with special attributes:
2574 3) Just like %sc -l, this is a list with special attributes:
2560
2575
2561 .l (or .list) : value as list.
2576 .l (or .list) : value as list.
2562 .n (or .nlstr): value as newline-separated string.
2577 .n (or .nlstr): value as newline-separated string.
2563 .s (or .spstr): value as whitespace-separated string.
2578 .s (or .spstr): value as whitespace-separated string.
2564
2579
2565 This is very useful when trying to use such lists as arguments to
2580 This is very useful when trying to use such lists as arguments to
2566 system commands."""
2581 system commands."""
2567
2582
2568 if parameter_s:
2583 if parameter_s:
2569 out,err = self.shell.getoutputerror(parameter_s)
2584 out,err = self.shell.getoutputerror(parameter_s)
2570 if err:
2585 if err:
2571 print >> Term.cerr,err
2586 print >> Term.cerr,err
2572 return SList(out.split('\n'))
2587 return SList(out.split('\n'))
2573
2588
2574 def magic_bg(self, parameter_s=''):
2589 def magic_bg(self, parameter_s=''):
2575 """Run a job in the background, in a separate thread.
2590 """Run a job in the background, in a separate thread.
2576
2591
2577 For example,
2592 For example,
2578
2593
2579 %bg myfunc(x,y,z=1)
2594 %bg myfunc(x,y,z=1)
2580
2595
2581 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2596 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2582 execution starts, a message will be printed indicating the job
2597 execution starts, a message will be printed indicating the job
2583 number. If your job number is 5, you can use
2598 number. If your job number is 5, you can use
2584
2599
2585 myvar = jobs.result(5) or myvar = jobs[5].result
2600 myvar = jobs.result(5) or myvar = jobs[5].result
2586
2601
2587 to assign this result to variable 'myvar'.
2602 to assign this result to variable 'myvar'.
2588
2603
2589 IPython has a job manager, accessible via the 'jobs' object. You can
2604 IPython has a job manager, accessible via the 'jobs' object. You can
2590 type jobs? to get more information about it, and use jobs.<TAB> to see
2605 type jobs? to get more information about it, and use jobs.<TAB> to see
2591 its attributes. All attributes not starting with an underscore are
2606 its attributes. All attributes not starting with an underscore are
2592 meant for public use.
2607 meant for public use.
2593
2608
2594 In particular, look at the jobs.new() method, which is used to create
2609 In particular, look at the jobs.new() method, which is used to create
2595 new jobs. This magic %bg function is just a convenience wrapper
2610 new jobs. This magic %bg function is just a convenience wrapper
2596 around jobs.new(), for expression-based jobs. If you want to create a
2611 around jobs.new(), for expression-based jobs. If you want to create a
2597 new job with an explicit function object and arguments, you must call
2612 new job with an explicit function object and arguments, you must call
2598 jobs.new() directly.
2613 jobs.new() directly.
2599
2614
2600 The jobs.new docstring also describes in detail several important
2615 The jobs.new docstring also describes in detail several important
2601 caveats associated with a thread-based model for background job
2616 caveats associated with a thread-based model for background job
2602 execution. Type jobs.new? for details.
2617 execution. Type jobs.new? for details.
2603
2618
2604 You can check the status of all jobs with jobs.status().
2619 You can check the status of all jobs with jobs.status().
2605
2620
2606 The jobs variable is set by IPython into the Python builtin namespace.
2621 The jobs variable is set by IPython into the Python builtin namespace.
2607 If you ever declare a variable named 'jobs', you will shadow this
2622 If you ever declare a variable named 'jobs', you will shadow this
2608 name. You can either delete your global jobs variable to regain
2623 name. You can either delete your global jobs variable to regain
2609 access to the job manager, or make a new name and assign it manually
2624 access to the job manager, or make a new name and assign it manually
2610 to the manager (stored in IPython's namespace). For example, to
2625 to the manager (stored in IPython's namespace). For example, to
2611 assign the job manager to the Jobs name, use:
2626 assign the job manager to the Jobs name, use:
2612
2627
2613 Jobs = __builtins__.jobs"""
2628 Jobs = __builtins__.jobs"""
2614
2629
2615 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2630 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2616
2631
2617 def magic_store(self, parameter_s=''):
2632 def magic_store(self, parameter_s=''):
2618 """Lightweight persistence for python variables.
2633 """Lightweight persistence for python variables.
2619
2634
2620 Example:
2635 Example:
2621
2636
2622 ville@badger[~]|1> A = ['hello',10,'world']\\
2637 ville@badger[~]|1> A = ['hello',10,'world']\\
2623 ville@badger[~]|2> %store A\\
2638 ville@badger[~]|2> %store A\\
2624 ville@badger[~]|3> Exit
2639 ville@badger[~]|3> Exit
2625
2640
2626 (IPython session is closed and started again...)
2641 (IPython session is closed and started again...)
2627
2642
2628 ville@badger:~$ ipython -p pysh\\
2643 ville@badger:~$ ipython -p pysh\\
2629 ville@badger[~]|1> print A
2644 ville@badger[~]|1> print A
2630
2645
2631 ['hello', 10, 'world']
2646 ['hello', 10, 'world']
2632
2647
2633 Usage:
2648 Usage:
2634
2649
2635 %store - Show list of all variables and their current values\\
2650 %store - Show list of all variables and their current values\\
2636 %store <var> - Store the *current* value of the variable to disk\\
2651 %store <var> - Store the *current* value of the variable to disk\\
2637 %store -d <var> - Remove the variable and its value from storage\\
2652 %store -d <var> - Remove the variable and its value from storage\\
2638 %store -r - Remove all variables from storage
2653 %store -r - Remove all variables from storage
2639
2654
2640 It should be noted that if you change the value of a variable, you
2655 It should be noted that if you change the value of a variable, you
2641 need to %store it again if you want to persist the new value.
2656 need to %store it again if you want to persist the new value.
2642
2657
2643 Note also that the variables will need to be pickleable; most basic
2658 Note also that the variables will need to be pickleable; most basic
2644 python types can be safely %stored.
2659 python types can be safely %stored.
2645 """
2660 """
2646
2661
2647 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2662 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2648 # delete
2663 # delete
2649 if opts.has_key('d'):
2664 if opts.has_key('d'):
2650 try:
2665 try:
2651 todel = args[0]
2666 todel = args[0]
2652 except IndexError:
2667 except IndexError:
2653 error('You must provide the variable to forget')
2668 error('You must provide the variable to forget')
2654 else:
2669 else:
2655 try:
2670 try:
2656 del self.shell.persist['S:' + todel]
2671 del self.shell.persist['S:' + todel]
2657 except:
2672 except:
2658 error("Can't delete variable '%s'" % todel)
2673 error("Can't delete variable '%s'" % todel)
2659 # reset
2674 # reset
2660 elif opts.has_key('r'):
2675 elif opts.has_key('r'):
2661 for k in self.shell.persist.keys():
2676 for k in self.shell.persist.keys():
2662 if k.startswith('S:'):
2677 if k.startswith('S:'):
2663 del self.shell.persist[k]
2678 del self.shell.persist[k]
2664
2679
2665 # run without arguments -> list variables & values
2680 # run without arguments -> list variables & values
2666 elif not args:
2681 elif not args:
2667 vars = [v[2:] for v in self.shell.persist.keys()
2682 vars = [v[2:] for v in self.shell.persist.keys()
2668 if v.startswith('S:')]
2683 if v.startswith('S:')]
2669 vars.sort()
2684 vars.sort()
2670 if vars:
2685 if vars:
2671 size = max(map(len,vars))
2686 size = max(map(len,vars))
2672 else:
2687 else:
2673 size = 0
2688 size = 0
2674
2689
2675 print 'Stored variables and their in-memory values:'
2690 print 'Stored variables and their in-memory values:'
2676 fmt = '%-'+str(size)+'s -> %s'
2691 fmt = '%-'+str(size)+'s -> %s'
2677 get = self.shell.user_ns.get
2692 get = self.shell.user_ns.get
2678 for var in vars:
2693 for var in vars:
2679 # print 30 first characters from every var
2694 # print 30 first characters from every var
2680 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2695 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2681
2696
2682 # default action - store the variable
2697 # default action - store the variable
2683 else:
2698 else:
2684 obj = self.shell.user_ns[args[0] ]
2699 obj = self.shell.user_ns[args[0] ]
2685 if isinstance(inspect.getmodule(obj), FakeModule):
2700 if isinstance(inspect.getmodule(obj), FakeModule):
2686 print textwrap.dedent("""\
2701 print textwrap.dedent("""\
2687 Warning:%s is %s
2702 Warning:%s is %s
2688 Proper storage of interactively declared classes (or instances
2703 Proper storage of interactively declared classes (or instances
2689 of those classes) is not possible! Only instances
2704 of those classes) is not possible! Only instances
2690 of classes in real modules on file system can be %%store'd.
2705 of classes in real modules on file system can be %%store'd.
2691 """ % (args[0], obj) )
2706 """ % (args[0], obj) )
2692 return
2707 return
2693 pickled = pickle.dumps(obj)
2708 pickled = pickle.dumps(obj)
2694 self.shell.persist[ 'S:' + args[0] ] = pickled
2709 self.shell.persist[ 'S:' + args[0] ] = pickled
2695 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2710 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2696
2711
2697 def magic_bookmark(self, parameter_s=''):
2712 def magic_bookmark(self, parameter_s=''):
2698 """Manage IPython's bookmark system.
2713 """Manage IPython's bookmark system.
2699
2714
2700 %bookmark <name> - set bookmark to current dir
2715 %bookmark <name> - set bookmark to current dir
2701 %bookmark <name> <dir> - set bookmark to <dir>
2716 %bookmark <name> <dir> - set bookmark to <dir>
2702 %bookmark -l - list all bookmarks
2717 %bookmark -l - list all bookmarks
2703 %bookmark -d <name> - remove bookmark
2718 %bookmark -d <name> - remove bookmark
2704 %bookmark -r - remove all bookmarks
2719 %bookmark -r - remove all bookmarks
2705
2720
2706 You can later on access a bookmarked folder with:
2721 You can later on access a bookmarked folder with:
2707 %cd -b <name>
2722 %cd -b <name>
2708 or simply '%cd <name>' if there is no directory called <name> AND
2723 or simply '%cd <name>' if there is no directory called <name> AND
2709 there is such a bookmark defined.
2724 there is such a bookmark defined.
2710
2725
2711 Your bookmarks persist through IPython sessions, but they are
2726 Your bookmarks persist through IPython sessions, but they are
2712 associated with each profile."""
2727 associated with each profile."""
2713
2728
2714 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2729 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2715 if len(args) > 2:
2730 if len(args) > 2:
2716 error('You can only give at most two arguments')
2731 error('You can only give at most two arguments')
2717 return
2732 return
2718
2733
2719 bkms = self.shell.persist.get('bookmarks',{})
2734 bkms = self.shell.persist.get('bookmarks',{})
2720
2735
2721 if opts.has_key('d'):
2736 if opts.has_key('d'):
2722 try:
2737 try:
2723 todel = args[0]
2738 todel = args[0]
2724 except IndexError:
2739 except IndexError:
2725 error('You must provide a bookmark to delete')
2740 error('You must provide a bookmark to delete')
2726 else:
2741 else:
2727 try:
2742 try:
2728 del bkms[todel]
2743 del bkms[todel]
2729 except:
2744 except:
2730 error("Can't delete bookmark '%s'" % todel)
2745 error("Can't delete bookmark '%s'" % todel)
2731 elif opts.has_key('r'):
2746 elif opts.has_key('r'):
2732 bkms = {}
2747 bkms = {}
2733 elif opts.has_key('l'):
2748 elif opts.has_key('l'):
2734 bks = bkms.keys()
2749 bks = bkms.keys()
2735 bks.sort()
2750 bks.sort()
2736 if bks:
2751 if bks:
2737 size = max(map(len,bks))
2752 size = max(map(len,bks))
2738 else:
2753 else:
2739 size = 0
2754 size = 0
2740 fmt = '%-'+str(size)+'s -> %s'
2755 fmt = '%-'+str(size)+'s -> %s'
2741 print 'Current bookmarks:'
2756 print 'Current bookmarks:'
2742 for bk in bks:
2757 for bk in bks:
2743 print fmt % (bk,bkms[bk])
2758 print fmt % (bk,bkms[bk])
2744 else:
2759 else:
2745 if not args:
2760 if not args:
2746 error("You must specify the bookmark name")
2761 error("You must specify the bookmark name")
2747 elif len(args)==1:
2762 elif len(args)==1:
2748 bkms[args[0]] = os.getcwd()
2763 bkms[args[0]] = os.getcwd()
2749 elif len(args)==2:
2764 elif len(args)==2:
2750 bkms[args[0]] = args[1]
2765 bkms[args[0]] = args[1]
2751 self.shell.persist['bookmarks'] = bkms
2766 self.shell.persist['bookmarks'] = bkms
2752
2767
2753 def magic_pycat(self, parameter_s=''):
2768 def magic_pycat(self, parameter_s=''):
2754 """Show a syntax-highlighted file through a pager.
2769 """Show a syntax-highlighted file through a pager.
2755
2770
2756 This magic is similar to the cat utility, but it will assume the file
2771 This magic is similar to the cat utility, but it will assume the file
2757 to be Python source and will show it with syntax highlighting. """
2772 to be Python source and will show it with syntax highlighting. """
2758
2773
2759 filename = get_py_filename(parameter_s)
2774 filename = get_py_filename(parameter_s)
2760 page(self.shell.pycolorize(file_read(filename)),
2775 page(self.shell.pycolorize(file_read(filename)),
2761 screen_lines=self.shell.rc.screen_length)
2776 screen_lines=self.shell.rc.screen_length)
2762
2777
2763 def magic_cpaste(self, parameter_s=''):
2778 def magic_cpaste(self, parameter_s=''):
2764 """Allows you to paste & execute a pre-formatted code block from
2779 """Allows you to paste & execute a pre-formatted code block from
2765 clipboard.
2780 clipboard.
2766
2781
2767 You must terminate the block with '--' (two minus-signs) alone on the
2782 You must terminate the block with '--' (two minus-signs) alone on the
2768 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2783 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2769 is the new sentinel for this operation)
2784 is the new sentinel for this operation)
2770
2785
2771 The block is dedented prior to execution to enable execution of
2786 The block is dedented prior to execution to enable execution of
2772 method definitions. The executed block is also assigned to variable
2787 method definitions. The executed block is also assigned to variable
2773 named 'pasted_block' for later editing with '%edit pasted_block'.
2788 named 'pasted_block' for later editing with '%edit pasted_block'.
2774
2789
2775 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2790 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2776 This assigns the pasted block to variable 'foo' as string, without
2791 This assigns the pasted block to variable 'foo' as string, without
2777 dedenting or executing it.
2792 dedenting or executing it.
2778
2793
2779 Do not be alarmed by garbled output on Windows (it's a readline bug).
2794 Do not be alarmed by garbled output on Windows (it's a readline bug).
2780 Just press enter and type -- (and press enter again) and the block
2795 Just press enter and type -- (and press enter again) and the block
2781 will be what was just pasted.
2796 will be what was just pasted.
2782
2797
2783 IPython statements (magics, shell escapes) are not supported (yet).
2798 IPython statements (magics, shell escapes) are not supported (yet).
2784 """
2799 """
2785 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2800 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2786 par = args.strip()
2801 par = args.strip()
2787 sentinel = opts.get('s','--')
2802 sentinel = opts.get('s','--')
2788
2803
2789 from IPython import iplib
2804 from IPython import iplib
2790 lines = []
2805 lines = []
2791 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2806 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2792 while 1:
2807 while 1:
2793 l = iplib.raw_input_original(':')
2808 l = iplib.raw_input_original(':')
2794 if l ==sentinel:
2809 if l ==sentinel:
2795 break
2810 break
2796 lines.append(l)
2811 lines.append(l)
2797 block = "\n".join(lines)
2812 block = "\n".join(lines)
2798 #print "block:\n",block
2813 #print "block:\n",block
2799 if not par:
2814 if not par:
2800 b = textwrap.dedent(block)
2815 b = textwrap.dedent(block)
2801 exec b in self.user_ns
2816 exec b in self.user_ns
2802 self.user_ns['pasted_block'] = b
2817 self.user_ns['pasted_block'] = b
2803 else:
2818 else:
2804 self.user_ns[par] = block
2819 self.user_ns[par] = block
2805 print "Block assigned to '%s'" % par
2820 print "Block assigned to '%s'" % par
2806
2821
2807
2822
2808
2823
2809 # end Magic
2824 # end Magic
@@ -1,77 +1,78 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 1058 2006-01-22 14:30:01Z vivainio $"""
4 $Id: Release.py 1077 2006-01-24 18:15:27Z vivainio $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 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
25 version = '0.7.2.svn'
26 version = '0.7.2.svn'
26
27
27 revision = '$Revision: 1058 $'
28 revision = '$Revision: 1077 $'
28
29
29 description = "An enhanced interactive Python shell."
30 description = "An enhanced interactive Python shell."
30
31
31 long_description = \
32 long_description = \
32 """
33 """
33 IPython provides a replacement for the interactive Python interpreter with
34 IPython provides a replacement for the interactive Python interpreter with
34 extra functionality.
35 extra functionality.
35
36
36 Main features:
37 Main features:
37
38
38 * Comprehensive object introspection.
39 * Comprehensive object introspection.
39
40
40 * Input history, persistent across sessions.
41 * Input history, persistent across sessions.
41
42
42 * Caching of output results during a session with automatically generated
43 * Caching of output results during a session with automatically generated
43 references.
44 references.
44
45
45 * Readline based name completion.
46 * Readline based name completion.
46
47
47 * Extensible system of 'magic' commands for controlling the environment and
48 * Extensible system of 'magic' commands for controlling the environment and
48 performing many tasks related either to IPython or the operating system.
49 performing many tasks related either to IPython or the operating system.
49
50
50 * Configuration system with easy switching between different setups (simpler
51 * Configuration system with easy switching between different setups (simpler
51 than changing $PYTHONSTARTUP environment variables every time).
52 than changing $PYTHONSTARTUP environment variables every time).
52
53
53 * Session logging and reloading.
54 * Session logging and reloading.
54
55
55 * Extensible syntax processing for special purpose situations.
56 * Extensible syntax processing for special purpose situations.
56
57
57 * Access to the system shell with user-extensible alias system.
58 * Access to the system shell with user-extensible alias system.
58
59
59 * Easily embeddable in other Python programs.
60 * Easily embeddable in other Python programs.
60
61
61 * Integrated access to the pdb debugger and the Python profiler. """
62 * Integrated access to the pdb debugger and the Python profiler. """
62
63
63 license = 'BSD'
64 license = 'BSD'
64
65
65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
66 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
67 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
68 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
68 'Ville' : ('Ville Vainio','vivainio@gmail.com')
69 'Ville' : ('Ville Vainio','vivainio@gmail.com')
69 }
70 }
70
71
71 url = 'http://ipython.scipy.org'
72 url = 'http://ipython.scipy.org'
72
73
73 download_url = 'http://ipython.scipy.org/dist'
74 download_url = 'http://ipython.scipy.org/dist'
74
75
75 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
76 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
76
77
77 keywords = ['Interactive','Interpreter','Shell']
78 keywords = ['Interactive','Interpreter','Shell']
@@ -1,562 +1,562 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 ---------------------------------------------------------------------------
9 ---------------------------------------------------------------------------
10 Original rlcompleter documentation:
10 Original rlcompleter documentation:
11
11
12 This requires the latest extension to the readline module (the
12 This requires the latest extension to the readline module (the
13 completes keywords, built-ins and globals in __main__; when completing
13 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
15 completes its attributes.
16
16
17 It's very cool to do "import string" type "string.", hit the
17 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
18 completion key (twice), and see the list of names defined by the
19 string module!
19 string module!
20
20
21 Tip: to use the tab key as the completion key, call
21 Tip: to use the tab key as the completion key, call
22
22
23 readline.parse_and_bind("tab: complete")
23 readline.parse_and_bind("tab: complete")
24
24
25 Notes:
25 Notes:
26
26
27 - Exceptions raised by the completer function are *ignored* (and
27 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
28 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
29 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
30 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
31 reset and restore the tty state.
32
32
33 - The evaluation of the NAME.NAME... form may cause arbitrary
33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
34 application defined code to be executed if an object with a
35 __getattr__ hook is found. Since it is the responsibility of the
35 __getattr__ hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
36 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
37 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
38 indexing operations) are *not* evaluated.
39
39
40 - GNU readline is also used by the built-in functions input() and
40 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
41 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
42 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
43 specifying its own completer function and using raw_input() for all
44 its input.
44 its input.
45
45
46 - When the original stdin is not a tty device, GNU readline is never
46 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
47 used, and this module (and the readline module) are silently inactive.
48
48
49 """
49 """
50
50
51 #*****************************************************************************
51 #*****************************************************************************
52 #
52 #
53 # Since this file is essentially a minimally modified copy of the rlcompleter
53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 # module which is part of the standard Python distribution, I assume that the
54 # module which is part of the standard Python distribution, I assume that the
55 # proper procedure is to maintain its copyright as belonging to the Python
55 # proper procedure is to maintain its copyright as belonging to the Python
56 # Software Foundation (in addition to my own, for all new code).
56 # Software Foundation (in addition to my own, for all new code).
57 #
57 #
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
60 #
60 #
61 # Distributed under the terms of the BSD License. The full license is in
61 # Distributed under the terms of the BSD License. The full license is in
62 # the file COPYING, distributed as part of this software.
62 # the file COPYING, distributed as part of this software.
63 #
63 #
64 #*****************************************************************************
64 #*****************************************************************************
65
65
66 import __builtin__
66 import __builtin__
67 import __main__
67 import __main__
68 import glob
68 import glob
69 import keyword
69 import keyword
70 import os
70 import os
71 import re
71 import re
72 import readline
72 import readline
73 import sys
73 import sys
74 import types
74 import types
75
75
76 # Python 2.4 offers sets as a builtin
76 # Python 2.4 offers sets as a builtin
77 try:
77 try:
78 set([1,2])
78 set([1,2])
79 except NameError:
79 except NameError:
80 from sets import Set as set
80 from sets import Set as set
81
81
82
82
83 from IPython.genutils import shlex_split,debugp
83 from IPython.genutils import shlex_split,debugx
84
84
85 __all__ = ['Completer','IPCompleter']
85 __all__ = ['Completer','IPCompleter']
86
86
87 def get_class_members(cls):
87 def get_class_members(cls):
88 ret = dir(cls)
88 ret = dir(cls)
89 if hasattr(cls,'__bases__'):
89 if hasattr(cls,'__bases__'):
90 for base in cls.__bases__:
90 for base in cls.__bases__:
91 ret.extend(get_class_members(base))
91 ret.extend(get_class_members(base))
92 return ret
92 return ret
93
93
94 class Completer:
94 class Completer:
95 def __init__(self,namespace=None,global_namespace=None):
95 def __init__(self,namespace=None,global_namespace=None):
96 """Create a new completer for the command line.
96 """Create a new completer for the command line.
97
97
98 Completer([namespace,global_namespace]) -> completer instance.
98 Completer([namespace,global_namespace]) -> completer instance.
99
99
100 If unspecified, the default namespace where completions are performed
100 If unspecified, the default namespace where completions are performed
101 is __main__ (technically, __main__.__dict__). Namespaces should be
101 is __main__ (technically, __main__.__dict__). Namespaces should be
102 given as dictionaries.
102 given as dictionaries.
103
103
104 An optional second namespace can be given. This allows the completer
104 An optional second namespace can be given. This allows the completer
105 to handle cases where both the local and global scopes need to be
105 to handle cases where both the local and global scopes need to be
106 distinguished.
106 distinguished.
107
107
108 Completer instances should be used as the completion mechanism of
108 Completer instances should be used as the completion mechanism of
109 readline via the set_completer() call:
109 readline via the set_completer() call:
110
110
111 readline.set_completer(Completer(my_namespace).complete)
111 readline.set_completer(Completer(my_namespace).complete)
112 """
112 """
113
113
114 # some minimal strict typechecks. For some core data structures, I
114 # some minimal strict typechecks. For some core data structures, I
115 # want actual basic python types, not just anything that looks like
115 # want actual basic python types, not just anything that looks like
116 # one. This is especially true for namespaces.
116 # one. This is especially true for namespaces.
117 for ns in (namespace,global_namespace):
117 for ns in (namespace,global_namespace):
118 if ns is not None and type(ns) != types.DictType:
118 if ns is not None and type(ns) != types.DictType:
119 raise TypeError,'namespace must be a dictionary'
119 raise TypeError,'namespace must be a dictionary'
120
120
121 # Don't bind to namespace quite yet, but flag whether the user wants a
121 # Don't bind to namespace quite yet, but flag whether the user wants a
122 # specific namespace or to use __main__.__dict__. This will allow us
122 # specific namespace or to use __main__.__dict__. This will allow us
123 # to bind to __main__.__dict__ at completion time, not now.
123 # to bind to __main__.__dict__ at completion time, not now.
124 if namespace is None:
124 if namespace is None:
125 self.use_main_ns = 1
125 self.use_main_ns = 1
126 else:
126 else:
127 self.use_main_ns = 0
127 self.use_main_ns = 0
128 self.namespace = namespace
128 self.namespace = namespace
129
129
130 # The global namespace, if given, can be bound directly
130 # The global namespace, if given, can be bound directly
131 if global_namespace is None:
131 if global_namespace is None:
132 self.global_namespace = {}
132 self.global_namespace = {}
133 else:
133 else:
134 self.global_namespace = global_namespace
134 self.global_namespace = global_namespace
135
135
136 def complete(self, text, state):
136 def complete(self, text, state):
137 """Return the next possible completion for 'text'.
137 """Return the next possible completion for 'text'.
138
138
139 This is called successively with state == 0, 1, 2, ... until it
139 This is called successively with state == 0, 1, 2, ... until it
140 returns None. The completion should begin with 'text'.
140 returns None. The completion should begin with 'text'.
141
141
142 """
142 """
143 if self.use_main_ns:
143 if self.use_main_ns:
144 self.namespace = __main__.__dict__
144 self.namespace = __main__.__dict__
145
145
146 if state == 0:
146 if state == 0:
147 if "." in text:
147 if "." in text:
148 self.matches = self.attr_matches(text)
148 self.matches = self.attr_matches(text)
149 else:
149 else:
150 self.matches = self.global_matches(text)
150 self.matches = self.global_matches(text)
151 try:
151 try:
152 return self.matches[state]
152 return self.matches[state]
153 except IndexError:
153 except IndexError:
154 return None
154 return None
155
155
156 def global_matches(self, text):
156 def global_matches(self, text):
157 """Compute matches when text is a simple name.
157 """Compute matches when text is a simple name.
158
158
159 Return a list of all keywords, built-in functions and names currently
159 Return a list of all keywords, built-in functions and names currently
160 defined in self.namespace or self.global_namespace that match.
160 defined in self.namespace or self.global_namespace that match.
161
161
162 """
162 """
163 matches = []
163 matches = []
164 match_append = matches.append
164 match_append = matches.append
165 n = len(text)
165 n = len(text)
166 for lst in [keyword.kwlist,
166 for lst in [keyword.kwlist,
167 __builtin__.__dict__.keys(),
167 __builtin__.__dict__.keys(),
168 self.namespace.keys(),
168 self.namespace.keys(),
169 self.global_namespace.keys()]:
169 self.global_namespace.keys()]:
170 for word in lst:
170 for word in lst:
171 if word[:n] == text and word != "__builtins__":
171 if word[:n] == text and word != "__builtins__":
172 match_append(word)
172 match_append(word)
173 return matches
173 return matches
174
174
175 def attr_matches(self, text):
175 def attr_matches(self, text):
176 """Compute matches when text contains a dot.
176 """Compute matches when text contains a dot.
177
177
178 Assuming the text is of the form NAME.NAME....[NAME], and is
178 Assuming the text is of the form NAME.NAME....[NAME], and is
179 evaluatable in self.namespace or self.global_namespace, it will be
179 evaluatable in self.namespace or self.global_namespace, it will be
180 evaluated and its attributes (as revealed by dir()) are used as
180 evaluated and its attributes (as revealed by dir()) are used as
181 possible completions. (For class instances, class members are are
181 possible completions. (For class instances, class members are are
182 also considered.)
182 also considered.)
183
183
184 WARNING: this can still invoke arbitrary C code, if an object
184 WARNING: this can still invoke arbitrary C code, if an object
185 with a __getattr__ hook is evaluated.
185 with a __getattr__ hook is evaluated.
186
186
187 """
187 """
188 import re
188 import re
189
189
190 # Another option, seems to work great. Catches things like ''.<tab>
190 # Another option, seems to work great. Catches things like ''.<tab>
191 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
191 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
192
192
193 if not m:
193 if not m:
194 return []
194 return []
195
195
196 expr, attr = m.group(1, 3)
196 expr, attr = m.group(1, 3)
197 try:
197 try:
198 object = eval(expr, self.namespace)
198 object = eval(expr, self.namespace)
199 except:
199 except:
200 object = eval(expr, self.global_namespace)
200 object = eval(expr, self.global_namespace)
201
201
202 # Start building the attribute list via dir(), and then complete it
202 # Start building the attribute list via dir(), and then complete it
203 # with a few extra special-purpose calls.
203 # with a few extra special-purpose calls.
204 words = dir(object)
204 words = dir(object)
205
205
206 if hasattr(object,'__class__'):
206 if hasattr(object,'__class__'):
207 words.append('__class__')
207 words.append('__class__')
208 words.extend(get_class_members(object.__class__))
208 words.extend(get_class_members(object.__class__))
209
209
210 # this is the 'dir' function for objects with Enthought's traits
210 # this is the 'dir' function for objects with Enthought's traits
211 if hasattr(object, 'trait_names'):
211 if hasattr(object, 'trait_names'):
212 try:
212 try:
213 words.extend(object.trait_names())
213 words.extend(object.trait_names())
214 # eliminate possible duplicates, as some traits may also
214 # eliminate possible duplicates, as some traits may also
215 # appear as normal attributes in the dir() call.
215 # appear as normal attributes in the dir() call.
216 words = set(words)
216 words = set(words)
217 except TypeError:
217 except TypeError:
218 # This will happen if `object` is a class and not an instance.
218 # This will happen if `object` is a class and not an instance.
219 pass
219 pass
220
220
221 # filter out non-string attributes which may be stuffed by dir() calls
221 # filter out non-string attributes which may be stuffed by dir() calls
222 # and poor coding in third-party modules
222 # and poor coding in third-party modules
223 words = [w for w in words
223 words = [w for w in words
224 if isinstance(w, basestring) and w != "__builtins__"]
224 if isinstance(w, basestring) and w != "__builtins__"]
225 # Build match list to return
225 # Build match list to return
226 n = len(attr)
226 n = len(attr)
227 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
227 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
228
228
229 class IPCompleter(Completer):
229 class IPCompleter(Completer):
230 """Extension of the completer class with IPython-specific features"""
230 """Extension of the completer class with IPython-specific features"""
231
231
232 def __init__(self,shell,namespace=None,global_namespace=None,
232 def __init__(self,shell,namespace=None,global_namespace=None,
233 omit__names=0,alias_table=None):
233 omit__names=0,alias_table=None):
234 """IPCompleter() -> completer
234 """IPCompleter() -> completer
235
235
236 Return a completer object suitable for use by the readline library
236 Return a completer object suitable for use by the readline library
237 via readline.set_completer().
237 via readline.set_completer().
238
238
239 Inputs:
239 Inputs:
240
240
241 - shell: a pointer to the ipython shell itself. This is needed
241 - shell: a pointer to the ipython shell itself. This is needed
242 because this completer knows about magic functions, and those can
242 because this completer knows about magic functions, and those can
243 only be accessed via the ipython instance.
243 only be accessed via the ipython instance.
244
244
245 - namespace: an optional dict where completions are performed.
245 - namespace: an optional dict where completions are performed.
246
246
247 - global_namespace: secondary optional dict for completions, to
247 - global_namespace: secondary optional dict for completions, to
248 handle cases (such as IPython embedded inside functions) where
248 handle cases (such as IPython embedded inside functions) where
249 both Python scopes are visible.
249 both Python scopes are visible.
250
250
251 - The optional omit__names parameter sets the completer to omit the
251 - The optional omit__names parameter sets the completer to omit the
252 'magic' names (__magicname__) for python objects unless the text
252 'magic' names (__magicname__) for python objects unless the text
253 to be completed explicitly starts with one or more underscores.
253 to be completed explicitly starts with one or more underscores.
254
254
255 - If alias_table is supplied, it should be a dictionary of aliases
255 - If alias_table is supplied, it should be a dictionary of aliases
256 to complete. """
256 to complete. """
257
257
258 Completer.__init__(self,namespace,global_namespace)
258 Completer.__init__(self,namespace,global_namespace)
259 self.magic_prefix = shell.name+'.magic_'
259 self.magic_prefix = shell.name+'.magic_'
260 self.magic_escape = shell.ESC_MAGIC
260 self.magic_escape = shell.ESC_MAGIC
261 self.readline = readline
261 self.readline = readline
262 delims = self.readline.get_completer_delims()
262 delims = self.readline.get_completer_delims()
263 delims = delims.replace(self.magic_escape,'')
263 delims = delims.replace(self.magic_escape,'')
264 self.readline.set_completer_delims(delims)
264 self.readline.set_completer_delims(delims)
265 self.get_line_buffer = self.readline.get_line_buffer
265 self.get_line_buffer = self.readline.get_line_buffer
266 self.omit__names = omit__names
266 self.omit__names = omit__names
267 self.merge_completions = shell.rc.readline_merge_completions
267 self.merge_completions = shell.rc.readline_merge_completions
268
268
269 if alias_table is None:
269 if alias_table is None:
270 alias_table = {}
270 alias_table = {}
271 self.alias_table = alias_table
271 self.alias_table = alias_table
272 # Regexp to split filenames with spaces in them
272 # Regexp to split filenames with spaces in them
273 self.space_name_re = re.compile(r'([^\\] )')
273 self.space_name_re = re.compile(r'([^\\] )')
274 # Hold a local ref. to glob.glob for speed
274 # Hold a local ref. to glob.glob for speed
275 self.glob = glob.glob
275 self.glob = glob.glob
276
276
277 # Determine if we are running on 'dumb' terminals, like (X)Emacs
277 # Determine if we are running on 'dumb' terminals, like (X)Emacs
278 # buffers, to avoid completion problems.
278 # buffers, to avoid completion problems.
279 term = os.environ.get('TERM','xterm')
279 term = os.environ.get('TERM','xterm')
280 self.dumb_terminal = term in ['dumb','emacs']
280 self.dumb_terminal = term in ['dumb','emacs']
281
281
282 # Special handling of backslashes needed in win32 platforms
282 # Special handling of backslashes needed in win32 platforms
283 if sys.platform == "win32":
283 if sys.platform == "win32":
284 self.clean_glob = self._clean_glob_win32
284 self.clean_glob = self._clean_glob_win32
285 else:
285 else:
286 self.clean_glob = self._clean_glob
286 self.clean_glob = self._clean_glob
287 self.matchers = [self.python_matches,
287 self.matchers = [self.python_matches,
288 self.file_matches,
288 self.file_matches,
289 self.alias_matches,
289 self.alias_matches,
290 self.python_func_kw_matches]
290 self.python_func_kw_matches]
291
291
292 # Code contributed by Alex Schmolck, for ipython/emacs integration
292 # Code contributed by Alex Schmolck, for ipython/emacs integration
293 def all_completions(self, text):
293 def all_completions(self, text):
294 """Return all possible completions for the benefit of emacs."""
294 """Return all possible completions for the benefit of emacs."""
295
295
296 completions = []
296 completions = []
297 comp_append = completions.append
297 comp_append = completions.append
298 try:
298 try:
299 for i in xrange(sys.maxint):
299 for i in xrange(sys.maxint):
300 res = self.complete(text, i)
300 res = self.complete(text, i)
301
301
302 if not res: break
302 if not res: break
303
303
304 comp_append(res)
304 comp_append(res)
305 #XXX workaround for ``notDefined.<tab>``
305 #XXX workaround for ``notDefined.<tab>``
306 except NameError:
306 except NameError:
307 pass
307 pass
308 return completions
308 return completions
309 # /end Alex Schmolck code.
309 # /end Alex Schmolck code.
310
310
311 def _clean_glob(self,text):
311 def _clean_glob(self,text):
312 return self.glob("%s*" % text)
312 return self.glob("%s*" % text)
313
313
314 def _clean_glob_win32(self,text):
314 def _clean_glob_win32(self,text):
315 return [f.replace("\\","/")
315 return [f.replace("\\","/")
316 for f in self.glob("%s*" % text)]
316 for f in self.glob("%s*" % text)]
317
317
318 def file_matches(self, text):
318 def file_matches(self, text):
319 """Match filneames, expanding ~USER type strings.
319 """Match filneames, expanding ~USER type strings.
320
320
321 Most of the seemingly convoluted logic in this completer is an
321 Most of the seemingly convoluted logic in this completer is an
322 attempt to handle filenames with spaces in them. And yet it's not
322 attempt to handle filenames with spaces in them. And yet it's not
323 quite perfect, because Python's readline doesn't expose all of the
323 quite perfect, because Python's readline doesn't expose all of the
324 GNU readline details needed for this to be done correctly.
324 GNU readline details needed for this to be done correctly.
325
325
326 For a filename with a space in it, the printed completions will be
326 For a filename with a space in it, the printed completions will be
327 only the parts after what's already been typed (instead of the
327 only the parts after what's already been typed (instead of the
328 full completions, as is normally done). I don't think with the
328 full completions, as is normally done). I don't think with the
329 current (as of Python 2.3) Python readline it's possible to do
329 current (as of Python 2.3) Python readline it's possible to do
330 better."""
330 better."""
331
331
332 #print 'Completer->file_matches: <%s>' % text # dbg
332 #print 'Completer->file_matches: <%s>' % text # dbg
333
333
334 # chars that require escaping with backslash - i.e. chars
334 # chars that require escaping with backslash - i.e. chars
335 # that readline treats incorrectly as delimiters, but we
335 # that readline treats incorrectly as delimiters, but we
336 # don't want to treat as delimiters in filename matching
336 # don't want to treat as delimiters in filename matching
337 # when escaped with backslash
337 # when escaped with backslash
338
338
339 protectables = ' ()[]{}'
339 protectables = ' ()[]{}'
340
340
341 def protect_filename(s):
341 def protect_filename(s):
342 return "".join([(ch in protectables and '\\' + ch or ch)
342 return "".join([(ch in protectables and '\\' + ch or ch)
343 for ch in s])
343 for ch in s])
344
344
345 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
345 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
346 open_quotes = 0 # track strings with open quotes
346 open_quotes = 0 # track strings with open quotes
347 try:
347 try:
348 lsplit = shlex_split(lbuf)[-1]
348 lsplit = shlex_split(lbuf)[-1]
349 except ValueError:
349 except ValueError:
350 # typically an unmatched ", or backslash without escaped char.
350 # typically an unmatched ", or backslash without escaped char.
351 if lbuf.count('"')==1:
351 if lbuf.count('"')==1:
352 open_quotes = 1
352 open_quotes = 1
353 lsplit = lbuf.split('"')[-1]
353 lsplit = lbuf.split('"')[-1]
354 elif lbuf.count("'")==1:
354 elif lbuf.count("'")==1:
355 open_quotes = 1
355 open_quotes = 1
356 lsplit = lbuf.split("'")[-1]
356 lsplit = lbuf.split("'")[-1]
357 else:
357 else:
358 return None
358 return None
359 except IndexError:
359 except IndexError:
360 # tab pressed on empty line
360 # tab pressed on empty line
361 lsplit = ""
361 lsplit = ""
362
362
363 if lsplit != protect_filename(lsplit):
363 if lsplit != protect_filename(lsplit):
364 # if protectables are found, do matching on the whole escaped
364 # if protectables are found, do matching on the whole escaped
365 # name
365 # name
366 has_protectables = 1
366 has_protectables = 1
367 text0,text = text,lsplit
367 text0,text = text,lsplit
368 else:
368 else:
369 has_protectables = 0
369 has_protectables = 0
370 text = os.path.expanduser(text)
370 text = os.path.expanduser(text)
371
371
372 if text == "":
372 if text == "":
373 return [protect_filename(f) for f in self.glob("*")]
373 return [protect_filename(f) for f in self.glob("*")]
374
374
375 m0 = self.clean_glob(text.replace('\\',''))
375 m0 = self.clean_glob(text.replace('\\',''))
376 if has_protectables:
376 if has_protectables:
377 # If we had protectables, we need to revert our changes to the
377 # If we had protectables, we need to revert our changes to the
378 # beginning of filename so that we don't double-write the part
378 # beginning of filename so that we don't double-write the part
379 # of the filename we have so far
379 # of the filename we have so far
380 len_lsplit = len(lsplit)
380 len_lsplit = len(lsplit)
381 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
381 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
382 else:
382 else:
383 if open_quotes:
383 if open_quotes:
384 # if we have a string with an open quote, we don't need to
384 # if we have a string with an open quote, we don't need to
385 # protect the names at all (and we _shouldn't_, as it
385 # protect the names at all (and we _shouldn't_, as it
386 # would cause bugs when the filesystem call is made).
386 # would cause bugs when the filesystem call is made).
387 matches = m0
387 matches = m0
388 else:
388 else:
389 matches = [protect_filename(f) for f in m0]
389 matches = [protect_filename(f) for f in m0]
390 if len(matches) == 1 and os.path.isdir(matches[0]):
390 if len(matches) == 1 and os.path.isdir(matches[0]):
391 # Takes care of links to directories also. Use '/'
391 # Takes care of links to directories also. Use '/'
392 # explicitly, even under Windows, so that name completions
392 # explicitly, even under Windows, so that name completions
393 # don't end up escaped.
393 # don't end up escaped.
394 matches[0] += '/'
394 matches[0] += '/'
395 return matches
395 return matches
396
396
397 def alias_matches(self, text):
397 def alias_matches(self, text):
398 """Match internal system aliases"""
398 """Match internal system aliases"""
399
399
400 #print 'Completer->alias_matches:',text # dbg
400 #print 'Completer->alias_matches:',text # dbg
401 text = os.path.expanduser(text)
401 text = os.path.expanduser(text)
402 aliases = self.alias_table.keys()
402 aliases = self.alias_table.keys()
403 if text == "":
403 if text == "":
404 return aliases
404 return aliases
405 else:
405 else:
406 return [alias for alias in aliases if alias.startswith(text)]
406 return [alias for alias in aliases if alias.startswith(text)]
407
407
408 def python_matches(self,text):
408 def python_matches(self,text):
409 """Match attributes or global python names"""
409 """Match attributes or global python names"""
410
410
411 #print 'Completer->python_matches, txt=<%s>' % text # dbg
411 #print 'Completer->python_matches, txt=<%s>' % text # dbg
412 if "." in text:
412 if "." in text:
413 try:
413 try:
414 matches = self.attr_matches(text)
414 matches = self.attr_matches(text)
415 if text.endswith('.') and self.omit__names:
415 if text.endswith('.') and self.omit__names:
416 if self.omit__names == 1:
416 if self.omit__names == 1:
417 # true if txt is _not_ a __ name, false otherwise:
417 # true if txt is _not_ a __ name, false otherwise:
418 no__name = (lambda txt:
418 no__name = (lambda txt:
419 re.match(r'.*\.__.*?__',txt) is None)
419 re.match(r'.*\.__.*?__',txt) is None)
420 else:
420 else:
421 # true if txt is _not_ a _ name, false otherwise:
421 # true if txt is _not_ a _ name, false otherwise:
422 no__name = (lambda txt:
422 no__name = (lambda txt:
423 re.match(r'.*\._.*?',txt) is None)
423 re.match(r'.*\._.*?',txt) is None)
424 matches = filter(no__name, matches)
424 matches = filter(no__name, matches)
425 except NameError:
425 except NameError:
426 # catches <undefined attributes>.<tab>
426 # catches <undefined attributes>.<tab>
427 matches = []
427 matches = []
428 else:
428 else:
429 matches = self.global_matches(text)
429 matches = self.global_matches(text)
430 # this is so completion finds magics when automagic is on:
430 # this is so completion finds magics when automagic is on:
431 if matches == [] and not text.startswith(os.sep):
431 if matches == [] and not text.startswith(os.sep):
432 matches = self.attr_matches(self.magic_prefix+text)
432 matches = self.attr_matches(self.magic_prefix+text)
433 return matches
433 return matches
434
434
435 def _default_arguments(self, obj):
435 def _default_arguments(self, obj):
436 """Return the list of default arguments of obj if it is callable,
436 """Return the list of default arguments of obj if it is callable,
437 or empty list otherwise."""
437 or empty list otherwise."""
438
438
439 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
439 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
440 # for classes, check for __init__,__new__
440 # for classes, check for __init__,__new__
441 if inspect.isclass(obj):
441 if inspect.isclass(obj):
442 obj = (getattr(obj,'__init__',None) or
442 obj = (getattr(obj,'__init__',None) or
443 getattr(obj,'__new__',None))
443 getattr(obj,'__new__',None))
444 # for all others, check if they are __call__able
444 # for all others, check if they are __call__able
445 elif hasattr(obj, '__call__'):
445 elif hasattr(obj, '__call__'):
446 obj = obj.__call__
446 obj = obj.__call__
447 # XXX: is there a way to handle the builtins ?
447 # XXX: is there a way to handle the builtins ?
448 try:
448 try:
449 args,_,_1,defaults = inspect.getargspec(obj)
449 args,_,_1,defaults = inspect.getargspec(obj)
450 if defaults:
450 if defaults:
451 return args[-len(defaults):]
451 return args[-len(defaults):]
452 except TypeError: pass
452 except TypeError: pass
453 return []
453 return []
454
454
455 def python_func_kw_matches(self,text):
455 def python_func_kw_matches(self,text):
456 """Match named parameters (kwargs) of the last open function"""
456 """Match named parameters (kwargs) of the last open function"""
457
457
458 if "." in text: # a parameter cannot be dotted
458 if "." in text: # a parameter cannot be dotted
459 return []
459 return []
460 try: regexp = self.__funcParamsRegex
460 try: regexp = self.__funcParamsRegex
461 except AttributeError:
461 except AttributeError:
462 regexp = self.__funcParamsRegex = re.compile(r'''
462 regexp = self.__funcParamsRegex = re.compile(r'''
463 '.*?' | # single quoted strings or
463 '.*?' | # single quoted strings or
464 ".*?" | # double quoted strings or
464 ".*?" | # double quoted strings or
465 \w+ | # identifier
465 \w+ | # identifier
466 \S # other characters
466 \S # other characters
467 ''', re.VERBOSE | re.DOTALL)
467 ''', re.VERBOSE | re.DOTALL)
468 # 1. find the nearest identifier that comes before an unclosed
468 # 1. find the nearest identifier that comes before an unclosed
469 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
469 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
470 tokens = regexp.findall(self.get_line_buffer())
470 tokens = regexp.findall(self.get_line_buffer())
471 tokens.reverse()
471 tokens.reverse()
472 iterTokens = iter(tokens); openPar = 0
472 iterTokens = iter(tokens); openPar = 0
473 for token in iterTokens:
473 for token in iterTokens:
474 if token == ')':
474 if token == ')':
475 openPar -= 1
475 openPar -= 1
476 elif token == '(':
476 elif token == '(':
477 openPar += 1
477 openPar += 1
478 if openPar > 0:
478 if openPar > 0:
479 # found the last unclosed parenthesis
479 # found the last unclosed parenthesis
480 break
480 break
481 else:
481 else:
482 return []
482 return []
483 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
483 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
484 ids = []
484 ids = []
485 isId = re.compile(r'\w+$').match
485 isId = re.compile(r'\w+$').match
486 while True:
486 while True:
487 try:
487 try:
488 ids.append(iterTokens.next())
488 ids.append(iterTokens.next())
489 if not isId(ids[-1]):
489 if not isId(ids[-1]):
490 ids.pop(); break
490 ids.pop(); break
491 if not iterTokens.next() == '.':
491 if not iterTokens.next() == '.':
492 break
492 break
493 except StopIteration:
493 except StopIteration:
494 break
494 break
495 # lookup the candidate callable matches either using global_matches
495 # lookup the candidate callable matches either using global_matches
496 # or attr_matches for dotted names
496 # or attr_matches for dotted names
497 if len(ids) == 1:
497 if len(ids) == 1:
498 callableMatches = self.global_matches(ids[0])
498 callableMatches = self.global_matches(ids[0])
499 else:
499 else:
500 callableMatches = self.attr_matches('.'.join(ids[::-1]))
500 callableMatches = self.attr_matches('.'.join(ids[::-1]))
501 argMatches = []
501 argMatches = []
502 for callableMatch in callableMatches:
502 for callableMatch in callableMatches:
503 try: namedArgs = self._default_arguments(eval(callableMatch,
503 try: namedArgs = self._default_arguments(eval(callableMatch,
504 self.namespace))
504 self.namespace))
505 except: continue
505 except: continue
506 for namedArg in namedArgs:
506 for namedArg in namedArgs:
507 if namedArg.startswith(text):
507 if namedArg.startswith(text):
508 argMatches.append("%s=" %namedArg)
508 argMatches.append("%s=" %namedArg)
509 return argMatches
509 return argMatches
510
510
511 def complete(self, text, state):
511 def complete(self, text, state):
512 """Return the next possible completion for 'text'.
512 """Return the next possible completion for 'text'.
513
513
514 This is called successively with state == 0, 1, 2, ... until it
514 This is called successively with state == 0, 1, 2, ... until it
515 returns None. The completion should begin with 'text'. """
515 returns None. The completion should begin with 'text'. """
516
516
517 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
517 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
518
518
519 # if there is only a tab on a line with only whitespace, instead
519 # if there is only a tab on a line with only whitespace, instead
520 # of the mostly useless 'do you want to see all million
520 # of the mostly useless 'do you want to see all million
521 # completions' message, just do the right thing and give the user
521 # completions' message, just do the right thing and give the user
522 # his tab! Incidentally, this enables pasting of tabbed text from
522 # his tab! Incidentally, this enables pasting of tabbed text from
523 # an editor (as long as autoindent is off).
523 # an editor (as long as autoindent is off).
524
524
525 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
525 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
526 # don't interfere with their own tab-completion mechanism.
526 # don't interfere with their own tab-completion mechanism.
527 if not (self.dumb_terminal or self.get_line_buffer().strip()):
527 if not (self.dumb_terminal or self.get_line_buffer().strip()):
528 self.readline.insert_text('\t')
528 self.readline.insert_text('\t')
529 return None
529 return None
530
530
531 magic_escape = self.magic_escape
531 magic_escape = self.magic_escape
532 magic_prefix = self.magic_prefix
532 magic_prefix = self.magic_prefix
533
533
534 try:
534 try:
535 if text.startswith(magic_escape):
535 if text.startswith(magic_escape):
536 text = text.replace(magic_escape,magic_prefix)
536 text = text.replace(magic_escape,magic_prefix)
537 elif text.startswith('~'):
537 elif text.startswith('~'):
538 text = os.path.expanduser(text)
538 text = os.path.expanduser(text)
539 if state == 0:
539 if state == 0:
540 # Extend the list of completions with the results of each
540 # Extend the list of completions with the results of each
541 # matcher, so we return results to the user from all
541 # matcher, so we return results to the user from all
542 # namespaces.
542 # namespaces.
543 if self.merge_completions:
543 if self.merge_completions:
544 self.matches = []
544 self.matches = []
545 for matcher in self.matchers:
545 for matcher in self.matchers:
546 self.matches.extend(matcher(text))
546 self.matches.extend(matcher(text))
547 else:
547 else:
548 for matcher in self.matchers:
548 for matcher in self.matchers:
549 self.matches = matcher(text)
549 self.matches = matcher(text)
550 if self.matches:
550 if self.matches:
551 break
551 break
552
552
553 try:
553 try:
554 return self.matches[state].replace(magic_prefix,magic_escape)
554 return self.matches[state].replace(magic_prefix,magic_escape)
555 except IndexError:
555 except IndexError:
556 return None
556 return None
557 except:
557 except:
558 #from IPython.ultraTB import AutoFormattedTB; # dbg
558 #from IPython.ultraTB import AutoFormattedTB; # dbg
559 #tb=AutoFormattedTB('Verbose');tb() #dbg
559 #tb=AutoFormattedTB('Verbose');tb() #dbg
560
560
561 # If completion fails, don't annoy the user.
561 # If completion fails, don't annoy the user.
562 return None
562 return None
@@ -1,1772 +1,1773 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 1058 2006-01-22 14:30:01Z vivainio $"""
8 $Id: genutils.py 1077 2006-01-24 18:15:27Z vivainio $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from __future__ import generators # 2.2 compatibility
17 from __future__ import generators # 2.2 compatibility
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 #****************************************************************************
23 #****************************************************************************
24 # required modules from the Python standard library
24 # required modules from the Python standard library
25 import __main__
25 import __main__
26 import commands
26 import commands
27 import os
27 import os
28 import re
28 import re
29 import shlex
29 import shlex
30 import shutil
30 import shutil
31 import sys
31 import sys
32 import tempfile
32 import tempfile
33 import time
33 import time
34 import types
34 import types
35
35
36 # Other IPython utilities
36 # Other IPython utilities
37 from IPython.Itpl import Itpl,itpl,printpl
37 from IPython.Itpl import Itpl,itpl,printpl
38 from IPython import DPyGetOpt
38 from IPython import DPyGetOpt
39 from IPython.path import path
39 from IPython.path import path
40 if os.name == "nt":
40 if os.name == "nt":
41 from IPython.winconsole import get_console_size
41 from IPython.winconsole import get_console_size
42
42
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 # 2.2-friendly
44 # 2.2-friendly
45 try:
45 try:
46 basestring
46 basestring
47 except NameError:
47 except NameError:
48 import types
48 import types
49 basestring = (types.StringType, types.UnicodeType)
49 basestring = (types.StringType, types.UnicodeType)
50 True = 1==1
50 True = 1==1
51 False = 1==0
51 False = 1==0
52
52
53 def enumerate(obj):
53 def enumerate(obj):
54 i = -1
54 i = -1
55 for item in obj:
55 for item in obj:
56 i += 1
56 i += 1
57 yield i, item
57 yield i, item
58
58
59 # add these to the builtin namespace, so that all modules find them
59 # add these to the builtin namespace, so that all modules find them
60 import __builtin__
60 import __builtin__
61 __builtin__.basestring = basestring
61 __builtin__.basestring = basestring
62 __builtin__.True = True
62 __builtin__.True = True
63 __builtin__.False = False
63 __builtin__.False = False
64 __builtin__.enumerate = enumerate
64 __builtin__.enumerate = enumerate
65
65
66 # Try to use shlex.split for converting an input string into a sys.argv-type
66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 try:
68 try:
69 shlex_split = shlex.split
69 shlex_split = shlex.split
70 except AttributeError:
70 except AttributeError:
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
76 % os.sep)
76 % os.sep)
77
77
78 def shlex_split(s):
78 def shlex_split(s):
79 """Simplified backport to Python 2.2 of shlex.split().
79 """Simplified backport to Python 2.2 of shlex.split().
80
80
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 several of the features needed to really match the functionality of
82 several of the features needed to really match the functionality of
83 shlex.split() in 2.3."""
83 shlex.split() in 2.3."""
84
84
85 lex = shlex.shlex(StringIO(s))
85 lex = shlex.shlex(StringIO(s))
86 # Try to get options, extensions and path separators as characters
86 # Try to get options, extensions and path separators as characters
87 lex.wordchars = _wordchars
87 lex.wordchars = _wordchars
88 lex.commenters = ''
88 lex.commenters = ''
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 # iterator.
90 # iterator.
91 lout = []
91 lout = []
92 while 1:
92 while 1:
93 token = lex.get_token()
93 token = lex.get_token()
94 if token == '':
94 if token == '':
95 break
95 break
96 # Try to handle quoted tokens correctly
96 # Try to handle quoted tokens correctly
97 quotes = _quotesre.match(token)
97 quotes = _quotesre.match(token)
98 if quotes:
98 if quotes:
99 token = quotes.group(1)
99 token = quotes.group(1)
100 lout.append(token)
100 lout.append(token)
101 return lout
101 return lout
102
102
103 #****************************************************************************
103 #****************************************************************************
104 # Exceptions
104 # Exceptions
105 class Error(Exception):
105 class Error(Exception):
106 """Base class for exceptions in this module."""
106 """Base class for exceptions in this module."""
107 pass
107 pass
108
108
109 #----------------------------------------------------------------------------
109 #----------------------------------------------------------------------------
110 class IOStream:
110 class IOStream:
111 def __init__(self,stream,fallback):
111 def __init__(self,stream,fallback):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 stream = fallback
113 stream = fallback
114 self.stream = stream
114 self.stream = stream
115 self._swrite = stream.write
115 self._swrite = stream.write
116 self.flush = stream.flush
116 self.flush = stream.flush
117
117
118 def write(self,data):
118 def write(self,data):
119 try:
119 try:
120 self._swrite(data)
120 self._swrite(data)
121 except:
121 except:
122 try:
122 try:
123 # print handles some unicode issues which may trip a plain
123 # print handles some unicode issues which may trip a plain
124 # write() call. Attempt to emulate write() by using a
124 # write() call. Attempt to emulate write() by using a
125 # trailing comma
125 # trailing comma
126 print >> self.stream, data,
126 print >> self.stream, data,
127 except:
127 except:
128 # if we get here, something is seriously broken.
128 # if we get here, something is seriously broken.
129 print >> sys.stderr, \
129 print >> sys.stderr, \
130 'ERROR - failed to write data to stream:', stream
130 'ERROR - failed to write data to stream:', stream
131
131
132 class IOTerm:
132 class IOTerm:
133 """ Term holds the file or file-like objects for handling I/O operations.
133 """ Term holds the file or file-like objects for handling I/O operations.
134
134
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 Windows they can can replaced to allow editing the strings before they are
136 Windows they can can replaced to allow editing the strings before they are
137 displayed."""
137 displayed."""
138
138
139 # In the future, having IPython channel all its I/O operations through
139 # In the future, having IPython channel all its I/O operations through
140 # this class will make it easier to embed it into other environments which
140 # this class will make it easier to embed it into other environments which
141 # are not a normal terminal (such as a GUI-based shell)
141 # are not a normal terminal (such as a GUI-based shell)
142 def __init__(self,cin=None,cout=None,cerr=None):
142 def __init__(self,cin=None,cout=None,cerr=None):
143 self.cin = IOStream(cin,sys.stdin)
143 self.cin = IOStream(cin,sys.stdin)
144 self.cout = IOStream(cout,sys.stdout)
144 self.cout = IOStream(cout,sys.stdout)
145 self.cerr = IOStream(cerr,sys.stderr)
145 self.cerr = IOStream(cerr,sys.stderr)
146
146
147 # Global variable to be used for all I/O
147 # Global variable to be used for all I/O
148 Term = IOTerm()
148 Term = IOTerm()
149
149
150 # Windows-specific code to load Gary Bishop's readline and configure it
150 # Windows-specific code to load Gary Bishop's readline and configure it
151 # automatically for the users
151 # automatically for the users
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
153 # windows. Cygwin returns 'cygwin' for sys.platform.
153 # windows. Cygwin returns 'cygwin' for sys.platform.
154 if os.name == 'nt':
154 if os.name == 'nt':
155 try:
155 try:
156 import readline
156 import readline
157 except ImportError:
157 except ImportError:
158 pass
158 pass
159 else:
159 else:
160 try:
160 try:
161 _out = readline.GetOutputFile()
161 _out = readline.GetOutputFile()
162 except AttributeError:
162 except AttributeError:
163 pass
163 pass
164 else:
164 else:
165 # Remake Term to use the readline i/o facilities
165 # Remake Term to use the readline i/o facilities
166 Term = IOTerm(cout=_out,cerr=_out)
166 Term = IOTerm(cout=_out,cerr=_out)
167 del _out
167 del _out
168
168
169 #****************************************************************************
169 #****************************************************************************
170 # Generic warning/error printer, used by everything else
170 # Generic warning/error printer, used by everything else
171 def warn(msg,level=2,exit_val=1):
171 def warn(msg,level=2,exit_val=1):
172 """Standard warning printer. Gives formatting consistency.
172 """Standard warning printer. Gives formatting consistency.
173
173
174 Output is sent to Term.cerr (sys.stderr by default).
174 Output is sent to Term.cerr (sys.stderr by default).
175
175
176 Options:
176 Options:
177
177
178 -level(2): allows finer control:
178 -level(2): allows finer control:
179 0 -> Do nothing, dummy function.
179 0 -> Do nothing, dummy function.
180 1 -> Print message.
180 1 -> Print message.
181 2 -> Print 'WARNING:' + message. (Default level).
181 2 -> Print 'WARNING:' + message. (Default level).
182 3 -> Print 'ERROR:' + message.
182 3 -> Print 'ERROR:' + message.
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184
184
185 -exit_val (1): exit value returned by sys.exit() for a level 4
185 -exit_val (1): exit value returned by sys.exit() for a level 4
186 warning. Ignored for all other levels."""
186 warning. Ignored for all other levels."""
187
187
188 if level>0:
188 if level>0:
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 print >> Term.cerr, '%s%s' % (header[level],msg)
190 print >> Term.cerr, '%s%s' % (header[level],msg)
191 if level == 4:
191 if level == 4:
192 print >> Term.cerr,'Exiting.\n'
192 print >> Term.cerr,'Exiting.\n'
193 sys.exit(exit_val)
193 sys.exit(exit_val)
194
194
195 def info(msg):
195 def info(msg):
196 """Equivalent to warn(msg,level=1)."""
196 """Equivalent to warn(msg,level=1)."""
197
197
198 warn(msg,level=1)
198 warn(msg,level=1)
199
199
200 def error(msg):
200 def error(msg):
201 """Equivalent to warn(msg,level=3)."""
201 """Equivalent to warn(msg,level=3)."""
202
202
203 warn(msg,level=3)
203 warn(msg,level=3)
204
204
205 def fatal(msg,exit_val=1):
205 def fatal(msg,exit_val=1):
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207
207
208 warn(msg,exit_val=exit_val,level=4)
208 warn(msg,exit_val=exit_val,level=4)
209
209
210
210 #---------------------------------------------------------------------------
211 # useful for debugging
211 # Debugging routines
212 def debugp(expr,pre_msg=''):
212 #
213 def debugx(expr,pre_msg=''):
213 """Print the value of an expression from the caller's frame.
214 """Print the value of an expression from the caller's frame.
214
215
215 Takes an expression, evaluates it in the caller's frame and prints both
216 Takes an expression, evaluates it in the caller's frame and prints both
216 the given expression and the resulting value (as well as a debug mark
217 the given expression and the resulting value (as well as a debug mark
217 indicating the name of the calling function. The input must be of a form
218 indicating the name of the calling function. The input must be of a form
218 suitable for eval().
219 suitable for eval().
219
220
220 An optional message can be passed, which will be prepended to the printed
221 An optional message can be passed, which will be prepended to the printed
221 expr->value pair."""
222 expr->value pair."""
222
223
223 cf = sys._getframe(1)
224 cf = sys._getframe(1)
224 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
225 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
225 eval(expr,cf.f_globals,cf.f_locals))
226 eval(expr,cf.f_globals,cf.f_locals))
226
227
227 # deactivate it by uncommenting the following line, which makes it a no-op
228 # deactivate it by uncommenting the following line, which makes it a no-op
228 def debugp(expr,pre_msg=''): pass
229 #def debugx(expr,pre_msg=''): pass
229
230
230 #----------------------------------------------------------------------------
231 #----------------------------------------------------------------------------
231 StringTypes = types.StringTypes
232 StringTypes = types.StringTypes
232
233
233 # Basic timing functionality
234 # Basic timing functionality
234
235
235 # If possible (Unix), use the resource module instead of time.clock()
236 # If possible (Unix), use the resource module instead of time.clock()
236 try:
237 try:
237 import resource
238 import resource
238 def clock():
239 def clock():
239 """clock() -> floating point number
240 """clock() -> floating point number
240
241
241 Return the CPU time in seconds (user time only, system time is
242 Return the CPU time in seconds (user time only, system time is
242 ignored) since the start of the process. This is done via a call to
243 ignored) since the start of the process. This is done via a call to
243 resource.getrusage, so it avoids the wraparound problems in
244 resource.getrusage, so it avoids the wraparound problems in
244 time.clock()."""
245 time.clock()."""
245
246
246 return resource.getrusage(resource.RUSAGE_SELF)[0]
247 return resource.getrusage(resource.RUSAGE_SELF)[0]
247
248
248 def clock2():
249 def clock2():
249 """clock2() -> (t_user,t_system)
250 """clock2() -> (t_user,t_system)
250
251
251 Similar to clock(), but return a tuple of user/system times."""
252 Similar to clock(), but return a tuple of user/system times."""
252 return resource.getrusage(resource.RUSAGE_SELF)[:2]
253 return resource.getrusage(resource.RUSAGE_SELF)[:2]
253
254
254 except ImportError:
255 except ImportError:
255 clock = time.clock
256 clock = time.clock
256 def clock2():
257 def clock2():
257 """Under windows, system CPU time can't be measured.
258 """Under windows, system CPU time can't be measured.
258
259
259 This just returns clock() and zero."""
260 This just returns clock() and zero."""
260 return time.clock(),0.0
261 return time.clock(),0.0
261
262
262 def timings_out(reps,func,*args,**kw):
263 def timings_out(reps,func,*args,**kw):
263 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
264 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
264
265
265 Execute a function reps times, return a tuple with the elapsed total
266 Execute a function reps times, return a tuple with the elapsed total
266 CPU time in seconds, the time per call and the function's output.
267 CPU time in seconds, the time per call and the function's output.
267
268
268 Under Unix, the return value is the sum of user+system time consumed by
269 Under Unix, the return value is the sum of user+system time consumed by
269 the process, computed via the resource module. This prevents problems
270 the process, computed via the resource module. This prevents problems
270 related to the wraparound effect which the time.clock() function has.
271 related to the wraparound effect which the time.clock() function has.
271
272
272 Under Windows the return value is in wall clock seconds. See the
273 Under Windows the return value is in wall clock seconds. See the
273 documentation for the time module for more details."""
274 documentation for the time module for more details."""
274
275
275 reps = int(reps)
276 reps = int(reps)
276 assert reps >=1, 'reps must be >= 1'
277 assert reps >=1, 'reps must be >= 1'
277 if reps==1:
278 if reps==1:
278 start = clock()
279 start = clock()
279 out = func(*args,**kw)
280 out = func(*args,**kw)
280 tot_time = clock()-start
281 tot_time = clock()-start
281 else:
282 else:
282 rng = xrange(reps-1) # the last time is executed separately to store output
283 rng = xrange(reps-1) # the last time is executed separately to store output
283 start = clock()
284 start = clock()
284 for dummy in rng: func(*args,**kw)
285 for dummy in rng: func(*args,**kw)
285 out = func(*args,**kw) # one last time
286 out = func(*args,**kw) # one last time
286 tot_time = clock()-start
287 tot_time = clock()-start
287 av_time = tot_time / reps
288 av_time = tot_time / reps
288 return tot_time,av_time,out
289 return tot_time,av_time,out
289
290
290 def timings(reps,func,*args,**kw):
291 def timings(reps,func,*args,**kw):
291 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
292 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
292
293
293 Execute a function reps times, return a tuple with the elapsed total CPU
294 Execute a function reps times, return a tuple with the elapsed total CPU
294 time in seconds and the time per call. These are just the first two values
295 time in seconds and the time per call. These are just the first two values
295 in timings_out()."""
296 in timings_out()."""
296
297
297 return timings_out(reps,func,*args,**kw)[0:2]
298 return timings_out(reps,func,*args,**kw)[0:2]
298
299
299 def timing(func,*args,**kw):
300 def timing(func,*args,**kw):
300 """timing(func,*args,**kw) -> t_total
301 """timing(func,*args,**kw) -> t_total
301
302
302 Execute a function once, return the elapsed total CPU time in
303 Execute a function once, return the elapsed total CPU time in
303 seconds. This is just the first value in timings_out()."""
304 seconds. This is just the first value in timings_out()."""
304
305
305 return timings_out(1,func,*args,**kw)[0]
306 return timings_out(1,func,*args,**kw)[0]
306
307
307 #****************************************************************************
308 #****************************************************************************
308 # file and system
309 # file and system
309
310
310 def system(cmd,verbose=0,debug=0,header=''):
311 def system(cmd,verbose=0,debug=0,header=''):
311 """Execute a system command, return its exit status.
312 """Execute a system command, return its exit status.
312
313
313 Options:
314 Options:
314
315
315 - verbose (0): print the command to be executed.
316 - verbose (0): print the command to be executed.
316
317
317 - debug (0): only print, do not actually execute.
318 - debug (0): only print, do not actually execute.
318
319
319 - header (''): Header to print on screen prior to the executed command (it
320 - header (''): Header to print on screen prior to the executed command (it
320 is only prepended to the command, no newlines are added).
321 is only prepended to the command, no newlines are added).
321
322
322 Note: a stateful version of this function is available through the
323 Note: a stateful version of this function is available through the
323 SystemExec class."""
324 SystemExec class."""
324
325
325 stat = 0
326 stat = 0
326 if verbose or debug: print header+cmd
327 if verbose or debug: print header+cmd
327 sys.stdout.flush()
328 sys.stdout.flush()
328 if not debug: stat = os.system(cmd)
329 if not debug: stat = os.system(cmd)
329 return stat
330 return stat
330
331
331 # This function is used by ipython in a lot of places to make system calls.
332 # This function is used by ipython in a lot of places to make system calls.
332 # We need it to be slightly different under win32, due to the vagaries of
333 # We need it to be slightly different under win32, due to the vagaries of
333 # 'network shares'. A win32 override is below.
334 # 'network shares'. A win32 override is below.
334
335
335 def shell(cmd,verbose=0,debug=0,header=''):
336 def shell(cmd,verbose=0,debug=0,header=''):
336 """Execute a command in the system shell, always return None.
337 """Execute a command in the system shell, always return None.
337
338
338 Options:
339 Options:
339
340
340 - verbose (0): print the command to be executed.
341 - verbose (0): print the command to be executed.
341
342
342 - debug (0): only print, do not actually execute.
343 - debug (0): only print, do not actually execute.
343
344
344 - header (''): Header to print on screen prior to the executed command (it
345 - header (''): Header to print on screen prior to the executed command (it
345 is only prepended to the command, no newlines are added).
346 is only prepended to the command, no newlines are added).
346
347
347 Note: this is similar to genutils.system(), but it returns None so it can
348 Note: this is similar to genutils.system(), but it returns None so it can
348 be conveniently used in interactive loops without getting the return value
349 be conveniently used in interactive loops without getting the return value
349 (typically 0) printed many times."""
350 (typically 0) printed many times."""
350
351
351 stat = 0
352 stat = 0
352 if verbose or debug: print header+cmd
353 if verbose or debug: print header+cmd
353 # flush stdout so we don't mangle python's buffering
354 # flush stdout so we don't mangle python's buffering
354 sys.stdout.flush()
355 sys.stdout.flush()
355 if not debug:
356 if not debug:
356 os.system(cmd)
357 os.system(cmd)
357
358
358 # override shell() for win32 to deal with network shares
359 # override shell() for win32 to deal with network shares
359 if os.name in ('nt','dos'):
360 if os.name in ('nt','dos'):
360
361
361 shell_ori = shell
362 shell_ori = shell
362
363
363 def shell(cmd,verbose=0,debug=0,header=''):
364 def shell(cmd,verbose=0,debug=0,header=''):
364 if os.getcwd().startswith(r"\\"):
365 if os.getcwd().startswith(r"\\"):
365 path = os.getcwd()
366 path = os.getcwd()
366 # change to c drive (cannot be on UNC-share when issuing os.system,
367 # change to c drive (cannot be on UNC-share when issuing os.system,
367 # as cmd.exe cannot handle UNC addresses)
368 # as cmd.exe cannot handle UNC addresses)
368 os.chdir("c:")
369 os.chdir("c:")
369 # issue pushd to the UNC-share and then run the command
370 # issue pushd to the UNC-share and then run the command
370 try:
371 try:
371 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
372 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
372 finally:
373 finally:
373 os.chdir(path)
374 os.chdir(path)
374 else:
375 else:
375 shell_ori(cmd,verbose,debug,header)
376 shell_ori(cmd,verbose,debug,header)
376
377
377 shell.__doc__ = shell_ori.__doc__
378 shell.__doc__ = shell_ori.__doc__
378
379
379 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
380 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
380 """Dummy substitute for perl's backquotes.
381 """Dummy substitute for perl's backquotes.
381
382
382 Executes a command and returns the output.
383 Executes a command and returns the output.
383
384
384 Accepts the same arguments as system(), plus:
385 Accepts the same arguments as system(), plus:
385
386
386 - split(0): if true, the output is returned as a list split on newlines.
387 - split(0): if true, the output is returned as a list split on newlines.
387
388
388 Note: a stateful version of this function is available through the
389 Note: a stateful version of this function is available through the
389 SystemExec class."""
390 SystemExec class."""
390
391
391 if verbose or debug: print header+cmd
392 if verbose or debug: print header+cmd
392 if not debug:
393 if not debug:
393 output = commands.getoutput(cmd)
394 output = commands.getoutput(cmd)
394 if split:
395 if split:
395 return output.split('\n')
396 return output.split('\n')
396 else:
397 else:
397 return output
398 return output
398
399
399 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
400 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
400 """Return (standard output,standard error) of executing cmd in a shell.
401 """Return (standard output,standard error) of executing cmd in a shell.
401
402
402 Accepts the same arguments as system(), plus:
403 Accepts the same arguments as system(), plus:
403
404
404 - split(0): if true, each of stdout/err is returned as a list split on
405 - split(0): if true, each of stdout/err is returned as a list split on
405 newlines.
406 newlines.
406
407
407 Note: a stateful version of this function is available through the
408 Note: a stateful version of this function is available through the
408 SystemExec class."""
409 SystemExec class."""
409
410
410 if verbose or debug: print header+cmd
411 if verbose or debug: print header+cmd
411 if not cmd:
412 if not cmd:
412 if split:
413 if split:
413 return [],[]
414 return [],[]
414 else:
415 else:
415 return '',''
416 return '',''
416 if not debug:
417 if not debug:
417 pin,pout,perr = os.popen3(cmd)
418 pin,pout,perr = os.popen3(cmd)
418 tout = pout.read().rstrip()
419 tout = pout.read().rstrip()
419 terr = perr.read().rstrip()
420 terr = perr.read().rstrip()
420 pin.close()
421 pin.close()
421 pout.close()
422 pout.close()
422 perr.close()
423 perr.close()
423 if split:
424 if split:
424 return tout.split('\n'),terr.split('\n')
425 return tout.split('\n'),terr.split('\n')
425 else:
426 else:
426 return tout,terr
427 return tout,terr
427
428
428 # for compatibility with older naming conventions
429 # for compatibility with older naming conventions
429 xsys = system
430 xsys = system
430 bq = getoutput
431 bq = getoutput
431
432
432 class SystemExec:
433 class SystemExec:
433 """Access the system and getoutput functions through a stateful interface.
434 """Access the system and getoutput functions through a stateful interface.
434
435
435 Note: here we refer to the system and getoutput functions from this
436 Note: here we refer to the system and getoutput functions from this
436 library, not the ones from the standard python library.
437 library, not the ones from the standard python library.
437
438
438 This class offers the system and getoutput functions as methods, but the
439 This class offers the system and getoutput functions as methods, but the
439 verbose, debug and header parameters can be set for the instance (at
440 verbose, debug and header parameters can be set for the instance (at
440 creation time or later) so that they don't need to be specified on each
441 creation time or later) so that they don't need to be specified on each
441 call.
442 call.
442
443
443 For efficiency reasons, there's no way to override the parameters on a
444 For efficiency reasons, there's no way to override the parameters on a
444 per-call basis other than by setting instance attributes. If you need
445 per-call basis other than by setting instance attributes. If you need
445 local overrides, it's best to directly call system() or getoutput().
446 local overrides, it's best to directly call system() or getoutput().
446
447
447 The following names are provided as alternate options:
448 The following names are provided as alternate options:
448 - xsys: alias to system
449 - xsys: alias to system
449 - bq: alias to getoutput
450 - bq: alias to getoutput
450
451
451 An instance can then be created as:
452 An instance can then be created as:
452 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
453 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
453
454
454 And used as:
455 And used as:
455 >>> sysexec.xsys('pwd')
456 >>> sysexec.xsys('pwd')
456 >>> dirlist = sysexec.bq('ls -l')
457 >>> dirlist = sysexec.bq('ls -l')
457 """
458 """
458
459
459 def __init__(self,verbose=0,debug=0,header='',split=0):
460 def __init__(self,verbose=0,debug=0,header='',split=0):
460 """Specify the instance's values for verbose, debug and header."""
461 """Specify the instance's values for verbose, debug and header."""
461 setattr_list(self,'verbose debug header split')
462 setattr_list(self,'verbose debug header split')
462
463
463 def system(self,cmd):
464 def system(self,cmd):
464 """Stateful interface to system(), with the same keyword parameters."""
465 """Stateful interface to system(), with the same keyword parameters."""
465
466
466 system(cmd,self.verbose,self.debug,self.header)
467 system(cmd,self.verbose,self.debug,self.header)
467
468
468 def shell(self,cmd):
469 def shell(self,cmd):
469 """Stateful interface to shell(), with the same keyword parameters."""
470 """Stateful interface to shell(), with the same keyword parameters."""
470
471
471 shell(cmd,self.verbose,self.debug,self.header)
472 shell(cmd,self.verbose,self.debug,self.header)
472
473
473 xsys = system # alias
474 xsys = system # alias
474
475
475 def getoutput(self,cmd):
476 def getoutput(self,cmd):
476 """Stateful interface to getoutput()."""
477 """Stateful interface to getoutput()."""
477
478
478 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
479 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
479
480
480 def getoutputerror(self,cmd):
481 def getoutputerror(self,cmd):
481 """Stateful interface to getoutputerror()."""
482 """Stateful interface to getoutputerror()."""
482
483
483 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
484 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
484
485
485 bq = getoutput # alias
486 bq = getoutput # alias
486
487
487 #-----------------------------------------------------------------------------
488 #-----------------------------------------------------------------------------
488 def mutex_opts(dict,ex_op):
489 def mutex_opts(dict,ex_op):
489 """Check for presence of mutually exclusive keys in a dict.
490 """Check for presence of mutually exclusive keys in a dict.
490
491
491 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
492 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
492 for op1,op2 in ex_op:
493 for op1,op2 in ex_op:
493 if op1 in dict and op2 in dict:
494 if op1 in dict and op2 in dict:
494 raise ValueError,'\n*** ERROR in Arguments *** '\
495 raise ValueError,'\n*** ERROR in Arguments *** '\
495 'Options '+op1+' and '+op2+' are mutually exclusive.'
496 'Options '+op1+' and '+op2+' are mutually exclusive.'
496
497
497 #-----------------------------------------------------------------------------
498 #-----------------------------------------------------------------------------
498 def get_py_filename(name):
499 def get_py_filename(name):
499 """Return a valid python filename in the current directory.
500 """Return a valid python filename in the current directory.
500
501
501 If the given name is not a file, it adds '.py' and searches again.
502 If the given name is not a file, it adds '.py' and searches again.
502 Raises IOError with an informative message if the file isn't found."""
503 Raises IOError with an informative message if the file isn't found."""
503
504
504 name = os.path.expanduser(name)
505 name = os.path.expanduser(name)
505 if not os.path.isfile(name) and not name.endswith('.py'):
506 if not os.path.isfile(name) and not name.endswith('.py'):
506 name += '.py'
507 name += '.py'
507 if os.path.isfile(name):
508 if os.path.isfile(name):
508 return name
509 return name
509 else:
510 else:
510 raise IOError,'File `%s` not found.' % name
511 raise IOError,'File `%s` not found.' % name
511
512
512 #-----------------------------------------------------------------------------
513 #-----------------------------------------------------------------------------
513 def filefind(fname,alt_dirs = None):
514 def filefind(fname,alt_dirs = None):
514 """Return the given filename either in the current directory, if it
515 """Return the given filename either in the current directory, if it
515 exists, or in a specified list of directories.
516 exists, or in a specified list of directories.
516
517
517 ~ expansion is done on all file and directory names.
518 ~ expansion is done on all file and directory names.
518
519
519 Upon an unsuccessful search, raise an IOError exception."""
520 Upon an unsuccessful search, raise an IOError exception."""
520
521
521 if alt_dirs is None:
522 if alt_dirs is None:
522 try:
523 try:
523 alt_dirs = get_home_dir()
524 alt_dirs = get_home_dir()
524 except HomeDirError:
525 except HomeDirError:
525 alt_dirs = os.getcwd()
526 alt_dirs = os.getcwd()
526 search = [fname] + list_strings(alt_dirs)
527 search = [fname] + list_strings(alt_dirs)
527 search = map(os.path.expanduser,search)
528 search = map(os.path.expanduser,search)
528 #print 'search list for',fname,'list:',search # dbg
529 #print 'search list for',fname,'list:',search # dbg
529 fname = search[0]
530 fname = search[0]
530 if os.path.isfile(fname):
531 if os.path.isfile(fname):
531 return fname
532 return fname
532 for direc in search[1:]:
533 for direc in search[1:]:
533 testname = os.path.join(direc,fname)
534 testname = os.path.join(direc,fname)
534 #print 'testname',testname # dbg
535 #print 'testname',testname # dbg
535 if os.path.isfile(testname):
536 if os.path.isfile(testname):
536 return testname
537 return testname
537 raise IOError,'File' + `fname` + \
538 raise IOError,'File' + `fname` + \
538 ' not found in current or supplied directories:' + `alt_dirs`
539 ' not found in current or supplied directories:' + `alt_dirs`
539
540
540 #----------------------------------------------------------------------------
541 #----------------------------------------------------------------------------
541 def file_read(filename):
542 def file_read(filename):
542 """Read a file and close it. Returns the file source."""
543 """Read a file and close it. Returns the file source."""
543 fobj=open(filename,'r');
544 fobj=open(filename,'r');
544 source = fobj.read();
545 source = fobj.read();
545 fobj.close()
546 fobj.close()
546 return source
547 return source
547
548
548 #----------------------------------------------------------------------------
549 #----------------------------------------------------------------------------
549 def target_outdated(target,deps):
550 def target_outdated(target,deps):
550 """Determine whether a target is out of date.
551 """Determine whether a target is out of date.
551
552
552 target_outdated(target,deps) -> 1/0
553 target_outdated(target,deps) -> 1/0
553
554
554 deps: list of filenames which MUST exist.
555 deps: list of filenames which MUST exist.
555 target: single filename which may or may not exist.
556 target: single filename which may or may not exist.
556
557
557 If target doesn't exist or is older than any file listed in deps, return
558 If target doesn't exist or is older than any file listed in deps, return
558 true, otherwise return false.
559 true, otherwise return false.
559 """
560 """
560 try:
561 try:
561 target_time = os.path.getmtime(target)
562 target_time = os.path.getmtime(target)
562 except os.error:
563 except os.error:
563 return 1
564 return 1
564 for dep in deps:
565 for dep in deps:
565 dep_time = os.path.getmtime(dep)
566 dep_time = os.path.getmtime(dep)
566 if dep_time > target_time:
567 if dep_time > target_time:
567 #print "For target",target,"Dep failed:",dep # dbg
568 #print "For target",target,"Dep failed:",dep # dbg
568 #print "times (dep,tar):",dep_time,target_time # dbg
569 #print "times (dep,tar):",dep_time,target_time # dbg
569 return 1
570 return 1
570 return 0
571 return 0
571
572
572 #-----------------------------------------------------------------------------
573 #-----------------------------------------------------------------------------
573 def target_update(target,deps,cmd):
574 def target_update(target,deps,cmd):
574 """Update a target with a given command given a list of dependencies.
575 """Update a target with a given command given a list of dependencies.
575
576
576 target_update(target,deps,cmd) -> runs cmd if target is outdated.
577 target_update(target,deps,cmd) -> runs cmd if target is outdated.
577
578
578 This is just a wrapper around target_outdated() which calls the given
579 This is just a wrapper around target_outdated() which calls the given
579 command if target is outdated."""
580 command if target is outdated."""
580
581
581 if target_outdated(target,deps):
582 if target_outdated(target,deps):
582 xsys(cmd)
583 xsys(cmd)
583
584
584 #----------------------------------------------------------------------------
585 #----------------------------------------------------------------------------
585 def unquote_ends(istr):
586 def unquote_ends(istr):
586 """Remove a single pair of quotes from the endpoints of a string."""
587 """Remove a single pair of quotes from the endpoints of a string."""
587
588
588 if not istr:
589 if not istr:
589 return istr
590 return istr
590 if (istr[0]=="'" and istr[-1]=="'") or \
591 if (istr[0]=="'" and istr[-1]=="'") or \
591 (istr[0]=='"' and istr[-1]=='"'):
592 (istr[0]=='"' and istr[-1]=='"'):
592 return istr[1:-1]
593 return istr[1:-1]
593 else:
594 else:
594 return istr
595 return istr
595
596
596 #----------------------------------------------------------------------------
597 #----------------------------------------------------------------------------
597 def process_cmdline(argv,names=[],defaults={},usage=''):
598 def process_cmdline(argv,names=[],defaults={},usage=''):
598 """ Process command-line options and arguments.
599 """ Process command-line options and arguments.
599
600
600 Arguments:
601 Arguments:
601
602
602 - argv: list of arguments, typically sys.argv.
603 - argv: list of arguments, typically sys.argv.
603
604
604 - names: list of option names. See DPyGetOpt docs for details on options
605 - names: list of option names. See DPyGetOpt docs for details on options
605 syntax.
606 syntax.
606
607
607 - defaults: dict of default values.
608 - defaults: dict of default values.
608
609
609 - usage: optional usage notice to print if a wrong argument is passed.
610 - usage: optional usage notice to print if a wrong argument is passed.
610
611
611 Return a dict of options and a list of free arguments."""
612 Return a dict of options and a list of free arguments."""
612
613
613 getopt = DPyGetOpt.DPyGetOpt()
614 getopt = DPyGetOpt.DPyGetOpt()
614 getopt.setIgnoreCase(0)
615 getopt.setIgnoreCase(0)
615 getopt.parseConfiguration(names)
616 getopt.parseConfiguration(names)
616
617
617 try:
618 try:
618 getopt.processArguments(argv)
619 getopt.processArguments(argv)
619 except:
620 except:
620 print usage
621 print usage
621 warn(`sys.exc_value`,level=4)
622 warn(`sys.exc_value`,level=4)
622
623
623 defaults.update(getopt.optionValues)
624 defaults.update(getopt.optionValues)
624 args = getopt.freeValues
625 args = getopt.freeValues
625
626
626 return defaults,args
627 return defaults,args
627
628
628 #----------------------------------------------------------------------------
629 #----------------------------------------------------------------------------
629 def optstr2types(ostr):
630 def optstr2types(ostr):
630 """Convert a string of option names to a dict of type mappings.
631 """Convert a string of option names to a dict of type mappings.
631
632
632 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
633 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
633
634
634 This is used to get the types of all the options in a string formatted
635 This is used to get the types of all the options in a string formatted
635 with the conventions of DPyGetOpt. The 'type' None is used for options
636 with the conventions of DPyGetOpt. The 'type' None is used for options
636 which are strings (they need no further conversion). This function's main
637 which are strings (they need no further conversion). This function's main
637 use is to get a typemap for use with read_dict().
638 use is to get a typemap for use with read_dict().
638 """
639 """
639
640
640 typeconv = {None:'',int:'',float:''}
641 typeconv = {None:'',int:'',float:''}
641 typemap = {'s':None,'i':int,'f':float}
642 typemap = {'s':None,'i':int,'f':float}
642 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
643 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
643
644
644 for w in ostr.split():
645 for w in ostr.split():
645 oname,alias,otype = opt_re.match(w).groups()
646 oname,alias,otype = opt_re.match(w).groups()
646 if otype == '' or alias == '!': # simple switches are integers too
647 if otype == '' or alias == '!': # simple switches are integers too
647 otype = 'i'
648 otype = 'i'
648 typeconv[typemap[otype]] += oname + ' '
649 typeconv[typemap[otype]] += oname + ' '
649 return typeconv
650 return typeconv
650
651
651 #----------------------------------------------------------------------------
652 #----------------------------------------------------------------------------
652 def read_dict(filename,type_conv=None,**opt):
653 def read_dict(filename,type_conv=None,**opt):
653
654
654 """Read a dictionary of key=value pairs from an input file, optionally
655 """Read a dictionary of key=value pairs from an input file, optionally
655 performing conversions on the resulting values.
656 performing conversions on the resulting values.
656
657
657 read_dict(filename,type_conv,**opt) -> dict
658 read_dict(filename,type_conv,**opt) -> dict
658
659
659 Only one value per line is accepted, the format should be
660 Only one value per line is accepted, the format should be
660 # optional comments are ignored
661 # optional comments are ignored
661 key value\n
662 key value\n
662
663
663 Args:
664 Args:
664
665
665 - type_conv: A dictionary specifying which keys need to be converted to
666 - type_conv: A dictionary specifying which keys need to be converted to
666 which types. By default all keys are read as strings. This dictionary
667 which types. By default all keys are read as strings. This dictionary
667 should have as its keys valid conversion functions for strings
668 should have as its keys valid conversion functions for strings
668 (int,long,float,complex, or your own). The value for each key
669 (int,long,float,complex, or your own). The value for each key
669 (converter) should be a whitespace separated string containing the names
670 (converter) should be a whitespace separated string containing the names
670 of all the entries in the file to be converted using that function. For
671 of all the entries in the file to be converted using that function. For
671 keys to be left alone, use None as the conversion function (only needed
672 keys to be left alone, use None as the conversion function (only needed
672 with purge=1, see below).
673 with purge=1, see below).
673
674
674 - opt: dictionary with extra options as below (default in parens)
675 - opt: dictionary with extra options as below (default in parens)
675
676
676 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
677 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
677 of the dictionary to be returned. If purge is going to be used, the
678 of the dictionary to be returned. If purge is going to be used, the
678 set of keys to be left as strings also has to be explicitly specified
679 set of keys to be left as strings also has to be explicitly specified
679 using the (non-existent) conversion function None.
680 using the (non-existent) conversion function None.
680
681
681 fs(None): field separator. This is the key/value separator to be used
682 fs(None): field separator. This is the key/value separator to be used
682 when parsing the file. The None default means any whitespace [behavior
683 when parsing the file. The None default means any whitespace [behavior
683 of string.split()].
684 of string.split()].
684
685
685 strip(0): if 1, strip string values of leading/trailinig whitespace.
686 strip(0): if 1, strip string values of leading/trailinig whitespace.
686
687
687 warn(1): warning level if requested keys are not found in file.
688 warn(1): warning level if requested keys are not found in file.
688 - 0: silently ignore.
689 - 0: silently ignore.
689 - 1: inform but proceed.
690 - 1: inform but proceed.
690 - 2: raise KeyError exception.
691 - 2: raise KeyError exception.
691
692
692 no_empty(0): if 1, remove keys with whitespace strings as a value.
693 no_empty(0): if 1, remove keys with whitespace strings as a value.
693
694
694 unique([]): list of keys (or space separated string) which can't be
695 unique([]): list of keys (or space separated string) which can't be
695 repeated. If one such key is found in the file, each new instance
696 repeated. If one such key is found in the file, each new instance
696 overwrites the previous one. For keys not listed here, the behavior is
697 overwrites the previous one. For keys not listed here, the behavior is
697 to make a list of all appearances.
698 to make a list of all appearances.
698
699
699 Example:
700 Example:
700 If the input file test.ini has:
701 If the input file test.ini has:
701 i 3
702 i 3
702 x 4.5
703 x 4.5
703 y 5.5
704 y 5.5
704 s hi ho
705 s hi ho
705 Then:
706 Then:
706
707
707 >>> type_conv={int:'i',float:'x',None:'s'}
708 >>> type_conv={int:'i',float:'x',None:'s'}
708 >>> read_dict('test.ini')
709 >>> read_dict('test.ini')
709 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
710 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
710 >>> read_dict('test.ini',type_conv)
711 >>> read_dict('test.ini',type_conv)
711 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
712 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
712 >>> read_dict('test.ini',type_conv,purge=1)
713 >>> read_dict('test.ini',type_conv,purge=1)
713 {'i': 3, 's': 'hi ho', 'x': 4.5}
714 {'i': 3, 's': 'hi ho', 'x': 4.5}
714 """
715 """
715
716
716 # starting config
717 # starting config
717 opt.setdefault('purge',0)
718 opt.setdefault('purge',0)
718 opt.setdefault('fs',None) # field sep defaults to any whitespace
719 opt.setdefault('fs',None) # field sep defaults to any whitespace
719 opt.setdefault('strip',0)
720 opt.setdefault('strip',0)
720 opt.setdefault('warn',1)
721 opt.setdefault('warn',1)
721 opt.setdefault('no_empty',0)
722 opt.setdefault('no_empty',0)
722 opt.setdefault('unique','')
723 opt.setdefault('unique','')
723 if type(opt['unique']) in StringTypes:
724 if type(opt['unique']) in StringTypes:
724 unique_keys = qw(opt['unique'])
725 unique_keys = qw(opt['unique'])
725 elif type(opt['unique']) in (types.TupleType,types.ListType):
726 elif type(opt['unique']) in (types.TupleType,types.ListType):
726 unique_keys = opt['unique']
727 unique_keys = opt['unique']
727 else:
728 else:
728 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
729 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
729
730
730 dict = {}
731 dict = {}
731 # first read in table of values as strings
732 # first read in table of values as strings
732 file = open(filename,'r')
733 file = open(filename,'r')
733 for line in file.readlines():
734 for line in file.readlines():
734 line = line.strip()
735 line = line.strip()
735 if len(line) and line[0]=='#': continue
736 if len(line) and line[0]=='#': continue
736 if len(line)>0:
737 if len(line)>0:
737 lsplit = line.split(opt['fs'],1)
738 lsplit = line.split(opt['fs'],1)
738 try:
739 try:
739 key,val = lsplit
740 key,val = lsplit
740 except ValueError:
741 except ValueError:
741 key,val = lsplit[0],''
742 key,val = lsplit[0],''
742 key = key.strip()
743 key = key.strip()
743 if opt['strip']: val = val.strip()
744 if opt['strip']: val = val.strip()
744 if val == "''" or val == '""': val = ''
745 if val == "''" or val == '""': val = ''
745 if opt['no_empty'] and (val=='' or val.isspace()):
746 if opt['no_empty'] and (val=='' or val.isspace()):
746 continue
747 continue
747 # if a key is found more than once in the file, build a list
748 # if a key is found more than once in the file, build a list
748 # unless it's in the 'unique' list. In that case, last found in file
749 # unless it's in the 'unique' list. In that case, last found in file
749 # takes precedence. User beware.
750 # takes precedence. User beware.
750 try:
751 try:
751 if dict[key] and key in unique_keys:
752 if dict[key] and key in unique_keys:
752 dict[key] = val
753 dict[key] = val
753 elif type(dict[key]) is types.ListType:
754 elif type(dict[key]) is types.ListType:
754 dict[key].append(val)
755 dict[key].append(val)
755 else:
756 else:
756 dict[key] = [dict[key],val]
757 dict[key] = [dict[key],val]
757 except KeyError:
758 except KeyError:
758 dict[key] = val
759 dict[key] = val
759 # purge if requested
760 # purge if requested
760 if opt['purge']:
761 if opt['purge']:
761 accepted_keys = qwflat(type_conv.values())
762 accepted_keys = qwflat(type_conv.values())
762 for key in dict.keys():
763 for key in dict.keys():
763 if key in accepted_keys: continue
764 if key in accepted_keys: continue
764 del(dict[key])
765 del(dict[key])
765 # now convert if requested
766 # now convert if requested
766 if type_conv==None: return dict
767 if type_conv==None: return dict
767 conversions = type_conv.keys()
768 conversions = type_conv.keys()
768 try: conversions.remove(None)
769 try: conversions.remove(None)
769 except: pass
770 except: pass
770 for convert in conversions:
771 for convert in conversions:
771 for val in qw(type_conv[convert]):
772 for val in qw(type_conv[convert]):
772 try:
773 try:
773 dict[val] = convert(dict[val])
774 dict[val] = convert(dict[val])
774 except KeyError,e:
775 except KeyError,e:
775 if opt['warn'] == 0:
776 if opt['warn'] == 0:
776 pass
777 pass
777 elif opt['warn'] == 1:
778 elif opt['warn'] == 1:
778 print >>sys.stderr, 'Warning: key',val,\
779 print >>sys.stderr, 'Warning: key',val,\
779 'not found in file',filename
780 'not found in file',filename
780 elif opt['warn'] == 2:
781 elif opt['warn'] == 2:
781 raise KeyError,e
782 raise KeyError,e
782 else:
783 else:
783 raise ValueError,'Warning level must be 0,1 or 2'
784 raise ValueError,'Warning level must be 0,1 or 2'
784
785
785 return dict
786 return dict
786
787
787 #----------------------------------------------------------------------------
788 #----------------------------------------------------------------------------
788 def flag_calls(func):
789 def flag_calls(func):
789 """Wrap a function to detect and flag when it gets called.
790 """Wrap a function to detect and flag when it gets called.
790
791
791 This is a decorator which takes a function and wraps it in a function with
792 This is a decorator which takes a function and wraps it in a function with
792 a 'called' attribute. wrapper.called is initialized to False.
793 a 'called' attribute. wrapper.called is initialized to False.
793
794
794 The wrapper.called attribute is set to False right before each call to the
795 The wrapper.called attribute is set to False right before each call to the
795 wrapped function, so if the call fails it remains False. After the call
796 wrapped function, so if the call fails it remains False. After the call
796 completes, wrapper.called is set to True and the output is returned.
797 completes, wrapper.called is set to True and the output is returned.
797
798
798 Testing for truth in wrapper.called allows you to determine if a call to
799 Testing for truth in wrapper.called allows you to determine if a call to
799 func() was attempted and succeeded."""
800 func() was attempted and succeeded."""
800
801
801 def wrapper(*args,**kw):
802 def wrapper(*args,**kw):
802 wrapper.called = False
803 wrapper.called = False
803 out = func(*args,**kw)
804 out = func(*args,**kw)
804 wrapper.called = True
805 wrapper.called = True
805 return out
806 return out
806
807
807 wrapper.called = False
808 wrapper.called = False
808 wrapper.__doc__ = func.__doc__
809 wrapper.__doc__ = func.__doc__
809 return wrapper
810 return wrapper
810
811
811 #----------------------------------------------------------------------------
812 #----------------------------------------------------------------------------
812 class HomeDirError(Error):
813 class HomeDirError(Error):
813 pass
814 pass
814
815
815 def get_home_dir():
816 def get_home_dir():
816 """Return the closest possible equivalent to a 'home' directory.
817 """Return the closest possible equivalent to a 'home' directory.
817
818
818 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
819 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
819
820
820 Currently only Posix and NT are implemented, a HomeDirError exception is
821 Currently only Posix and NT are implemented, a HomeDirError exception is
821 raised for all other OSes. """
822 raised for all other OSes. """
822
823
823 isdir = os.path.isdir
824 isdir = os.path.isdir
824 env = os.environ
825 env = os.environ
825 try:
826 try:
826 homedir = env['HOME']
827 homedir = env['HOME']
827 if not isdir(homedir):
828 if not isdir(homedir):
828 # in case a user stuck some string which does NOT resolve to a
829 # in case a user stuck some string which does NOT resolve to a
829 # valid path, it's as good as if we hadn't foud it
830 # valid path, it's as good as if we hadn't foud it
830 raise KeyError
831 raise KeyError
831 return homedir
832 return homedir
832 except KeyError:
833 except KeyError:
833 if os.name == 'posix':
834 if os.name == 'posix':
834 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
835 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
835 elif os.name == 'nt':
836 elif os.name == 'nt':
836 # For some strange reason, win9x returns 'nt' for os.name.
837 # For some strange reason, win9x returns 'nt' for os.name.
837 try:
838 try:
838 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
839 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
839 if not isdir(homedir):
840 if not isdir(homedir):
840 homedir = os.path.join(env['USERPROFILE'])
841 homedir = os.path.join(env['USERPROFILE'])
841 if not isdir(homedir):
842 if not isdir(homedir):
842 raise HomeDirError
843 raise HomeDirError
843 return homedir
844 return homedir
844 except:
845 except:
845 try:
846 try:
846 # Use the registry to get the 'My Documents' folder.
847 # Use the registry to get the 'My Documents' folder.
847 import _winreg as wreg
848 import _winreg as wreg
848 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
849 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
849 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
850 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
850 homedir = wreg.QueryValueEx(key,'Personal')[0]
851 homedir = wreg.QueryValueEx(key,'Personal')[0]
851 key.Close()
852 key.Close()
852 if not isdir(homedir):
853 if not isdir(homedir):
853 e = ('Invalid "Personal" folder registry key '
854 e = ('Invalid "Personal" folder registry key '
854 'typically "My Documents".\n'
855 'typically "My Documents".\n'
855 'Value: %s\n'
856 'Value: %s\n'
856 'This is not a valid directory on your system.' %
857 'This is not a valid directory on your system.' %
857 homedir)
858 homedir)
858 raise HomeDirError(e)
859 raise HomeDirError(e)
859 return homedir
860 return homedir
860 except HomeDirError:
861 except HomeDirError:
861 raise
862 raise
862 except:
863 except:
863 return 'C:\\'
864 return 'C:\\'
864 elif os.name == 'dos':
865 elif os.name == 'dos':
865 # Desperate, may do absurd things in classic MacOS. May work under DOS.
866 # Desperate, may do absurd things in classic MacOS. May work under DOS.
866 return 'C:\\'
867 return 'C:\\'
867 else:
868 else:
868 raise HomeDirError,'support for your operating system not implemented.'
869 raise HomeDirError,'support for your operating system not implemented.'
869
870
870 #****************************************************************************
871 #****************************************************************************
871 # strings and text
872 # strings and text
872
873
873 class LSString(str):
874 class LSString(str):
874 """String derivative with a special access attributes.
875 """String derivative with a special access attributes.
875
876
876 These are normal strings, but with the special attributes:
877 These are normal strings, but with the special attributes:
877
878
878 .l (or .list) : value as list (split on newlines).
879 .l (or .list) : value as list (split on newlines).
879 .n (or .nlstr): original value (the string itself).
880 .n (or .nlstr): original value (the string itself).
880 .s (or .spstr): value as whitespace-separated string.
881 .s (or .spstr): value as whitespace-separated string.
881
882
882 Any values which require transformations are computed only once and
883 Any values which require transformations are computed only once and
883 cached.
884 cached.
884
885
885 Such strings are very useful to efficiently interact with the shell, which
886 Such strings are very useful to efficiently interact with the shell, which
886 typically only understands whitespace-separated options for commands."""
887 typically only understands whitespace-separated options for commands."""
887
888
888 def get_list(self):
889 def get_list(self):
889 try:
890 try:
890 return self.__list
891 return self.__list
891 except AttributeError:
892 except AttributeError:
892 self.__list = self.split('\n')
893 self.__list = self.split('\n')
893 return self.__list
894 return self.__list
894
895
895 l = list = property(get_list)
896 l = list = property(get_list)
896
897
897 def get_spstr(self):
898 def get_spstr(self):
898 try:
899 try:
899 return self.__spstr
900 return self.__spstr
900 except AttributeError:
901 except AttributeError:
901 self.__spstr = self.replace('\n',' ')
902 self.__spstr = self.replace('\n',' ')
902 return self.__spstr
903 return self.__spstr
903
904
904 s = spstr = property(get_spstr)
905 s = spstr = property(get_spstr)
905
906
906 def get_nlstr(self):
907 def get_nlstr(self):
907 return self
908 return self
908
909
909 n = nlstr = property(get_nlstr)
910 n = nlstr = property(get_nlstr)
910
911
911 def get_paths(self):
912 def get_paths(self):
912 try:
913 try:
913 return self.__paths
914 return self.__paths
914 except AttributeError:
915 except AttributeError:
915 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
916 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
916 return self.__paths
917 return self.__paths
917
918
918 p = paths = property(get_paths)
919 p = paths = property(get_paths)
919
920
920
921
921 #----------------------------------------------------------------------------
922 #----------------------------------------------------------------------------
922 class SList(list):
923 class SList(list):
923 """List derivative with a special access attributes.
924 """List derivative with a special access attributes.
924
925
925 These are normal lists, but with the special attributes:
926 These are normal lists, but with the special attributes:
926
927
927 .l (or .list) : value as list (the list itself).
928 .l (or .list) : value as list (the list itself).
928 .n (or .nlstr): value as a string, joined on newlines.
929 .n (or .nlstr): value as a string, joined on newlines.
929 .s (or .spstr): value as a string, joined on spaces.
930 .s (or .spstr): value as a string, joined on spaces.
930
931
931 Any values which require transformations are computed only once and
932 Any values which require transformations are computed only once and
932 cached."""
933 cached."""
933
934
934 def get_list(self):
935 def get_list(self):
935 return self
936 return self
936
937
937 l = list = property(get_list)
938 l = list = property(get_list)
938
939
939 def get_spstr(self):
940 def get_spstr(self):
940 try:
941 try:
941 return self.__spstr
942 return self.__spstr
942 except AttributeError:
943 except AttributeError:
943 self.__spstr = ' '.join(self)
944 self.__spstr = ' '.join(self)
944 return self.__spstr
945 return self.__spstr
945
946
946 s = spstr = property(get_spstr)
947 s = spstr = property(get_spstr)
947
948
948 def get_nlstr(self):
949 def get_nlstr(self):
949 try:
950 try:
950 return self.__nlstr
951 return self.__nlstr
951 except AttributeError:
952 except AttributeError:
952 self.__nlstr = '\n'.join(self)
953 self.__nlstr = '\n'.join(self)
953 return self.__nlstr
954 return self.__nlstr
954
955
955 n = nlstr = property(get_nlstr)
956 n = nlstr = property(get_nlstr)
956
957
957 def get_paths(self):
958 def get_paths(self):
958 try:
959 try:
959 return self.__paths
960 return self.__paths
960 except AttributeError:
961 except AttributeError:
961 self.__paths = [path(p) for p in self if os.path.exists(p)]
962 self.__paths = [path(p) for p in self if os.path.exists(p)]
962 return self.__paths
963 return self.__paths
963
964
964 p = paths = property(get_paths)
965 p = paths = property(get_paths)
965
966
966 #----------------------------------------------------------------------------
967 #----------------------------------------------------------------------------
967 def esc_quotes(strng):
968 def esc_quotes(strng):
968 """Return the input string with single and double quotes escaped out"""
969 """Return the input string with single and double quotes escaped out"""
969
970
970 return strng.replace('"','\\"').replace("'","\\'")
971 return strng.replace('"','\\"').replace("'","\\'")
971
972
972 #----------------------------------------------------------------------------
973 #----------------------------------------------------------------------------
973 def make_quoted_expr(s):
974 def make_quoted_expr(s):
974 """Return string s in appropriate quotes, using raw string if possible.
975 """Return string s in appropriate quotes, using raw string if possible.
975
976
976 Effectively this turns string: cd \ao\ao\
977 Effectively this turns string: cd \ao\ao\
977 to: r"cd \ao\ao\_"[:-1]
978 to: r"cd \ao\ao\_"[:-1]
978
979
979 Note the use of raw string and padding at the end to allow trailing backslash.
980 Note the use of raw string and padding at the end to allow trailing backslash.
980
981
981 """
982 """
982
983
983 tail = ''
984 tail = ''
984 tailpadding = ''
985 tailpadding = ''
985 raw = ''
986 raw = ''
986 if "\\" in s:
987 if "\\" in s:
987 raw = 'r'
988 raw = 'r'
988 if s.endswith('\\'):
989 if s.endswith('\\'):
989 tail = '[:-1]'
990 tail = '[:-1]'
990 tailpadding = '_'
991 tailpadding = '_'
991 if '"' not in s:
992 if '"' not in s:
992 quote = '"'
993 quote = '"'
993 elif "'" not in s:
994 elif "'" not in s:
994 quote = "'"
995 quote = "'"
995 elif '"""' not in s and not s.endswith('"'):
996 elif '"""' not in s and not s.endswith('"'):
996 quote = '"""'
997 quote = '"""'
997 elif "'''" not in s and not s.endswith("'"):
998 elif "'''" not in s and not s.endswith("'"):
998 quote = "'''"
999 quote = "'''"
999 else:
1000 else:
1000 # give up, backslash-escaped string will do
1001 # give up, backslash-escaped string will do
1001 return '"%s"' % esc_quotes(s)
1002 return '"%s"' % esc_quotes(s)
1002 res = itpl("$raw$quote$s$tailpadding$quote$tail")
1003 res = itpl("$raw$quote$s$tailpadding$quote$tail")
1003 return res
1004 return res
1004
1005
1005
1006
1006 #----------------------------------------------------------------------------
1007 #----------------------------------------------------------------------------
1007 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1008 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1008 """Take multiple lines of input.
1009 """Take multiple lines of input.
1009
1010
1010 A list with each line of input as a separate element is returned when a
1011 A list with each line of input as a separate element is returned when a
1011 termination string is entered (defaults to a single '.'). Input can also
1012 termination string is entered (defaults to a single '.'). Input can also
1012 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1013 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1013
1014
1014 Lines of input which end in \\ are joined into single entries (and a
1015 Lines of input which end in \\ are joined into single entries (and a
1015 secondary continuation prompt is issued as long as the user terminates
1016 secondary continuation prompt is issued as long as the user terminates
1016 lines with \\). This allows entering very long strings which are still
1017 lines with \\). This allows entering very long strings which are still
1017 meant to be treated as single entities.
1018 meant to be treated as single entities.
1018 """
1019 """
1019
1020
1020 try:
1021 try:
1021 if header:
1022 if header:
1022 header += '\n'
1023 header += '\n'
1023 lines = [raw_input(header + ps1)]
1024 lines = [raw_input(header + ps1)]
1024 except EOFError:
1025 except EOFError:
1025 return []
1026 return []
1026 terminate = [terminate_str]
1027 terminate = [terminate_str]
1027 try:
1028 try:
1028 while lines[-1:] != terminate:
1029 while lines[-1:] != terminate:
1029 new_line = raw_input(ps1)
1030 new_line = raw_input(ps1)
1030 while new_line.endswith('\\'):
1031 while new_line.endswith('\\'):
1031 new_line = new_line[:-1] + raw_input(ps2)
1032 new_line = new_line[:-1] + raw_input(ps2)
1032 lines.append(new_line)
1033 lines.append(new_line)
1033
1034
1034 return lines[:-1] # don't return the termination command
1035 return lines[:-1] # don't return the termination command
1035 except EOFError:
1036 except EOFError:
1036 print
1037 print
1037 return lines
1038 return lines
1038
1039
1039 #----------------------------------------------------------------------------
1040 #----------------------------------------------------------------------------
1040 def raw_input_ext(prompt='', ps2='... '):
1041 def raw_input_ext(prompt='', ps2='... '):
1041 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1042 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1042
1043
1043 line = raw_input(prompt)
1044 line = raw_input(prompt)
1044 while line.endswith('\\'):
1045 while line.endswith('\\'):
1045 line = line[:-1] + raw_input(ps2)
1046 line = line[:-1] + raw_input(ps2)
1046 return line
1047 return line
1047
1048
1048 #----------------------------------------------------------------------------
1049 #----------------------------------------------------------------------------
1049 def ask_yes_no(prompt,default=None):
1050 def ask_yes_no(prompt,default=None):
1050 """Asks a question and returns an integer 1/0 (y/n) answer.
1051 """Asks a question and returns an integer 1/0 (y/n) answer.
1051
1052
1052 If default is given (one of 'y','n'), it is used if the user input is
1053 If default is given (one of 'y','n'), it is used if the user input is
1053 empty. Otherwise the question is repeated until an answer is given.
1054 empty. Otherwise the question is repeated until an answer is given.
1054 If EOF occurs 20 times consecutively, the default answer is assumed,
1055 If EOF occurs 20 times consecutively, the default answer is assumed,
1055 or if there is no default, an exception is raised to prevent infinite
1056 or if there is no default, an exception is raised to prevent infinite
1056 loops.
1057 loops.
1057
1058
1058 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1059 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1059
1060
1060 answers = {'y':True,'n':False,'yes':True,'no':False}
1061 answers = {'y':True,'n':False,'yes':True,'no':False}
1061 ans = None
1062 ans = None
1062 eofs, max_eofs = 0, 20
1063 eofs, max_eofs = 0, 20
1063 while ans not in answers.keys():
1064 while ans not in answers.keys():
1064 try:
1065 try:
1065 ans = raw_input(prompt+' ').lower()
1066 ans = raw_input(prompt+' ').lower()
1066 if not ans: # response was an empty string
1067 if not ans: # response was an empty string
1067 ans = default
1068 ans = default
1068 eofs = 0
1069 eofs = 0
1069 except (EOFError,KeyboardInterrupt):
1070 except (EOFError,KeyboardInterrupt):
1070 eofs = eofs + 1
1071 eofs = eofs + 1
1071 if eofs >= max_eofs:
1072 if eofs >= max_eofs:
1072 if default in answers.keys():
1073 if default in answers.keys():
1073 ans = default
1074 ans = default
1074 else:
1075 else:
1075 raise
1076 raise
1076
1077
1077 return answers[ans]
1078 return answers[ans]
1078
1079
1079 #----------------------------------------------------------------------------
1080 #----------------------------------------------------------------------------
1080 def marquee(txt='',width=78,mark='*'):
1081 def marquee(txt='',width=78,mark='*'):
1081 """Return the input string centered in a 'marquee'."""
1082 """Return the input string centered in a 'marquee'."""
1082 if not txt:
1083 if not txt:
1083 return (mark*width)[:width]
1084 return (mark*width)[:width]
1084 nmark = (width-len(txt)-2)/len(mark)/2
1085 nmark = (width-len(txt)-2)/len(mark)/2
1085 if nmark < 0: nmark =0
1086 if nmark < 0: nmark =0
1086 marks = mark*nmark
1087 marks = mark*nmark
1087 return '%s %s %s' % (marks,txt,marks)
1088 return '%s %s %s' % (marks,txt,marks)
1088
1089
1089 #----------------------------------------------------------------------------
1090 #----------------------------------------------------------------------------
1090 class EvalDict:
1091 class EvalDict:
1091 """
1092 """
1092 Emulate a dict which evaluates its contents in the caller's frame.
1093 Emulate a dict which evaluates its contents in the caller's frame.
1093
1094
1094 Usage:
1095 Usage:
1095 >>>number = 19
1096 >>>number = 19
1096 >>>text = "python"
1097 >>>text = "python"
1097 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1098 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1098 """
1099 """
1099
1100
1100 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1101 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1101 # modified (shorter) version of:
1102 # modified (shorter) version of:
1102 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1103 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1103 # Skip Montanaro (skip@pobox.com).
1104 # Skip Montanaro (skip@pobox.com).
1104
1105
1105 def __getitem__(self, name):
1106 def __getitem__(self, name):
1106 frame = sys._getframe(1)
1107 frame = sys._getframe(1)
1107 return eval(name, frame.f_globals, frame.f_locals)
1108 return eval(name, frame.f_globals, frame.f_locals)
1108
1109
1109 EvalString = EvalDict # for backwards compatibility
1110 EvalString = EvalDict # for backwards compatibility
1110 #----------------------------------------------------------------------------
1111 #----------------------------------------------------------------------------
1111 def qw(words,flat=0,sep=None,maxsplit=-1):
1112 def qw(words,flat=0,sep=None,maxsplit=-1):
1112 """Similar to Perl's qw() operator, but with some more options.
1113 """Similar to Perl's qw() operator, but with some more options.
1113
1114
1114 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1115 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1115
1116
1116 words can also be a list itself, and with flat=1, the output will be
1117 words can also be a list itself, and with flat=1, the output will be
1117 recursively flattened. Examples:
1118 recursively flattened. Examples:
1118
1119
1119 >>> qw('1 2')
1120 >>> qw('1 2')
1120 ['1', '2']
1121 ['1', '2']
1121 >>> qw(['a b','1 2',['m n','p q']])
1122 >>> qw(['a b','1 2',['m n','p q']])
1122 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1123 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1123 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1124 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1124 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1125 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1125
1126
1126 if type(words) in StringTypes:
1127 if type(words) in StringTypes:
1127 return [word.strip() for word in words.split(sep,maxsplit)
1128 return [word.strip() for word in words.split(sep,maxsplit)
1128 if word and not word.isspace() ]
1129 if word and not word.isspace() ]
1129 if flat:
1130 if flat:
1130 return flatten(map(qw,words,[1]*len(words)))
1131 return flatten(map(qw,words,[1]*len(words)))
1131 return map(qw,words)
1132 return map(qw,words)
1132
1133
1133 #----------------------------------------------------------------------------
1134 #----------------------------------------------------------------------------
1134 def qwflat(words,sep=None,maxsplit=-1):
1135 def qwflat(words,sep=None,maxsplit=-1):
1135 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1136 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1136 return qw(words,1,sep,maxsplit)
1137 return qw(words,1,sep,maxsplit)
1137
1138
1138 #----------------------------------------------------------------------------
1139 #----------------------------------------------------------------------------
1139 def qw_lol(indata):
1140 def qw_lol(indata):
1140 """qw_lol('a b') -> [['a','b']],
1141 """qw_lol('a b') -> [['a','b']],
1141 otherwise it's just a call to qw().
1142 otherwise it's just a call to qw().
1142
1143
1143 We need this to make sure the modules_some keys *always* end up as a
1144 We need this to make sure the modules_some keys *always* end up as a
1144 list of lists."""
1145 list of lists."""
1145
1146
1146 if type(indata) in StringTypes:
1147 if type(indata) in StringTypes:
1147 return [qw(indata)]
1148 return [qw(indata)]
1148 else:
1149 else:
1149 return qw(indata)
1150 return qw(indata)
1150
1151
1151 #-----------------------------------------------------------------------------
1152 #-----------------------------------------------------------------------------
1152 def list_strings(arg):
1153 def list_strings(arg):
1153 """Always return a list of strings, given a string or list of strings
1154 """Always return a list of strings, given a string or list of strings
1154 as input."""
1155 as input."""
1155
1156
1156 if type(arg) in StringTypes: return [arg]
1157 if type(arg) in StringTypes: return [arg]
1157 else: return arg
1158 else: return arg
1158
1159
1159 #----------------------------------------------------------------------------
1160 #----------------------------------------------------------------------------
1160 def grep(pat,list,case=1):
1161 def grep(pat,list,case=1):
1161 """Simple minded grep-like function.
1162 """Simple minded grep-like function.
1162 grep(pat,list) returns occurrences of pat in list, None on failure.
1163 grep(pat,list) returns occurrences of pat in list, None on failure.
1163
1164
1164 It only does simple string matching, with no support for regexps. Use the
1165 It only does simple string matching, with no support for regexps. Use the
1165 option case=0 for case-insensitive matching."""
1166 option case=0 for case-insensitive matching."""
1166
1167
1167 # This is pretty crude. At least it should implement copying only references
1168 # This is pretty crude. At least it should implement copying only references
1168 # to the original data in case it's big. Now it copies the data for output.
1169 # to the original data in case it's big. Now it copies the data for output.
1169 out=[]
1170 out=[]
1170 if case:
1171 if case:
1171 for term in list:
1172 for term in list:
1172 if term.find(pat)>-1: out.append(term)
1173 if term.find(pat)>-1: out.append(term)
1173 else:
1174 else:
1174 lpat=pat.lower()
1175 lpat=pat.lower()
1175 for term in list:
1176 for term in list:
1176 if term.lower().find(lpat)>-1: out.append(term)
1177 if term.lower().find(lpat)>-1: out.append(term)
1177
1178
1178 if len(out): return out
1179 if len(out): return out
1179 else: return None
1180 else: return None
1180
1181
1181 #----------------------------------------------------------------------------
1182 #----------------------------------------------------------------------------
1182 def dgrep(pat,*opts):
1183 def dgrep(pat,*opts):
1183 """Return grep() on dir()+dir(__builtins__).
1184 """Return grep() on dir()+dir(__builtins__).
1184
1185
1185 A very common use of grep() when working interactively."""
1186 A very common use of grep() when working interactively."""
1186
1187
1187 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1188 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1188
1189
1189 #----------------------------------------------------------------------------
1190 #----------------------------------------------------------------------------
1190 def idgrep(pat):
1191 def idgrep(pat):
1191 """Case-insensitive dgrep()"""
1192 """Case-insensitive dgrep()"""
1192
1193
1193 return dgrep(pat,0)
1194 return dgrep(pat,0)
1194
1195
1195 #----------------------------------------------------------------------------
1196 #----------------------------------------------------------------------------
1196 def igrep(pat,list):
1197 def igrep(pat,list):
1197 """Synonym for case-insensitive grep."""
1198 """Synonym for case-insensitive grep."""
1198
1199
1199 return grep(pat,list,case=0)
1200 return grep(pat,list,case=0)
1200
1201
1201 #----------------------------------------------------------------------------
1202 #----------------------------------------------------------------------------
1202 def indent(str,nspaces=4,ntabs=0):
1203 def indent(str,nspaces=4,ntabs=0):
1203 """Indent a string a given number of spaces or tabstops.
1204 """Indent a string a given number of spaces or tabstops.
1204
1205
1205 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1206 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1206 """
1207 """
1207 if str is None:
1208 if str is None:
1208 return
1209 return
1209 ind = '\t'*ntabs+' '*nspaces
1210 ind = '\t'*ntabs+' '*nspaces
1210 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1211 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1211 if outstr.endswith(os.linesep+ind):
1212 if outstr.endswith(os.linesep+ind):
1212 return outstr[:-len(ind)]
1213 return outstr[:-len(ind)]
1213 else:
1214 else:
1214 return outstr
1215 return outstr
1215
1216
1216 #-----------------------------------------------------------------------------
1217 #-----------------------------------------------------------------------------
1217 def native_line_ends(filename,backup=1):
1218 def native_line_ends(filename,backup=1):
1218 """Convert (in-place) a file to line-ends native to the current OS.
1219 """Convert (in-place) a file to line-ends native to the current OS.
1219
1220
1220 If the optional backup argument is given as false, no backup of the
1221 If the optional backup argument is given as false, no backup of the
1221 original file is left. """
1222 original file is left. """
1222
1223
1223 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1224 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1224
1225
1225 bak_filename = filename + backup_suffixes[os.name]
1226 bak_filename = filename + backup_suffixes[os.name]
1226
1227
1227 original = open(filename).read()
1228 original = open(filename).read()
1228 shutil.copy2(filename,bak_filename)
1229 shutil.copy2(filename,bak_filename)
1229 try:
1230 try:
1230 new = open(filename,'wb')
1231 new = open(filename,'wb')
1231 new.write(os.linesep.join(original.splitlines()))
1232 new.write(os.linesep.join(original.splitlines()))
1232 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1233 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1233 new.close()
1234 new.close()
1234 except:
1235 except:
1235 os.rename(bak_filename,filename)
1236 os.rename(bak_filename,filename)
1236 if not backup:
1237 if not backup:
1237 try:
1238 try:
1238 os.remove(bak_filename)
1239 os.remove(bak_filename)
1239 except:
1240 except:
1240 pass
1241 pass
1241
1242
1242 #----------------------------------------------------------------------------
1243 #----------------------------------------------------------------------------
1243 def get_pager_cmd(pager_cmd = None):
1244 def get_pager_cmd(pager_cmd = None):
1244 """Return a pager command.
1245 """Return a pager command.
1245
1246
1246 Makes some attempts at finding an OS-correct one."""
1247 Makes some attempts at finding an OS-correct one."""
1247
1248
1248 if os.name == 'posix':
1249 if os.name == 'posix':
1249 default_pager_cmd = 'less -r' # -r for color control sequences
1250 default_pager_cmd = 'less -r' # -r for color control sequences
1250 elif os.name in ['nt','dos']:
1251 elif os.name in ['nt','dos']:
1251 default_pager_cmd = 'type'
1252 default_pager_cmd = 'type'
1252
1253
1253 if pager_cmd is None:
1254 if pager_cmd is None:
1254 try:
1255 try:
1255 pager_cmd = os.environ['PAGER']
1256 pager_cmd = os.environ['PAGER']
1256 except:
1257 except:
1257 pager_cmd = default_pager_cmd
1258 pager_cmd = default_pager_cmd
1258 return pager_cmd
1259 return pager_cmd
1259
1260
1260 #-----------------------------------------------------------------------------
1261 #-----------------------------------------------------------------------------
1261 def get_pager_start(pager,start):
1262 def get_pager_start(pager,start):
1262 """Return the string for paging files with an offset.
1263 """Return the string for paging files with an offset.
1263
1264
1264 This is the '+N' argument which less and more (under Unix) accept.
1265 This is the '+N' argument which less and more (under Unix) accept.
1265 """
1266 """
1266
1267
1267 if pager in ['less','more']:
1268 if pager in ['less','more']:
1268 if start:
1269 if start:
1269 start_string = '+' + str(start)
1270 start_string = '+' + str(start)
1270 else:
1271 else:
1271 start_string = ''
1272 start_string = ''
1272 else:
1273 else:
1273 start_string = ''
1274 start_string = ''
1274 return start_string
1275 return start_string
1275
1276
1276 #----------------------------------------------------------------------------
1277 #----------------------------------------------------------------------------
1277 if os.name == "nt":
1278 if os.name == "nt":
1278 import msvcrt
1279 import msvcrt
1279 def page_more():
1280 def page_more():
1280 """ Smart pausing between pages
1281 """ Smart pausing between pages
1281
1282
1282 @return: True if need print more lines, False if quit
1283 @return: True if need print more lines, False if quit
1283 """
1284 """
1284 Term.cout.write('---Return to continue, q to quit--- ')
1285 Term.cout.write('---Return to continue, q to quit--- ')
1285 ans = msvcrt.getch()
1286 ans = msvcrt.getch()
1286 if ans in ("q", "Q"):
1287 if ans in ("q", "Q"):
1287 result = False
1288 result = False
1288 else:
1289 else:
1289 result = True
1290 result = True
1290 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1291 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1291 return result
1292 return result
1292 else:
1293 else:
1293 def page_more():
1294 def page_more():
1294 ans = raw_input('---Return to continue, q to quit--- ')
1295 ans = raw_input('---Return to continue, q to quit--- ')
1295 if ans.lower().startswith('q'):
1296 if ans.lower().startswith('q'):
1296 return False
1297 return False
1297 else:
1298 else:
1298 return True
1299 return True
1299
1300
1300 esc_re = re.compile(r"(\x1b[^m]+m)")
1301 esc_re = re.compile(r"(\x1b[^m]+m)")
1301
1302
1302 def page_dumb(strng,start=0,screen_lines=25):
1303 def page_dumb(strng,start=0,screen_lines=25):
1303 """Very dumb 'pager' in Python, for when nothing else works.
1304 """Very dumb 'pager' in Python, for when nothing else works.
1304
1305
1305 Only moves forward, same interface as page(), except for pager_cmd and
1306 Only moves forward, same interface as page(), except for pager_cmd and
1306 mode."""
1307 mode."""
1307
1308
1308 out_ln = strng.splitlines()[start:]
1309 out_ln = strng.splitlines()[start:]
1309 screens = chop(out_ln,screen_lines-1)
1310 screens = chop(out_ln,screen_lines-1)
1310 if len(screens) == 1:
1311 if len(screens) == 1:
1311 print >>Term.cout, os.linesep.join(screens[0])
1312 print >>Term.cout, os.linesep.join(screens[0])
1312 else:
1313 else:
1313 last_escape = ""
1314 last_escape = ""
1314 for scr in screens[0:-1]:
1315 for scr in screens[0:-1]:
1315 hunk = os.linesep.join(scr)
1316 hunk = os.linesep.join(scr)
1316 print >>Term.cout, last_escape + hunk
1317 print >>Term.cout, last_escape + hunk
1317 if not page_more():
1318 if not page_more():
1318 return
1319 return
1319 esc_list = esc_re.findall(hunk)
1320 esc_list = esc_re.findall(hunk)
1320 if len(esc_list) > 0:
1321 if len(esc_list) > 0:
1321 last_escape = esc_list[-1]
1322 last_escape = esc_list[-1]
1322 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1323 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1323
1324
1324 #----------------------------------------------------------------------------
1325 #----------------------------------------------------------------------------
1325 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1326 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1326 """Print a string, piping through a pager after a certain length.
1327 """Print a string, piping through a pager after a certain length.
1327
1328
1328 The screen_lines parameter specifies the number of *usable* lines of your
1329 The screen_lines parameter specifies the number of *usable* lines of your
1329 terminal screen (total lines minus lines you need to reserve to show other
1330 terminal screen (total lines minus lines you need to reserve to show other
1330 information).
1331 information).
1331
1332
1332 If you set screen_lines to a number <=0, page() will try to auto-determine
1333 If you set screen_lines to a number <=0, page() will try to auto-determine
1333 your screen size and will only use up to (screen_size+screen_lines) for
1334 your screen size and will only use up to (screen_size+screen_lines) for
1334 printing, paging after that. That is, if you want auto-detection but need
1335 printing, paging after that. That is, if you want auto-detection but need
1335 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1336 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1336 auto-detection without any lines reserved simply use screen_lines = 0.
1337 auto-detection without any lines reserved simply use screen_lines = 0.
1337
1338
1338 If a string won't fit in the allowed lines, it is sent through the
1339 If a string won't fit in the allowed lines, it is sent through the
1339 specified pager command. If none given, look for PAGER in the environment,
1340 specified pager command. If none given, look for PAGER in the environment,
1340 and ultimately default to less.
1341 and ultimately default to less.
1341
1342
1342 If no system pager works, the string is sent through a 'dumb pager'
1343 If no system pager works, the string is sent through a 'dumb pager'
1343 written in python, very simplistic.
1344 written in python, very simplistic.
1344 """
1345 """
1345
1346
1346 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1347 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1347 TERM = os.environ.get('TERM','dumb')
1348 TERM = os.environ.get('TERM','dumb')
1348 if TERM in ['dumb','emacs'] and os.name != 'nt':
1349 if TERM in ['dumb','emacs'] and os.name != 'nt':
1349 print strng
1350 print strng
1350 return
1351 return
1351 # chop off the topmost part of the string we don't want to see
1352 # chop off the topmost part of the string we don't want to see
1352 str_lines = strng.split(os.linesep)[start:]
1353 str_lines = strng.split(os.linesep)[start:]
1353 str_toprint = os.linesep.join(str_lines)
1354 str_toprint = os.linesep.join(str_lines)
1354 num_newlines = len(str_lines)
1355 num_newlines = len(str_lines)
1355 len_str = len(str_toprint)
1356 len_str = len(str_toprint)
1356
1357
1357 # Dumb heuristics to guesstimate number of on-screen lines the string
1358 # Dumb heuristics to guesstimate number of on-screen lines the string
1358 # takes. Very basic, but good enough for docstrings in reasonable
1359 # takes. Very basic, but good enough for docstrings in reasonable
1359 # terminals. If someone later feels like refining it, it's not hard.
1360 # terminals. If someone later feels like refining it, it's not hard.
1360 numlines = max(num_newlines,int(len_str/80)+1)
1361 numlines = max(num_newlines,int(len_str/80)+1)
1361
1362
1362 if os.name == "nt":
1363 if os.name == "nt":
1363 screen_lines_def = get_console_size(defaulty=25)[1]
1364 screen_lines_def = get_console_size(defaulty=25)[1]
1364 else:
1365 else:
1365 screen_lines_def = 25 # default value if we can't auto-determine
1366 screen_lines_def = 25 # default value if we can't auto-determine
1366
1367
1367 # auto-determine screen size
1368 # auto-determine screen size
1368 if screen_lines <= 0:
1369 if screen_lines <= 0:
1369 if TERM=='xterm':
1370 if TERM=='xterm':
1370 try:
1371 try:
1371 import curses
1372 import curses
1372 if hasattr(curses,'initscr'):
1373 if hasattr(curses,'initscr'):
1373 use_curses = 1
1374 use_curses = 1
1374 else:
1375 else:
1375 use_curses = 0
1376 use_curses = 0
1376 except ImportError:
1377 except ImportError:
1377 use_curses = 0
1378 use_curses = 0
1378 else:
1379 else:
1379 # curses causes problems on many terminals other than xterm.
1380 # curses causes problems on many terminals other than xterm.
1380 use_curses = 0
1381 use_curses = 0
1381 if use_curses:
1382 if use_curses:
1382 scr = curses.initscr()
1383 scr = curses.initscr()
1383 screen_lines_real,screen_cols = scr.getmaxyx()
1384 screen_lines_real,screen_cols = scr.getmaxyx()
1384 curses.endwin()
1385 curses.endwin()
1385 screen_lines += screen_lines_real
1386 screen_lines += screen_lines_real
1386 #print '***Screen size:',screen_lines_real,'lines x',\
1387 #print '***Screen size:',screen_lines_real,'lines x',\
1387 #screen_cols,'columns.' # dbg
1388 #screen_cols,'columns.' # dbg
1388 else:
1389 else:
1389 screen_lines += screen_lines_def
1390 screen_lines += screen_lines_def
1390
1391
1391 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1392 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1392 if numlines <= screen_lines :
1393 if numlines <= screen_lines :
1393 #print '*** normal print' # dbg
1394 #print '*** normal print' # dbg
1394 print >>Term.cout, str_toprint
1395 print >>Term.cout, str_toprint
1395 else:
1396 else:
1396 # Try to open pager and default to internal one if that fails.
1397 # Try to open pager and default to internal one if that fails.
1397 # All failure modes are tagged as 'retval=1', to match the return
1398 # All failure modes are tagged as 'retval=1', to match the return
1398 # value of a failed system command. If any intermediate attempt
1399 # value of a failed system command. If any intermediate attempt
1399 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1400 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1400 pager_cmd = get_pager_cmd(pager_cmd)
1401 pager_cmd = get_pager_cmd(pager_cmd)
1401 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1402 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1402 if os.name == 'nt':
1403 if os.name == 'nt':
1403 if pager_cmd.startswith('type'):
1404 if pager_cmd.startswith('type'):
1404 # The default WinXP 'type' command is failing on complex strings.
1405 # The default WinXP 'type' command is failing on complex strings.
1405 retval = 1
1406 retval = 1
1406 else:
1407 else:
1407 tmpname = tempfile.mktemp('.txt')
1408 tmpname = tempfile.mktemp('.txt')
1408 tmpfile = file(tmpname,'wt')
1409 tmpfile = file(tmpname,'wt')
1409 tmpfile.write(strng)
1410 tmpfile.write(strng)
1410 tmpfile.close()
1411 tmpfile.close()
1411 cmd = "%s < %s" % (pager_cmd,tmpname)
1412 cmd = "%s < %s" % (pager_cmd,tmpname)
1412 if os.system(cmd):
1413 if os.system(cmd):
1413 retval = 1
1414 retval = 1
1414 else:
1415 else:
1415 retval = None
1416 retval = None
1416 os.remove(tmpname)
1417 os.remove(tmpname)
1417 else:
1418 else:
1418 try:
1419 try:
1419 retval = None
1420 retval = None
1420 # if I use popen4, things hang. No idea why.
1421 # if I use popen4, things hang. No idea why.
1421 #pager,shell_out = os.popen4(pager_cmd)
1422 #pager,shell_out = os.popen4(pager_cmd)
1422 pager = os.popen(pager_cmd,'w')
1423 pager = os.popen(pager_cmd,'w')
1423 pager.write(strng)
1424 pager.write(strng)
1424 pager.close()
1425 pager.close()
1425 retval = pager.close() # success returns None
1426 retval = pager.close() # success returns None
1426 except IOError,msg: # broken pipe when user quits
1427 except IOError,msg: # broken pipe when user quits
1427 if msg.args == (32,'Broken pipe'):
1428 if msg.args == (32,'Broken pipe'):
1428 retval = None
1429 retval = None
1429 else:
1430 else:
1430 retval = 1
1431 retval = 1
1431 except OSError:
1432 except OSError:
1432 # Other strange problems, sometimes seen in Win2k/cygwin
1433 # Other strange problems, sometimes seen in Win2k/cygwin
1433 retval = 1
1434 retval = 1
1434 if retval is not None:
1435 if retval is not None:
1435 page_dumb(strng,screen_lines=screen_lines)
1436 page_dumb(strng,screen_lines=screen_lines)
1436
1437
1437 #----------------------------------------------------------------------------
1438 #----------------------------------------------------------------------------
1438 def page_file(fname,start = 0, pager_cmd = None):
1439 def page_file(fname,start = 0, pager_cmd = None):
1439 """Page a file, using an optional pager command and starting line.
1440 """Page a file, using an optional pager command and starting line.
1440 """
1441 """
1441
1442
1442 pager_cmd = get_pager_cmd(pager_cmd)
1443 pager_cmd = get_pager_cmd(pager_cmd)
1443 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1444 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1444
1445
1445 try:
1446 try:
1446 if os.environ['TERM'] in ['emacs','dumb']:
1447 if os.environ['TERM'] in ['emacs','dumb']:
1447 raise EnvironmentError
1448 raise EnvironmentError
1448 xsys(pager_cmd + ' ' + fname)
1449 xsys(pager_cmd + ' ' + fname)
1449 except:
1450 except:
1450 try:
1451 try:
1451 if start > 0:
1452 if start > 0:
1452 start -= 1
1453 start -= 1
1453 page(open(fname).read(),start)
1454 page(open(fname).read(),start)
1454 except:
1455 except:
1455 print 'Unable to show file',`fname`
1456 print 'Unable to show file',`fname`
1456
1457
1457 #----------------------------------------------------------------------------
1458 #----------------------------------------------------------------------------
1458 def snip_print(str,width = 75,print_full = 0,header = ''):
1459 def snip_print(str,width = 75,print_full = 0,header = ''):
1459 """Print a string snipping the midsection to fit in width.
1460 """Print a string snipping the midsection to fit in width.
1460
1461
1461 print_full: mode control:
1462 print_full: mode control:
1462 - 0: only snip long strings
1463 - 0: only snip long strings
1463 - 1: send to page() directly.
1464 - 1: send to page() directly.
1464 - 2: snip long strings and ask for full length viewing with page()
1465 - 2: snip long strings and ask for full length viewing with page()
1465 Return 1 if snipping was necessary, 0 otherwise."""
1466 Return 1 if snipping was necessary, 0 otherwise."""
1466
1467
1467 if print_full == 1:
1468 if print_full == 1:
1468 page(header+str)
1469 page(header+str)
1469 return 0
1470 return 0
1470
1471
1471 print header,
1472 print header,
1472 if len(str) < width:
1473 if len(str) < width:
1473 print str
1474 print str
1474 snip = 0
1475 snip = 0
1475 else:
1476 else:
1476 whalf = int((width -5)/2)
1477 whalf = int((width -5)/2)
1477 print str[:whalf] + ' <...> ' + str[-whalf:]
1478 print str[:whalf] + ' <...> ' + str[-whalf:]
1478 snip = 1
1479 snip = 1
1479 if snip and print_full == 2:
1480 if snip and print_full == 2:
1480 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1481 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1481 page(str)
1482 page(str)
1482 return snip
1483 return snip
1483
1484
1484 #****************************************************************************
1485 #****************************************************************************
1485 # lists, dicts and structures
1486 # lists, dicts and structures
1486
1487
1487 def belong(candidates,checklist):
1488 def belong(candidates,checklist):
1488 """Check whether a list of items appear in a given list of options.
1489 """Check whether a list of items appear in a given list of options.
1489
1490
1490 Returns a list of 1 and 0, one for each candidate given."""
1491 Returns a list of 1 and 0, one for each candidate given."""
1491
1492
1492 return [x in checklist for x in candidates]
1493 return [x in checklist for x in candidates]
1493
1494
1494 #----------------------------------------------------------------------------
1495 #----------------------------------------------------------------------------
1495 def uniq_stable(elems):
1496 def uniq_stable(elems):
1496 """uniq_stable(elems) -> list
1497 """uniq_stable(elems) -> list
1497
1498
1498 Return from an iterable, a list of all the unique elements in the input,
1499 Return from an iterable, a list of all the unique elements in the input,
1499 but maintaining the order in which they first appear.
1500 but maintaining the order in which they first appear.
1500
1501
1501 A naive solution to this problem which just makes a dictionary with the
1502 A naive solution to this problem which just makes a dictionary with the
1502 elements as keys fails to respect the stability condition, since
1503 elements as keys fails to respect the stability condition, since
1503 dictionaries are unsorted by nature.
1504 dictionaries are unsorted by nature.
1504
1505
1505 Note: All elements in the input must be valid dictionary keys for this
1506 Note: All elements in the input must be valid dictionary keys for this
1506 routine to work, as it internally uses a dictionary for efficiency
1507 routine to work, as it internally uses a dictionary for efficiency
1507 reasons."""
1508 reasons."""
1508
1509
1509 unique = []
1510 unique = []
1510 unique_dict = {}
1511 unique_dict = {}
1511 for nn in elems:
1512 for nn in elems:
1512 if nn not in unique_dict:
1513 if nn not in unique_dict:
1513 unique.append(nn)
1514 unique.append(nn)
1514 unique_dict[nn] = None
1515 unique_dict[nn] = None
1515 return unique
1516 return unique
1516
1517
1517 #----------------------------------------------------------------------------
1518 #----------------------------------------------------------------------------
1518 class NLprinter:
1519 class NLprinter:
1519 """Print an arbitrarily nested list, indicating index numbers.
1520 """Print an arbitrarily nested list, indicating index numbers.
1520
1521
1521 An instance of this class called nlprint is available and callable as a
1522 An instance of this class called nlprint is available and callable as a
1522 function.
1523 function.
1523
1524
1524 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1525 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1525 and using 'sep' to separate the index from the value. """
1526 and using 'sep' to separate the index from the value. """
1526
1527
1527 def __init__(self):
1528 def __init__(self):
1528 self.depth = 0
1529 self.depth = 0
1529
1530
1530 def __call__(self,lst,pos='',**kw):
1531 def __call__(self,lst,pos='',**kw):
1531 """Prints the nested list numbering levels."""
1532 """Prints the nested list numbering levels."""
1532 kw.setdefault('indent',' ')
1533 kw.setdefault('indent',' ')
1533 kw.setdefault('sep',': ')
1534 kw.setdefault('sep',': ')
1534 kw.setdefault('start',0)
1535 kw.setdefault('start',0)
1535 kw.setdefault('stop',len(lst))
1536 kw.setdefault('stop',len(lst))
1536 # we need to remove start and stop from kw so they don't propagate
1537 # we need to remove start and stop from kw so they don't propagate
1537 # into a recursive call for a nested list.
1538 # into a recursive call for a nested list.
1538 start = kw['start']; del kw['start']
1539 start = kw['start']; del kw['start']
1539 stop = kw['stop']; del kw['stop']
1540 stop = kw['stop']; del kw['stop']
1540 if self.depth == 0 and 'header' in kw.keys():
1541 if self.depth == 0 and 'header' in kw.keys():
1541 print kw['header']
1542 print kw['header']
1542
1543
1543 for idx in range(start,stop):
1544 for idx in range(start,stop):
1544 elem = lst[idx]
1545 elem = lst[idx]
1545 if type(elem)==type([]):
1546 if type(elem)==type([]):
1546 self.depth += 1
1547 self.depth += 1
1547 self.__call__(elem,itpl('$pos$idx,'),**kw)
1548 self.__call__(elem,itpl('$pos$idx,'),**kw)
1548 self.depth -= 1
1549 self.depth -= 1
1549 else:
1550 else:
1550 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1551 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1551
1552
1552 nlprint = NLprinter()
1553 nlprint = NLprinter()
1553 #----------------------------------------------------------------------------
1554 #----------------------------------------------------------------------------
1554 def all_belong(candidates,checklist):
1555 def all_belong(candidates,checklist):
1555 """Check whether a list of items ALL appear in a given list of options.
1556 """Check whether a list of items ALL appear in a given list of options.
1556
1557
1557 Returns a single 1 or 0 value."""
1558 Returns a single 1 or 0 value."""
1558
1559
1559 return 1-(0 in [x in checklist for x in candidates])
1560 return 1-(0 in [x in checklist for x in candidates])
1560
1561
1561 #----------------------------------------------------------------------------
1562 #----------------------------------------------------------------------------
1562 def sort_compare(lst1,lst2,inplace = 1):
1563 def sort_compare(lst1,lst2,inplace = 1):
1563 """Sort and compare two lists.
1564 """Sort and compare two lists.
1564
1565
1565 By default it does it in place, thus modifying the lists. Use inplace = 0
1566 By default it does it in place, thus modifying the lists. Use inplace = 0
1566 to avoid that (at the cost of temporary copy creation)."""
1567 to avoid that (at the cost of temporary copy creation)."""
1567 if not inplace:
1568 if not inplace:
1568 lst1 = lst1[:]
1569 lst1 = lst1[:]
1569 lst2 = lst2[:]
1570 lst2 = lst2[:]
1570 lst1.sort(); lst2.sort()
1571 lst1.sort(); lst2.sort()
1571 return lst1 == lst2
1572 return lst1 == lst2
1572
1573
1573 #----------------------------------------------------------------------------
1574 #----------------------------------------------------------------------------
1574 def mkdict(**kwargs):
1575 def mkdict(**kwargs):
1575 """Return a dict from a keyword list.
1576 """Return a dict from a keyword list.
1576
1577
1577 It's just syntactic sugar for making ditcionary creation more convenient:
1578 It's just syntactic sugar for making ditcionary creation more convenient:
1578 # the standard way
1579 # the standard way
1579 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1580 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1580 # a cleaner way
1581 # a cleaner way
1581 >>>data = dict(red=1, green=2, blue=3)
1582 >>>data = dict(red=1, green=2, blue=3)
1582
1583
1583 If you need more than this, look at the Struct() class."""
1584 If you need more than this, look at the Struct() class."""
1584
1585
1585 return kwargs
1586 return kwargs
1586
1587
1587 #----------------------------------------------------------------------------
1588 #----------------------------------------------------------------------------
1588 def list2dict(lst):
1589 def list2dict(lst):
1589 """Takes a list of (key,value) pairs and turns it into a dict."""
1590 """Takes a list of (key,value) pairs and turns it into a dict."""
1590
1591
1591 dic = {}
1592 dic = {}
1592 for k,v in lst: dic[k] = v
1593 for k,v in lst: dic[k] = v
1593 return dic
1594 return dic
1594
1595
1595 #----------------------------------------------------------------------------
1596 #----------------------------------------------------------------------------
1596 def list2dict2(lst,default=''):
1597 def list2dict2(lst,default=''):
1597 """Takes a list and turns it into a dict.
1598 """Takes a list and turns it into a dict.
1598 Much slower than list2dict, but more versatile. This version can take
1599 Much slower than list2dict, but more versatile. This version can take
1599 lists with sublists of arbitrary length (including sclars)."""
1600 lists with sublists of arbitrary length (including sclars)."""
1600
1601
1601 dic = {}
1602 dic = {}
1602 for elem in lst:
1603 for elem in lst:
1603 if type(elem) in (types.ListType,types.TupleType):
1604 if type(elem) in (types.ListType,types.TupleType):
1604 size = len(elem)
1605 size = len(elem)
1605 if size == 0:
1606 if size == 0:
1606 pass
1607 pass
1607 elif size == 1:
1608 elif size == 1:
1608 dic[elem] = default
1609 dic[elem] = default
1609 else:
1610 else:
1610 k,v = elem[0], elem[1:]
1611 k,v = elem[0], elem[1:]
1611 if len(v) == 1: v = v[0]
1612 if len(v) == 1: v = v[0]
1612 dic[k] = v
1613 dic[k] = v
1613 else:
1614 else:
1614 dic[elem] = default
1615 dic[elem] = default
1615 return dic
1616 return dic
1616
1617
1617 #----------------------------------------------------------------------------
1618 #----------------------------------------------------------------------------
1618 def flatten(seq):
1619 def flatten(seq):
1619 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1620 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1620
1621
1621 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1622 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1622
1623
1623 # if the x=0 isn't made, a *global* variable x is left over after calling
1624 # if the x=0 isn't made, a *global* variable x is left over after calling
1624 # this function, with the value of the last element in the return
1625 # this function, with the value of the last element in the return
1625 # list. This does seem like a bug big time to me.
1626 # list. This does seem like a bug big time to me.
1626
1627
1627 # the problem is fixed with the x=0, which seems to force the creation of
1628 # the problem is fixed with the x=0, which seems to force the creation of
1628 # a local name
1629 # a local name
1629
1630
1630 x = 0
1631 x = 0
1631 return [x for subseq in seq for x in subseq]
1632 return [x for subseq in seq for x in subseq]
1632
1633
1633 #----------------------------------------------------------------------------
1634 #----------------------------------------------------------------------------
1634 def get_slice(seq,start=0,stop=None,step=1):
1635 def get_slice(seq,start=0,stop=None,step=1):
1635 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1636 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1636 if stop == None:
1637 if stop == None:
1637 stop = len(seq)
1638 stop = len(seq)
1638 item = lambda i: seq[i]
1639 item = lambda i: seq[i]
1639 return map(item,xrange(start,stop,step))
1640 return map(item,xrange(start,stop,step))
1640
1641
1641 #----------------------------------------------------------------------------
1642 #----------------------------------------------------------------------------
1642 def chop(seq,size):
1643 def chop(seq,size):
1643 """Chop a sequence into chunks of the given size."""
1644 """Chop a sequence into chunks of the given size."""
1644 chunk = lambda i: seq[i:i+size]
1645 chunk = lambda i: seq[i:i+size]
1645 return map(chunk,xrange(0,len(seq),size))
1646 return map(chunk,xrange(0,len(seq),size))
1646
1647
1647 #----------------------------------------------------------------------------
1648 #----------------------------------------------------------------------------
1648 def with(object, **args):
1649 def with(object, **args):
1649 """Set multiple attributes for an object, similar to Pascal's with.
1650 """Set multiple attributes for an object, similar to Pascal's with.
1650
1651
1651 Example:
1652 Example:
1652 with(jim,
1653 with(jim,
1653 born = 1960,
1654 born = 1960,
1654 haircolour = 'Brown',
1655 haircolour = 'Brown',
1655 eyecolour = 'Green')
1656 eyecolour = 'Green')
1656
1657
1657 Credit: Greg Ewing, in
1658 Credit: Greg Ewing, in
1658 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1659 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1659
1660
1660 object.__dict__.update(args)
1661 object.__dict__.update(args)
1661
1662
1662 #----------------------------------------------------------------------------
1663 #----------------------------------------------------------------------------
1663 def setattr_list(obj,alist,nspace = None):
1664 def setattr_list(obj,alist,nspace = None):
1664 """Set a list of attributes for an object taken from a namespace.
1665 """Set a list of attributes for an object taken from a namespace.
1665
1666
1666 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1667 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1667 alist with their values taken from nspace, which must be a dict (something
1668 alist with their values taken from nspace, which must be a dict (something
1668 like locals() will often do) If nspace isn't given, locals() of the
1669 like locals() will often do) If nspace isn't given, locals() of the
1669 *caller* is used, so in most cases you can omit it.
1670 *caller* is used, so in most cases you can omit it.
1670
1671
1671 Note that alist can be given as a string, which will be automatically
1672 Note that alist can be given as a string, which will be automatically
1672 split into a list on whitespace. If given as a list, it must be a list of
1673 split into a list on whitespace. If given as a list, it must be a list of
1673 *strings* (the variable names themselves), not of variables."""
1674 *strings* (the variable names themselves), not of variables."""
1674
1675
1675 # this grabs the local variables from the *previous* call frame -- that is
1676 # this grabs the local variables from the *previous* call frame -- that is
1676 # the locals from the function that called setattr_list().
1677 # the locals from the function that called setattr_list().
1677 # - snipped from weave.inline()
1678 # - snipped from weave.inline()
1678 if nspace is None:
1679 if nspace is None:
1679 call_frame = sys._getframe().f_back
1680 call_frame = sys._getframe().f_back
1680 nspace = call_frame.f_locals
1681 nspace = call_frame.f_locals
1681
1682
1682 if type(alist) in StringTypes:
1683 if type(alist) in StringTypes:
1683 alist = alist.split()
1684 alist = alist.split()
1684 for attr in alist:
1685 for attr in alist:
1685 val = eval(attr,nspace)
1686 val = eval(attr,nspace)
1686 setattr(obj,attr,val)
1687 setattr(obj,attr,val)
1687
1688
1688 #----------------------------------------------------------------------------
1689 #----------------------------------------------------------------------------
1689 def getattr_list(obj,alist,*args):
1690 def getattr_list(obj,alist,*args):
1690 """getattr_list(obj,alist[, default]) -> attribute list.
1691 """getattr_list(obj,alist[, default]) -> attribute list.
1691
1692
1692 Get a list of named attributes for an object. When a default argument is
1693 Get a list of named attributes for an object. When a default argument is
1693 given, it is returned when the attribute doesn't exist; without it, an
1694 given, it is returned when the attribute doesn't exist; without it, an
1694 exception is raised in that case.
1695 exception is raised in that case.
1695
1696
1696 Note that alist can be given as a string, which will be automatically
1697 Note that alist can be given as a string, which will be automatically
1697 split into a list on whitespace. If given as a list, it must be a list of
1698 split into a list on whitespace. If given as a list, it must be a list of
1698 *strings* (the variable names themselves), not of variables."""
1699 *strings* (the variable names themselves), not of variables."""
1699
1700
1700 if type(alist) in StringTypes:
1701 if type(alist) in StringTypes:
1701 alist = alist.split()
1702 alist = alist.split()
1702 if args:
1703 if args:
1703 if len(args)==1:
1704 if len(args)==1:
1704 default = args[0]
1705 default = args[0]
1705 return map(lambda attr: getattr(obj,attr,default),alist)
1706 return map(lambda attr: getattr(obj,attr,default),alist)
1706 else:
1707 else:
1707 raise ValueError,'getattr_list() takes only one optional argument'
1708 raise ValueError,'getattr_list() takes only one optional argument'
1708 else:
1709 else:
1709 return map(lambda attr: getattr(obj,attr),alist)
1710 return map(lambda attr: getattr(obj,attr),alist)
1710
1711
1711 #----------------------------------------------------------------------------
1712 #----------------------------------------------------------------------------
1712 def map_method(method,object_list,*argseq,**kw):
1713 def map_method(method,object_list,*argseq,**kw):
1713 """map_method(method,object_list,*args,**kw) -> list
1714 """map_method(method,object_list,*args,**kw) -> list
1714
1715
1715 Return a list of the results of applying the methods to the items of the
1716 Return a list of the results of applying the methods to the items of the
1716 argument sequence(s). If more than one sequence is given, the method is
1717 argument sequence(s). If more than one sequence is given, the method is
1717 called with an argument list consisting of the corresponding item of each
1718 called with an argument list consisting of the corresponding item of each
1718 sequence. All sequences must be of the same length.
1719 sequence. All sequences must be of the same length.
1719
1720
1720 Keyword arguments are passed verbatim to all objects called.
1721 Keyword arguments are passed verbatim to all objects called.
1721
1722
1722 This is Python code, so it's not nearly as fast as the builtin map()."""
1723 This is Python code, so it's not nearly as fast as the builtin map()."""
1723
1724
1724 out_list = []
1725 out_list = []
1725 idx = 0
1726 idx = 0
1726 for object in object_list:
1727 for object in object_list:
1727 try:
1728 try:
1728 handler = getattr(object, method)
1729 handler = getattr(object, method)
1729 except AttributeError:
1730 except AttributeError:
1730 out_list.append(None)
1731 out_list.append(None)
1731 else:
1732 else:
1732 if argseq:
1733 if argseq:
1733 args = map(lambda lst:lst[idx],argseq)
1734 args = map(lambda lst:lst[idx],argseq)
1734 #print 'ob',object,'hand',handler,'ar',args # dbg
1735 #print 'ob',object,'hand',handler,'ar',args # dbg
1735 out_list.append(handler(args,**kw))
1736 out_list.append(handler(args,**kw))
1736 else:
1737 else:
1737 out_list.append(handler(**kw))
1738 out_list.append(handler(**kw))
1738 idx += 1
1739 idx += 1
1739 return out_list
1740 return out_list
1740
1741
1741 #----------------------------------------------------------------------------
1742 #----------------------------------------------------------------------------
1742 def import_fail_info(mod_name,fns=None):
1743 def import_fail_info(mod_name,fns=None):
1743 """Inform load failure for a module."""
1744 """Inform load failure for a module."""
1744
1745
1745 if fns == None:
1746 if fns == None:
1746 warn("Loading of %s failed.\n" % (mod_name,))
1747 warn("Loading of %s failed.\n" % (mod_name,))
1747 else:
1748 else:
1748 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1749 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1749
1750
1750 #----------------------------------------------------------------------------
1751 #----------------------------------------------------------------------------
1751 # Proposed popitem() extension, written as a method
1752 # Proposed popitem() extension, written as a method
1752
1753
1753 class NotGiven: pass
1754 class NotGiven: pass
1754
1755
1755 def popkey(dct,key,default=NotGiven):
1756 def popkey(dct,key,default=NotGiven):
1756 """Return dct[key] and delete dct[key].
1757 """Return dct[key] and delete dct[key].
1757
1758
1758 If default is given, return it if dct[key] doesn't exist, otherwise raise
1759 If default is given, return it if dct[key] doesn't exist, otherwise raise
1759 KeyError. """
1760 KeyError. """
1760
1761
1761 try:
1762 try:
1762 val = dct[key]
1763 val = dct[key]
1763 except KeyError:
1764 except KeyError:
1764 if default is NotGiven:
1765 if default is NotGiven:
1765 raise
1766 raise
1766 else:
1767 else:
1767 return default
1768 return default
1768 else:
1769 else:
1769 del dct[key]
1770 del dct[key]
1770 return val
1771 return val
1771 #*************************** end of file <genutils.py> **********************
1772 #*************************** end of file <genutils.py> **********************
1772
1773
@@ -1,174 +1,174 b''
1 ''' IPython customization API
1 ''' IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi as ip
28 import IPython.ipapi as ip
29
29
30 def ankka_f(self, arg):
30 def ankka_f(self, arg):
31 print "Ankka",self,"says uppercase:",arg.upper()
31 print "Ankka",self,"says uppercase:",arg.upper()
32
32
33 ip.expose_magic("ankka",ankka_f)
33 ip.expose_magic("ankka",ankka_f)
34
34
35 ip.magic('alias sayhi echo "Testing, hi ok"')
35 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias helloworld echo "Hello world"')
36 ip.magic('alias helloworld echo "Hello world"')
37 ip.system('pwd')
37 ip.system('pwd')
38
38
39 ip.ex('import re')
39 ip.ex('import re')
40 ip.ex("""
40 ip.ex("""
41 def funcci(a,b):
41 def funcci(a,b):
42 print a+b
42 print a+b
43 print funcci(3,4)
43 print funcci(3,4)
44 """)
44 """)
45 ip.ex("funcci(348,9)")
45 ip.ex("funcci(348,9)")
46
46
47 def jed_editor(self,filename, linenum=None):
47 def jed_editor(self,filename, linenum=None):
48 print "Calling my own editor, jed ... via hook!"
48 print "Calling my own editor, jed ... via hook!"
49 import os
49 import os
50 if linenum is None: linenum = 0
50 if linenum is None: linenum = 0
51 os.system('jed +%d %s' % (linenum, filename))
51 os.system('jed +%d %s' % (linenum, filename))
52 print "exiting jed"
52 print "exiting jed"
53
53
54 ip.set_hook('editor',jed_editor)
54 ip.set_hook('editor',jed_editor)
55
55
56 o = ip.options()
56 o = ip.options()
57 o.autocall = 2 # FULL autocall mode
57 o.autocall = 2 # FULL autocall mode
58
58
59 print "done!"
59 print "done!"
60
60
61 '''
61 '''
62
62
63
63
64 class TryNext(Exception):
64 class TryNext(Exception):
65 """ Try next hook exception.
65 """ Try next hook exception.
66
66
67 Raise this in your hook function to indicate that the next
67 Raise this in your hook function to indicate that the next
68 hook handler should be used to handle the operation.
68 hook handler should be used to handle the operation.
69 """
69 """
70
70
71
71
72
72
73 __IP = None
73 __IP = None
74
74
75 def _init_with_shell(ip):
75 def _init_with_shell(ip):
76 global magic
76 global magic
77 magic = ip.ipmagic
77 magic = ip.ipmagic
78 global system
78 global system
79 system = ip.ipsystem
79 system = ip.ipsystem
80 global set_hook
80 global set_hook
81 set_hook = ip.set_hook
81 set_hook = ip.set_hook
82
82
83 global __IP
83 global __IP
84 __IP = ip
84 __IP = ip
85
85
86 def options():
86 def options():
87 """ All configurable variables """
87 """ All configurable variables """
88 return __IP.rc
88 return __IP.rc
89
89
90 def user_ns():
90 def user_ns():
91 return __IP.user_ns
91 return __IP.user_ns
92
92
93 def expose_magic(magicname, func):
93 def expose_magic(magicname, func):
94 ''' Expose own function as magic function for ipython
94 ''' Expose own function as magic function for ipython
95
95
96 def foo_impl(self,parameter_s=''):
96 def foo_impl(self,parameter_s=''):
97 """My very own magic!. (Use docstrings, IPython reads them)."""
97 """My very own magic!. (Use docstrings, IPython reads them)."""
98 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
98 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
99 print 'The self object is:',self
99 print 'The self object is:',self
100
100
101 ipapi.expose_magic("foo",foo_impl)
101 ipapi.expose_magic("foo",foo_impl)
102 '''
102 '''
103
103
104 from IPython import Magic
104 from IPython import Magic
105 import new
105 import new
106 im = new.instancemethod(func,__IP, __IP.__class__)
106 im = new.instancemethod(func,__IP, __IP.__class__)
107 setattr(__IP, "magic_" + magicname, im)
107 setattr(__IP, "magic_" + magicname, im)
108
108
109 class asmagic:
109 class asmagic:
110 """ Decorator for exposing magics in a friendly 2.4 decorator form
110 """ Decorator for exposing magics in a friendly 2.4 decorator form
111
111
112 @ip.asmagic("foo")
112 @ip.asmagic("foo")
113 def f(self,arg):
113 def f(self,arg):
114 pring "arg given:",arg
114 pring "arg given:",arg
115
115
116 After this, %foo is a magic function.
116 After this, %foo is a magic function.
117 """
117 """
118
118
119 def __init__(self,magicname):
119 def __init__(self,magicname):
120 self.name = magicname
120 self.name = magicname
121
121
122 def __call__(self,f):
122 def __call__(self,f):
123 expose_magic(self.name, f)
123 expose_magic(self.name, f)
124 return f
124 return f
125
125
126 class ashook:
126 class ashook:
127 """ Decorator for exposing magics in a friendly 2.4 decorator form
127 """ Decorator for exposing magics in a friendly 2.4 decorator form
128
128
129 @ip.ashook("editor")
129 @ip.ashook("editor")
130 def jed_editor(self,filename, linenum=None):
130 def jed_editor(self,filename, linenum=None):
131 import os
131 import os
132 if linenum is None: linenum = 0
132 if linenum is None: linenum = 0
133 os.system('jed +%d %s' % (linenum, filename))
133 os.system('jed +%d %s' % (linenum, filename))
134
134
135 """
135 """
136
136
137 def __init__(self,name,priority=50):
137 def __init__(self,name,priority=50):
138 self.name = name
138 self.name = name
139 self.prio = priority
139 self.prio = priority
140
140
141 def __call__(self,f):
141 def __call__(self,f):
142 set_hook(self.name, f, self.prio)
142 set_hook(self.name, f, self.prio)
143 return f
143 return f
144
144
145
145
146 def ex(cmd):
146 def ex(cmd):
147 """ Execute a normal python statement in user namespace """
147 """ Execute a normal python statement in user namespace """
148 exec cmd in user_ns()
148 exec cmd in user_ns()
149
149
150 def ev(expr):
150 def ev(expr):
151 """ Evaluate python expression expr in user namespace
151 """ Evaluate python expression expr in user namespace
152
152
153 Returns the result """
153 Returns the result """
154 return eval(expr,user_ns())
154 return eval(expr,user_ns())
155
155
156 def launch_new_instance():
156 def launch_new_instance():
157 """ Creata and start a new ipython instance.
157 """ Create and start a new ipython instance.
158
158
159 This can be called even without having an already initialized
159 This can be called even without having an already initialized
160 ipython session running.
160 ipython session running.
161
161
162 """
162 """
163 import IPython
163 import IPython
164
164
165 IPython.Shell.start().mainloop()
165 IPython.Shell.start().mainloop()
166
166
167 def is_ipython_session():
167 def is_ipython_session():
168 """ Return a true value if running inside IPython.
168 """ Return a true value if running inside IPython.
169
169
170 """
170 """
171
171
172 # Yes, this is the shell object or None - however, it's an implementation
172 # Yes, this is the shell object or None - however, it's an implementation
173 # detail and should not be relied on, only truth value matters.
173 # detail and should not be relied on, only truth value matters.
174 return __IP
174 return __IP
@@ -1,2229 +1,2234 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.3 or newer.
5 Requires Python 2.3 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 1058 2006-01-22 14:30:01Z vivainio $
9 $Id: iplib.py 1077 2006-01-24 18:15:27Z vivainio $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __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 tempfile
58 import tempfile
59 import traceback
59 import traceback
60 import types
60 import types
61
61
62 from pprint import pprint, pformat
62 from pprint import pprint, pformat
63
63
64 # IPython's own modules
64 # IPython's own modules
65 import IPython
65 import IPython
66 from IPython import OInspect,PyColorize,ultraTB
66 from IPython import OInspect,PyColorize,ultraTB
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 from IPython.FakeModule import FakeModule
68 from IPython.FakeModule import FakeModule
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 from IPython.Logger import Logger
70 from IPython.Logger import Logger
71 from IPython.Magic import Magic
71 from IPython.Magic import Magic
72 from IPython.Prompts import CachedOutput
72 from IPython.Prompts import CachedOutput
73 from IPython.ipstruct import Struct
73 from IPython.ipstruct import Struct
74 from IPython.background_jobs import BackgroundJobManager
74 from IPython.background_jobs import BackgroundJobManager
75 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.usage import cmd_line_usage,interactive_usage
76 from IPython.genutils import *
76 from IPython.genutils import *
77 import IPython.ipapi
77 import IPython.ipapi
78
78
79 # Globals
79 # Globals
80
80
81 # store the builtin raw_input globally, and use this always, in case user code
81 # store the builtin raw_input globally, and use this always, in case user code
82 # overwrites it (like wx.py.PyShell does)
82 # overwrites it (like wx.py.PyShell does)
83 raw_input_original = raw_input
83 raw_input_original = raw_input
84
84
85 # compiled regexps for autoindent management
85 # compiled regexps for autoindent management
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87
87
88
88
89 #****************************************************************************
89 #****************************************************************************
90 # Some utility function definitions
90 # Some utility function definitions
91
91
92 ini_spaces_re = re.compile(r'^(\s+)')
92 ini_spaces_re = re.compile(r'^(\s+)')
93
93
94 def num_ini_spaces(strng):
94 def num_ini_spaces(strng):
95 """Return the number of initial spaces in a string"""
95 """Return the number of initial spaces in a string"""
96
96
97 ini_spaces = ini_spaces_re.match(strng)
97 ini_spaces = ini_spaces_re.match(strng)
98 if ini_spaces:
98 if ini_spaces:
99 return ini_spaces.end()
99 return ini_spaces.end()
100 else:
100 else:
101 return 0
101 return 0
102
102
103 def softspace(file, newvalue):
103 def softspace(file, newvalue):
104 """Copied from code.py, to remove the dependency"""
104 """Copied from code.py, to remove the dependency"""
105
105
106 oldvalue = 0
106 oldvalue = 0
107 try:
107 try:
108 oldvalue = file.softspace
108 oldvalue = file.softspace
109 except AttributeError:
109 except AttributeError:
110 pass
110 pass
111 try:
111 try:
112 file.softspace = newvalue
112 file.softspace = newvalue
113 except (AttributeError, TypeError):
113 except (AttributeError, TypeError):
114 # "attribute-less object" or "read-only attributes"
114 # "attribute-less object" or "read-only attributes"
115 pass
115 pass
116 return oldvalue
116 return oldvalue
117
117
118
118
119 #****************************************************************************
119 #****************************************************************************
120 # Local use exceptions
120 # Local use exceptions
121 class SpaceInInput(exceptions.Exception): pass
121 class SpaceInInput(exceptions.Exception): pass
122
122
123
123
124 #****************************************************************************
124 #****************************************************************************
125 # Local use classes
125 # Local use classes
126 class Bunch: pass
126 class Bunch: pass
127
127
128 class Undefined: pass
128 class Undefined: pass
129
129
130 class InputList(list):
130 class InputList(list):
131 """Class to store user input.
131 """Class to store user input.
132
132
133 It's basically a list, but slices return a string instead of a list, thus
133 It's basically a list, but slices return a string instead of a list, thus
134 allowing things like (assuming 'In' is an instance):
134 allowing things like (assuming 'In' is an instance):
135
135
136 exec In[4:7]
136 exec In[4:7]
137
137
138 or
138 or
139
139
140 exec In[5:9] + In[14] + In[21:25]"""
140 exec In[5:9] + In[14] + In[21:25]"""
141
141
142 def __getslice__(self,i,j):
142 def __getslice__(self,i,j):
143 return ''.join(list.__getslice__(self,i,j))
143 return ''.join(list.__getslice__(self,i,j))
144
144
145 class SyntaxTB(ultraTB.ListTB):
145 class SyntaxTB(ultraTB.ListTB):
146 """Extension which holds some state: the last exception value"""
146 """Extension which holds some state: the last exception value"""
147
147
148 def __init__(self,color_scheme = 'NoColor'):
148 def __init__(self,color_scheme = 'NoColor'):
149 ultraTB.ListTB.__init__(self,color_scheme)
149 ultraTB.ListTB.__init__(self,color_scheme)
150 self.last_syntax_error = None
150 self.last_syntax_error = None
151
151
152 def __call__(self, etype, value, elist):
152 def __call__(self, etype, value, elist):
153 self.last_syntax_error = value
153 self.last_syntax_error = value
154 ultraTB.ListTB.__call__(self,etype,value,elist)
154 ultraTB.ListTB.__call__(self,etype,value,elist)
155
155
156 def clear_err_state(self):
156 def clear_err_state(self):
157 """Return the current error state and clear it"""
157 """Return the current error state and clear it"""
158 e = self.last_syntax_error
158 e = self.last_syntax_error
159 self.last_syntax_error = None
159 self.last_syntax_error = None
160 return e
160 return e
161
161
162 #****************************************************************************
162 #****************************************************************************
163 # Main IPython class
163 # Main IPython class
164
164
165 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
165 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
166 # until a full rewrite is made. I've cleaned all cross-class uses of
166 # until a full rewrite is made. I've cleaned all cross-class uses of
167 # attributes and methods, but too much user code out there relies on the
167 # attributes and methods, but too much user code out there relies on the
168 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
168 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
169 #
169 #
170 # But at least now, all the pieces have been separated and we could, in
170 # But at least now, all the pieces have been separated and we could, in
171 # principle, stop using the mixin. This will ease the transition to the
171 # principle, stop using the mixin. This will ease the transition to the
172 # chainsaw branch.
172 # chainsaw branch.
173
173
174 # For reference, the following is the list of 'self.foo' uses in the Magic
174 # For reference, the following is the list of 'self.foo' uses in the Magic
175 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
175 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
176 # class, to prevent clashes.
176 # class, to prevent clashes.
177
177
178 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
178 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
179 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
179 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
180 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
180 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
181 # 'self.value']
181 # 'self.value']
182
182
183 class InteractiveShell(object,Magic):
183 class InteractiveShell(object,Magic):
184 """An enhanced console for Python."""
184 """An enhanced console for Python."""
185
185
186 # class attribute to indicate whether the class supports threads or not.
186 # class attribute to indicate whether the class supports threads or not.
187 # Subclasses with thread support should override this as needed.
187 # Subclasses with thread support should override this as needed.
188 isthreaded = False
188 isthreaded = False
189
189
190 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
190 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
191 user_ns = None,user_global_ns=None,banner2='',
191 user_ns = None,user_global_ns=None,banner2='',
192 custom_exceptions=((),None),embedded=False):
192 custom_exceptions=((),None),embedded=False):
193
193
194 # log system
194 # log system
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
196
196
197 # introduce ourselves to IPython.ipapi which is uncallable
197 # introduce ourselves to IPython.ipapi which is uncallable
198 # before it knows an InteractiveShell object.
198 # before it knows an InteractiveShell object.
199 IPython.ipapi._init_with_shell(self)
199 IPython.ipapi._init_with_shell(self)
200
200
201 # some minimal strict typechecks. For some core data structures, I
201 # some minimal strict typechecks. For some core data structures, I
202 # want actual basic python types, not just anything that looks like
202 # want actual basic python types, not just anything that looks like
203 # one. This is especially true for namespaces.
203 # one. This is especially true for namespaces.
204 for ns in (user_ns,user_global_ns):
204 for ns in (user_ns,user_global_ns):
205 if ns is not None and type(ns) != types.DictType:
205 if ns is not None and type(ns) != types.DictType:
206 raise TypeError,'namespace must be a dictionary'
206 raise TypeError,'namespace must be a dictionary'
207
207
208 # Job manager (for jobs run as background threads)
208 # Job manager (for jobs run as background threads)
209 self.jobs = BackgroundJobManager()
209 self.jobs = BackgroundJobManager()
210
210
211 # track which builtins we add, so we can clean up later
211 # track which builtins we add, so we can clean up later
212 self.builtins_added = {}
212 self.builtins_added = {}
213 # This method will add the necessary builtins for operation, but
213 # This method will add the necessary builtins for operation, but
214 # tracking what it did via the builtins_added dict.
214 # tracking what it did via the builtins_added dict.
215 self.add_builtins()
215 self.add_builtins()
216
216
217 # Do the intuitively correct thing for quit/exit: we remove the
217 # Do the intuitively correct thing for quit/exit: we remove the
218 # builtins if they exist, and our own magics will deal with this
218 # builtins if they exist, and our own magics will deal with this
219 try:
219 try:
220 del __builtin__.exit, __builtin__.quit
220 del __builtin__.exit, __builtin__.quit
221 except AttributeError:
221 except AttributeError:
222 pass
222 pass
223
223
224 # Store the actual shell's name
224 # Store the actual shell's name
225 self.name = name
225 self.name = name
226
226
227 # We need to know whether the instance is meant for embedding, since
227 # We need to know whether the instance is meant for embedding, since
228 # global/local namespaces need to be handled differently in that case
228 # global/local namespaces need to be handled differently in that case
229 self.embedded = embedded
229 self.embedded = embedded
230
230
231 # command compiler
231 # command compiler
232 self.compile = codeop.CommandCompiler()
232 self.compile = codeop.CommandCompiler()
233
233
234 # User input buffer
234 # User input buffer
235 self.buffer = []
235 self.buffer = []
236
236
237 # Default name given in compilation of code
237 # Default name given in compilation of code
238 self.filename = '<ipython console>'
238 self.filename = '<ipython console>'
239
239
240 # Make an empty namespace, which extension writers can rely on both
240 # Make an empty namespace, which extension writers can rely on both
241 # existing and NEVER being used by ipython itself. This gives them a
241 # existing and NEVER being used by ipython itself. This gives them a
242 # convenient location for storing additional information and state
242 # convenient location for storing additional information and state
243 # their extensions may require, without fear of collisions with other
243 # their extensions may require, without fear of collisions with other
244 # ipython names that may develop later.
244 # ipython names that may develop later.
245 self.meta = Bunch()
245 self.meta = Bunch()
246
246
247 # Create the namespace where the user will operate. user_ns is
247 # Create the namespace where the user will operate. user_ns is
248 # normally the only one used, and it is passed to the exec calls as
248 # normally the only one used, and it is passed to the exec calls as
249 # the locals argument. But we do carry a user_global_ns namespace
249 # the locals argument. But we do carry a user_global_ns namespace
250 # given as the exec 'globals' argument, This is useful in embedding
250 # given as the exec 'globals' argument, This is useful in embedding
251 # situations where the ipython shell opens in a context where the
251 # situations where the ipython shell opens in a context where the
252 # distinction between locals and globals is meaningful.
252 # distinction between locals and globals is meaningful.
253
253
254 # FIXME. For some strange reason, __builtins__ is showing up at user
254 # FIXME. For some strange reason, __builtins__ is showing up at user
255 # level as a dict instead of a module. This is a manual fix, but I
255 # level as a dict instead of a module. This is a manual fix, but I
256 # should really track down where the problem is coming from. Alex
256 # should really track down where the problem is coming from. Alex
257 # Schmolck reported this problem first.
257 # Schmolck reported this problem first.
258
258
259 # A useful post by Alex Martelli on this topic:
259 # A useful post by Alex Martelli on this topic:
260 # Re: inconsistent value from __builtins__
260 # Re: inconsistent value from __builtins__
261 # Von: Alex Martelli <aleaxit@yahoo.com>
261 # Von: Alex Martelli <aleaxit@yahoo.com>
262 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
262 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
263 # Gruppen: comp.lang.python
263 # Gruppen: comp.lang.python
264
264
265 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
265 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
266 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
266 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
267 # > <type 'dict'>
267 # > <type 'dict'>
268 # > >>> print type(__builtins__)
268 # > >>> print type(__builtins__)
269 # > <type 'module'>
269 # > <type 'module'>
270 # > Is this difference in return value intentional?
270 # > Is this difference in return value intentional?
271
271
272 # Well, it's documented that '__builtins__' can be either a dictionary
272 # Well, it's documented that '__builtins__' can be either a dictionary
273 # or a module, and it's been that way for a long time. Whether it's
273 # or a module, and it's been that way for a long time. Whether it's
274 # intentional (or sensible), I don't know. In any case, the idea is
274 # intentional (or sensible), I don't know. In any case, the idea is
275 # that if you need to access the built-in namespace directly, you
275 # that if you need to access the built-in namespace directly, you
276 # should start with "import __builtin__" (note, no 's') which will
276 # should start with "import __builtin__" (note, no 's') which will
277 # definitely give you a module. Yeah, it's somewhat confusing:-(.
277 # definitely give you a module. Yeah, it's somewhat confusing:-(.
278
278
279 if user_ns is None:
279 if user_ns is None:
280 # Set __name__ to __main__ to better match the behavior of the
280 # Set __name__ to __main__ to better match the behavior of the
281 # normal interpreter.
281 # normal interpreter.
282 user_ns = {'__name__' :'__main__',
282 user_ns = {'__name__' :'__main__',
283 '__builtins__' : __builtin__,
283 '__builtins__' : __builtin__,
284 }
284 }
285
285
286 if user_global_ns is None:
286 if user_global_ns is None:
287 user_global_ns = {}
287 user_global_ns = {}
288
288
289 # Assign namespaces
289 # Assign namespaces
290 # This is the namespace where all normal user variables live
290 # This is the namespace where all normal user variables live
291 self.user_ns = user_ns
291 self.user_ns = user_ns
292 # Embedded instances require a separate namespace for globals.
292 # Embedded instances require a separate namespace for globals.
293 # Normally this one is unused by non-embedded instances.
293 # Normally this one is unused by non-embedded instances.
294 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
295 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
296 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
297 self.internal_ns = {}
297 self.internal_ns = {}
298
298
299 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
300 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
301 # of positional arguments of the alias.
301 # of positional arguments of the alias.
302 self.alias_table = {}
302 self.alias_table = {}
303
303
304 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
305 # introspection facilities can search easily.
305 # introspection facilities can search easily.
306 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
307 'user_global':user_global_ns,
307 'user_global':user_global_ns,
308 'alias':self.alias_table,
308 'alias':self.alias_table,
309 'internal':self.internal_ns,
309 'internal':self.internal_ns,
310 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
311 }
311 }
312
312
313 # The user namespace MUST have a pointer to the shell itself.
313 # The user namespace MUST have a pointer to the shell itself.
314 self.user_ns[name] = self
314 self.user_ns[name] = self
315
315
316 # We need to insert into sys.modules something that looks like a
316 # We need to insert into sys.modules something that looks like a
317 # module but which accesses the IPython namespace, for shelve and
317 # module but which accesses the IPython namespace, for shelve and
318 # pickle to work interactively. Normally they rely on getting
318 # pickle to work interactively. Normally they rely on getting
319 # everything out of __main__, but for embedding purposes each IPython
319 # everything out of __main__, but for embedding purposes each IPython
320 # instance has its own private namespace, so we can't go shoving
320 # instance has its own private namespace, so we can't go shoving
321 # everything into __main__.
321 # everything into __main__.
322
322
323 # note, however, that we should only do this for non-embedded
323 # note, however, that we should only do this for non-embedded
324 # ipythons, which really mimic the __main__.__dict__ with their own
324 # ipythons, which really mimic the __main__.__dict__ with their own
325 # namespace. Embedded instances, on the other hand, should not do
325 # namespace. Embedded instances, on the other hand, should not do
326 # this because they need to manage the user local/global namespaces
326 # this because they need to manage the user local/global namespaces
327 # only, but they live within a 'normal' __main__ (meaning, they
327 # only, but they live within a 'normal' __main__ (meaning, they
328 # shouldn't overtake the execution environment of the script they're
328 # shouldn't overtake the execution environment of the script they're
329 # embedded in).
329 # embedded in).
330
330
331 if not embedded:
331 if not embedded:
332 try:
332 try:
333 main_name = self.user_ns['__name__']
333 main_name = self.user_ns['__name__']
334 except KeyError:
334 except KeyError:
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 else:
336 else:
337 #print "pickle hack in place" # dbg
337 #print "pickle hack in place" # dbg
338 #print 'main_name:',main_name # dbg
338 #print 'main_name:',main_name # dbg
339 sys.modules[main_name] = FakeModule(self.user_ns)
339 sys.modules[main_name] = FakeModule(self.user_ns)
340
340
341 # List of input with multi-line handling.
341 # List of input with multi-line handling.
342 # Fill its zero entry, user counter starts at 1
342 # Fill its zero entry, user counter starts at 1
343 self.input_hist = InputList(['\n'])
343 self.input_hist = InputList(['\n'])
344 # This one will hold the 'raw' input history, without any
345 # pre-processing. This will allow users to retrieve the input just as
346 # it was exactly typed in by the user, with %hist -r.
347 self.input_hist_raw = InputList(['\n'])
344
348
345 # list of visited directories
349 # list of visited directories
346 try:
350 try:
347 self.dir_hist = [os.getcwd()]
351 self.dir_hist = [os.getcwd()]
348 except IOError, e:
352 except IOError, e:
349 self.dir_hist = []
353 self.dir_hist = []
350
354
351 # dict of output history
355 # dict of output history
352 self.output_hist = {}
356 self.output_hist = {}
353
357
354 # dict of things NOT to alias (keywords, builtins and some magics)
358 # dict of things NOT to alias (keywords, builtins and some magics)
355 no_alias = {}
359 no_alias = {}
356 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
357 for key in keyword.kwlist + no_alias_magics:
361 for key in keyword.kwlist + no_alias_magics:
358 no_alias[key] = 1
362 no_alias[key] = 1
359 no_alias.update(__builtin__.__dict__)
363 no_alias.update(__builtin__.__dict__)
360 self.no_alias = no_alias
364 self.no_alias = no_alias
361
365
362 # make global variables for user access to these
366 # make global variables for user access to these
363 self.user_ns['_ih'] = self.input_hist
367 self.user_ns['_ih'] = self.input_hist
364 self.user_ns['_oh'] = self.output_hist
368 self.user_ns['_oh'] = self.output_hist
365 self.user_ns['_dh'] = self.dir_hist
369 self.user_ns['_dh'] = self.dir_hist
366
370
367 # user aliases to input and output histories
371 # user aliases to input and output histories
368 self.user_ns['In'] = self.input_hist
372 self.user_ns['In'] = self.input_hist
369 self.user_ns['Out'] = self.output_hist
373 self.user_ns['Out'] = self.output_hist
370
374
371 # Object variable to store code object waiting execution. This is
375 # Object variable to store code object waiting execution. This is
372 # used mainly by the multithreaded shells, but it can come in handy in
376 # used mainly by the multithreaded shells, but it can come in handy in
373 # other situations. No need to use a Queue here, since it's a single
377 # other situations. No need to use a Queue here, since it's a single
374 # item which gets cleared once run.
378 # item which gets cleared once run.
375 self.code_to_run = None
379 self.code_to_run = None
376
380
377 # escapes for automatic behavior on the command line
381 # escapes for automatic behavior on the command line
378 self.ESC_SHELL = '!'
382 self.ESC_SHELL = '!'
379 self.ESC_HELP = '?'
383 self.ESC_HELP = '?'
380 self.ESC_MAGIC = '%'
384 self.ESC_MAGIC = '%'
381 self.ESC_QUOTE = ','
385 self.ESC_QUOTE = ','
382 self.ESC_QUOTE2 = ';'
386 self.ESC_QUOTE2 = ';'
383 self.ESC_PAREN = '/'
387 self.ESC_PAREN = '/'
384
388
385 # And their associated handlers
389 # And their associated handlers
386 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
387 self.ESC_QUOTE : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
388 self.ESC_QUOTE2 : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
389 self.ESC_MAGIC : self.handle_magic,
393 self.ESC_MAGIC : self.handle_magic,
390 self.ESC_HELP : self.handle_help,
394 self.ESC_HELP : self.handle_help,
391 self.ESC_SHELL : self.handle_shell_escape,
395 self.ESC_SHELL : self.handle_shell_escape,
392 }
396 }
393
397
394 # class initializations
398 # class initializations
395 Magic.__init__(self,self)
399 Magic.__init__(self,self)
396
400
397 # Python source parser/formatter for syntax highlighting
401 # Python source parser/formatter for syntax highlighting
398 pyformat = PyColorize.Parser().format
402 pyformat = PyColorize.Parser().format
399 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
400
404
401 # hooks holds pointers used for user-side customizations
405 # hooks holds pointers used for user-side customizations
402 self.hooks = Struct()
406 self.hooks = Struct()
403
407
404 # Set all default hooks, defined in the IPython.hooks module.
408 # Set all default hooks, defined in the IPython.hooks module.
405 hooks = IPython.hooks
409 hooks = IPython.hooks
406 for hook_name in hooks.__all__:
410 for hook_name in hooks.__all__:
407 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
411 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
408 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
412 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
409
413
410 # Flag to mark unconditional exit
414 # Flag to mark unconditional exit
411 self.exit_now = False
415 self.exit_now = False
412
416
413 self.usage_min = """\
417 self.usage_min = """\
414 An enhanced console for Python.
418 An enhanced console for Python.
415 Some of its features are:
419 Some of its features are:
416 - Readline support if the readline library is present.
420 - Readline support if the readline library is present.
417 - Tab completion in the local namespace.
421 - Tab completion in the local namespace.
418 - Logging of input, see command-line options.
422 - Logging of input, see command-line options.
419 - System shell escape via ! , eg !ls.
423 - System shell escape via ! , eg !ls.
420 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
424 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
421 - Keeps track of locally defined variables via %who, %whos.
425 - Keeps track of locally defined variables via %who, %whos.
422 - Show object information with a ? eg ?x or x? (use ?? for more info).
426 - Show object information with a ? eg ?x or x? (use ?? for more info).
423 """
427 """
424 if usage: self.usage = usage
428 if usage: self.usage = usage
425 else: self.usage = self.usage_min
429 else: self.usage = self.usage_min
426
430
427 # Storage
431 # Storage
428 self.rc = rc # This will hold all configuration information
432 self.rc = rc # This will hold all configuration information
429 self.pager = 'less'
433 self.pager = 'less'
430 # temporary files used for various purposes. Deleted at exit.
434 # temporary files used for various purposes. Deleted at exit.
431 self.tempfiles = []
435 self.tempfiles = []
432
436
433 # Keep track of readline usage (later set by init_readline)
437 # Keep track of readline usage (later set by init_readline)
434 self.has_readline = False
438 self.has_readline = False
435
439
436 # template for logfile headers. It gets resolved at runtime by the
440 # template for logfile headers. It gets resolved at runtime by the
437 # logstart method.
441 # logstart method.
438 self.loghead_tpl = \
442 self.loghead_tpl = \
439 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
443 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
440 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
444 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
441 #log# opts = %s
445 #log# opts = %s
442 #log# args = %s
446 #log# args = %s
443 #log# It is safe to make manual edits below here.
447 #log# It is safe to make manual edits below here.
444 #log#-----------------------------------------------------------------------
448 #log#-----------------------------------------------------------------------
445 """
449 """
446 # for pushd/popd management
450 # for pushd/popd management
447 try:
451 try:
448 self.home_dir = get_home_dir()
452 self.home_dir = get_home_dir()
449 except HomeDirError,msg:
453 except HomeDirError,msg:
450 fatal(msg)
454 fatal(msg)
451
455
452 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
456 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
453
457
454 # Functions to call the underlying shell.
458 # Functions to call the underlying shell.
455
459
456 # utility to expand user variables via Itpl
460 # utility to expand user variables via Itpl
457 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
461 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
458 self.user_ns))
462 self.user_ns))
459 # The first is similar to os.system, but it doesn't return a value,
463 # The first is similar to os.system, but it doesn't return a value,
460 # and it allows interpolation of variables in the user's namespace.
464 # and it allows interpolation of variables in the user's namespace.
461 self.system = lambda cmd: shell(self.var_expand(cmd),
465 self.system = lambda cmd: shell(self.var_expand(cmd),
462 header='IPython system call: ',
466 header='IPython system call: ',
463 verbose=self.rc.system_verbose)
467 verbose=self.rc.system_verbose)
464 # These are for getoutput and getoutputerror:
468 # These are for getoutput and getoutputerror:
465 self.getoutput = lambda cmd: \
469 self.getoutput = lambda cmd: \
466 getoutput(self.var_expand(cmd),
470 getoutput(self.var_expand(cmd),
467 header='IPython system call: ',
471 header='IPython system call: ',
468 verbose=self.rc.system_verbose)
472 verbose=self.rc.system_verbose)
469 self.getoutputerror = lambda cmd: \
473 self.getoutputerror = lambda cmd: \
470 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
474 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
471 self.user_ns)),
475 self.user_ns)),
472 header='IPython system call: ',
476 header='IPython system call: ',
473 verbose=self.rc.system_verbose)
477 verbose=self.rc.system_verbose)
474
478
475 # RegExp for splitting line contents into pre-char//first
479 # RegExp for splitting line contents into pre-char//first
476 # word-method//rest. For clarity, each group in on one line.
480 # word-method//rest. For clarity, each group in on one line.
477
481
478 # WARNING: update the regexp if the above escapes are changed, as they
482 # WARNING: update the regexp if the above escapes are changed, as they
479 # are hardwired in.
483 # are hardwired in.
480
484
481 # Don't get carried away with trying to make the autocalling catch too
485 # Don't get carried away with trying to make the autocalling catch too
482 # much: it's better to be conservative rather than to trigger hidden
486 # much: it's better to be conservative rather than to trigger hidden
483 # evals() somewhere and end up causing side effects.
487 # evals() somewhere and end up causing side effects.
484
488
485 self.line_split = re.compile(r'^([\s*,;/])'
489 self.line_split = re.compile(r'^([\s*,;/])'
486 r'([\?\w\.]+\w*\s*)'
490 r'([\?\w\.]+\w*\s*)'
487 r'(\(?.*$)')
491 r'(\(?.*$)')
488
492
489 # Original re, keep around for a while in case changes break something
493 # Original re, keep around for a while in case changes break something
490 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
494 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
491 # r'(\s*[\?\w\.]+\w*\s*)'
495 # r'(\s*[\?\w\.]+\w*\s*)'
492 # r'(\(?.*$)')
496 # r'(\(?.*$)')
493
497
494 # RegExp to identify potential function names
498 # RegExp to identify potential function names
495 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
499 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
496
500
497 # RegExp to exclude strings with this start from autocalling. In
501 # RegExp to exclude strings with this start from autocalling. In
498 # particular, all binary operators should be excluded, so that if foo
502 # particular, all binary operators should be excluded, so that if foo
499 # is callable, foo OP bar doesn't become foo(OP bar), which is
503 # is callable, foo OP bar doesn't become foo(OP bar), which is
500 # invalid. The characters '!=()' don't need to be checked for, as the
504 # invalid. The characters '!=()' don't need to be checked for, as the
501 # _prefilter routine explicitely does so, to catch direct calls and
505 # _prefilter routine explicitely does so, to catch direct calls and
502 # rebindings of existing names.
506 # rebindings of existing names.
503
507
504 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
508 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
505 # it affects the rest of the group in square brackets.
509 # it affects the rest of the group in square brackets.
506 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
510 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
507 '|^is |^not |^in |^and |^or ')
511 '|^is |^not |^in |^and |^or ')
508
512
509 # try to catch also methods for stuff in lists/tuples/dicts: off
513 # try to catch also methods for stuff in lists/tuples/dicts: off
510 # (experimental). For this to work, the line_split regexp would need
514 # (experimental). For this to work, the line_split regexp would need
511 # to be modified so it wouldn't break things at '['. That line is
515 # to be modified so it wouldn't break things at '['. That line is
512 # nasty enough that I shouldn't change it until I can test it _well_.
516 # nasty enough that I shouldn't change it until I can test it _well_.
513 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
517 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
514
518
515 # keep track of where we started running (mainly for crash post-mortem)
519 # keep track of where we started running (mainly for crash post-mortem)
516 self.starting_dir = os.getcwd()
520 self.starting_dir = os.getcwd()
517
521
518 # Various switches which can be set
522 # Various switches which can be set
519 self.CACHELENGTH = 5000 # this is cheap, it's just text
523 self.CACHELENGTH = 5000 # this is cheap, it's just text
520 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
524 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
521 self.banner2 = banner2
525 self.banner2 = banner2
522
526
523 # TraceBack handlers:
527 # TraceBack handlers:
524
528
525 # Syntax error handler.
529 # Syntax error handler.
526 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
530 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
527
531
528 # The interactive one is initialized with an offset, meaning we always
532 # The interactive one is initialized with an offset, meaning we always
529 # want to remove the topmost item in the traceback, which is our own
533 # want to remove the topmost item in the traceback, which is our own
530 # internal code. Valid modes: ['Plain','Context','Verbose']
534 # internal code. Valid modes: ['Plain','Context','Verbose']
531 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
535 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
532 color_scheme='NoColor',
536 color_scheme='NoColor',
533 tb_offset = 1)
537 tb_offset = 1)
534
538
535 # IPython itself shouldn't crash. This will produce a detailed
539 # IPython itself shouldn't crash. This will produce a detailed
536 # post-mortem if it does. But we only install the crash handler for
540 # post-mortem if it does. But we only install the crash handler for
537 # non-threaded shells, the threaded ones use a normal verbose reporter
541 # non-threaded shells, the threaded ones use a normal verbose reporter
538 # and lose the crash handler. This is because exceptions in the main
542 # and lose the crash handler. This is because exceptions in the main
539 # thread (such as in GUI code) propagate directly to sys.excepthook,
543 # thread (such as in GUI code) propagate directly to sys.excepthook,
540 # and there's no point in printing crash dumps for every user exception.
544 # and there's no point in printing crash dumps for every user exception.
541 if self.isthreaded:
545 if self.isthreaded:
542 sys.excepthook = ultraTB.FormattedTB()
546 sys.excepthook = ultraTB.FormattedTB()
543 else:
547 else:
544 from IPython import CrashHandler
548 from IPython import CrashHandler
545 sys.excepthook = CrashHandler.CrashHandler(self)
549 sys.excepthook = CrashHandler.CrashHandler(self)
546
550
547 # The instance will store a pointer to this, so that runtime code
551 # The instance will store a pointer to this, so that runtime code
548 # (such as magics) can access it. This is because during the
552 # (such as magics) can access it. This is because during the
549 # read-eval loop, it gets temporarily overwritten (to deal with GUI
553 # read-eval loop, it gets temporarily overwritten (to deal with GUI
550 # frameworks).
554 # frameworks).
551 self.sys_excepthook = sys.excepthook
555 self.sys_excepthook = sys.excepthook
552
556
553 # and add any custom exception handlers the user may have specified
557 # and add any custom exception handlers the user may have specified
554 self.set_custom_exc(*custom_exceptions)
558 self.set_custom_exc(*custom_exceptions)
555
559
556 # Object inspector
560 # Object inspector
557 self.inspector = OInspect.Inspector(OInspect.InspectColors,
561 self.inspector = OInspect.Inspector(OInspect.InspectColors,
558 PyColorize.ANSICodeColors,
562 PyColorize.ANSICodeColors,
559 'NoColor')
563 'NoColor')
560 # indentation management
564 # indentation management
561 self.autoindent = False
565 self.autoindent = False
562 self.indent_current_nsp = 0
566 self.indent_current_nsp = 0
563
567
564 # Make some aliases automatically
568 # Make some aliases automatically
565 # Prepare list of shell aliases to auto-define
569 # Prepare list of shell aliases to auto-define
566 if os.name == 'posix':
570 if os.name == 'posix':
567 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
571 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
568 'mv mv -i','rm rm -i','cp cp -i',
572 'mv mv -i','rm rm -i','cp cp -i',
569 'cat cat','less less','clear clear',
573 'cat cat','less less','clear clear',
570 # a better ls
574 # a better ls
571 'ls ls -F',
575 'ls ls -F',
572 # long ls
576 # long ls
573 'll ls -lF',
577 'll ls -lF',
574 # color ls
578 # color ls
575 'lc ls -F -o --color',
579 'lc ls -F -o --color',
576 # ls normal files only
580 # ls normal files only
577 'lf ls -F -o --color %l | grep ^-',
581 'lf ls -F -o --color %l | grep ^-',
578 # ls symbolic links
582 # ls symbolic links
579 'lk ls -F -o --color %l | grep ^l',
583 'lk ls -F -o --color %l | grep ^l',
580 # directories or links to directories,
584 # directories or links to directories,
581 'ldir ls -F -o --color %l | grep /$',
585 'ldir ls -F -o --color %l | grep /$',
582 # things which are executable
586 # things which are executable
583 'lx ls -F -o --color %l | grep ^-..x',
587 'lx ls -F -o --color %l | grep ^-..x',
584 )
588 )
585 elif os.name in ['nt','dos']:
589 elif os.name in ['nt','dos']:
586 auto_alias = ('dir dir /on', 'ls dir /on',
590 auto_alias = ('dir dir /on', 'ls dir /on',
587 'ddir dir /ad /on', 'ldir dir /ad /on',
591 'ddir dir /ad /on', 'ldir dir /ad /on',
588 'mkdir mkdir','rmdir rmdir','echo echo',
592 'mkdir mkdir','rmdir rmdir','echo echo',
589 'ren ren','cls cls','copy copy')
593 'ren ren','cls cls','copy copy')
590 else:
594 else:
591 auto_alias = ()
595 auto_alias = ()
592 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
596 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
593 # Call the actual (public) initializer
597 # Call the actual (public) initializer
594 self.init_auto_alias()
598 self.init_auto_alias()
595 # end __init__
599 # end __init__
596
600
597 def post_config_initialization(self):
601 def post_config_initialization(self):
598 """Post configuration init method
602 """Post configuration init method
599
603
600 This is called after the configuration files have been processed to
604 This is called after the configuration files have been processed to
601 'finalize' the initialization."""
605 'finalize' the initialization."""
602
606
603 rc = self.rc
607 rc = self.rc
604
608
605 # Load readline proper
609 # Load readline proper
606 if rc.readline:
610 if rc.readline:
607 self.init_readline()
611 self.init_readline()
608
612
609 # local shortcut, this is used a LOT
613 # local shortcut, this is used a LOT
610 self.log = self.logger.log
614 self.log = self.logger.log
611
615
612 # Initialize cache, set in/out prompts and printing system
616 # Initialize cache, set in/out prompts and printing system
613 self.outputcache = CachedOutput(self,
617 self.outputcache = CachedOutput(self,
614 rc.cache_size,
618 rc.cache_size,
615 rc.pprint,
619 rc.pprint,
616 input_sep = rc.separate_in,
620 input_sep = rc.separate_in,
617 output_sep = rc.separate_out,
621 output_sep = rc.separate_out,
618 output_sep2 = rc.separate_out2,
622 output_sep2 = rc.separate_out2,
619 ps1 = rc.prompt_in1,
623 ps1 = rc.prompt_in1,
620 ps2 = rc.prompt_in2,
624 ps2 = rc.prompt_in2,
621 ps_out = rc.prompt_out,
625 ps_out = rc.prompt_out,
622 pad_left = rc.prompts_pad_left)
626 pad_left = rc.prompts_pad_left)
623
627
624 # user may have over-ridden the default print hook:
628 # user may have over-ridden the default print hook:
625 try:
629 try:
626 self.outputcache.__class__.display = self.hooks.display
630 self.outputcache.__class__.display = self.hooks.display
627 except AttributeError:
631 except AttributeError:
628 pass
632 pass
629
633
630 # I don't like assigning globally to sys, because it means when embedding
634 # I don't like assigning globally to sys, because it means when embedding
631 # instances, each embedded instance overrides the previous choice. But
635 # instances, each embedded instance overrides the previous choice. But
632 # sys.displayhook seems to be called internally by exec, so I don't see a
636 # sys.displayhook seems to be called internally by exec, so I don't see a
633 # way around it.
637 # way around it.
634 sys.displayhook = self.outputcache
638 sys.displayhook = self.outputcache
635
639
636 # Set user colors (don't do it in the constructor above so that it
640 # Set user colors (don't do it in the constructor above so that it
637 # doesn't crash if colors option is invalid)
641 # doesn't crash if colors option is invalid)
638 self.magic_colors(rc.colors)
642 self.magic_colors(rc.colors)
639
643
640 # Set calling of pdb on exceptions
644 # Set calling of pdb on exceptions
641 self.call_pdb = rc.pdb
645 self.call_pdb = rc.pdb
642
646
643 # Load user aliases
647 # Load user aliases
644 for alias in rc.alias:
648 for alias in rc.alias:
645 self.magic_alias(alias)
649 self.magic_alias(alias)
646
650
647 # dynamic data that survives through sessions
651 # dynamic data that survives through sessions
648 # XXX make the filename a config option?
652 # XXX make the filename a config option?
649 persist_base = 'persist'
653 persist_base = 'persist'
650 if rc.profile:
654 if rc.profile:
651 persist_base += '_%s' % rc.profile
655 persist_base += '_%s' % rc.profile
652 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
656 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
653
657
654 try:
658 try:
655 self.persist = pickle.load(file(self.persist_fname))
659 self.persist = pickle.load(file(self.persist_fname))
656 except:
660 except:
657 self.persist = {}
661 self.persist = {}
658
662
659
663
660 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
664 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
661 try:
665 try:
662 obj = pickle.loads(value)
666 obj = pickle.loads(value)
663 except:
667 except:
664
668
665 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
669 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
666 print "The error was:",sys.exc_info()[0]
670 print "The error was:",sys.exc_info()[0]
667 continue
671 continue
668
672
669
673
670 self.user_ns[key] = obj
674 self.user_ns[key] = obj
671
675
672 def add_builtins(self):
676 def add_builtins(self):
673 """Store ipython references into the builtin namespace.
677 """Store ipython references into the builtin namespace.
674
678
675 Some parts of ipython operate via builtins injected here, which hold a
679 Some parts of ipython operate via builtins injected here, which hold a
676 reference to IPython itself."""
680 reference to IPython itself."""
677
681
678 builtins_new = dict(__IPYTHON__ = self,
682 builtins_new = dict(__IPYTHON__ = self,
679 ip_set_hook = self.set_hook,
683 ip_set_hook = self.set_hook,
680 jobs = self.jobs,
684 jobs = self.jobs,
681 ipmagic = self.ipmagic,
685 ipmagic = self.ipmagic,
682 ipalias = self.ipalias,
686 ipalias = self.ipalias,
683 ipsystem = self.ipsystem,
687 ipsystem = self.ipsystem,
684 )
688 )
685 for biname,bival in builtins_new.items():
689 for biname,bival in builtins_new.items():
686 try:
690 try:
687 # store the orignal value so we can restore it
691 # store the orignal value so we can restore it
688 self.builtins_added[biname] = __builtin__.__dict__[biname]
692 self.builtins_added[biname] = __builtin__.__dict__[biname]
689 except KeyError:
693 except KeyError:
690 # or mark that it wasn't defined, and we'll just delete it at
694 # or mark that it wasn't defined, and we'll just delete it at
691 # cleanup
695 # cleanup
692 self.builtins_added[biname] = Undefined
696 self.builtins_added[biname] = Undefined
693 __builtin__.__dict__[biname] = bival
697 __builtin__.__dict__[biname] = bival
694
698
695 # Keep in the builtins a flag for when IPython is active. We set it
699 # Keep in the builtins a flag for when IPython is active. We set it
696 # with setdefault so that multiple nested IPythons don't clobber one
700 # with setdefault so that multiple nested IPythons don't clobber one
697 # another. Each will increase its value by one upon being activated,
701 # another. Each will increase its value by one upon being activated,
698 # which also gives us a way to determine the nesting level.
702 # which also gives us a way to determine the nesting level.
699 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
703 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
700
704
701 def clean_builtins(self):
705 def clean_builtins(self):
702 """Remove any builtins which might have been added by add_builtins, or
706 """Remove any builtins which might have been added by add_builtins, or
703 restore overwritten ones to their previous values."""
707 restore overwritten ones to their previous values."""
704 for biname,bival in self.builtins_added.items():
708 for biname,bival in self.builtins_added.items():
705 if bival is Undefined:
709 if bival is Undefined:
706 del __builtin__.__dict__[biname]
710 del __builtin__.__dict__[biname]
707 else:
711 else:
708 __builtin__.__dict__[biname] = bival
712 __builtin__.__dict__[biname] = bival
709 self.builtins_added.clear()
713 self.builtins_added.clear()
710
714
711 def set_hook(self,name,hook, priority = 50):
715 def set_hook(self,name,hook, priority = 50):
712 """set_hook(name,hook) -> sets an internal IPython hook.
716 """set_hook(name,hook) -> sets an internal IPython hook.
713
717
714 IPython exposes some of its internal API as user-modifiable hooks. By
718 IPython exposes some of its internal API as user-modifiable hooks. By
715 adding your function to one of these hooks, you can modify IPython's
719 adding your function to one of these hooks, you can modify IPython's
716 behavior to call at runtime your own routines."""
720 behavior to call at runtime your own routines."""
717
721
718 # At some point in the future, this should validate the hook before it
722 # At some point in the future, this should validate the hook before it
719 # accepts it. Probably at least check that the hook takes the number
723 # accepts it. Probably at least check that the hook takes the number
720 # of args it's supposed to.
724 # of args it's supposed to.
721 dp = getattr(self.hooks, name, None)
725 dp = getattr(self.hooks, name, None)
722 if not dp:
726 if not dp:
723 dp = IPython.hooks.CommandChainDispatcher()
727 dp = IPython.hooks.CommandChainDispatcher()
724
728
725 f = new.instancemethod(hook,self,self.__class__)
729 f = new.instancemethod(hook,self,self.__class__)
726 try:
730 try:
727 dp.add(f,priority)
731 dp.add(f,priority)
728 except AttributeError:
732 except AttributeError:
729 # it was not commandchain, plain old func - replace
733 # it was not commandchain, plain old func - replace
730 dp = f
734 dp = f
731
735
732 setattr(self.hooks,name, dp)
736 setattr(self.hooks,name, dp)
733
737
734
738
735 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
739 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
736
740
737 def set_custom_exc(self,exc_tuple,handler):
741 def set_custom_exc(self,exc_tuple,handler):
738 """set_custom_exc(exc_tuple,handler)
742 """set_custom_exc(exc_tuple,handler)
739
743
740 Set a custom exception handler, which will be called if any of the
744 Set a custom exception handler, which will be called if any of the
741 exceptions in exc_tuple occur in the mainloop (specifically, in the
745 exceptions in exc_tuple occur in the mainloop (specifically, in the
742 runcode() method.
746 runcode() method.
743
747
744 Inputs:
748 Inputs:
745
749
746 - exc_tuple: a *tuple* of valid exceptions to call the defined
750 - exc_tuple: a *tuple* of valid exceptions to call the defined
747 handler for. It is very important that you use a tuple, and NOT A
751 handler for. It is very important that you use a tuple, and NOT A
748 LIST here, because of the way Python's except statement works. If
752 LIST here, because of the way Python's except statement works. If
749 you only want to trap a single exception, use a singleton tuple:
753 you only want to trap a single exception, use a singleton tuple:
750
754
751 exc_tuple == (MyCustomException,)
755 exc_tuple == (MyCustomException,)
752
756
753 - handler: this must be defined as a function with the following
757 - handler: this must be defined as a function with the following
754 basic interface: def my_handler(self,etype,value,tb).
758 basic interface: def my_handler(self,etype,value,tb).
755
759
756 This will be made into an instance method (via new.instancemethod)
760 This will be made into an instance method (via new.instancemethod)
757 of IPython itself, and it will be called if any of the exceptions
761 of IPython itself, and it will be called if any of the exceptions
758 listed in the exc_tuple are caught. If the handler is None, an
762 listed in the exc_tuple are caught. If the handler is None, an
759 internal basic one is used, which just prints basic info.
763 internal basic one is used, which just prints basic info.
760
764
761 WARNING: by putting in your own exception handler into IPython's main
765 WARNING: by putting in your own exception handler into IPython's main
762 execution loop, you run a very good chance of nasty crashes. This
766 execution loop, you run a very good chance of nasty crashes. This
763 facility should only be used if you really know what you are doing."""
767 facility should only be used if you really know what you are doing."""
764
768
765 assert type(exc_tuple)==type(()) , \
769 assert type(exc_tuple)==type(()) , \
766 "The custom exceptions must be given AS A TUPLE."
770 "The custom exceptions must be given AS A TUPLE."
767
771
768 def dummy_handler(self,etype,value,tb):
772 def dummy_handler(self,etype,value,tb):
769 print '*** Simple custom exception handler ***'
773 print '*** Simple custom exception handler ***'
770 print 'Exception type :',etype
774 print 'Exception type :',etype
771 print 'Exception value:',value
775 print 'Exception value:',value
772 print 'Traceback :',tb
776 print 'Traceback :',tb
773 print 'Source code :','\n'.join(self.buffer)
777 print 'Source code :','\n'.join(self.buffer)
774
778
775 if handler is None: handler = dummy_handler
779 if handler is None: handler = dummy_handler
776
780
777 self.CustomTB = new.instancemethod(handler,self,self.__class__)
781 self.CustomTB = new.instancemethod(handler,self,self.__class__)
778 self.custom_exceptions = exc_tuple
782 self.custom_exceptions = exc_tuple
779
783
780 def set_custom_completer(self,completer,pos=0):
784 def set_custom_completer(self,completer,pos=0):
781 """set_custom_completer(completer,pos=0)
785 """set_custom_completer(completer,pos=0)
782
786
783 Adds a new custom completer function.
787 Adds a new custom completer function.
784
788
785 The position argument (defaults to 0) is the index in the completers
789 The position argument (defaults to 0) is the index in the completers
786 list where you want the completer to be inserted."""
790 list where you want the completer to be inserted."""
787
791
788 newcomp = new.instancemethod(completer,self.Completer,
792 newcomp = new.instancemethod(completer,self.Completer,
789 self.Completer.__class__)
793 self.Completer.__class__)
790 self.Completer.matchers.insert(pos,newcomp)
794 self.Completer.matchers.insert(pos,newcomp)
791
795
792 def _get_call_pdb(self):
796 def _get_call_pdb(self):
793 return self._call_pdb
797 return self._call_pdb
794
798
795 def _set_call_pdb(self,val):
799 def _set_call_pdb(self,val):
796
800
797 if val not in (0,1,False,True):
801 if val not in (0,1,False,True):
798 raise ValueError,'new call_pdb value must be boolean'
802 raise ValueError,'new call_pdb value must be boolean'
799
803
800 # store value in instance
804 # store value in instance
801 self._call_pdb = val
805 self._call_pdb = val
802
806
803 # notify the actual exception handlers
807 # notify the actual exception handlers
804 self.InteractiveTB.call_pdb = val
808 self.InteractiveTB.call_pdb = val
805 if self.isthreaded:
809 if self.isthreaded:
806 try:
810 try:
807 self.sys_excepthook.call_pdb = val
811 self.sys_excepthook.call_pdb = val
808 except:
812 except:
809 warn('Failed to activate pdb for threaded exception handler')
813 warn('Failed to activate pdb for threaded exception handler')
810
814
811 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
815 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
812 'Control auto-activation of pdb at exceptions')
816 'Control auto-activation of pdb at exceptions')
813
817
814
818
815 # These special functions get installed in the builtin namespace, to
819 # These special functions get installed in the builtin namespace, to
816 # provide programmatic (pure python) access to magics, aliases and system
820 # provide programmatic (pure python) access to magics, aliases and system
817 # calls. This is important for logging, user scripting, and more.
821 # calls. This is important for logging, user scripting, and more.
818
822
819 # We are basically exposing, via normal python functions, the three
823 # We are basically exposing, via normal python functions, the three
820 # mechanisms in which ipython offers special call modes (magics for
824 # mechanisms in which ipython offers special call modes (magics for
821 # internal control, aliases for direct system access via pre-selected
825 # internal control, aliases for direct system access via pre-selected
822 # names, and !cmd for calling arbitrary system commands).
826 # names, and !cmd for calling arbitrary system commands).
823
827
824 def ipmagic(self,arg_s):
828 def ipmagic(self,arg_s):
825 """Call a magic function by name.
829 """Call a magic function by name.
826
830
827 Input: a string containing the name of the magic function to call and any
831 Input: a string containing the name of the magic function to call and any
828 additional arguments to be passed to the magic.
832 additional arguments to be passed to the magic.
829
833
830 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
834 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
831 prompt:
835 prompt:
832
836
833 In[1]: %name -opt foo bar
837 In[1]: %name -opt foo bar
834
838
835 To call a magic without arguments, simply use ipmagic('name').
839 To call a magic without arguments, simply use ipmagic('name').
836
840
837 This provides a proper Python function to call IPython's magics in any
841 This provides a proper Python function to call IPython's magics in any
838 valid Python code you can type at the interpreter, including loops and
842 valid Python code you can type at the interpreter, including loops and
839 compound statements. It is added by IPython to the Python builtin
843 compound statements. It is added by IPython to the Python builtin
840 namespace upon initialization."""
844 namespace upon initialization."""
841
845
842 args = arg_s.split(' ',1)
846 args = arg_s.split(' ',1)
843 magic_name = args[0]
847 magic_name = args[0]
844 magic_name = magic_name.lstrip(self.ESC_MAGIC)
848 magic_name = magic_name.lstrip(self.ESC_MAGIC)
845
849
846 try:
850 try:
847 magic_args = args[1]
851 magic_args = args[1]
848 except IndexError:
852 except IndexError:
849 magic_args = ''
853 magic_args = ''
850 fn = getattr(self,'magic_'+magic_name,None)
854 fn = getattr(self,'magic_'+magic_name,None)
851 if fn is None:
855 if fn is None:
852 error("Magic function `%s` not found." % magic_name)
856 error("Magic function `%s` not found." % magic_name)
853 else:
857 else:
854 magic_args = self.var_expand(magic_args)
858 magic_args = self.var_expand(magic_args)
855 return fn(magic_args)
859 return fn(magic_args)
856
860
857 def ipalias(self,arg_s):
861 def ipalias(self,arg_s):
858 """Call an alias by name.
862 """Call an alias by name.
859
863
860 Input: a string containing the name of the alias to call and any
864 Input: a string containing the name of the alias to call and any
861 additional arguments to be passed to the magic.
865 additional arguments to be passed to the magic.
862
866
863 ipalias('name -opt foo bar') is equivalent to typing at the ipython
867 ipalias('name -opt foo bar') is equivalent to typing at the ipython
864 prompt:
868 prompt:
865
869
866 In[1]: name -opt foo bar
870 In[1]: name -opt foo bar
867
871
868 To call an alias without arguments, simply use ipalias('name').
872 To call an alias without arguments, simply use ipalias('name').
869
873
870 This provides a proper Python function to call IPython's aliases in any
874 This provides a proper Python function to call IPython's aliases in any
871 valid Python code you can type at the interpreter, including loops and
875 valid Python code you can type at the interpreter, including loops and
872 compound statements. It is added by IPython to the Python builtin
876 compound statements. It is added by IPython to the Python builtin
873 namespace upon initialization."""
877 namespace upon initialization."""
874
878
875 args = arg_s.split(' ',1)
879 args = arg_s.split(' ',1)
876 alias_name = args[0]
880 alias_name = args[0]
877 try:
881 try:
878 alias_args = args[1]
882 alias_args = args[1]
879 except IndexError:
883 except IndexError:
880 alias_args = ''
884 alias_args = ''
881 if alias_name in self.alias_table:
885 if alias_name in self.alias_table:
882 self.call_alias(alias_name,alias_args)
886 self.call_alias(alias_name,alias_args)
883 else:
887 else:
884 error("Alias `%s` not found." % alias_name)
888 error("Alias `%s` not found." % alias_name)
885
889
886 def ipsystem(self,arg_s):
890 def ipsystem(self,arg_s):
887 """Make a system call, using IPython."""
891 """Make a system call, using IPython."""
888
892
889 self.system(arg_s)
893 self.system(arg_s)
890
894
891 def complete(self,text):
895 def complete(self,text):
892 """Return a sorted list of all possible completions on text.
896 """Return a sorted list of all possible completions on text.
893
897
894 Inputs:
898 Inputs:
895
899
896 - text: a string of text to be completed on.
900 - text: a string of text to be completed on.
897
901
898 This is a wrapper around the completion mechanism, similar to what
902 This is a wrapper around the completion mechanism, similar to what
899 readline does at the command line when the TAB key is hit. By
903 readline does at the command line when the TAB key is hit. By
900 exposing it as a method, it can be used by other non-readline
904 exposing it as a method, it can be used by other non-readline
901 environments (such as GUIs) for text completion.
905 environments (such as GUIs) for text completion.
902
906
903 Simple usage example:
907 Simple usage example:
904
908
905 In [1]: x = 'hello'
909 In [1]: x = 'hello'
906
910
907 In [2]: __IP.complete('x.l')
911 In [2]: __IP.complete('x.l')
908 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
912 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
909
913
910 complete = self.Completer.complete
914 complete = self.Completer.complete
911 state = 0
915 state = 0
912 # use a dict so we get unique keys, since ipyhton's multiple
916 # use a dict so we get unique keys, since ipyhton's multiple
913 # completers can return duplicates.
917 # completers can return duplicates.
914 comps = {}
918 comps = {}
915 while True:
919 while True:
916 newcomp = complete(text,state)
920 newcomp = complete(text,state)
917 if newcomp is None:
921 if newcomp is None:
918 break
922 break
919 comps[newcomp] = 1
923 comps[newcomp] = 1
920 state += 1
924 state += 1
921 outcomps = comps.keys()
925 outcomps = comps.keys()
922 outcomps.sort()
926 outcomps.sort()
923 return outcomps
927 return outcomps
924
928
925 def set_completer_frame(self, frame=None):
929 def set_completer_frame(self, frame=None):
926 if frame:
930 if frame:
927 self.Completer.namespace = frame.f_locals
931 self.Completer.namespace = frame.f_locals
928 self.Completer.global_namespace = frame.f_globals
932 self.Completer.global_namespace = frame.f_globals
929 else:
933 else:
930 self.Completer.namespace = self.user_ns
934 self.Completer.namespace = self.user_ns
931 self.Completer.global_namespace = self.user_global_ns
935 self.Completer.global_namespace = self.user_global_ns
932
936
933 def init_auto_alias(self):
937 def init_auto_alias(self):
934 """Define some aliases automatically.
938 """Define some aliases automatically.
935
939
936 These are ALL parameter-less aliases"""
940 These are ALL parameter-less aliases"""
937
941
938 for alias,cmd in self.auto_alias:
942 for alias,cmd in self.auto_alias:
939 self.alias_table[alias] = (0,cmd)
943 self.alias_table[alias] = (0,cmd)
940
944
941 def alias_table_validate(self,verbose=0):
945 def alias_table_validate(self,verbose=0):
942 """Update information about the alias table.
946 """Update information about the alias table.
943
947
944 In particular, make sure no Python keywords/builtins are in it."""
948 In particular, make sure no Python keywords/builtins are in it."""
945
949
946 no_alias = self.no_alias
950 no_alias = self.no_alias
947 for k in self.alias_table.keys():
951 for k in self.alias_table.keys():
948 if k in no_alias:
952 if k in no_alias:
949 del self.alias_table[k]
953 del self.alias_table[k]
950 if verbose:
954 if verbose:
951 print ("Deleting alias <%s>, it's a Python "
955 print ("Deleting alias <%s>, it's a Python "
952 "keyword or builtin." % k)
956 "keyword or builtin." % k)
953
957
954 def set_autoindent(self,value=None):
958 def set_autoindent(self,value=None):
955 """Set the autoindent flag, checking for readline support.
959 """Set the autoindent flag, checking for readline support.
956
960
957 If called with no arguments, it acts as a toggle."""
961 If called with no arguments, it acts as a toggle."""
958
962
959 if not self.has_readline:
963 if not self.has_readline:
960 if os.name == 'posix':
964 if os.name == 'posix':
961 warn("The auto-indent feature requires the readline library")
965 warn("The auto-indent feature requires the readline library")
962 self.autoindent = 0
966 self.autoindent = 0
963 return
967 return
964 if value is None:
968 if value is None:
965 self.autoindent = not self.autoindent
969 self.autoindent = not self.autoindent
966 else:
970 else:
967 self.autoindent = value
971 self.autoindent = value
968
972
969 def rc_set_toggle(self,rc_field,value=None):
973 def rc_set_toggle(self,rc_field,value=None):
970 """Set or toggle a field in IPython's rc config. structure.
974 """Set or toggle a field in IPython's rc config. structure.
971
975
972 If called with no arguments, it acts as a toggle.
976 If called with no arguments, it acts as a toggle.
973
977
974 If called with a non-existent field, the resulting AttributeError
978 If called with a non-existent field, the resulting AttributeError
975 exception will propagate out."""
979 exception will propagate out."""
976
980
977 rc_val = getattr(self.rc,rc_field)
981 rc_val = getattr(self.rc,rc_field)
978 if value is None:
982 if value is None:
979 value = not rc_val
983 value = not rc_val
980 setattr(self.rc,rc_field,value)
984 setattr(self.rc,rc_field,value)
981
985
982 def user_setup(self,ipythondir,rc_suffix,mode='install'):
986 def user_setup(self,ipythondir,rc_suffix,mode='install'):
983 """Install the user configuration directory.
987 """Install the user configuration directory.
984
988
985 Can be called when running for the first time or to upgrade the user's
989 Can be called when running for the first time or to upgrade the user's
986 .ipython/ directory with the mode parameter. Valid modes are 'install'
990 .ipython/ directory with the mode parameter. Valid modes are 'install'
987 and 'upgrade'."""
991 and 'upgrade'."""
988
992
989 def wait():
993 def wait():
990 try:
994 try:
991 raw_input("Please press <RETURN> to start IPython.")
995 raw_input("Please press <RETURN> to start IPython.")
992 except EOFError:
996 except EOFError:
993 print >> Term.cout
997 print >> Term.cout
994 print '*'*70
998 print '*'*70
995
999
996 cwd = os.getcwd() # remember where we started
1000 cwd = os.getcwd() # remember where we started
997 glb = glob.glob
1001 glb = glob.glob
998 print '*'*70
1002 print '*'*70
999 if mode == 'install':
1003 if mode == 'install':
1000 print \
1004 print \
1001 """Welcome to IPython. I will try to create a personal configuration directory
1005 """Welcome to IPython. I will try to create a personal configuration directory
1002 where you can customize many aspects of IPython's functionality in:\n"""
1006 where you can customize many aspects of IPython's functionality in:\n"""
1003 else:
1007 else:
1004 print 'I am going to upgrade your configuration in:'
1008 print 'I am going to upgrade your configuration in:'
1005
1009
1006 print ipythondir
1010 print ipythondir
1007
1011
1008 rcdirend = os.path.join('IPython','UserConfig')
1012 rcdirend = os.path.join('IPython','UserConfig')
1009 cfg = lambda d: os.path.join(d,rcdirend)
1013 cfg = lambda d: os.path.join(d,rcdirend)
1010 try:
1014 try:
1011 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1015 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1012 except IOError:
1016 except IOError:
1013 warning = """
1017 warning = """
1014 Installation error. IPython's directory was not found.
1018 Installation error. IPython's directory was not found.
1015
1019
1016 Check the following:
1020 Check the following:
1017
1021
1018 The ipython/IPython directory should be in a directory belonging to your
1022 The ipython/IPython directory should be in a directory belonging to your
1019 PYTHONPATH environment variable (that is, it should be in a directory
1023 PYTHONPATH environment variable (that is, it should be in a directory
1020 belonging to sys.path). You can copy it explicitly there or just link to it.
1024 belonging to sys.path). You can copy it explicitly there or just link to it.
1021
1025
1022 IPython will proceed with builtin defaults.
1026 IPython will proceed with builtin defaults.
1023 """
1027 """
1024 warn(warning)
1028 warn(warning)
1025 wait()
1029 wait()
1026 return
1030 return
1027
1031
1028 if mode == 'install':
1032 if mode == 'install':
1029 try:
1033 try:
1030 shutil.copytree(rcdir,ipythondir)
1034 shutil.copytree(rcdir,ipythondir)
1031 os.chdir(ipythondir)
1035 os.chdir(ipythondir)
1032 rc_files = glb("ipythonrc*")
1036 rc_files = glb("ipythonrc*")
1033 for rc_file in rc_files:
1037 for rc_file in rc_files:
1034 os.rename(rc_file,rc_file+rc_suffix)
1038 os.rename(rc_file,rc_file+rc_suffix)
1035 except:
1039 except:
1036 warning = """
1040 warning = """
1037
1041
1038 There was a problem with the installation:
1042 There was a problem with the installation:
1039 %s
1043 %s
1040 Try to correct it or contact the developers if you think it's a bug.
1044 Try to correct it or contact the developers if you think it's a bug.
1041 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1045 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1042 warn(warning)
1046 warn(warning)
1043 wait()
1047 wait()
1044 return
1048 return
1045
1049
1046 elif mode == 'upgrade':
1050 elif mode == 'upgrade':
1047 try:
1051 try:
1048 os.chdir(ipythondir)
1052 os.chdir(ipythondir)
1049 except:
1053 except:
1050 print """
1054 print """
1051 Can not upgrade: changing to directory %s failed. Details:
1055 Can not upgrade: changing to directory %s failed. Details:
1052 %s
1056 %s
1053 """ % (ipythondir,sys.exc_info()[1])
1057 """ % (ipythondir,sys.exc_info()[1])
1054 wait()
1058 wait()
1055 return
1059 return
1056 else:
1060 else:
1057 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1061 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1058 for new_full_path in sources:
1062 for new_full_path in sources:
1059 new_filename = os.path.basename(new_full_path)
1063 new_filename = os.path.basename(new_full_path)
1060 if new_filename.startswith('ipythonrc'):
1064 if new_filename.startswith('ipythonrc'):
1061 new_filename = new_filename + rc_suffix
1065 new_filename = new_filename + rc_suffix
1062 # The config directory should only contain files, skip any
1066 # The config directory should only contain files, skip any
1063 # directories which may be there (like CVS)
1067 # directories which may be there (like CVS)
1064 if os.path.isdir(new_full_path):
1068 if os.path.isdir(new_full_path):
1065 continue
1069 continue
1066 if os.path.exists(new_filename):
1070 if os.path.exists(new_filename):
1067 old_file = new_filename+'.old'
1071 old_file = new_filename+'.old'
1068 if os.path.exists(old_file):
1072 if os.path.exists(old_file):
1069 os.remove(old_file)
1073 os.remove(old_file)
1070 os.rename(new_filename,old_file)
1074 os.rename(new_filename,old_file)
1071 shutil.copy(new_full_path,new_filename)
1075 shutil.copy(new_full_path,new_filename)
1072 else:
1076 else:
1073 raise ValueError,'unrecognized mode for install:',`mode`
1077 raise ValueError,'unrecognized mode for install:',`mode`
1074
1078
1075 # Fix line-endings to those native to each platform in the config
1079 # Fix line-endings to those native to each platform in the config
1076 # directory.
1080 # directory.
1077 try:
1081 try:
1078 os.chdir(ipythondir)
1082 os.chdir(ipythondir)
1079 except:
1083 except:
1080 print """
1084 print """
1081 Problem: changing to directory %s failed.
1085 Problem: changing to directory %s failed.
1082 Details:
1086 Details:
1083 %s
1087 %s
1084
1088
1085 Some configuration files may have incorrect line endings. This should not
1089 Some configuration files may have incorrect line endings. This should not
1086 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1090 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1087 wait()
1091 wait()
1088 else:
1092 else:
1089 for fname in glb('ipythonrc*'):
1093 for fname in glb('ipythonrc*'):
1090 try:
1094 try:
1091 native_line_ends(fname,backup=0)
1095 native_line_ends(fname,backup=0)
1092 except IOError:
1096 except IOError:
1093 pass
1097 pass
1094
1098
1095 if mode == 'install':
1099 if mode == 'install':
1096 print """
1100 print """
1097 Successful installation!
1101 Successful installation!
1098
1102
1099 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1103 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1100 IPython manual (there are both HTML and PDF versions supplied with the
1104 IPython manual (there are both HTML and PDF versions supplied with the
1101 distribution) to make sure that your system environment is properly configured
1105 distribution) to make sure that your system environment is properly configured
1102 to take advantage of IPython's features.
1106 to take advantage of IPython's features.
1103
1107
1104 Important note: the configuration system has changed! The old system is
1108 Important note: the configuration system has changed! The old system is
1105 still in place, but its setting may be partly overridden by the settings in
1109 still in place, but its setting may be partly overridden by the settings in
1106 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1110 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1107 if some of the new settings bother you.
1111 if some of the new settings bother you.
1108
1112
1109 """
1113 """
1110 else:
1114 else:
1111 print """
1115 print """
1112 Successful upgrade!
1116 Successful upgrade!
1113
1117
1114 All files in your directory:
1118 All files in your directory:
1115 %(ipythondir)s
1119 %(ipythondir)s
1116 which would have been overwritten by the upgrade were backed up with a .old
1120 which would have been overwritten by the upgrade were backed up with a .old
1117 extension. If you had made particular customizations in those files you may
1121 extension. If you had made particular customizations in those files you may
1118 want to merge them back into the new files.""" % locals()
1122 want to merge them back into the new files.""" % locals()
1119 wait()
1123 wait()
1120 os.chdir(cwd)
1124 os.chdir(cwd)
1121 # end user_setup()
1125 # end user_setup()
1122
1126
1123 def atexit_operations(self):
1127 def atexit_operations(self):
1124 """This will be executed at the time of exit.
1128 """This will be executed at the time of exit.
1125
1129
1126 Saving of persistent data should be performed here. """
1130 Saving of persistent data should be performed here. """
1127
1131
1128 #print '*** IPython exit cleanup ***' # dbg
1132 #print '*** IPython exit cleanup ***' # dbg
1129 # input history
1133 # input history
1130 self.savehist()
1134 self.savehist()
1131
1135
1132 # Cleanup all tempfiles left around
1136 # Cleanup all tempfiles left around
1133 for tfile in self.tempfiles:
1137 for tfile in self.tempfiles:
1134 try:
1138 try:
1135 os.unlink(tfile)
1139 os.unlink(tfile)
1136 except OSError:
1140 except OSError:
1137 pass
1141 pass
1138
1142
1139 # save the "persistent data" catch-all dictionary
1143 # save the "persistent data" catch-all dictionary
1140 try:
1144 try:
1141 pickle.dump(self.persist, open(self.persist_fname,"w"))
1145 pickle.dump(self.persist, open(self.persist_fname,"w"))
1142 except:
1146 except:
1143 print "*** ERROR *** persistent data saving failed."
1147 print "*** ERROR *** persistent data saving failed."
1144
1148
1145 def savehist(self):
1149 def savehist(self):
1146 """Save input history to a file (via readline library)."""
1150 """Save input history to a file (via readline library)."""
1147 try:
1151 try:
1148 self.readline.write_history_file(self.histfile)
1152 self.readline.write_history_file(self.histfile)
1149 except:
1153 except:
1150 print 'Unable to save IPython command history to file: ' + \
1154 print 'Unable to save IPython command history to file: ' + \
1151 `self.histfile`
1155 `self.histfile`
1152
1156
1153 def pre_readline(self):
1157 def pre_readline(self):
1154 """readline hook to be used at the start of each line.
1158 """readline hook to be used at the start of each line.
1155
1159
1156 Currently it handles auto-indent only."""
1160 Currently it handles auto-indent only."""
1157
1161
1158 #debugp('self.indent_current_nsp','pre_readline:')
1162 #debugx('self.indent_current_nsp','pre_readline:')
1159 self.readline.insert_text(self.indent_current_str())
1163 self.readline.insert_text(self.indent_current_str())
1160
1164
1161 def init_readline(self):
1165 def init_readline(self):
1162 """Command history completion/saving/reloading."""
1166 """Command history completion/saving/reloading."""
1163 try:
1167 try:
1164 import readline
1168 import readline
1165 except ImportError:
1169 except ImportError:
1166 self.has_readline = 0
1170 self.has_readline = 0
1167 self.readline = None
1171 self.readline = None
1168 # no point in bugging windows users with this every time:
1172 # no point in bugging windows users with this every time:
1169 if os.name == 'posix':
1173 if os.name == 'posix':
1170 warn('Readline services not available on this platform.')
1174 warn('Readline services not available on this platform.')
1171 else:
1175 else:
1172 import atexit
1176 import atexit
1173 from IPython.completer import IPCompleter
1177 from IPython.completer import IPCompleter
1174 self.Completer = IPCompleter(self,
1178 self.Completer = IPCompleter(self,
1175 self.user_ns,
1179 self.user_ns,
1176 self.user_global_ns,
1180 self.user_global_ns,
1177 self.rc.readline_omit__names,
1181 self.rc.readline_omit__names,
1178 self.alias_table)
1182 self.alias_table)
1179
1183
1180 # Platform-specific configuration
1184 # Platform-specific configuration
1181 if os.name == 'nt':
1185 if os.name == 'nt':
1182 self.readline_startup_hook = readline.set_pre_input_hook
1186 self.readline_startup_hook = readline.set_pre_input_hook
1183 else:
1187 else:
1184 self.readline_startup_hook = readline.set_startup_hook
1188 self.readline_startup_hook = readline.set_startup_hook
1185
1189
1186 # Load user's initrc file (readline config)
1190 # Load user's initrc file (readline config)
1187 inputrc_name = os.environ.get('INPUTRC')
1191 inputrc_name = os.environ.get('INPUTRC')
1188 if inputrc_name is None:
1192 if inputrc_name is None:
1189 home_dir = get_home_dir()
1193 home_dir = get_home_dir()
1190 if home_dir is not None:
1194 if home_dir is not None:
1191 inputrc_name = os.path.join(home_dir,'.inputrc')
1195 inputrc_name = os.path.join(home_dir,'.inputrc')
1192 if os.path.isfile(inputrc_name):
1196 if os.path.isfile(inputrc_name):
1193 try:
1197 try:
1194 readline.read_init_file(inputrc_name)
1198 readline.read_init_file(inputrc_name)
1195 except:
1199 except:
1196 warn('Problems reading readline initialization file <%s>'
1200 warn('Problems reading readline initialization file <%s>'
1197 % inputrc_name)
1201 % inputrc_name)
1198
1202
1199 self.has_readline = 1
1203 self.has_readline = 1
1200 self.readline = readline
1204 self.readline = readline
1201 # save this in sys so embedded copies can restore it properly
1205 # save this in sys so embedded copies can restore it properly
1202 sys.ipcompleter = self.Completer.complete
1206 sys.ipcompleter = self.Completer.complete
1203 readline.set_completer(self.Completer.complete)
1207 readline.set_completer(self.Completer.complete)
1204
1208
1205 # Configure readline according to user's prefs
1209 # Configure readline according to user's prefs
1206 for rlcommand in self.rc.readline_parse_and_bind:
1210 for rlcommand in self.rc.readline_parse_and_bind:
1207 readline.parse_and_bind(rlcommand)
1211 readline.parse_and_bind(rlcommand)
1208
1212
1209 # remove some chars from the delimiters list
1213 # remove some chars from the delimiters list
1210 delims = readline.get_completer_delims()
1214 delims = readline.get_completer_delims()
1211 delims = delims.translate(string._idmap,
1215 delims = delims.translate(string._idmap,
1212 self.rc.readline_remove_delims)
1216 self.rc.readline_remove_delims)
1213 readline.set_completer_delims(delims)
1217 readline.set_completer_delims(delims)
1214 # otherwise we end up with a monster history after a while:
1218 # otherwise we end up with a monster history after a while:
1215 readline.set_history_length(1000)
1219 readline.set_history_length(1000)
1216 try:
1220 try:
1217 #print '*** Reading readline history' # dbg
1221 #print '*** Reading readline history' # dbg
1218 readline.read_history_file(self.histfile)
1222 readline.read_history_file(self.histfile)
1219 except IOError:
1223 except IOError:
1220 pass # It doesn't exist yet.
1224 pass # It doesn't exist yet.
1221
1225
1222 atexit.register(self.atexit_operations)
1226 atexit.register(self.atexit_operations)
1223 del atexit
1227 del atexit
1224
1228
1225 # Configure auto-indent for all platforms
1229 # Configure auto-indent for all platforms
1226 self.set_autoindent(self.rc.autoindent)
1230 self.set_autoindent(self.rc.autoindent)
1227
1231
1228 def _should_recompile(self,e):
1232 def _should_recompile(self,e):
1229 """Utility routine for edit_syntax_error"""
1233 """Utility routine for edit_syntax_error"""
1230
1234
1231 if e.filename in ('<ipython console>','<input>','<string>',
1235 if e.filename in ('<ipython console>','<input>','<string>',
1232 '<console>',None):
1236 '<console>',None):
1233
1237
1234 return False
1238 return False
1235 try:
1239 try:
1236 if not ask_yes_no('Return to editor to correct syntax error? '
1240 if not ask_yes_no('Return to editor to correct syntax error? '
1237 '[Y/n] ','y'):
1241 '[Y/n] ','y'):
1238 return False
1242 return False
1239 except EOFError:
1243 except EOFError:
1240 return False
1244 return False
1241
1245
1242 def int0(x):
1246 def int0(x):
1243 try:
1247 try:
1244 return int(x)
1248 return int(x)
1245 except TypeError:
1249 except TypeError:
1246 return 0
1250 return 0
1247 # always pass integer line and offset values to editor hook
1251 # always pass integer line and offset values to editor hook
1248 self.hooks.fix_error_editor(e.filename,
1252 self.hooks.fix_error_editor(e.filename,
1249 int0(e.lineno),int0(e.offset),e.msg)
1253 int0(e.lineno),int0(e.offset),e.msg)
1250 return True
1254 return True
1251
1255
1252 def edit_syntax_error(self):
1256 def edit_syntax_error(self):
1253 """The bottom half of the syntax error handler called in the main loop.
1257 """The bottom half of the syntax error handler called in the main loop.
1254
1258
1255 Loop until syntax error is fixed or user cancels.
1259 Loop until syntax error is fixed or user cancels.
1256 """
1260 """
1257
1261
1258 while self.SyntaxTB.last_syntax_error:
1262 while self.SyntaxTB.last_syntax_error:
1259 # copy and clear last_syntax_error
1263 # copy and clear last_syntax_error
1260 err = self.SyntaxTB.clear_err_state()
1264 err = self.SyntaxTB.clear_err_state()
1261 if not self._should_recompile(err):
1265 if not self._should_recompile(err):
1262 return
1266 return
1263 try:
1267 try:
1264 # may set last_syntax_error again if a SyntaxError is raised
1268 # may set last_syntax_error again if a SyntaxError is raised
1265 self.safe_execfile(err.filename,self.shell.user_ns)
1269 self.safe_execfile(err.filename,self.shell.user_ns)
1266 except:
1270 except:
1267 self.showtraceback()
1271 self.showtraceback()
1268 else:
1272 else:
1269 f = file(err.filename)
1273 f = file(err.filename)
1270 try:
1274 try:
1271 sys.displayhook(f.read())
1275 sys.displayhook(f.read())
1272 finally:
1276 finally:
1273 f.close()
1277 f.close()
1274
1278
1275 def showsyntaxerror(self, filename=None):
1279 def showsyntaxerror(self, filename=None):
1276 """Display the syntax error that just occurred.
1280 """Display the syntax error that just occurred.
1277
1281
1278 This doesn't display a stack trace because there isn't one.
1282 This doesn't display a stack trace because there isn't one.
1279
1283
1280 If a filename is given, it is stuffed in the exception instead
1284 If a filename is given, it is stuffed in the exception instead
1281 of what was there before (because Python's parser always uses
1285 of what was there before (because Python's parser always uses
1282 "<string>" when reading from a string).
1286 "<string>" when reading from a string).
1283 """
1287 """
1284 etype, value, last_traceback = sys.exc_info()
1288 etype, value, last_traceback = sys.exc_info()
1285 if filename and etype is SyntaxError:
1289 if filename and etype is SyntaxError:
1286 # Work hard to stuff the correct filename in the exception
1290 # Work hard to stuff the correct filename in the exception
1287 try:
1291 try:
1288 msg, (dummy_filename, lineno, offset, line) = value
1292 msg, (dummy_filename, lineno, offset, line) = value
1289 except:
1293 except:
1290 # Not the format we expect; leave it alone
1294 # Not the format we expect; leave it alone
1291 pass
1295 pass
1292 else:
1296 else:
1293 # Stuff in the right filename
1297 # Stuff in the right filename
1294 try:
1298 try:
1295 # Assume SyntaxError is a class exception
1299 # Assume SyntaxError is a class exception
1296 value = SyntaxError(msg, (filename, lineno, offset, line))
1300 value = SyntaxError(msg, (filename, lineno, offset, line))
1297 except:
1301 except:
1298 # If that failed, assume SyntaxError is a string
1302 # If that failed, assume SyntaxError is a string
1299 value = msg, (filename, lineno, offset, line)
1303 value = msg, (filename, lineno, offset, line)
1300 self.SyntaxTB(etype,value,[])
1304 self.SyntaxTB(etype,value,[])
1301
1305
1302 def debugger(self):
1306 def debugger(self):
1303 """Call the pdb debugger."""
1307 """Call the pdb debugger."""
1304
1308
1305 if not self.rc.pdb:
1309 if not self.rc.pdb:
1306 return
1310 return
1307 pdb.pm()
1311 pdb.pm()
1308
1312
1309 def showtraceback(self,exc_tuple = None,filename=None):
1313 def showtraceback(self,exc_tuple = None,filename=None):
1310 """Display the exception that just occurred."""
1314 """Display the exception that just occurred."""
1311
1315
1312 # Though this won't be called by syntax errors in the input line,
1316 # Though this won't be called by syntax errors in the input line,
1313 # there may be SyntaxError cases whith imported code.
1317 # there may be SyntaxError cases whith imported code.
1314 if exc_tuple is None:
1318 if exc_tuple is None:
1315 type, value, tb = sys.exc_info()
1319 type, value, tb = sys.exc_info()
1316 else:
1320 else:
1317 type, value, tb = exc_tuple
1321 type, value, tb = exc_tuple
1318 if type is SyntaxError:
1322 if type is SyntaxError:
1319 self.showsyntaxerror(filename)
1323 self.showsyntaxerror(filename)
1320 else:
1324 else:
1321 self.InteractiveTB()
1325 self.InteractiveTB()
1322 if self.InteractiveTB.call_pdb and self.has_readline:
1326 if self.InteractiveTB.call_pdb and self.has_readline:
1323 # pdb mucks up readline, fix it back
1327 # pdb mucks up readline, fix it back
1324 self.readline.set_completer(self.Completer.complete)
1328 self.readline.set_completer(self.Completer.complete)
1325
1329
1326 def mainloop(self,banner=None):
1330 def mainloop(self,banner=None):
1327 """Creates the local namespace and starts the mainloop.
1331 """Creates the local namespace and starts the mainloop.
1328
1332
1329 If an optional banner argument is given, it will override the
1333 If an optional banner argument is given, it will override the
1330 internally created default banner."""
1334 internally created default banner."""
1331
1335
1332 if self.rc.c: # Emulate Python's -c option
1336 if self.rc.c: # Emulate Python's -c option
1333 self.exec_init_cmd()
1337 self.exec_init_cmd()
1334 if banner is None:
1338 if banner is None:
1335 if self.rc.banner:
1339 if self.rc.banner:
1336 banner = self.BANNER+self.banner2
1340 banner = self.BANNER+self.banner2
1337 else:
1341 else:
1338 banner = ''
1342 banner = ''
1339 self.interact(banner)
1343 self.interact(banner)
1340
1344
1341 def exec_init_cmd(self):
1345 def exec_init_cmd(self):
1342 """Execute a command given at the command line.
1346 """Execute a command given at the command line.
1343
1347
1344 This emulates Python's -c option."""
1348 This emulates Python's -c option."""
1345
1349
1346 sys.argv = ['-c']
1350 sys.argv = ['-c']
1347 self.push(self.rc.c)
1351 self.push(self.rc.c)
1348
1352
1349 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1353 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1350 """Embeds IPython into a running python program.
1354 """Embeds IPython into a running python program.
1351
1355
1352 Input:
1356 Input:
1353
1357
1354 - header: An optional header message can be specified.
1358 - header: An optional header message can be specified.
1355
1359
1356 - local_ns, global_ns: working namespaces. If given as None, the
1360 - local_ns, global_ns: working namespaces. If given as None, the
1357 IPython-initialized one is updated with __main__.__dict__, so that
1361 IPython-initialized one is updated with __main__.__dict__, so that
1358 program variables become visible but user-specific configuration
1362 program variables become visible but user-specific configuration
1359 remains possible.
1363 remains possible.
1360
1364
1361 - stack_depth: specifies how many levels in the stack to go to
1365 - stack_depth: specifies how many levels in the stack to go to
1362 looking for namespaces (when local_ns and global_ns are None). This
1366 looking for namespaces (when local_ns and global_ns are None). This
1363 allows an intermediate caller to make sure that this function gets
1367 allows an intermediate caller to make sure that this function gets
1364 the namespace from the intended level in the stack. By default (0)
1368 the namespace from the intended level in the stack. By default (0)
1365 it will get its locals and globals from the immediate caller.
1369 it will get its locals and globals from the immediate caller.
1366
1370
1367 Warning: it's possible to use this in a program which is being run by
1371 Warning: it's possible to use this in a program which is being run by
1368 IPython itself (via %run), but some funny things will happen (a few
1372 IPython itself (via %run), but some funny things will happen (a few
1369 globals get overwritten). In the future this will be cleaned up, as
1373 globals get overwritten). In the future this will be cleaned up, as
1370 there is no fundamental reason why it can't work perfectly."""
1374 there is no fundamental reason why it can't work perfectly."""
1371
1375
1372 # Get locals and globals from caller
1376 # Get locals and globals from caller
1373 if local_ns is None or global_ns is None:
1377 if local_ns is None or global_ns is None:
1374 call_frame = sys._getframe(stack_depth).f_back
1378 call_frame = sys._getframe(stack_depth).f_back
1375
1379
1376 if local_ns is None:
1380 if local_ns is None:
1377 local_ns = call_frame.f_locals
1381 local_ns = call_frame.f_locals
1378 if global_ns is None:
1382 if global_ns is None:
1379 global_ns = call_frame.f_globals
1383 global_ns = call_frame.f_globals
1380
1384
1381 # Update namespaces and fire up interpreter
1385 # Update namespaces and fire up interpreter
1382
1386
1383 # The global one is easy, we can just throw it in
1387 # The global one is easy, we can just throw it in
1384 self.user_global_ns = global_ns
1388 self.user_global_ns = global_ns
1385
1389
1386 # but the user/local one is tricky: ipython needs it to store internal
1390 # but the user/local one is tricky: ipython needs it to store internal
1387 # data, but we also need the locals. We'll copy locals in the user
1391 # data, but we also need the locals. We'll copy locals in the user
1388 # one, but will track what got copied so we can delete them at exit.
1392 # one, but will track what got copied so we can delete them at exit.
1389 # This is so that a later embedded call doesn't see locals from a
1393 # This is so that a later embedded call doesn't see locals from a
1390 # previous call (which most likely existed in a separate scope).
1394 # previous call (which most likely existed in a separate scope).
1391 local_varnames = local_ns.keys()
1395 local_varnames = local_ns.keys()
1392 self.user_ns.update(local_ns)
1396 self.user_ns.update(local_ns)
1393
1397
1394 # Patch for global embedding to make sure that things don't overwrite
1398 # Patch for global embedding to make sure that things don't overwrite
1395 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1399 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1396 # FIXME. Test this a bit more carefully (the if.. is new)
1400 # FIXME. Test this a bit more carefully (the if.. is new)
1397 if local_ns is None and global_ns is None:
1401 if local_ns is None and global_ns is None:
1398 self.user_global_ns.update(__main__.__dict__)
1402 self.user_global_ns.update(__main__.__dict__)
1399
1403
1400 # make sure the tab-completer has the correct frame information, so it
1404 # make sure the tab-completer has the correct frame information, so it
1401 # actually completes using the frame's locals/globals
1405 # actually completes using the frame's locals/globals
1402 self.set_completer_frame()
1406 self.set_completer_frame()
1403
1407
1404 # before activating the interactive mode, we need to make sure that
1408 # before activating the interactive mode, we need to make sure that
1405 # all names in the builtin namespace needed by ipython point to
1409 # all names in the builtin namespace needed by ipython point to
1406 # ourselves, and not to other instances.
1410 # ourselves, and not to other instances.
1407 self.add_builtins()
1411 self.add_builtins()
1408
1412
1409 self.interact(header)
1413 self.interact(header)
1410
1414
1411 # now, purge out the user namespace from anything we might have added
1415 # now, purge out the user namespace from anything we might have added
1412 # from the caller's local namespace
1416 # from the caller's local namespace
1413 delvar = self.user_ns.pop
1417 delvar = self.user_ns.pop
1414 for var in local_varnames:
1418 for var in local_varnames:
1415 delvar(var,None)
1419 delvar(var,None)
1416 # and clean builtins we may have overridden
1420 # and clean builtins we may have overridden
1417 self.clean_builtins()
1421 self.clean_builtins()
1418
1422
1419 def interact(self, banner=None):
1423 def interact(self, banner=None):
1420 """Closely emulate the interactive Python console.
1424 """Closely emulate the interactive Python console.
1421
1425
1422 The optional banner argument specify the banner to print
1426 The optional banner argument specify the banner to print
1423 before the first interaction; by default it prints a banner
1427 before the first interaction; by default it prints a banner
1424 similar to the one printed by the real Python interpreter,
1428 similar to the one printed by the real Python interpreter,
1425 followed by the current class name in parentheses (so as not
1429 followed by the current class name in parentheses (so as not
1426 to confuse this with the real interpreter -- since it's so
1430 to confuse this with the real interpreter -- since it's so
1427 close!).
1431 close!).
1428
1432
1429 """
1433 """
1430 cprt = 'Type "copyright", "credits" or "license" for more information.'
1434 cprt = 'Type "copyright", "credits" or "license" for more information.'
1431 if banner is None:
1435 if banner is None:
1432 self.write("Python %s on %s\n%s\n(%s)\n" %
1436 self.write("Python %s on %s\n%s\n(%s)\n" %
1433 (sys.version, sys.platform, cprt,
1437 (sys.version, sys.platform, cprt,
1434 self.__class__.__name__))
1438 self.__class__.__name__))
1435 else:
1439 else:
1436 self.write(banner)
1440 self.write(banner)
1437
1441
1438 more = 0
1442 more = 0
1439
1443
1440 # Mark activity in the builtins
1444 # Mark activity in the builtins
1441 __builtin__.__dict__['__IPYTHON__active'] += 1
1445 __builtin__.__dict__['__IPYTHON__active'] += 1
1442
1446
1443 # exit_now is set by a call to %Exit or %Quit
1447 # exit_now is set by a call to %Exit or %Quit
1444 self.exit_now = False
1448 self.exit_now = False
1445 while not self.exit_now:
1449 while not self.exit_now:
1446
1450
1447 try:
1451 try:
1448 if more:
1452 if more:
1449 prompt = self.outputcache.prompt2
1453 prompt = self.outputcache.prompt2
1450 if self.autoindent:
1454 if self.autoindent:
1451 self.readline_startup_hook(self.pre_readline)
1455 self.readline_startup_hook(self.pre_readline)
1452 else:
1456 else:
1453 prompt = self.outputcache.prompt1
1457 prompt = self.outputcache.prompt1
1454 try:
1458 try:
1455 line = self.raw_input(prompt,more)
1459 line = self.raw_input(prompt,more)
1456 if self.autoindent:
1460 if self.autoindent:
1457 self.readline_startup_hook(None)
1461 self.readline_startup_hook(None)
1458 except EOFError:
1462 except EOFError:
1459 if self.autoindent:
1463 if self.autoindent:
1460 self.readline_startup_hook(None)
1464 self.readline_startup_hook(None)
1461 self.write("\n")
1465 self.write("\n")
1462 self.exit()
1466 self.exit()
1463 except:
1467 except:
1464 # exceptions here are VERY RARE, but they can be triggered
1468 # exceptions here are VERY RARE, but they can be triggered
1465 # asynchronously by signal handlers, for example.
1469 # asynchronously by signal handlers, for example.
1466 self.showtraceback()
1470 self.showtraceback()
1467 else:
1471 else:
1468 more = self.push(line)
1472 more = self.push(line)
1469
1473
1470 if (self.SyntaxTB.last_syntax_error and
1474 if (self.SyntaxTB.last_syntax_error and
1471 self.rc.autoedit_syntax):
1475 self.rc.autoedit_syntax):
1472 self.edit_syntax_error()
1476 self.edit_syntax_error()
1473
1477
1474 except KeyboardInterrupt:
1478 except KeyboardInterrupt:
1475 self.write("\nKeyboardInterrupt\n")
1479 self.write("\nKeyboardInterrupt\n")
1476 self.resetbuffer()
1480 self.resetbuffer()
1477 more = 0
1481 more = 0
1478 # keep cache in sync with the prompt counter:
1482 # keep cache in sync with the prompt counter:
1479 self.outputcache.prompt_count -= 1
1483 self.outputcache.prompt_count -= 1
1480
1484
1481 if self.autoindent:
1485 if self.autoindent:
1482 self.indent_current_nsp = 0
1486 self.indent_current_nsp = 0
1483
1487
1484 except bdb.BdbQuit:
1488 except bdb.BdbQuit:
1485 warn("The Python debugger has exited with a BdbQuit exception.\n"
1489 warn("The Python debugger has exited with a BdbQuit exception.\n"
1486 "Because of how pdb handles the stack, it is impossible\n"
1490 "Because of how pdb handles the stack, it is impossible\n"
1487 "for IPython to properly format this particular exception.\n"
1491 "for IPython to properly format this particular exception.\n"
1488 "IPython will resume normal operation.")
1492 "IPython will resume normal operation.")
1489
1493
1490 # We are off again...
1494 # We are off again...
1491 __builtin__.__dict__['__IPYTHON__active'] -= 1
1495 __builtin__.__dict__['__IPYTHON__active'] -= 1
1492
1496
1493 def excepthook(self, type, value, tb):
1497 def excepthook(self, type, value, tb):
1494 """One more defense for GUI apps that call sys.excepthook.
1498 """One more defense for GUI apps that call sys.excepthook.
1495
1499
1496 GUI frameworks like wxPython trap exceptions and call
1500 GUI frameworks like wxPython trap exceptions and call
1497 sys.excepthook themselves. I guess this is a feature that
1501 sys.excepthook themselves. I guess this is a feature that
1498 enables them to keep running after exceptions that would
1502 enables them to keep running after exceptions that would
1499 otherwise kill their mainloop. This is a bother for IPython
1503 otherwise kill their mainloop. This is a bother for IPython
1500 which excepts to catch all of the program exceptions with a try:
1504 which excepts to catch all of the program exceptions with a try:
1501 except: statement.
1505 except: statement.
1502
1506
1503 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1507 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1504 any app directly invokes sys.excepthook, it will look to the user like
1508 any app directly invokes sys.excepthook, it will look to the user like
1505 IPython crashed. In order to work around this, we can disable the
1509 IPython crashed. In order to work around this, we can disable the
1506 CrashHandler and replace it with this excepthook instead, which prints a
1510 CrashHandler and replace it with this excepthook instead, which prints a
1507 regular traceback using our InteractiveTB. In this fashion, apps which
1511 regular traceback using our InteractiveTB. In this fashion, apps which
1508 call sys.excepthook will generate a regular-looking exception from
1512 call sys.excepthook will generate a regular-looking exception from
1509 IPython, and the CrashHandler will only be triggered by real IPython
1513 IPython, and the CrashHandler will only be triggered by real IPython
1510 crashes.
1514 crashes.
1511
1515
1512 This hook should be used sparingly, only in places which are not likely
1516 This hook should be used sparingly, only in places which are not likely
1513 to be true IPython errors.
1517 to be true IPython errors.
1514 """
1518 """
1515
1519
1516 self.InteractiveTB(type, value, tb, tb_offset=0)
1520 self.InteractiveTB(type, value, tb, tb_offset=0)
1517 if self.InteractiveTB.call_pdb and self.has_readline:
1521 if self.InteractiveTB.call_pdb and self.has_readline:
1518 self.readline.set_completer(self.Completer.complete)
1522 self.readline.set_completer(self.Completer.complete)
1519
1523
1520 def call_alias(self,alias,rest=''):
1524 def call_alias(self,alias,rest=''):
1521 """Call an alias given its name and the rest of the line.
1525 """Call an alias given its name and the rest of the line.
1522
1526
1523 This function MUST be given a proper alias, because it doesn't make
1527 This function MUST be given a proper alias, because it doesn't make
1524 any checks when looking up into the alias table. The caller is
1528 any checks when looking up into the alias table. The caller is
1525 responsible for invoking it only with a valid alias."""
1529 responsible for invoking it only with a valid alias."""
1526
1530
1527 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1531 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1528 nargs,cmd = self.alias_table[alias]
1532 nargs,cmd = self.alias_table[alias]
1529 # Expand the %l special to be the user's input line
1533 # Expand the %l special to be the user's input line
1530 if cmd.find('%l') >= 0:
1534 if cmd.find('%l') >= 0:
1531 cmd = cmd.replace('%l',rest)
1535 cmd = cmd.replace('%l',rest)
1532 rest = ''
1536 rest = ''
1533 if nargs==0:
1537 if nargs==0:
1534 # Simple, argument-less aliases
1538 # Simple, argument-less aliases
1535 cmd = '%s %s' % (cmd,rest)
1539 cmd = '%s %s' % (cmd,rest)
1536 else:
1540 else:
1537 # Handle aliases with positional arguments
1541 # Handle aliases with positional arguments
1538 args = rest.split(None,nargs)
1542 args = rest.split(None,nargs)
1539 if len(args)< nargs:
1543 if len(args)< nargs:
1540 error('Alias <%s> requires %s arguments, %s given.' %
1544 error('Alias <%s> requires %s arguments, %s given.' %
1541 (alias,nargs,len(args)))
1545 (alias,nargs,len(args)))
1542 return
1546 return
1543 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1547 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1544 # Now call the macro, evaluating in the user's namespace
1548 # Now call the macro, evaluating in the user's namespace
1545 try:
1549 try:
1546 self.system(cmd)
1550 self.system(cmd)
1547 except:
1551 except:
1548 self.showtraceback()
1552 self.showtraceback()
1549
1553
1550 def indent_current_str(self):
1554 def indent_current_str(self):
1551 """return the current level of indentation as a string"""
1555 """return the current level of indentation as a string"""
1552 return self.indent_current_nsp * ' '
1556 return self.indent_current_nsp * ' '
1553
1557
1554 def autoindent_update(self,line):
1558 def autoindent_update(self,line):
1555 """Keep track of the indent level."""
1559 """Keep track of the indent level."""
1556
1560
1557 #import traceback; traceback.print_stack() # dbg
1561 #debugx('line')
1558 debugp('line')
1562 #debugx('self.indent_current_nsp')
1559 debugp('self.indent_current_nsp')
1560 if self.autoindent:
1563 if self.autoindent:
1561 if line:
1564 if line:
1562 inisp = num_ini_spaces(line)
1565 inisp = num_ini_spaces(line)
1563 if inisp < self.indent_current_nsp:
1566 if inisp < self.indent_current_nsp:
1564 self.indent_current_nsp = inisp
1567 self.indent_current_nsp = inisp
1565
1568
1566 if line[-1] == ':':
1569 if line[-1] == ':':
1567 self.indent_current_nsp += 4
1570 self.indent_current_nsp += 4
1568 elif dedent_re.match(line):
1571 elif dedent_re.match(line):
1569 self.indent_current_nsp -= 4
1572 self.indent_current_nsp -= 4
1570 else:
1573 else:
1571 self.indent_current_nsp = 0
1574 self.indent_current_nsp = 0
1572
1575
1573 def runlines(self,lines):
1576 def runlines(self,lines):
1574 """Run a string of one or more lines of source.
1577 """Run a string of one or more lines of source.
1575
1578
1576 This method is capable of running a string containing multiple source
1579 This method is capable of running a string containing multiple source
1577 lines, as if they had been entered at the IPython prompt. Since it
1580 lines, as if they had been entered at the IPython prompt. Since it
1578 exposes IPython's processing machinery, the given strings can contain
1581 exposes IPython's processing machinery, the given strings can contain
1579 magic calls (%magic), special shell access (!cmd), etc."""
1582 magic calls (%magic), special shell access (!cmd), etc."""
1580
1583
1581 # We must start with a clean buffer, in case this is run from an
1584 # We must start with a clean buffer, in case this is run from an
1582 # interactive IPython session (via a magic, for example).
1585 # interactive IPython session (via a magic, for example).
1583 self.resetbuffer()
1586 self.resetbuffer()
1584 lines = lines.split('\n')
1587 lines = lines.split('\n')
1585 more = 0
1588 more = 0
1586 for line in lines:
1589 for line in lines:
1587 # skip blank lines so we don't mess up the prompt counter, but do
1590 # skip blank lines so we don't mess up the prompt counter, but do
1588 # NOT skip even a blank line if we are in a code block (more is
1591 # NOT skip even a blank line if we are in a code block (more is
1589 # true)
1592 # true)
1590 if line or more:
1593 if line or more:
1591 more = self.push(self.prefilter(line,more))
1594 more = self.push(self.prefilter(line,more))
1592 # IPython's runsource returns None if there was an error
1595 # IPython's runsource returns None if there was an error
1593 # compiling the code. This allows us to stop processing right
1596 # compiling the code. This allows us to stop processing right
1594 # away, so the user gets the error message at the right place.
1597 # away, so the user gets the error message at the right place.
1595 if more is None:
1598 if more is None:
1596 break
1599 break
1597 # final newline in case the input didn't have it, so that the code
1600 # final newline in case the input didn't have it, so that the code
1598 # actually does get executed
1601 # actually does get executed
1599 if more:
1602 if more:
1600 self.push('\n')
1603 self.push('\n')
1601
1604
1602 def runsource(self, source, filename='<input>', symbol='single'):
1605 def runsource(self, source, filename='<input>', symbol='single'):
1603 """Compile and run some source in the interpreter.
1606 """Compile and run some source in the interpreter.
1604
1607
1605 Arguments are as for compile_command().
1608 Arguments are as for compile_command().
1606
1609
1607 One several things can happen:
1610 One several things can happen:
1608
1611
1609 1) The input is incorrect; compile_command() raised an
1612 1) The input is incorrect; compile_command() raised an
1610 exception (SyntaxError or OverflowError). A syntax traceback
1613 exception (SyntaxError or OverflowError). A syntax traceback
1611 will be printed by calling the showsyntaxerror() method.
1614 will be printed by calling the showsyntaxerror() method.
1612
1615
1613 2) The input is incomplete, and more input is required;
1616 2) The input is incomplete, and more input is required;
1614 compile_command() returned None. Nothing happens.
1617 compile_command() returned None. Nothing happens.
1615
1618
1616 3) The input is complete; compile_command() returned a code
1619 3) The input is complete; compile_command() returned a code
1617 object. The code is executed by calling self.runcode() (which
1620 object. The code is executed by calling self.runcode() (which
1618 also handles run-time exceptions, except for SystemExit).
1621 also handles run-time exceptions, except for SystemExit).
1619
1622
1620 The return value is:
1623 The return value is:
1621
1624
1622 - True in case 2
1625 - True in case 2
1623
1626
1624 - False in the other cases, unless an exception is raised, where
1627 - False in the other cases, unless an exception is raised, where
1625 None is returned instead. This can be used by external callers to
1628 None is returned instead. This can be used by external callers to
1626 know whether to continue feeding input or not.
1629 know whether to continue feeding input or not.
1627
1630
1628 The return value can be used to decide whether to use sys.ps1 or
1631 The return value can be used to decide whether to use sys.ps1 or
1629 sys.ps2 to prompt the next line."""
1632 sys.ps2 to prompt the next line."""
1630
1633
1631 try:
1634 try:
1632 code = self.compile(source,filename,symbol)
1635 code = self.compile(source,filename,symbol)
1633 except (OverflowError, SyntaxError, ValueError):
1636 except (OverflowError, SyntaxError, ValueError):
1634 # Case 1
1637 # Case 1
1635 self.showsyntaxerror(filename)
1638 self.showsyntaxerror(filename)
1636 return None
1639 return None
1637
1640
1638 if code is None:
1641 if code is None:
1639 # Case 2
1642 # Case 2
1640 return True
1643 return True
1641
1644
1642 # Case 3
1645 # Case 3
1643 # We store the code object so that threaded shells and
1646 # We store the code object so that threaded shells and
1644 # custom exception handlers can access all this info if needed.
1647 # custom exception handlers can access all this info if needed.
1645 # The source corresponding to this can be obtained from the
1648 # The source corresponding to this can be obtained from the
1646 # buffer attribute as '\n'.join(self.buffer).
1649 # buffer attribute as '\n'.join(self.buffer).
1647 self.code_to_run = code
1650 self.code_to_run = code
1648 # now actually execute the code object
1651 # now actually execute the code object
1649 if self.runcode(code) == 0:
1652 if self.runcode(code) == 0:
1650 return False
1653 return False
1651 else:
1654 else:
1652 return None
1655 return None
1653
1656
1654 def runcode(self,code_obj):
1657 def runcode(self,code_obj):
1655 """Execute a code object.
1658 """Execute a code object.
1656
1659
1657 When an exception occurs, self.showtraceback() is called to display a
1660 When an exception occurs, self.showtraceback() is called to display a
1658 traceback.
1661 traceback.
1659
1662
1660 Return value: a flag indicating whether the code to be run completed
1663 Return value: a flag indicating whether the code to be run completed
1661 successfully:
1664 successfully:
1662
1665
1663 - 0: successful execution.
1666 - 0: successful execution.
1664 - 1: an error occurred.
1667 - 1: an error occurred.
1665 """
1668 """
1666
1669
1667 # Set our own excepthook in case the user code tries to call it
1670 # Set our own excepthook in case the user code tries to call it
1668 # directly, so that the IPython crash handler doesn't get triggered
1671 # directly, so that the IPython crash handler doesn't get triggered
1669 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1672 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1670
1673
1671 # we save the original sys.excepthook in the instance, in case config
1674 # we save the original sys.excepthook in the instance, in case config
1672 # code (such as magics) needs access to it.
1675 # code (such as magics) needs access to it.
1673 self.sys_excepthook = old_excepthook
1676 self.sys_excepthook = old_excepthook
1674 outflag = 1 # happens in more places, so it's easier as default
1677 outflag = 1 # happens in more places, so it's easier as default
1675 try:
1678 try:
1676 try:
1679 try:
1677 # Embedded instances require separate global/local namespaces
1680 # Embedded instances require separate global/local namespaces
1678 # so they can see both the surrounding (local) namespace and
1681 # so they can see both the surrounding (local) namespace and
1679 # the module-level globals when called inside another function.
1682 # the module-level globals when called inside another function.
1680 if self.embedded:
1683 if self.embedded:
1681 exec code_obj in self.user_global_ns, self.user_ns
1684 exec code_obj in self.user_global_ns, self.user_ns
1682 # Normal (non-embedded) instances should only have a single
1685 # Normal (non-embedded) instances should only have a single
1683 # namespace for user code execution, otherwise functions won't
1686 # namespace for user code execution, otherwise functions won't
1684 # see interactive top-level globals.
1687 # see interactive top-level globals.
1685 else:
1688 else:
1686 exec code_obj in self.user_ns
1689 exec code_obj in self.user_ns
1687 finally:
1690 finally:
1688 # Reset our crash handler in place
1691 # Reset our crash handler in place
1689 sys.excepthook = old_excepthook
1692 sys.excepthook = old_excepthook
1690 except SystemExit:
1693 except SystemExit:
1691 self.resetbuffer()
1694 self.resetbuffer()
1692 self.showtraceback()
1695 self.showtraceback()
1693 warn("Type exit or quit to exit IPython "
1696 warn("Type exit or quit to exit IPython "
1694 "(%Exit or %Quit do so unconditionally).",level=1)
1697 "(%Exit or %Quit do so unconditionally).",level=1)
1695 except self.custom_exceptions:
1698 except self.custom_exceptions:
1696 etype,value,tb = sys.exc_info()
1699 etype,value,tb = sys.exc_info()
1697 self.CustomTB(etype,value,tb)
1700 self.CustomTB(etype,value,tb)
1698 except:
1701 except:
1699 self.showtraceback()
1702 self.showtraceback()
1700 else:
1703 else:
1701 outflag = 0
1704 outflag = 0
1702 if softspace(sys.stdout, 0):
1705 if softspace(sys.stdout, 0):
1703 print
1706 print
1704 # Flush out code object which has been run (and source)
1707 # Flush out code object which has been run (and source)
1705 self.code_to_run = None
1708 self.code_to_run = None
1706 return outflag
1709 return outflag
1707
1710
1708 def push(self, line):
1711 def push(self, line):
1709 """Push a line to the interpreter.
1712 """Push a line to the interpreter.
1710
1713
1711 The line should not have a trailing newline; it may have
1714 The line should not have a trailing newline; it may have
1712 internal newlines. The line is appended to a buffer and the
1715 internal newlines. The line is appended to a buffer and the
1713 interpreter's runsource() method is called with the
1716 interpreter's runsource() method is called with the
1714 concatenated contents of the buffer as source. If this
1717 concatenated contents of the buffer as source. If this
1715 indicates that the command was executed or invalid, the buffer
1718 indicates that the command was executed or invalid, the buffer
1716 is reset; otherwise, the command is incomplete, and the buffer
1719 is reset; otherwise, the command is incomplete, and the buffer
1717 is left as it was after the line was appended. The return
1720 is left as it was after the line was appended. The return
1718 value is 1 if more input is required, 0 if the line was dealt
1721 value is 1 if more input is required, 0 if the line was dealt
1719 with in some way (this is the same as runsource()).
1722 with in some way (this is the same as runsource()).
1720 """
1723 """
1721
1724
1722 # autoindent management should be done here, and not in the
1725 # autoindent management should be done here, and not in the
1723 # interactive loop, since that one is only seen by keyboard input. We
1726 # interactive loop, since that one is only seen by keyboard input. We
1724 # need this done correctly even for code run via runlines (which uses
1727 # need this done correctly even for code run via runlines (which uses
1725 # push).
1728 # push).
1726
1729
1727 #print 'push line: <%s>' % line # dbg
1730 #print 'push line: <%s>' % line # dbg
1728 self.autoindent_update(line)
1731 self.autoindent_update(line)
1729
1732
1730 self.buffer.append(line)
1733 self.buffer.append(line)
1731 more = self.runsource('\n'.join(self.buffer), self.filename)
1734 more = self.runsource('\n'.join(self.buffer), self.filename)
1732 if not more:
1735 if not more:
1733 self.resetbuffer()
1736 self.resetbuffer()
1734 return more
1737 return more
1735
1738
1736 def resetbuffer(self):
1739 def resetbuffer(self):
1737 """Reset the input buffer."""
1740 """Reset the input buffer."""
1738 self.buffer[:] = []
1741 self.buffer[:] = []
1739
1742
1740 def raw_input(self,prompt='',continue_prompt=False):
1743 def raw_input(self,prompt='',continue_prompt=False):
1741 """Write a prompt and read a line.
1744 """Write a prompt and read a line.
1742
1745
1743 The returned line does not include the trailing newline.
1746 The returned line does not include the trailing newline.
1744 When the user enters the EOF key sequence, EOFError is raised.
1747 When the user enters the EOF key sequence, EOFError is raised.
1745
1748
1746 Optional inputs:
1749 Optional inputs:
1747
1750
1748 - prompt(''): a string to be printed to prompt the user.
1751 - prompt(''): a string to be printed to prompt the user.
1749
1752
1750 - continue_prompt(False): whether this line is the first one or a
1753 - continue_prompt(False): whether this line is the first one or a
1751 continuation in a sequence of inputs.
1754 continuation in a sequence of inputs.
1752 """
1755 """
1753
1756
1754 line = raw_input_original(prompt)
1757 line = raw_input_original(prompt)
1755 # Try to be reasonably smart about not re-indenting pasted input more
1758 # Try to be reasonably smart about not re-indenting pasted input more
1756 # than necessary. We do this by trimming out the auto-indent initial
1759 # than necessary. We do this by trimming out the auto-indent initial
1757 # spaces, if the user's actual input started itself with whitespace.
1760 # spaces, if the user's actual input started itself with whitespace.
1758 #debugp('self.buffer[-1]')
1761 #debugx('self.buffer[-1]')
1759
1762
1760 debugp('line')
1761 debugp('self.indent_current_nsp')
1762 if self.autoindent:
1763 if self.autoindent:
1763 if num_ini_spaces(line) > self.indent_current_nsp:
1764 if num_ini_spaces(line) > self.indent_current_nsp:
1764 line = line[self.indent_current_nsp:]
1765 line = line[self.indent_current_nsp:]
1765 self.indent_current_nsp = 0
1766 self.indent_current_nsp = 0
1766 debugp('self.indent_current_nsp')
1767
1767
1768 debugp('line')
1768 # store the unfiltered input before the user has any chance to modify
1769 # it.
1770 if line.strip():
1771 if continue_prompt:
1772 self.input_hist_raw[-1] += '%s\n' % line
1773 else:
1774 self.input_hist_raw.append('%s\n' % line)
1775
1769 lineout = self.prefilter(line,continue_prompt)
1776 lineout = self.prefilter(line,continue_prompt)
1770 debugp('lineout')
1771 return lineout
1777 return lineout
1772
1778
1773 def split_user_input(self,line):
1779 def split_user_input(self,line):
1774 """Split user input into pre-char, function part and rest."""
1780 """Split user input into pre-char, function part and rest."""
1775
1781
1776 lsplit = self.line_split.match(line)
1782 lsplit = self.line_split.match(line)
1777 if lsplit is None: # no regexp match returns None
1783 if lsplit is None: # no regexp match returns None
1778 try:
1784 try:
1779 iFun,theRest = line.split(None,1)
1785 iFun,theRest = line.split(None,1)
1780 except ValueError:
1786 except ValueError:
1781 iFun,theRest = line,''
1787 iFun,theRest = line,''
1782 pre = re.match('^(\s*)(.*)',line).groups()[0]
1788 pre = re.match('^(\s*)(.*)',line).groups()[0]
1783 else:
1789 else:
1784 pre,iFun,theRest = lsplit.groups()
1790 pre,iFun,theRest = lsplit.groups()
1785
1791
1786 #print 'line:<%s>' % line # dbg
1792 #print 'line:<%s>' % line # dbg
1787 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1793 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1788 return pre,iFun.strip(),theRest
1794 return pre,iFun.strip(),theRest
1789
1795
1790 def _prefilter(self, line, continue_prompt):
1796 def _prefilter(self, line, continue_prompt):
1791 """Calls different preprocessors, depending on the form of line."""
1797 """Calls different preprocessors, depending on the form of line."""
1792
1798
1793 # All handlers *must* return a value, even if it's blank ('').
1799 # All handlers *must* return a value, even if it's blank ('').
1794
1800
1795 # Lines are NOT logged here. Handlers should process the line as
1801 # Lines are NOT logged here. Handlers should process the line as
1796 # needed, update the cache AND log it (so that the input cache array
1802 # needed, update the cache AND log it (so that the input cache array
1797 # stays synced).
1803 # stays synced).
1798
1804
1799 # This function is _very_ delicate, and since it's also the one which
1805 # This function is _very_ delicate, and since it's also the one which
1800 # determines IPython's response to user input, it must be as efficient
1806 # determines IPython's response to user input, it must be as efficient
1801 # as possible. For this reason it has _many_ returns in it, trying
1807 # as possible. For this reason it has _many_ returns in it, trying
1802 # always to exit as quickly as it can figure out what it needs to do.
1808 # always to exit as quickly as it can figure out what it needs to do.
1803
1809
1804 # This function is the main responsible for maintaining IPython's
1810 # This function is the main responsible for maintaining IPython's
1805 # behavior respectful of Python's semantics. So be _very_ careful if
1811 # behavior respectful of Python's semantics. So be _very_ careful if
1806 # making changes to anything here.
1812 # making changes to anything here.
1807
1813
1808 #.....................................................................
1814 #.....................................................................
1809 # Code begins
1815 # Code begins
1810
1816
1811 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1817 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1812
1818
1813 # save the line away in case we crash, so the post-mortem handler can
1819 # save the line away in case we crash, so the post-mortem handler can
1814 # record it
1820 # record it
1815 self._last_input_line = line
1821 self._last_input_line = line
1816
1822
1817 #print '***line: <%s>' % line # dbg
1823 #print '***line: <%s>' % line # dbg
1818
1824
1819 # the input history needs to track even empty lines
1825 # the input history needs to track even empty lines
1820 if not line.strip():
1826 if not line.strip():
1821 if not continue_prompt:
1827 if not continue_prompt:
1822 self.outputcache.prompt_count -= 1
1828 self.outputcache.prompt_count -= 1
1823 return self.handle_normal(line,continue_prompt)
1829 return self.handle_normal(line,continue_prompt)
1824 #return self.handle_normal('',continue_prompt)
1830 #return self.handle_normal('',continue_prompt)
1825
1831
1826 # print '***cont',continue_prompt # dbg
1832 # print '***cont',continue_prompt # dbg
1827 # special handlers are only allowed for single line statements
1833 # special handlers are only allowed for single line statements
1828 if continue_prompt and not self.rc.multi_line_specials:
1834 if continue_prompt and not self.rc.multi_line_specials:
1829 return self.handle_normal(line,continue_prompt)
1835 return self.handle_normal(line,continue_prompt)
1830
1836
1831 # For the rest, we need the structure of the input
1837 # For the rest, we need the structure of the input
1832 pre,iFun,theRest = self.split_user_input(line)
1838 pre,iFun,theRest = self.split_user_input(line)
1833 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1839 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1834
1840
1835 # First check for explicit escapes in the last/first character
1841 # First check for explicit escapes in the last/first character
1836 handler = None
1842 handler = None
1837 if line[-1] == self.ESC_HELP:
1843 if line[-1] == self.ESC_HELP:
1838 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1844 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1839 if handler is None:
1845 if handler is None:
1840 # look at the first character of iFun, NOT of line, so we skip
1846 # look at the first character of iFun, NOT of line, so we skip
1841 # leading whitespace in multiline input
1847 # leading whitespace in multiline input
1842 handler = self.esc_handlers.get(iFun[0:1])
1848 handler = self.esc_handlers.get(iFun[0:1])
1843 if handler is not None:
1849 if handler is not None:
1844 return handler(line,continue_prompt,pre,iFun,theRest)
1850 return handler(line,continue_prompt,pre,iFun,theRest)
1845 # Emacs ipython-mode tags certain input lines
1851 # Emacs ipython-mode tags certain input lines
1846 if line.endswith('# PYTHON-MODE'):
1852 if line.endswith('# PYTHON-MODE'):
1847 return self.handle_emacs(line,continue_prompt)
1853 return self.handle_emacs(line,continue_prompt)
1848
1854
1849 # Next, check if we can automatically execute this thing
1855 # Next, check if we can automatically execute this thing
1850
1856
1851 # Allow ! in multi-line statements if multi_line_specials is on:
1857 # Allow ! in multi-line statements if multi_line_specials is on:
1852 if continue_prompt and self.rc.multi_line_specials and \
1858 if continue_prompt and self.rc.multi_line_specials and \
1853 iFun.startswith(self.ESC_SHELL):
1859 iFun.startswith(self.ESC_SHELL):
1854 return self.handle_shell_escape(line,continue_prompt,
1860 return self.handle_shell_escape(line,continue_prompt,
1855 pre=pre,iFun=iFun,
1861 pre=pre,iFun=iFun,
1856 theRest=theRest)
1862 theRest=theRest)
1857
1863
1858 # Let's try to find if the input line is a magic fn
1864 # Let's try to find if the input line is a magic fn
1859 oinfo = None
1865 oinfo = None
1860 if hasattr(self,'magic_'+iFun):
1866 if hasattr(self,'magic_'+iFun):
1861 # WARNING: _ofind uses getattr(), so it can consume generators and
1867 # WARNING: _ofind uses getattr(), so it can consume generators and
1862 # cause other side effects.
1868 # cause other side effects.
1863 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1869 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1864 if oinfo['ismagic']:
1870 if oinfo['ismagic']:
1865 # Be careful not to call magics when a variable assignment is
1871 # Be careful not to call magics when a variable assignment is
1866 # being made (ls='hi', for example)
1872 # being made (ls='hi', for example)
1867 if self.rc.automagic and \
1873 if self.rc.automagic and \
1868 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1874 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1869 (self.rc.multi_line_specials or not continue_prompt):
1875 (self.rc.multi_line_specials or not continue_prompt):
1870 return self.handle_magic(line,continue_prompt,
1876 return self.handle_magic(line,continue_prompt,
1871 pre,iFun,theRest)
1877 pre,iFun,theRest)
1872 else:
1878 else:
1873 return self.handle_normal(line,continue_prompt)
1879 return self.handle_normal(line,continue_prompt)
1874
1880
1875 # If the rest of the line begins with an (in)equality, assginment or
1881 # If the rest of the line begins with an (in)equality, assginment or
1876 # function call, we should not call _ofind but simply execute it.
1882 # function call, we should not call _ofind but simply execute it.
1877 # This avoids spurious geattr() accesses on objects upon assignment.
1883 # This avoids spurious geattr() accesses on objects upon assignment.
1878 #
1884 #
1879 # It also allows users to assign to either alias or magic names true
1885 # It also allows users to assign to either alias or magic names true
1880 # python variables (the magic/alias systems always take second seat to
1886 # python variables (the magic/alias systems always take second seat to
1881 # true python code).
1887 # true python code).
1882 if theRest and theRest[0] in '!=()':
1888 if theRest and theRest[0] in '!=()':
1883 return self.handle_normal(line,continue_prompt)
1889 return self.handle_normal(line,continue_prompt)
1884
1890
1885 if oinfo is None:
1891 if oinfo is None:
1886 # let's try to ensure that _oinfo is ONLY called when autocall is
1892 # let's try to ensure that _oinfo is ONLY called when autocall is
1887 # on. Since it has inevitable potential side effects, at least
1893 # on. Since it has inevitable potential side effects, at least
1888 # having autocall off should be a guarantee to the user that no
1894 # having autocall off should be a guarantee to the user that no
1889 # weird things will happen.
1895 # weird things will happen.
1890
1896
1891 if self.rc.autocall:
1897 if self.rc.autocall:
1892 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1898 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1893 else:
1899 else:
1894 # in this case, all that's left is either an alias or
1900 # in this case, all that's left is either an alias or
1895 # processing the line normally.
1901 # processing the line normally.
1896 if iFun in self.alias_table:
1902 if iFun in self.alias_table:
1897 return self.handle_alias(line,continue_prompt,
1903 return self.handle_alias(line,continue_prompt,
1898 pre,iFun,theRest)
1904 pre,iFun,theRest)
1899
1905
1900 else:
1906 else:
1901 return self.handle_normal(line,continue_prompt)
1907 return self.handle_normal(line,continue_prompt)
1902
1908
1903 if not oinfo['found']:
1909 if not oinfo['found']:
1904 return self.handle_normal(line,continue_prompt)
1910 return self.handle_normal(line,continue_prompt)
1905 else:
1911 else:
1906 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1912 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1907 if oinfo['isalias']:
1913 if oinfo['isalias']:
1908 return self.handle_alias(line,continue_prompt,
1914 return self.handle_alias(line,continue_prompt,
1909 pre,iFun,theRest)
1915 pre,iFun,theRest)
1910
1916
1911 if (self.rc.autocall
1917 if (self.rc.autocall
1912 and
1918 and
1913 (
1919 (
1914 #only consider exclusion re if not "," or ";" autoquoting
1920 #only consider exclusion re if not "," or ";" autoquoting
1915 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2) or
1921 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2) or
1916 (not self.re_exclude_auto.match(theRest)))
1922 (not self.re_exclude_auto.match(theRest)))
1917 and
1923 and
1918 self.re_fun_name.match(iFun) and
1924 self.re_fun_name.match(iFun) and
1919 callable(oinfo['obj'])) :
1925 callable(oinfo['obj'])) :
1920 #print 'going auto' # dbg
1926 #print 'going auto' # dbg
1921 return self.handle_auto(line,continue_prompt,
1927 return self.handle_auto(line,continue_prompt,
1922 pre,iFun,theRest,oinfo['obj'])
1928 pre,iFun,theRest,oinfo['obj'])
1923 else:
1929 else:
1924 #print 'was callable?', callable(oinfo['obj']) # dbg
1930 #print 'was callable?', callable(oinfo['obj']) # dbg
1925 return self.handle_normal(line,continue_prompt)
1931 return self.handle_normal(line,continue_prompt)
1926
1932
1927 # If we get here, we have a normal Python line. Log and return.
1933 # If we get here, we have a normal Python line. Log and return.
1928 return self.handle_normal(line,continue_prompt)
1934 return self.handle_normal(line,continue_prompt)
1929
1935
1930 def _prefilter_dumb(self, line, continue_prompt):
1936 def _prefilter_dumb(self, line, continue_prompt):
1931 """simple prefilter function, for debugging"""
1937 """simple prefilter function, for debugging"""
1932 return self.handle_normal(line,continue_prompt)
1938 return self.handle_normal(line,continue_prompt)
1933
1939
1934 # Set the default prefilter() function (this can be user-overridden)
1940 # Set the default prefilter() function (this can be user-overridden)
1935 prefilter = _prefilter
1941 prefilter = _prefilter
1936
1942
1937 def handle_normal(self,line,continue_prompt=None,
1943 def handle_normal(self,line,continue_prompt=None,
1938 pre=None,iFun=None,theRest=None):
1944 pre=None,iFun=None,theRest=None):
1939 """Handle normal input lines. Use as a template for handlers."""
1945 """Handle normal input lines. Use as a template for handlers."""
1940
1946
1941 # With autoindent on, we need some way to exit the input loop, and I
1947 # With autoindent on, we need some way to exit the input loop, and I
1942 # don't want to force the user to have to backspace all the way to
1948 # don't want to force the user to have to backspace all the way to
1943 # clear the line. The rule will be in this case, that either two
1949 # clear the line. The rule will be in this case, that either two
1944 # lines of pure whitespace in a row, or a line of pure whitespace but
1950 # lines of pure whitespace in a row, or a line of pure whitespace but
1945 # of a size different to the indent level, will exit the input loop.
1951 # of a size different to the indent level, will exit the input loop.
1946
1952
1947 if (continue_prompt and self.autoindent and line.isspace() and
1953 if (continue_prompt and self.autoindent and line.isspace() and
1948 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1954 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1949 (self.buffer[-1]).isspace() )):
1955 (self.buffer[-1]).isspace() )):
1950 #print 'reset line' # dbg
1951 line = ''
1956 line = ''
1952
1957
1953 self.log(line,continue_prompt)
1958 self.log(line,continue_prompt)
1954 return line
1959 return line
1955
1960
1956 def handle_alias(self,line,continue_prompt=None,
1961 def handle_alias(self,line,continue_prompt=None,
1957 pre=None,iFun=None,theRest=None):
1962 pre=None,iFun=None,theRest=None):
1958 """Handle alias input lines. """
1963 """Handle alias input lines. """
1959
1964
1960 # pre is needed, because it carries the leading whitespace. Otherwise
1965 # pre is needed, because it carries the leading whitespace. Otherwise
1961 # aliases won't work in indented sections.
1966 # aliases won't work in indented sections.
1962 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1967 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1963 self.log(line_out,continue_prompt)
1968 self.log(line_out,continue_prompt)
1964 return line_out
1969 return line_out
1965
1970
1966 def handle_shell_escape(self, line, continue_prompt=None,
1971 def handle_shell_escape(self, line, continue_prompt=None,
1967 pre=None,iFun=None,theRest=None):
1972 pre=None,iFun=None,theRest=None):
1968 """Execute the line in a shell, empty return value"""
1973 """Execute the line in a shell, empty return value"""
1969
1974
1970 #print 'line in :', `line` # dbg
1975 #print 'line in :', `line` # dbg
1971 # Example of a special handler. Others follow a similar pattern.
1976 # Example of a special handler. Others follow a similar pattern.
1972 if line.lstrip().startswith('!!'):
1977 if line.lstrip().startswith('!!'):
1973 # rewrite iFun/theRest to properly hold the call to %sx and
1978 # rewrite iFun/theRest to properly hold the call to %sx and
1974 # the actual command to be executed, so handle_magic can work
1979 # the actual command to be executed, so handle_magic can work
1975 # correctly
1980 # correctly
1976 theRest = '%s %s' % (iFun[2:],theRest)
1981 theRest = '%s %s' % (iFun[2:],theRest)
1977 iFun = 'sx'
1982 iFun = 'sx'
1978 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
1983 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
1979 line.lstrip()[2:]),
1984 line.lstrip()[2:]),
1980 continue_prompt,pre,iFun,theRest)
1985 continue_prompt,pre,iFun,theRest)
1981 else:
1986 else:
1982 cmd=line.lstrip().lstrip('!')
1987 cmd=line.lstrip().lstrip('!')
1983 line_out = '%sipsystem(%s)' % (pre,make_quoted_expr(cmd))
1988 line_out = '%sipsystem(%s)' % (pre,make_quoted_expr(cmd))
1984 # update cache/log and return
1989 # update cache/log and return
1985 self.log(line_out,continue_prompt)
1990 self.log(line_out,continue_prompt)
1986 return line_out
1991 return line_out
1987
1992
1988 def handle_magic(self, line, continue_prompt=None,
1993 def handle_magic(self, line, continue_prompt=None,
1989 pre=None,iFun=None,theRest=None):
1994 pre=None,iFun=None,theRest=None):
1990 """Execute magic functions."""
1995 """Execute magic functions."""
1991
1996
1992
1997
1993 cmd = '%sipmagic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1998 cmd = '%sipmagic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1994 self.log(cmd,continue_prompt)
1999 self.log(cmd,continue_prompt)
1995 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2000 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1996 return cmd
2001 return cmd
1997
2002
1998 def handle_auto(self, line, continue_prompt=None,
2003 def handle_auto(self, line, continue_prompt=None,
1999 pre=None,iFun=None,theRest=None,obj=None):
2004 pre=None,iFun=None,theRest=None,obj=None):
2000 """Hande lines which can be auto-executed, quoting if requested."""
2005 """Hande lines which can be auto-executed, quoting if requested."""
2001
2006
2002 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2007 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2003
2008
2004 # This should only be active for single-line input!
2009 # This should only be active for single-line input!
2005 if continue_prompt:
2010 if continue_prompt:
2006 self.log(line,continue_prompt)
2011 self.log(line,continue_prompt)
2007 return line
2012 return line
2008
2013
2009 auto_rewrite = True
2014 auto_rewrite = True
2010 if pre == self.ESC_QUOTE:
2015 if pre == self.ESC_QUOTE:
2011 # Auto-quote splitting on whitespace
2016 # Auto-quote splitting on whitespace
2012 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2017 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2013 elif pre == self.ESC_QUOTE2:
2018 elif pre == self.ESC_QUOTE2:
2014 # Auto-quote whole string
2019 # Auto-quote whole string
2015 newcmd = '%s("%s")' % (iFun,theRest)
2020 newcmd = '%s("%s")' % (iFun,theRest)
2016 else:
2021 else:
2017 # Auto-paren.
2022 # Auto-paren.
2018 # We only apply it to argument-less calls if the autocall
2023 # We only apply it to argument-less calls if the autocall
2019 # parameter is set to 2. We only need to check that autocall is <
2024 # parameter is set to 2. We only need to check that autocall is <
2020 # 2, since this function isn't called unless it's at least 1.
2025 # 2, since this function isn't called unless it's at least 1.
2021 if not theRest and (self.rc.autocall < 2):
2026 if not theRest and (self.rc.autocall < 2):
2022 newcmd = '%s %s' % (iFun,theRest)
2027 newcmd = '%s %s' % (iFun,theRest)
2023 auto_rewrite = False
2028 auto_rewrite = False
2024 else:
2029 else:
2025 if theRest.startswith('['):
2030 if theRest.startswith('['):
2026 if hasattr(obj,'__getitem__'):
2031 if hasattr(obj,'__getitem__'):
2027 # Don't autocall in this case: item access for an object
2032 # Don't autocall in this case: item access for an object
2028 # which is BOTH callable and implements __getitem__.
2033 # which is BOTH callable and implements __getitem__.
2029 newcmd = '%s %s' % (iFun,theRest)
2034 newcmd = '%s %s' % (iFun,theRest)
2030 auto_rewrite = False
2035 auto_rewrite = False
2031 else:
2036 else:
2032 # if the object doesn't support [] access, go ahead and
2037 # if the object doesn't support [] access, go ahead and
2033 # autocall
2038 # autocall
2034 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2039 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2035 elif theRest.endswith(';'):
2040 elif theRest.endswith(';'):
2036 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2041 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2037 else:
2042 else:
2038 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2043 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2039
2044
2040 if auto_rewrite:
2045 if auto_rewrite:
2041 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2046 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2042 # log what is now valid Python, not the actual user input (without the
2047 # log what is now valid Python, not the actual user input (without the
2043 # final newline)
2048 # final newline)
2044 self.log(newcmd,continue_prompt)
2049 self.log(newcmd,continue_prompt)
2045 return newcmd
2050 return newcmd
2046
2051
2047 def handle_help(self, line, continue_prompt=None,
2052 def handle_help(self, line, continue_prompt=None,
2048 pre=None,iFun=None,theRest=None):
2053 pre=None,iFun=None,theRest=None):
2049 """Try to get some help for the object.
2054 """Try to get some help for the object.
2050
2055
2051 obj? or ?obj -> basic information.
2056 obj? or ?obj -> basic information.
2052 obj?? or ??obj -> more details.
2057 obj?? or ??obj -> more details.
2053 """
2058 """
2054
2059
2055 # We need to make sure that we don't process lines which would be
2060 # We need to make sure that we don't process lines which would be
2056 # otherwise valid python, such as "x=1 # what?"
2061 # otherwise valid python, such as "x=1 # what?"
2057 try:
2062 try:
2058 codeop.compile_command(line)
2063 codeop.compile_command(line)
2059 except SyntaxError:
2064 except SyntaxError:
2060 # We should only handle as help stuff which is NOT valid syntax
2065 # We should only handle as help stuff which is NOT valid syntax
2061 if line[0]==self.ESC_HELP:
2066 if line[0]==self.ESC_HELP:
2062 line = line[1:]
2067 line = line[1:]
2063 elif line[-1]==self.ESC_HELP:
2068 elif line[-1]==self.ESC_HELP:
2064 line = line[:-1]
2069 line = line[:-1]
2065 self.log('#?'+line)
2070 self.log('#?'+line)
2066 if line:
2071 if line:
2067 self.magic_pinfo(line)
2072 self.magic_pinfo(line)
2068 else:
2073 else:
2069 page(self.usage,screen_lines=self.rc.screen_length)
2074 page(self.usage,screen_lines=self.rc.screen_length)
2070 return '' # Empty string is needed here!
2075 return '' # Empty string is needed here!
2071 except:
2076 except:
2072 # Pass any other exceptions through to the normal handler
2077 # Pass any other exceptions through to the normal handler
2073 return self.handle_normal(line,continue_prompt)
2078 return self.handle_normal(line,continue_prompt)
2074 else:
2079 else:
2075 # If the code compiles ok, we should handle it normally
2080 # If the code compiles ok, we should handle it normally
2076 return self.handle_normal(line,continue_prompt)
2081 return self.handle_normal(line,continue_prompt)
2077
2082
2078 def handle_emacs(self,line,continue_prompt=None,
2083 def handle_emacs(self,line,continue_prompt=None,
2079 pre=None,iFun=None,theRest=None):
2084 pre=None,iFun=None,theRest=None):
2080 """Handle input lines marked by python-mode."""
2085 """Handle input lines marked by python-mode."""
2081
2086
2082 # Currently, nothing is done. Later more functionality can be added
2087 # Currently, nothing is done. Later more functionality can be added
2083 # here if needed.
2088 # here if needed.
2084
2089
2085 # The input cache shouldn't be updated
2090 # The input cache shouldn't be updated
2086
2091
2087 return line
2092 return line
2088
2093
2089 def mktempfile(self,data=None):
2094 def mktempfile(self,data=None):
2090 """Make a new tempfile and return its filename.
2095 """Make a new tempfile and return its filename.
2091
2096
2092 This makes a call to tempfile.mktemp, but it registers the created
2097 This makes a call to tempfile.mktemp, but it registers the created
2093 filename internally so ipython cleans it up at exit time.
2098 filename internally so ipython cleans it up at exit time.
2094
2099
2095 Optional inputs:
2100 Optional inputs:
2096
2101
2097 - data(None): if data is given, it gets written out to the temp file
2102 - data(None): if data is given, it gets written out to the temp file
2098 immediately, and the file is closed again."""
2103 immediately, and the file is closed again."""
2099
2104
2100 filename = tempfile.mktemp('.py','ipython_edit_')
2105 filename = tempfile.mktemp('.py','ipython_edit_')
2101 self.tempfiles.append(filename)
2106 self.tempfiles.append(filename)
2102
2107
2103 if data:
2108 if data:
2104 tmp_file = open(filename,'w')
2109 tmp_file = open(filename,'w')
2105 tmp_file.write(data)
2110 tmp_file.write(data)
2106 tmp_file.close()
2111 tmp_file.close()
2107 return filename
2112 return filename
2108
2113
2109 def write(self,data):
2114 def write(self,data):
2110 """Write a string to the default output"""
2115 """Write a string to the default output"""
2111 Term.cout.write(data)
2116 Term.cout.write(data)
2112
2117
2113 def write_err(self,data):
2118 def write_err(self,data):
2114 """Write a string to the default error output"""
2119 """Write a string to the default error output"""
2115 Term.cerr.write(data)
2120 Term.cerr.write(data)
2116
2121
2117 def exit(self):
2122 def exit(self):
2118 """Handle interactive exit.
2123 """Handle interactive exit.
2119
2124
2120 This method sets the exit_now attribute."""
2125 This method sets the exit_now attribute."""
2121
2126
2122 if self.rc.confirm_exit:
2127 if self.rc.confirm_exit:
2123 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2128 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2124 self.exit_now = True
2129 self.exit_now = True
2125 else:
2130 else:
2126 self.exit_now = True
2131 self.exit_now = True
2127 return self.exit_now
2132 return self.exit_now
2128
2133
2129 def safe_execfile(self,fname,*where,**kw):
2134 def safe_execfile(self,fname,*where,**kw):
2130 fname = os.path.expanduser(fname)
2135 fname = os.path.expanduser(fname)
2131
2136
2132 # find things also in current directory
2137 # find things also in current directory
2133 dname = os.path.dirname(fname)
2138 dname = os.path.dirname(fname)
2134 if not sys.path.count(dname):
2139 if not sys.path.count(dname):
2135 sys.path.append(dname)
2140 sys.path.append(dname)
2136
2141
2137 try:
2142 try:
2138 xfile = open(fname)
2143 xfile = open(fname)
2139 except:
2144 except:
2140 print >> Term.cerr, \
2145 print >> Term.cerr, \
2141 'Could not open file <%s> for safe execution.' % fname
2146 'Could not open file <%s> for safe execution.' % fname
2142 return None
2147 return None
2143
2148
2144 kw.setdefault('islog',0)
2149 kw.setdefault('islog',0)
2145 kw.setdefault('quiet',1)
2150 kw.setdefault('quiet',1)
2146 kw.setdefault('exit_ignore',0)
2151 kw.setdefault('exit_ignore',0)
2147 first = xfile.readline()
2152 first = xfile.readline()
2148 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2153 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2149 xfile.close()
2154 xfile.close()
2150 # line by line execution
2155 # line by line execution
2151 if first.startswith(loghead) or kw['islog']:
2156 if first.startswith(loghead) or kw['islog']:
2152 print 'Loading log file <%s> one line at a time...' % fname
2157 print 'Loading log file <%s> one line at a time...' % fname
2153 if kw['quiet']:
2158 if kw['quiet']:
2154 stdout_save = sys.stdout
2159 stdout_save = sys.stdout
2155 sys.stdout = StringIO.StringIO()
2160 sys.stdout = StringIO.StringIO()
2156 try:
2161 try:
2157 globs,locs = where[0:2]
2162 globs,locs = where[0:2]
2158 except:
2163 except:
2159 try:
2164 try:
2160 globs = locs = where[0]
2165 globs = locs = where[0]
2161 except:
2166 except:
2162 globs = locs = globals()
2167 globs = locs = globals()
2163 badblocks = []
2168 badblocks = []
2164
2169
2165 # we also need to identify indented blocks of code when replaying
2170 # we also need to identify indented blocks of code when replaying
2166 # logs and put them together before passing them to an exec
2171 # logs and put them together before passing them to an exec
2167 # statement. This takes a bit of regexp and look-ahead work in the
2172 # statement. This takes a bit of regexp and look-ahead work in the
2168 # file. It's easiest if we swallow the whole thing in memory
2173 # file. It's easiest if we swallow the whole thing in memory
2169 # first, and manually walk through the lines list moving the
2174 # first, and manually walk through the lines list moving the
2170 # counter ourselves.
2175 # counter ourselves.
2171 indent_re = re.compile('\s+\S')
2176 indent_re = re.compile('\s+\S')
2172 xfile = open(fname)
2177 xfile = open(fname)
2173 filelines = xfile.readlines()
2178 filelines = xfile.readlines()
2174 xfile.close()
2179 xfile.close()
2175 nlines = len(filelines)
2180 nlines = len(filelines)
2176 lnum = 0
2181 lnum = 0
2177 while lnum < nlines:
2182 while lnum < nlines:
2178 line = filelines[lnum]
2183 line = filelines[lnum]
2179 lnum += 1
2184 lnum += 1
2180 # don't re-insert logger status info into cache
2185 # don't re-insert logger status info into cache
2181 if line.startswith('#log#'):
2186 if line.startswith('#log#'):
2182 continue
2187 continue
2183 else:
2188 else:
2184 # build a block of code (maybe a single line) for execution
2189 # build a block of code (maybe a single line) for execution
2185 block = line
2190 block = line
2186 try:
2191 try:
2187 next = filelines[lnum] # lnum has already incremented
2192 next = filelines[lnum] # lnum has already incremented
2188 except:
2193 except:
2189 next = None
2194 next = None
2190 while next and indent_re.match(next):
2195 while next and indent_re.match(next):
2191 block += next
2196 block += next
2192 lnum += 1
2197 lnum += 1
2193 try:
2198 try:
2194 next = filelines[lnum]
2199 next = filelines[lnum]
2195 except:
2200 except:
2196 next = None
2201 next = None
2197 # now execute the block of one or more lines
2202 # now execute the block of one or more lines
2198 try:
2203 try:
2199 exec block in globs,locs
2204 exec block in globs,locs
2200 except SystemExit:
2205 except SystemExit:
2201 pass
2206 pass
2202 except:
2207 except:
2203 badblocks.append(block.rstrip())
2208 badblocks.append(block.rstrip())
2204 if kw['quiet']: # restore stdout
2209 if kw['quiet']: # restore stdout
2205 sys.stdout.close()
2210 sys.stdout.close()
2206 sys.stdout = stdout_save
2211 sys.stdout = stdout_save
2207 print 'Finished replaying log file <%s>' % fname
2212 print 'Finished replaying log file <%s>' % fname
2208 if badblocks:
2213 if badblocks:
2209 print >> sys.stderr, ('\nThe following lines/blocks in file '
2214 print >> sys.stderr, ('\nThe following lines/blocks in file '
2210 '<%s> reported errors:' % fname)
2215 '<%s> reported errors:' % fname)
2211
2216
2212 for badline in badblocks:
2217 for badline in badblocks:
2213 print >> sys.stderr, badline
2218 print >> sys.stderr, badline
2214 else: # regular file execution
2219 else: # regular file execution
2215 try:
2220 try:
2216 execfile(fname,*where)
2221 execfile(fname,*where)
2217 except SyntaxError:
2222 except SyntaxError:
2218 etype,evalue = sys.exc_info()[:2]
2223 etype,evalue = sys.exc_info()[:2]
2219 self.SyntaxTB(etype,evalue,[])
2224 self.SyntaxTB(etype,evalue,[])
2220 warn('Failure executing file: <%s>' % fname)
2225 warn('Failure executing file: <%s>' % fname)
2221 except SystemExit,status:
2226 except SystemExit,status:
2222 if not kw['exit_ignore']:
2227 if not kw['exit_ignore']:
2223 self.InteractiveTB()
2228 self.InteractiveTB()
2224 warn('Failure executing file: <%s>' % fname)
2229 warn('Failure executing file: <%s>' % fname)
2225 except:
2230 except:
2226 self.InteractiveTB()
2231 self.InteractiveTB()
2227 warn('Failure executing file: <%s>' % fname)
2232 warn('Failure executing file: <%s>' % fname)
2228
2233
2229 #************************* end of file <iplib.py> *****************************
2234 #************************* end of file <iplib.py> *****************************
@@ -1,5041 +1,5066 b''
1 2006-01-24 Ville Vainio <vivainio@gmail.com>
1 2006-01-24 Ville Vainio <vivainio@gmail.com>
2
2
3 * iplib.py, hooks.py: 'result_display' hook can return a non-None
3 * iplib.py, hooks.py: 'result_display' hook can return a non-None
4 value to manipulate resulting history entry.
4 value to manipulate resulting history entry.
5
5
6 * ipapi.py: Moved TryNext here from hooks.py, added
6 * ipapi.py: Moved TryNext here from hooks.py, added
7 is_ipython_session() to determine whether we are running
7 is_ipython_session() to determine whether we are running
8 inside an ipython session.
8 inside an ipython session.
9
10 * Merged 1071-1076 from banches/0.7.1
11
12 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
13
14 * tools/release (daystamp): Fix build tools to use the new
15 eggsetup.py script to build lightweight eggs.
16
17 * Applied changesets 1062 and 1064 before 0.7.1 release.
18
19 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
20 see the raw input history (without conversions like %ls ->
21 ipmagic("ls")). After a request from W. Stein, SAGE
22 (http://modular.ucsd.edu/sage) developer. This information is
23 stored in the input_hist_raw attribute of the IPython instance, so
24 developers can access it if needed (it's an InputList instance).
25
26 * Versionstring = 0.7.2.svn
27
28 * eggsetup.py: A separate script for constructing eggs, creates
29 proper launch scripts even on Windows (an .exe file in
30 \python24\scripts).
31
32 * ipapi.py: launch_new_instance, launch entry point needed for the
33 egg.
9
34
10 2006-01-23 Ville Vainio <vivainio@gmail.com>
35 2006-01-23 Ville Vainio <vivainio@gmail.com>
11
36
12 * Added %cpaste magic for pasting python code
37 * Added %cpaste magic for pasting python code
13
38
14 2006-01-22 Ville Vainio <vivainio@gmail.com>
39 2006-01-22 Ville Vainio <vivainio@gmail.com>
15
40
16 * Merge from branches/0.7.1 into trunk, revs 1052-1057
41 * Merge from branches/0.7.1 into trunk, revs 1052-1057
17
42
18 * Versionstring = 0.7.2.svn
43 * Versionstring = 0.7.2.svn
19
44
20 * eggsetup.py: A separate script for constructing eggs, creates
45 * eggsetup.py: A separate script for constructing eggs, creates
21 proper launch scripts even on Windows (an .exe file in
46 proper launch scripts even on Windows (an .exe file in
22 \python24\scripts).
47 \python24\scripts).
23
48
24 * ipapi.py: launch_new_instance, launch entry point needed for the
49 * ipapi.py: launch_new_instance, launch entry point needed for the
25 egg.
50 egg.
26
51
27 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
52 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
28
53
29 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
54 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
30 %pfile foo would print the file for foo even if it was a binary.
55 %pfile foo would print the file for foo even if it was a binary.
31 Now, extensions '.so' and '.dll' are skipped.
56 Now, extensions '.so' and '.dll' are skipped.
32
57
33 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
58 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
34 bug, where macros would fail in all threaded modes. I'm not 100%
59 bug, where macros would fail in all threaded modes. I'm not 100%
35 sure, so I'm going to put out an rc instead of making a release
60 sure, so I'm going to put out an rc instead of making a release
36 today, and wait for feedback for at least a few days.
61 today, and wait for feedback for at least a few days.
37
62
38 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
63 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
39 it...) the handling of pasting external code with autoindent on.
64 it...) the handling of pasting external code with autoindent on.
40 To get out of a multiline input, the rule will appear for most
65 To get out of a multiline input, the rule will appear for most
41 users unchanged: two blank lines or change the indent level
66 users unchanged: two blank lines or change the indent level
42 proposed by IPython. But there is a twist now: you can
67 proposed by IPython. But there is a twist now: you can
43 add/subtract only *one or two spaces*. If you add/subtract three
68 add/subtract only *one or two spaces*. If you add/subtract three
44 or more (unless you completely delete the line), IPython will
69 or more (unless you completely delete the line), IPython will
45 accept that line, and you'll need to enter a second one of pure
70 accept that line, and you'll need to enter a second one of pure
46 whitespace. I know it sounds complicated, but I can't find a
71 whitespace. I know it sounds complicated, but I can't find a
47 different solution that covers all the cases, with the right
72 different solution that covers all the cases, with the right
48 heuristics. Hopefully in actual use, nobody will really notice
73 heuristics. Hopefully in actual use, nobody will really notice
49 all these strange rules and things will 'just work'.
74 all these strange rules and things will 'just work'.
50
75
51 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
76 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
52
77
53 * IPython/iplib.py (interact): catch exceptions which can be
78 * IPython/iplib.py (interact): catch exceptions which can be
54 triggered asynchronously by signal handlers. Thanks to an
79 triggered asynchronously by signal handlers. Thanks to an
55 automatic crash report, submitted by Colin Kingsley
80 automatic crash report, submitted by Colin Kingsley
56 <tercel-AT-gentoo.org>.
81 <tercel-AT-gentoo.org>.
57
82
58 2006-01-20 Ville Vainio <vivainio@gmail.com>
83 2006-01-20 Ville Vainio <vivainio@gmail.com>
59
84
60 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
85 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
61 (%rehashdir, very useful, try it out) of how to extend ipython
86 (%rehashdir, very useful, try it out) of how to extend ipython
62 with new magics. Also added Extensions dir to pythonpath to make
87 with new magics. Also added Extensions dir to pythonpath to make
63 importing extensions easy.
88 importing extensions easy.
64
89
65 * %store now complains when trying to store interactively declared
90 * %store now complains when trying to store interactively declared
66 classes / instances of those classes.
91 classes / instances of those classes.
67
92
68 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
93 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
69 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
94 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
70 if they exist, and ipy_user_conf.py with some defaults is created for
95 if they exist, and ipy_user_conf.py with some defaults is created for
71 the user.
96 the user.
72
97
73 * Startup rehashing done by the config file, not InterpreterExec.
98 * Startup rehashing done by the config file, not InterpreterExec.
74 This means system commands are available even without selecting the
99 This means system commands are available even without selecting the
75 pysh profile. It's the sensible default after all.
100 pysh profile. It's the sensible default after all.
76
101
77 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
102 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
78
103
79 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
104 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
80 multiline code with autoindent on working. But I am really not
105 multiline code with autoindent on working. But I am really not
81 sure, so this needs more testing. Will commit a debug-enabled
106 sure, so this needs more testing. Will commit a debug-enabled
82 version for now, while I test it some more, so that Ville and
107 version for now, while I test it some more, so that Ville and
83 others may also catch any problems. Also made
108 others may also catch any problems. Also made
84 self.indent_current_str() a method, to ensure that there's no
109 self.indent_current_str() a method, to ensure that there's no
85 chance of the indent space count and the corresponding string
110 chance of the indent space count and the corresponding string
86 falling out of sync. All code needing the string should just call
111 falling out of sync. All code needing the string should just call
87 the method.
112 the method.
88
113
89 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
114 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
90
115
91 * IPython/Magic.py (magic_edit): fix check for when users don't
116 * IPython/Magic.py (magic_edit): fix check for when users don't
92 save their output files, the try/except was in the wrong section.
117 save their output files, the try/except was in the wrong section.
93
118
94 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
119 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
95
120
96 * IPython/Magic.py (magic_run): fix __file__ global missing from
121 * IPython/Magic.py (magic_run): fix __file__ global missing from
97 script's namespace when executed via %run. After a report by
122 script's namespace when executed via %run. After a report by
98 Vivian.
123 Vivian.
99
124
100 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
125 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
101 when using python 2.4. The parent constructor changed in 2.4, and
126 when using python 2.4. The parent constructor changed in 2.4, and
102 we need to track it directly (we can't call it, as it messes up
127 we need to track it directly (we can't call it, as it messes up
103 readline and tab-completion inside our pdb would stop working).
128 readline and tab-completion inside our pdb would stop working).
104 After a bug report by R. Bernstein <rocky-AT-panix.com>.
129 After a bug report by R. Bernstein <rocky-AT-panix.com>.
105
130
106 2006-01-16 Ville Vainio <vivainio@gmail.com>
131 2006-01-16 Ville Vainio <vivainio@gmail.com>
107
132
108 * Ipython/magic.py:Reverted back to old %edit functionality
133 * Ipython/magic.py:Reverted back to old %edit functionality
109 that returns file contents on exit.
134 that returns file contents on exit.
110
135
111 * IPython/path.py: Added Jason Orendorff's "path" module to
136 * IPython/path.py: Added Jason Orendorff's "path" module to
112 IPython tree, http://www.jorendorff.com/articles/python/path/.
137 IPython tree, http://www.jorendorff.com/articles/python/path/.
113 You can get path objects conveniently through %sc, and !!, e.g.:
138 You can get path objects conveniently through %sc, and !!, e.g.:
114 sc files=ls
139 sc files=ls
115 for p in files.paths: # or files.p
140 for p in files.paths: # or files.p
116 print p,p.mtime
141 print p,p.mtime
117
142
118 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
143 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
119 now work again without considering the exclusion regexp -
144 now work again without considering the exclusion regexp -
120 hence, things like ',foo my/path' turn to 'foo("my/path")'
145 hence, things like ',foo my/path' turn to 'foo("my/path")'
121 instead of syntax error.
146 instead of syntax error.
122
147
123
148
124 2006-01-14 Ville Vainio <vivainio@gmail.com>
149 2006-01-14 Ville Vainio <vivainio@gmail.com>
125
150
126 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
151 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
127 ipapi decorators for python 2.4 users, options() provides access to rc
152 ipapi decorators for python 2.4 users, options() provides access to rc
128 data.
153 data.
129
154
130 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
155 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
131 as path separators (even on Linux ;-). Space character after
156 as path separators (even on Linux ;-). Space character after
132 backslash (as yielded by tab completer) is still space;
157 backslash (as yielded by tab completer) is still space;
133 "%cd long\ name" works as expected.
158 "%cd long\ name" works as expected.
134
159
135 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
160 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
136 as "chain of command", with priority. API stays the same,
161 as "chain of command", with priority. API stays the same,
137 TryNext exception raised by a hook function signals that
162 TryNext exception raised by a hook function signals that
138 current hook failed and next hook should try handling it, as
163 current hook failed and next hook should try handling it, as
139 suggested by Walter Dörwald <walter@livinglogic.de>. Walter also
164 suggested by Walter Dörwald <walter@livinglogic.de>. Walter also
140 requested configurable display hook, which is now implemented.
165 requested configurable display hook, which is now implemented.
141
166
142 2006-01-13 Ville Vainio <vivainio@gmail.com>
167 2006-01-13 Ville Vainio <vivainio@gmail.com>
143
168
144 * IPython/platutils*.py: platform specific utility functions,
169 * IPython/platutils*.py: platform specific utility functions,
145 so far only set_term_title is implemented (change terminal
170 so far only set_term_title is implemented (change terminal
146 label in windowing systems). %cd now changes the title to
171 label in windowing systems). %cd now changes the title to
147 current dir.
172 current dir.
148
173
149 * IPython/Release.py: Added myself to "authors" list,
174 * IPython/Release.py: Added myself to "authors" list,
150 had to create new files.
175 had to create new files.
151
176
152 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
177 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
153 shell escape; not a known bug but had potential to be one in the
178 shell escape; not a known bug but had potential to be one in the
154 future.
179 future.
155
180
156 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
181 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
157 extension API for IPython! See the module for usage example. Fix
182 extension API for IPython! See the module for usage example. Fix
158 OInspect for docstring-less magic functions.
183 OInspect for docstring-less magic functions.
159
184
160
185
161 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
186 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
162
187
163 * IPython/iplib.py (raw_input): temporarily deactivate all
188 * IPython/iplib.py (raw_input): temporarily deactivate all
164 attempts at allowing pasting of code with autoindent on. It
189 attempts at allowing pasting of code with autoindent on. It
165 introduced bugs (reported by Prabhu) and I can't seem to find a
190 introduced bugs (reported by Prabhu) and I can't seem to find a
166 robust combination which works in all cases. Will have to revisit
191 robust combination which works in all cases. Will have to revisit
167 later.
192 later.
168
193
169 * IPython/genutils.py: remove isspace() function. We've dropped
194 * IPython/genutils.py: remove isspace() function. We've dropped
170 2.2 compatibility, so it's OK to use the string method.
195 2.2 compatibility, so it's OK to use the string method.
171
196
172 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
197 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
173
198
174 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
199 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
175 matching what NOT to autocall on, to include all python binary
200 matching what NOT to autocall on, to include all python binary
176 operators (including things like 'and', 'or', 'is' and 'in').
201 operators (including things like 'and', 'or', 'is' and 'in').
177 Prompted by a bug report on 'foo & bar', but I realized we had
202 Prompted by a bug report on 'foo & bar', but I realized we had
178 many more potential bug cases with other operators. The regexp is
203 many more potential bug cases with other operators. The regexp is
179 self.re_exclude_auto, it's fairly commented.
204 self.re_exclude_auto, it's fairly commented.
180
205
181 2006-01-12 Ville Vainio <vivainio@gmail.com>
206 2006-01-12 Ville Vainio <vivainio@gmail.com>
182
207
183 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
208 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
184 Prettified and hardened string/backslash quoting with ipsystem(),
209 Prettified and hardened string/backslash quoting with ipsystem(),
185 ipalias() and ipmagic(). Now even \ characters are passed to
210 ipalias() and ipmagic(). Now even \ characters are passed to
186 %magics, !shell escapes and aliases exactly as they are in the
211 %magics, !shell escapes and aliases exactly as they are in the
187 ipython command line. Should improve backslash experience,
212 ipython command line. Should improve backslash experience,
188 particularly in Windows (path delimiter for some commands that
213 particularly in Windows (path delimiter for some commands that
189 won't understand '/'), but Unix benefits as well (regexps). %cd
214 won't understand '/'), but Unix benefits as well (regexps). %cd
190 magic still doesn't support backslash path delimiters, though. Also
215 magic still doesn't support backslash path delimiters, though. Also
191 deleted all pretense of supporting multiline command strings in
216 deleted all pretense of supporting multiline command strings in
192 !system or %magic commands. Thanks to Jerry McRae for suggestions.
217 !system or %magic commands. Thanks to Jerry McRae for suggestions.
193
218
194 * doc/build_doc_instructions.txt added. Documentation on how to
219 * doc/build_doc_instructions.txt added. Documentation on how to
195 use doc/update_manual.py, added yesterday. Both files contributed
220 use doc/update_manual.py, added yesterday. Both files contributed
196 by Jörgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
221 by Jörgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
197 doc/*.sh for deprecation at a later date.
222 doc/*.sh for deprecation at a later date.
198
223
199 * /ipython.py Added ipython.py to root directory for
224 * /ipython.py Added ipython.py to root directory for
200 zero-installation (tar xzvf ipython.tgz; cd ipython; python
225 zero-installation (tar xzvf ipython.tgz; cd ipython; python
201 ipython.py) and development convenience (no need to kee doing
226 ipython.py) and development convenience (no need to kee doing
202 "setup.py install" between changes).
227 "setup.py install" between changes).
203
228
204 * Made ! and !! shell escapes work (again) in multiline expressions:
229 * Made ! and !! shell escapes work (again) in multiline expressions:
205 if 1:
230 if 1:
206 !ls
231 !ls
207 !!ls
232 !!ls
208
233
209 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
234 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
210
235
211 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
236 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
212 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
237 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
213 module in case-insensitive installation. Was causing crashes
238 module in case-insensitive installation. Was causing crashes
214 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
239 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
215
240
216 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
241 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
217 <marienz-AT-gentoo.org>, closes
242 <marienz-AT-gentoo.org>, closes
218 http://www.scipy.net/roundup/ipython/issue51.
243 http://www.scipy.net/roundup/ipython/issue51.
219
244
220 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
245 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
221
246
222 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
247 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
223 problem of excessive CPU usage under *nix and keyboard lag under
248 problem of excessive CPU usage under *nix and keyboard lag under
224 win32.
249 win32.
225
250
226 2006-01-10 *** Released version 0.7.0
251 2006-01-10 *** Released version 0.7.0
227
252
228 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
253 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
229
254
230 * IPython/Release.py (revision): tag version number to 0.7.0,
255 * IPython/Release.py (revision): tag version number to 0.7.0,
231 ready for release.
256 ready for release.
232
257
233 * IPython/Magic.py (magic_edit): Add print statement to %edit so
258 * IPython/Magic.py (magic_edit): Add print statement to %edit so
234 it informs the user of the name of the temp. file used. This can
259 it informs the user of the name of the temp. file used. This can
235 help if you decide later to reuse that same file, so you know
260 help if you decide later to reuse that same file, so you know
236 where to copy the info from.
261 where to copy the info from.
237
262
238 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
263 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
239
264
240 * setup_bdist_egg.py: little script to build an egg. Added
265 * setup_bdist_egg.py: little script to build an egg. Added
241 support in the release tools as well.
266 support in the release tools as well.
242
267
243 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
268 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
244
269
245 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
270 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
246 version selection (new -wxversion command line and ipythonrc
271 version selection (new -wxversion command line and ipythonrc
247 parameter). Patch contributed by Arnd Baecker
272 parameter). Patch contributed by Arnd Baecker
248 <arnd.baecker-AT-web.de>.
273 <arnd.baecker-AT-web.de>.
249
274
250 * IPython/iplib.py (embed_mainloop): fix tab-completion in
275 * IPython/iplib.py (embed_mainloop): fix tab-completion in
251 embedded instances, for variables defined at the interactive
276 embedded instances, for variables defined at the interactive
252 prompt of the embedded ipython. Reported by Arnd.
277 prompt of the embedded ipython. Reported by Arnd.
253
278
254 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
279 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
255 it can be used as a (stateful) toggle, or with a direct parameter.
280 it can be used as a (stateful) toggle, or with a direct parameter.
256
281
257 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
282 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
258 could be triggered in certain cases and cause the traceback
283 could be triggered in certain cases and cause the traceback
259 printer not to work.
284 printer not to work.
260
285
261 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
286 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
262
287
263 * IPython/iplib.py (_should_recompile): Small fix, closes
288 * IPython/iplib.py (_should_recompile): Small fix, closes
264 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
289 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
265
290
266 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
291 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
267
292
268 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
293 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
269 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
294 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
270 Moad for help with tracking it down.
295 Moad for help with tracking it down.
271
296
272 * IPython/iplib.py (handle_auto): fix autocall handling for
297 * IPython/iplib.py (handle_auto): fix autocall handling for
273 objects which support BOTH __getitem__ and __call__ (so that f [x]
298 objects which support BOTH __getitem__ and __call__ (so that f [x]
274 is left alone, instead of becoming f([x]) automatically).
299 is left alone, instead of becoming f([x]) automatically).
275
300
276 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
301 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
277 Ville's patch.
302 Ville's patch.
278
303
279 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
304 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
280
305
281 * IPython/iplib.py (handle_auto): changed autocall semantics to
306 * IPython/iplib.py (handle_auto): changed autocall semantics to
282 include 'smart' mode, where the autocall transformation is NOT
307 include 'smart' mode, where the autocall transformation is NOT
283 applied if there are no arguments on the line. This allows you to
308 applied if there are no arguments on the line. This allows you to
284 just type 'foo' if foo is a callable to see its internal form,
309 just type 'foo' if foo is a callable to see its internal form,
285 instead of having it called with no arguments (typically a
310 instead of having it called with no arguments (typically a
286 mistake). The old 'full' autocall still exists: for that, you
311 mistake). The old 'full' autocall still exists: for that, you
287 need to set the 'autocall' parameter to 2 in your ipythonrc file.
312 need to set the 'autocall' parameter to 2 in your ipythonrc file.
288
313
289 * IPython/completer.py (Completer.attr_matches): add
314 * IPython/completer.py (Completer.attr_matches): add
290 tab-completion support for Enthoughts' traits. After a report by
315 tab-completion support for Enthoughts' traits. After a report by
291 Arnd and a patch by Prabhu.
316 Arnd and a patch by Prabhu.
292
317
293 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
318 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
294
319
295 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
320 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
296 Schmolck's patch to fix inspect.getinnerframes().
321 Schmolck's patch to fix inspect.getinnerframes().
297
322
298 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
323 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
299 for embedded instances, regarding handling of namespaces and items
324 for embedded instances, regarding handling of namespaces and items
300 added to the __builtin__ one. Multiple embedded instances and
325 added to the __builtin__ one. Multiple embedded instances and
301 recursive embeddings should work better now (though I'm not sure
326 recursive embeddings should work better now (though I'm not sure
302 I've got all the corner cases fixed, that code is a bit of a brain
327 I've got all the corner cases fixed, that code is a bit of a brain
303 twister).
328 twister).
304
329
305 * IPython/Magic.py (magic_edit): added support to edit in-memory
330 * IPython/Magic.py (magic_edit): added support to edit in-memory
306 macros (automatically creates the necessary temp files). %edit
331 macros (automatically creates the necessary temp files). %edit
307 also doesn't return the file contents anymore, it's just noise.
332 also doesn't return the file contents anymore, it's just noise.
308
333
309 * IPython/completer.py (Completer.attr_matches): revert change to
334 * IPython/completer.py (Completer.attr_matches): revert change to
310 complete only on attributes listed in __all__. I realized it
335 complete only on attributes listed in __all__. I realized it
311 cripples the tab-completion system as a tool for exploring the
336 cripples the tab-completion system as a tool for exploring the
312 internals of unknown libraries (it renders any non-__all__
337 internals of unknown libraries (it renders any non-__all__
313 attribute off-limits). I got bit by this when trying to see
338 attribute off-limits). I got bit by this when trying to see
314 something inside the dis module.
339 something inside the dis module.
315
340
316 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
341 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
317
342
318 * IPython/iplib.py (InteractiveShell.__init__): add .meta
343 * IPython/iplib.py (InteractiveShell.__init__): add .meta
319 namespace for users and extension writers to hold data in. This
344 namespace for users and extension writers to hold data in. This
320 follows the discussion in
345 follows the discussion in
321 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
346 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
322
347
323 * IPython/completer.py (IPCompleter.complete): small patch to help
348 * IPython/completer.py (IPCompleter.complete): small patch to help
324 tab-completion under Emacs, after a suggestion by John Barnard
349 tab-completion under Emacs, after a suggestion by John Barnard
325 <barnarj-AT-ccf.org>.
350 <barnarj-AT-ccf.org>.
326
351
327 * IPython/Magic.py (Magic.extract_input_slices): added support for
352 * IPython/Magic.py (Magic.extract_input_slices): added support for
328 the slice notation in magics to use N-M to represent numbers N...M
353 the slice notation in magics to use N-M to represent numbers N...M
329 (closed endpoints). This is used by %macro and %save.
354 (closed endpoints). This is used by %macro and %save.
330
355
331 * IPython/completer.py (Completer.attr_matches): for modules which
356 * IPython/completer.py (Completer.attr_matches): for modules which
332 define __all__, complete only on those. After a patch by Jeffrey
357 define __all__, complete only on those. After a patch by Jeffrey
333 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
358 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
334 speed up this routine.
359 speed up this routine.
335
360
336 * IPython/Logger.py (Logger.log): fix a history handling bug. I
361 * IPython/Logger.py (Logger.log): fix a history handling bug. I
337 don't know if this is the end of it, but the behavior now is
362 don't know if this is the end of it, but the behavior now is
338 certainly much more correct. Note that coupled with macros,
363 certainly much more correct. Note that coupled with macros,
339 slightly surprising (at first) behavior may occur: a macro will in
364 slightly surprising (at first) behavior may occur: a macro will in
340 general expand to multiple lines of input, so upon exiting, the
365 general expand to multiple lines of input, so upon exiting, the
341 in/out counters will both be bumped by the corresponding amount
366 in/out counters will both be bumped by the corresponding amount
342 (as if the macro's contents had been typed interactively). Typing
367 (as if the macro's contents had been typed interactively). Typing
343 %hist will reveal the intermediate (silently processed) lines.
368 %hist will reveal the intermediate (silently processed) lines.
344
369
345 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
370 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
346 pickle to fail (%run was overwriting __main__ and not restoring
371 pickle to fail (%run was overwriting __main__ and not restoring
347 it, but pickle relies on __main__ to operate).
372 it, but pickle relies on __main__ to operate).
348
373
349 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
374 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
350 using properties, but forgot to make the main InteractiveShell
375 using properties, but forgot to make the main InteractiveShell
351 class a new-style class. Properties fail silently, and
376 class a new-style class. Properties fail silently, and
352 misteriously, with old-style class (getters work, but
377 misteriously, with old-style class (getters work, but
353 setters don't do anything).
378 setters don't do anything).
354
379
355 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
380 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
356
381
357 * IPython/Magic.py (magic_history): fix history reporting bug (I
382 * IPython/Magic.py (magic_history): fix history reporting bug (I
358 know some nasties are still there, I just can't seem to find a
383 know some nasties are still there, I just can't seem to find a
359 reproducible test case to track them down; the input history is
384 reproducible test case to track them down; the input history is
360 falling out of sync...)
385 falling out of sync...)
361
386
362 * IPython/iplib.py (handle_shell_escape): fix bug where both
387 * IPython/iplib.py (handle_shell_escape): fix bug where both
363 aliases and system accesses where broken for indented code (such
388 aliases and system accesses where broken for indented code (such
364 as loops).
389 as loops).
365
390
366 * IPython/genutils.py (shell): fix small but critical bug for
391 * IPython/genutils.py (shell): fix small but critical bug for
367 win32 system access.
392 win32 system access.
368
393
369 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
394 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
370
395
371 * IPython/iplib.py (showtraceback): remove use of the
396 * IPython/iplib.py (showtraceback): remove use of the
372 sys.last_{type/value/traceback} structures, which are non
397 sys.last_{type/value/traceback} structures, which are non
373 thread-safe.
398 thread-safe.
374 (_prefilter): change control flow to ensure that we NEVER
399 (_prefilter): change control flow to ensure that we NEVER
375 introspect objects when autocall is off. This will guarantee that
400 introspect objects when autocall is off. This will guarantee that
376 having an input line of the form 'x.y', where access to attribute
401 having an input line of the form 'x.y', where access to attribute
377 'y' has side effects, doesn't trigger the side effect TWICE. It
402 'y' has side effects, doesn't trigger the side effect TWICE. It
378 is important to note that, with autocall on, these side effects
403 is important to note that, with autocall on, these side effects
379 can still happen.
404 can still happen.
380 (ipsystem): new builtin, to complete the ip{magic/alias/system}
405 (ipsystem): new builtin, to complete the ip{magic/alias/system}
381 trio. IPython offers these three kinds of special calls which are
406 trio. IPython offers these three kinds of special calls which are
382 not python code, and it's a good thing to have their call method
407 not python code, and it's a good thing to have their call method
383 be accessible as pure python functions (not just special syntax at
408 be accessible as pure python functions (not just special syntax at
384 the command line). It gives us a better internal implementation
409 the command line). It gives us a better internal implementation
385 structure, as well as exposing these for user scripting more
410 structure, as well as exposing these for user scripting more
386 cleanly.
411 cleanly.
387
412
388 * IPython/macro.py (Macro.__init__): moved macros to a standalone
413 * IPython/macro.py (Macro.__init__): moved macros to a standalone
389 file. Now that they'll be more likely to be used with the
414 file. Now that they'll be more likely to be used with the
390 persistance system (%store), I want to make sure their module path
415 persistance system (%store), I want to make sure their module path
391 doesn't change in the future, so that we don't break things for
416 doesn't change in the future, so that we don't break things for
392 users' persisted data.
417 users' persisted data.
393
418
394 * IPython/iplib.py (autoindent_update): move indentation
419 * IPython/iplib.py (autoindent_update): move indentation
395 management into the _text_ processing loop, not the keyboard
420 management into the _text_ processing loop, not the keyboard
396 interactive one. This is necessary to correctly process non-typed
421 interactive one. This is necessary to correctly process non-typed
397 multiline input (such as macros).
422 multiline input (such as macros).
398
423
399 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
424 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
400 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
425 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
401 which was producing problems in the resulting manual.
426 which was producing problems in the resulting manual.
402 (magic_whos): improve reporting of instances (show their class,
427 (magic_whos): improve reporting of instances (show their class,
403 instead of simply printing 'instance' which isn't terribly
428 instead of simply printing 'instance' which isn't terribly
404 informative).
429 informative).
405
430
406 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
431 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
407 (minor mods) to support network shares under win32.
432 (minor mods) to support network shares under win32.
408
433
409 * IPython/winconsole.py (get_console_size): add new winconsole
434 * IPython/winconsole.py (get_console_size): add new winconsole
410 module and fixes to page_dumb() to improve its behavior under
435 module and fixes to page_dumb() to improve its behavior under
411 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
436 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
412
437
413 * IPython/Magic.py (Macro): simplified Macro class to just
438 * IPython/Magic.py (Macro): simplified Macro class to just
414 subclass list. We've had only 2.2 compatibility for a very long
439 subclass list. We've had only 2.2 compatibility for a very long
415 time, yet I was still avoiding subclassing the builtin types. No
440 time, yet I was still avoiding subclassing the builtin types. No
416 more (I'm also starting to use properties, though I won't shift to
441 more (I'm also starting to use properties, though I won't shift to
417 2.3-specific features quite yet).
442 2.3-specific features quite yet).
418 (magic_store): added Ville's patch for lightweight variable
443 (magic_store): added Ville's patch for lightweight variable
419 persistence, after a request on the user list by Matt Wilkie
444 persistence, after a request on the user list by Matt Wilkie
420 <maphew-AT-gmail.com>. The new %store magic's docstring has full
445 <maphew-AT-gmail.com>. The new %store magic's docstring has full
421 details.
446 details.
422
447
423 * IPython/iplib.py (InteractiveShell.post_config_initialization):
448 * IPython/iplib.py (InteractiveShell.post_config_initialization):
424 changed the default logfile name from 'ipython.log' to
449 changed the default logfile name from 'ipython.log' to
425 'ipython_log.py'. These logs are real python files, and now that
450 'ipython_log.py'. These logs are real python files, and now that
426 we have much better multiline support, people are more likely to
451 we have much better multiline support, people are more likely to
427 want to use them as such. Might as well name them correctly.
452 want to use them as such. Might as well name them correctly.
428
453
429 * IPython/Magic.py: substantial cleanup. While we can't stop
454 * IPython/Magic.py: substantial cleanup. While we can't stop
430 using magics as mixins, due to the existing customizations 'out
455 using magics as mixins, due to the existing customizations 'out
431 there' which rely on the mixin naming conventions, at least I
456 there' which rely on the mixin naming conventions, at least I
432 cleaned out all cross-class name usage. So once we are OK with
457 cleaned out all cross-class name usage. So once we are OK with
433 breaking compatibility, the two systems can be separated.
458 breaking compatibility, the two systems can be separated.
434
459
435 * IPython/Logger.py: major cleanup. This one is NOT a mixin
460 * IPython/Logger.py: major cleanup. This one is NOT a mixin
436 anymore, and the class is a fair bit less hideous as well. New
461 anymore, and the class is a fair bit less hideous as well. New
437 features were also introduced: timestamping of input, and logging
462 features were also introduced: timestamping of input, and logging
438 of output results. These are user-visible with the -t and -o
463 of output results. These are user-visible with the -t and -o
439 options to %logstart. Closes
464 options to %logstart. Closes
440 http://www.scipy.net/roundup/ipython/issue11 and a request by
465 http://www.scipy.net/roundup/ipython/issue11 and a request by
441 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
466 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
442
467
443 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
468 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
444
469
445 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
470 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
446 better hadnle backslashes in paths. See the thread 'More Windows
471 better hadnle backslashes in paths. See the thread 'More Windows
447 questions part 2 - \/ characters revisited' on the iypthon user
472 questions part 2 - \/ characters revisited' on the iypthon user
448 list:
473 list:
449 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
474 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
450
475
451 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
476 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
452
477
453 (InteractiveShell.__init__): change threaded shells to not use the
478 (InteractiveShell.__init__): change threaded shells to not use the
454 ipython crash handler. This was causing more problems than not,
479 ipython crash handler. This was causing more problems than not,
455 as exceptions in the main thread (GUI code, typically) would
480 as exceptions in the main thread (GUI code, typically) would
456 always show up as a 'crash', when they really weren't.
481 always show up as a 'crash', when they really weren't.
457
482
458 The colors and exception mode commands (%colors/%xmode) have been
483 The colors and exception mode commands (%colors/%xmode) have been
459 synchronized to also take this into account, so users can get
484 synchronized to also take this into account, so users can get
460 verbose exceptions for their threaded code as well. I also added
485 verbose exceptions for their threaded code as well. I also added
461 support for activating pdb inside this exception handler as well,
486 support for activating pdb inside this exception handler as well,
462 so now GUI authors can use IPython's enhanced pdb at runtime.
487 so now GUI authors can use IPython's enhanced pdb at runtime.
463
488
464 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
489 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
465 true by default, and add it to the shipped ipythonrc file. Since
490 true by default, and add it to the shipped ipythonrc file. Since
466 this asks the user before proceeding, I think it's OK to make it
491 this asks the user before proceeding, I think it's OK to make it
467 true by default.
492 true by default.
468
493
469 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
494 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
470 of the previous special-casing of input in the eval loop. I think
495 of the previous special-casing of input in the eval loop. I think
471 this is cleaner, as they really are commands and shouldn't have
496 this is cleaner, as they really are commands and shouldn't have
472 a special role in the middle of the core code.
497 a special role in the middle of the core code.
473
498
474 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
499 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
475
500
476 * IPython/iplib.py (edit_syntax_error): added support for
501 * IPython/iplib.py (edit_syntax_error): added support for
477 automatically reopening the editor if the file had a syntax error
502 automatically reopening the editor if the file had a syntax error
478 in it. Thanks to scottt who provided the patch at:
503 in it. Thanks to scottt who provided the patch at:
479 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
504 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
480 version committed).
505 version committed).
481
506
482 * IPython/iplib.py (handle_normal): add suport for multi-line
507 * IPython/iplib.py (handle_normal): add suport for multi-line
483 input with emtpy lines. This fixes
508 input with emtpy lines. This fixes
484 http://www.scipy.net/roundup/ipython/issue43 and a similar
509 http://www.scipy.net/roundup/ipython/issue43 and a similar
485 discussion on the user list.
510 discussion on the user list.
486
511
487 WARNING: a behavior change is necessarily introduced to support
512 WARNING: a behavior change is necessarily introduced to support
488 blank lines: now a single blank line with whitespace does NOT
513 blank lines: now a single blank line with whitespace does NOT
489 break the input loop, which means that when autoindent is on, by
514 break the input loop, which means that when autoindent is on, by
490 default hitting return on the next (indented) line does NOT exit.
515 default hitting return on the next (indented) line does NOT exit.
491
516
492 Instead, to exit a multiline input you can either have:
517 Instead, to exit a multiline input you can either have:
493
518
494 - TWO whitespace lines (just hit return again), or
519 - TWO whitespace lines (just hit return again), or
495 - a single whitespace line of a different length than provided
520 - a single whitespace line of a different length than provided
496 by the autoindent (add or remove a space).
521 by the autoindent (add or remove a space).
497
522
498 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
523 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
499 module to better organize all readline-related functionality.
524 module to better organize all readline-related functionality.
500 I've deleted FlexCompleter and put all completion clases here.
525 I've deleted FlexCompleter and put all completion clases here.
501
526
502 * IPython/iplib.py (raw_input): improve indentation management.
527 * IPython/iplib.py (raw_input): improve indentation management.
503 It is now possible to paste indented code with autoindent on, and
528 It is now possible to paste indented code with autoindent on, and
504 the code is interpreted correctly (though it still looks bad on
529 the code is interpreted correctly (though it still looks bad on
505 screen, due to the line-oriented nature of ipython).
530 screen, due to the line-oriented nature of ipython).
506 (MagicCompleter.complete): change behavior so that a TAB key on an
531 (MagicCompleter.complete): change behavior so that a TAB key on an
507 otherwise empty line actually inserts a tab, instead of completing
532 otherwise empty line actually inserts a tab, instead of completing
508 on the entire global namespace. This makes it easier to use the
533 on the entire global namespace. This makes it easier to use the
509 TAB key for indentation. After a request by Hans Meine
534 TAB key for indentation. After a request by Hans Meine
510 <hans_meine-AT-gmx.net>
535 <hans_meine-AT-gmx.net>
511 (_prefilter): add support so that typing plain 'exit' or 'quit'
536 (_prefilter): add support so that typing plain 'exit' or 'quit'
512 does a sensible thing. Originally I tried to deviate as little as
537 does a sensible thing. Originally I tried to deviate as little as
513 possible from the default python behavior, but even that one may
538 possible from the default python behavior, but even that one may
514 change in this direction (thread on python-dev to that effect).
539 change in this direction (thread on python-dev to that effect).
515 Regardless, ipython should do the right thing even if CPython's
540 Regardless, ipython should do the right thing even if CPython's
516 '>>>' prompt doesn't.
541 '>>>' prompt doesn't.
517 (InteractiveShell): removed subclassing code.InteractiveConsole
542 (InteractiveShell): removed subclassing code.InteractiveConsole
518 class. By now we'd overridden just about all of its methods: I've
543 class. By now we'd overridden just about all of its methods: I've
519 copied the remaining two over, and now ipython is a standalone
544 copied the remaining two over, and now ipython is a standalone
520 class. This will provide a clearer picture for the chainsaw
545 class. This will provide a clearer picture for the chainsaw
521 branch refactoring.
546 branch refactoring.
522
547
523 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
548 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
524
549
525 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
550 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
526 failures for objects which break when dir() is called on them.
551 failures for objects which break when dir() is called on them.
527
552
528 * IPython/FlexCompleter.py (Completer.__init__): Added support for
553 * IPython/FlexCompleter.py (Completer.__init__): Added support for
529 distinct local and global namespaces in the completer API. This
554 distinct local and global namespaces in the completer API. This
530 change allows us top properly handle completion with distinct
555 change allows us top properly handle completion with distinct
531 scopes, including in embedded instances (this had never really
556 scopes, including in embedded instances (this had never really
532 worked correctly).
557 worked correctly).
533
558
534 Note: this introduces a change in the constructor for
559 Note: this introduces a change in the constructor for
535 MagicCompleter, as a new global_namespace parameter is now the
560 MagicCompleter, as a new global_namespace parameter is now the
536 second argument (the others were bumped one position).
561 second argument (the others were bumped one position).
537
562
538 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
563 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
539
564
540 * IPython/iplib.py (embed_mainloop): fix tab-completion in
565 * IPython/iplib.py (embed_mainloop): fix tab-completion in
541 embedded instances (which can be done now thanks to Vivian's
566 embedded instances (which can be done now thanks to Vivian's
542 frame-handling fixes for pdb).
567 frame-handling fixes for pdb).
543 (InteractiveShell.__init__): Fix namespace handling problem in
568 (InteractiveShell.__init__): Fix namespace handling problem in
544 embedded instances. We were overwriting __main__ unconditionally,
569 embedded instances. We were overwriting __main__ unconditionally,
545 and this should only be done for 'full' (non-embedded) IPython;
570 and this should only be done for 'full' (non-embedded) IPython;
546 embedded instances must respect the caller's __main__. Thanks to
571 embedded instances must respect the caller's __main__. Thanks to
547 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
572 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
548
573
549 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
574 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
550
575
551 * setup.py: added download_url to setup(). This registers the
576 * setup.py: added download_url to setup(). This registers the
552 download address at PyPI, which is not only useful to humans
577 download address at PyPI, which is not only useful to humans
553 browsing the site, but is also picked up by setuptools (the Eggs
578 browsing the site, but is also picked up by setuptools (the Eggs
554 machinery). Thanks to Ville and R. Kern for the info/discussion
579 machinery). Thanks to Ville and R. Kern for the info/discussion
555 on this.
580 on this.
556
581
557 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
582 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
558
583
559 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
584 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
560 This brings a lot of nice functionality to the pdb mode, which now
585 This brings a lot of nice functionality to the pdb mode, which now
561 has tab-completion, syntax highlighting, and better stack handling
586 has tab-completion, syntax highlighting, and better stack handling
562 than before. Many thanks to Vivian De Smedt
587 than before. Many thanks to Vivian De Smedt
563 <vivian-AT-vdesmedt.com> for the original patches.
588 <vivian-AT-vdesmedt.com> for the original patches.
564
589
565 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
590 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
566
591
567 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
592 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
568 sequence to consistently accept the banner argument. The
593 sequence to consistently accept the banner argument. The
569 inconsistency was tripping SAGE, thanks to Gary Zablackis
594 inconsistency was tripping SAGE, thanks to Gary Zablackis
570 <gzabl-AT-yahoo.com> for the report.
595 <gzabl-AT-yahoo.com> for the report.
571
596
572 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
597 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
573
598
574 * IPython/iplib.py (InteractiveShell.post_config_initialization):
599 * IPython/iplib.py (InteractiveShell.post_config_initialization):
575 Fix bug where a naked 'alias' call in the ipythonrc file would
600 Fix bug where a naked 'alias' call in the ipythonrc file would
576 cause a crash. Bug reported by Jorgen Stenarson.
601 cause a crash. Bug reported by Jorgen Stenarson.
577
602
578 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
603 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
579
604
580 * IPython/ipmaker.py (make_IPython): cleanups which should improve
605 * IPython/ipmaker.py (make_IPython): cleanups which should improve
581 startup time.
606 startup time.
582
607
583 * IPython/iplib.py (runcode): my globals 'fix' for embedded
608 * IPython/iplib.py (runcode): my globals 'fix' for embedded
584 instances had introduced a bug with globals in normal code. Now
609 instances had introduced a bug with globals in normal code. Now
585 it's working in all cases.
610 it's working in all cases.
586
611
587 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
612 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
588 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
613 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
589 has been introduced to set the default case sensitivity of the
614 has been introduced to set the default case sensitivity of the
590 searches. Users can still select either mode at runtime on a
615 searches. Users can still select either mode at runtime on a
591 per-search basis.
616 per-search basis.
592
617
593 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
618 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
594
619
595 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
620 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
596 attributes in wildcard searches for subclasses. Modified version
621 attributes in wildcard searches for subclasses. Modified version
597 of a patch by Jorgen.
622 of a patch by Jorgen.
598
623
599 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
624 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
600
625
601 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
626 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
602 embedded instances. I added a user_global_ns attribute to the
627 embedded instances. I added a user_global_ns attribute to the
603 InteractiveShell class to handle this.
628 InteractiveShell class to handle this.
604
629
605 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
630 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
606
631
607 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
632 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
608 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
633 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
609 (reported under win32, but may happen also in other platforms).
634 (reported under win32, but may happen also in other platforms).
610 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
635 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
611
636
612 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
637 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
613
638
614 * IPython/Magic.py (magic_psearch): new support for wildcard
639 * IPython/Magic.py (magic_psearch): new support for wildcard
615 patterns. Now, typing ?a*b will list all names which begin with a
640 patterns. Now, typing ?a*b will list all names which begin with a
616 and end in b, for example. The %psearch magic has full
641 and end in b, for example. The %psearch magic has full
617 docstrings. Many thanks to Jörgen Stenarson
642 docstrings. Many thanks to Jörgen Stenarson
618 <jorgen.stenarson-AT-bostream.nu>, author of the patches
643 <jorgen.stenarson-AT-bostream.nu>, author of the patches
619 implementing this functionality.
644 implementing this functionality.
620
645
621 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
646 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
622
647
623 * Manual: fixed long-standing annoyance of double-dashes (as in
648 * Manual: fixed long-standing annoyance of double-dashes (as in
624 --prefix=~, for example) being stripped in the HTML version. This
649 --prefix=~, for example) being stripped in the HTML version. This
625 is a latex2html bug, but a workaround was provided. Many thanks
650 is a latex2html bug, but a workaround was provided. Many thanks
626 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
651 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
627 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
652 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
628 rolling. This seemingly small issue had tripped a number of users
653 rolling. This seemingly small issue had tripped a number of users
629 when first installing, so I'm glad to see it gone.
654 when first installing, so I'm glad to see it gone.
630
655
631 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
656 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
632
657
633 * IPython/Extensions/numeric_formats.py: fix missing import,
658 * IPython/Extensions/numeric_formats.py: fix missing import,
634 reported by Stephen Walton.
659 reported by Stephen Walton.
635
660
636 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
661 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
637
662
638 * IPython/demo.py: finish demo module, fully documented now.
663 * IPython/demo.py: finish demo module, fully documented now.
639
664
640 * IPython/genutils.py (file_read): simple little utility to read a
665 * IPython/genutils.py (file_read): simple little utility to read a
641 file and ensure it's closed afterwards.
666 file and ensure it's closed afterwards.
642
667
643 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
668 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
644
669
645 * IPython/demo.py (Demo.__init__): added support for individually
670 * IPython/demo.py (Demo.__init__): added support for individually
646 tagging blocks for automatic execution.
671 tagging blocks for automatic execution.
647
672
648 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
673 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
649 syntax-highlighted python sources, requested by John.
674 syntax-highlighted python sources, requested by John.
650
675
651 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
676 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
652
677
653 * IPython/demo.py (Demo.again): fix bug where again() blocks after
678 * IPython/demo.py (Demo.again): fix bug where again() blocks after
654 finishing.
679 finishing.
655
680
656 * IPython/genutils.py (shlex_split): moved from Magic to here,
681 * IPython/genutils.py (shlex_split): moved from Magic to here,
657 where all 2.2 compatibility stuff lives. I needed it for demo.py.
682 where all 2.2 compatibility stuff lives. I needed it for demo.py.
658
683
659 * IPython/demo.py (Demo.__init__): added support for silent
684 * IPython/demo.py (Demo.__init__): added support for silent
660 blocks, improved marks as regexps, docstrings written.
685 blocks, improved marks as regexps, docstrings written.
661 (Demo.__init__): better docstring, added support for sys.argv.
686 (Demo.__init__): better docstring, added support for sys.argv.
662
687
663 * IPython/genutils.py (marquee): little utility used by the demo
688 * IPython/genutils.py (marquee): little utility used by the demo
664 code, handy in general.
689 code, handy in general.
665
690
666 * IPython/demo.py (Demo.__init__): new class for interactive
691 * IPython/demo.py (Demo.__init__): new class for interactive
667 demos. Not documented yet, I just wrote it in a hurry for
692 demos. Not documented yet, I just wrote it in a hurry for
668 scipy'05. Will docstring later.
693 scipy'05. Will docstring later.
669
694
670 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
695 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
671
696
672 * IPython/Shell.py (sigint_handler): Drastic simplification which
697 * IPython/Shell.py (sigint_handler): Drastic simplification which
673 also seems to make Ctrl-C work correctly across threads! This is
698 also seems to make Ctrl-C work correctly across threads! This is
674 so simple, that I can't beleive I'd missed it before. Needs more
699 so simple, that I can't beleive I'd missed it before. Needs more
675 testing, though.
700 testing, though.
676 (KBINT): Never mind, revert changes. I'm sure I'd tried something
701 (KBINT): Never mind, revert changes. I'm sure I'd tried something
677 like this before...
702 like this before...
678
703
679 * IPython/genutils.py (get_home_dir): add protection against
704 * IPython/genutils.py (get_home_dir): add protection against
680 non-dirs in win32 registry.
705 non-dirs in win32 registry.
681
706
682 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
707 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
683 bug where dict was mutated while iterating (pysh crash).
708 bug where dict was mutated while iterating (pysh crash).
684
709
685 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
710 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
686
711
687 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
712 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
688 spurious newlines added by this routine. After a report by
713 spurious newlines added by this routine. After a report by
689 F. Mantegazza.
714 F. Mantegazza.
690
715
691 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
716 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
692
717
693 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
718 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
694 calls. These were a leftover from the GTK 1.x days, and can cause
719 calls. These were a leftover from the GTK 1.x days, and can cause
695 problems in certain cases (after a report by John Hunter).
720 problems in certain cases (after a report by John Hunter).
696
721
697 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
722 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
698 os.getcwd() fails at init time. Thanks to patch from David Remahl
723 os.getcwd() fails at init time. Thanks to patch from David Remahl
699 <chmod007-AT-mac.com>.
724 <chmod007-AT-mac.com>.
700 (InteractiveShell.__init__): prevent certain special magics from
725 (InteractiveShell.__init__): prevent certain special magics from
701 being shadowed by aliases. Closes
726 being shadowed by aliases. Closes
702 http://www.scipy.net/roundup/ipython/issue41.
727 http://www.scipy.net/roundup/ipython/issue41.
703
728
704 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
729 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
705
730
706 * IPython/iplib.py (InteractiveShell.complete): Added new
731 * IPython/iplib.py (InteractiveShell.complete): Added new
707 top-level completion method to expose the completion mechanism
732 top-level completion method to expose the completion mechanism
708 beyond readline-based environments.
733 beyond readline-based environments.
709
734
710 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
735 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
711
736
712 * tools/ipsvnc (svnversion): fix svnversion capture.
737 * tools/ipsvnc (svnversion): fix svnversion capture.
713
738
714 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
739 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
715 attribute to self, which was missing. Before, it was set by a
740 attribute to self, which was missing. Before, it was set by a
716 routine which in certain cases wasn't being called, so the
741 routine which in certain cases wasn't being called, so the
717 instance could end up missing the attribute. This caused a crash.
742 instance could end up missing the attribute. This caused a crash.
718 Closes http://www.scipy.net/roundup/ipython/issue40.
743 Closes http://www.scipy.net/roundup/ipython/issue40.
719
744
720 2005-08-16 Fernando Perez <fperez@colorado.edu>
745 2005-08-16 Fernando Perez <fperez@colorado.edu>
721
746
722 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
747 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
723 contains non-string attribute. Closes
748 contains non-string attribute. Closes
724 http://www.scipy.net/roundup/ipython/issue38.
749 http://www.scipy.net/roundup/ipython/issue38.
725
750
726 2005-08-14 Fernando Perez <fperez@colorado.edu>
751 2005-08-14 Fernando Perez <fperez@colorado.edu>
727
752
728 * tools/ipsvnc: Minor improvements, to add changeset info.
753 * tools/ipsvnc: Minor improvements, to add changeset info.
729
754
730 2005-08-12 Fernando Perez <fperez@colorado.edu>
755 2005-08-12 Fernando Perez <fperez@colorado.edu>
731
756
732 * IPython/iplib.py (runsource): remove self.code_to_run_src
757 * IPython/iplib.py (runsource): remove self.code_to_run_src
733 attribute. I realized this is nothing more than
758 attribute. I realized this is nothing more than
734 '\n'.join(self.buffer), and having the same data in two different
759 '\n'.join(self.buffer), and having the same data in two different
735 places is just asking for synchronization bugs. This may impact
760 places is just asking for synchronization bugs. This may impact
736 people who have custom exception handlers, so I need to warn
761 people who have custom exception handlers, so I need to warn
737 ipython-dev about it (F. Mantegazza may use them).
762 ipython-dev about it (F. Mantegazza may use them).
738
763
739 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
764 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
740
765
741 * IPython/genutils.py: fix 2.2 compatibility (generators)
766 * IPython/genutils.py: fix 2.2 compatibility (generators)
742
767
743 2005-07-18 Fernando Perez <fperez@colorado.edu>
768 2005-07-18 Fernando Perez <fperez@colorado.edu>
744
769
745 * IPython/genutils.py (get_home_dir): fix to help users with
770 * IPython/genutils.py (get_home_dir): fix to help users with
746 invalid $HOME under win32.
771 invalid $HOME under win32.
747
772
748 2005-07-17 Fernando Perez <fperez@colorado.edu>
773 2005-07-17 Fernando Perez <fperez@colorado.edu>
749
774
750 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
775 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
751 some old hacks and clean up a bit other routines; code should be
776 some old hacks and clean up a bit other routines; code should be
752 simpler and a bit faster.
777 simpler and a bit faster.
753
778
754 * IPython/iplib.py (interact): removed some last-resort attempts
779 * IPython/iplib.py (interact): removed some last-resort attempts
755 to survive broken stdout/stderr. That code was only making it
780 to survive broken stdout/stderr. That code was only making it
756 harder to abstract out the i/o (necessary for gui integration),
781 harder to abstract out the i/o (necessary for gui integration),
757 and the crashes it could prevent were extremely rare in practice
782 and the crashes it could prevent were extremely rare in practice
758 (besides being fully user-induced in a pretty violent manner).
783 (besides being fully user-induced in a pretty violent manner).
759
784
760 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
785 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
761 Nothing major yet, but the code is simpler to read; this should
786 Nothing major yet, but the code is simpler to read; this should
762 make it easier to do more serious modifications in the future.
787 make it easier to do more serious modifications in the future.
763
788
764 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
789 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
765 which broke in .15 (thanks to a report by Ville).
790 which broke in .15 (thanks to a report by Ville).
766
791
767 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
792 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
768 be quite correct, I know next to nothing about unicode). This
793 be quite correct, I know next to nothing about unicode). This
769 will allow unicode strings to be used in prompts, amongst other
794 will allow unicode strings to be used in prompts, amongst other
770 cases. It also will prevent ipython from crashing when unicode
795 cases. It also will prevent ipython from crashing when unicode
771 shows up unexpectedly in many places. If ascii encoding fails, we
796 shows up unexpectedly in many places. If ascii encoding fails, we
772 assume utf_8. Currently the encoding is not a user-visible
797 assume utf_8. Currently the encoding is not a user-visible
773 setting, though it could be made so if there is demand for it.
798 setting, though it could be made so if there is demand for it.
774
799
775 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
800 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
776
801
777 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
802 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
778
803
779 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
804 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
780
805
781 * IPython/genutils.py: Add 2.2 compatibility here, so all other
806 * IPython/genutils.py: Add 2.2 compatibility here, so all other
782 code can work transparently for 2.2/2.3.
807 code can work transparently for 2.2/2.3.
783
808
784 2005-07-16 Fernando Perez <fperez@colorado.edu>
809 2005-07-16 Fernando Perez <fperez@colorado.edu>
785
810
786 * IPython/ultraTB.py (ExceptionColors): Make a global variable
811 * IPython/ultraTB.py (ExceptionColors): Make a global variable
787 out of the color scheme table used for coloring exception
812 out of the color scheme table used for coloring exception
788 tracebacks. This allows user code to add new schemes at runtime.
813 tracebacks. This allows user code to add new schemes at runtime.
789 This is a minimally modified version of the patch at
814 This is a minimally modified version of the patch at
790 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
815 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
791 for the contribution.
816 for the contribution.
792
817
793 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
818 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
794 slightly modified version of the patch in
819 slightly modified version of the patch in
795 http://www.scipy.net/roundup/ipython/issue34, which also allows me
820 http://www.scipy.net/roundup/ipython/issue34, which also allows me
796 to remove the previous try/except solution (which was costlier).
821 to remove the previous try/except solution (which was costlier).
797 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
822 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
798
823
799 2005-06-08 Fernando Perez <fperez@colorado.edu>
824 2005-06-08 Fernando Perez <fperez@colorado.edu>
800
825
801 * IPython/iplib.py (write/write_err): Add methods to abstract all
826 * IPython/iplib.py (write/write_err): Add methods to abstract all
802 I/O a bit more.
827 I/O a bit more.
803
828
804 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
829 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
805 warning, reported by Aric Hagberg, fix by JD Hunter.
830 warning, reported by Aric Hagberg, fix by JD Hunter.
806
831
807 2005-06-02 *** Released version 0.6.15
832 2005-06-02 *** Released version 0.6.15
808
833
809 2005-06-01 Fernando Perez <fperez@colorado.edu>
834 2005-06-01 Fernando Perez <fperez@colorado.edu>
810
835
811 * IPython/iplib.py (MagicCompleter.file_matches): Fix
836 * IPython/iplib.py (MagicCompleter.file_matches): Fix
812 tab-completion of filenames within open-quoted strings. Note that
837 tab-completion of filenames within open-quoted strings. Note that
813 this requires that in ~/.ipython/ipythonrc, users change the
838 this requires that in ~/.ipython/ipythonrc, users change the
814 readline delimiters configuration to read:
839 readline delimiters configuration to read:
815
840
816 readline_remove_delims -/~
841 readline_remove_delims -/~
817
842
818
843
819 2005-05-31 *** Released version 0.6.14
844 2005-05-31 *** Released version 0.6.14
820
845
821 2005-05-29 Fernando Perez <fperez@colorado.edu>
846 2005-05-29 Fernando Perez <fperez@colorado.edu>
822
847
823 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
848 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
824 with files not on the filesystem. Reported by Eliyahu Sandler
849 with files not on the filesystem. Reported by Eliyahu Sandler
825 <eli@gondolin.net>
850 <eli@gondolin.net>
826
851
827 2005-05-22 Fernando Perez <fperez@colorado.edu>
852 2005-05-22 Fernando Perez <fperez@colorado.edu>
828
853
829 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
854 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
830 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
855 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
831
856
832 2005-05-19 Fernando Perez <fperez@colorado.edu>
857 2005-05-19 Fernando Perez <fperez@colorado.edu>
833
858
834 * IPython/iplib.py (safe_execfile): close a file which could be
859 * IPython/iplib.py (safe_execfile): close a file which could be
835 left open (causing problems in win32, which locks open files).
860 left open (causing problems in win32, which locks open files).
836 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
861 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
837
862
838 2005-05-18 Fernando Perez <fperez@colorado.edu>
863 2005-05-18 Fernando Perez <fperez@colorado.edu>
839
864
840 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
865 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
841 keyword arguments correctly to safe_execfile().
866 keyword arguments correctly to safe_execfile().
842
867
843 2005-05-13 Fernando Perez <fperez@colorado.edu>
868 2005-05-13 Fernando Perez <fperez@colorado.edu>
844
869
845 * ipython.1: Added info about Qt to manpage, and threads warning
870 * ipython.1: Added info about Qt to manpage, and threads warning
846 to usage page (invoked with --help).
871 to usage page (invoked with --help).
847
872
848 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
873 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
849 new matcher (it goes at the end of the priority list) to do
874 new matcher (it goes at the end of the priority list) to do
850 tab-completion on named function arguments. Submitted by George
875 tab-completion on named function arguments. Submitted by George
851 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
876 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
852 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
877 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
853 for more details.
878 for more details.
854
879
855 * IPython/Magic.py (magic_run): Added new -e flag to ignore
880 * IPython/Magic.py (magic_run): Added new -e flag to ignore
856 SystemExit exceptions in the script being run. Thanks to a report
881 SystemExit exceptions in the script being run. Thanks to a report
857 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
882 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
858 producing very annoying behavior when running unit tests.
883 producing very annoying behavior when running unit tests.
859
884
860 2005-05-12 Fernando Perez <fperez@colorado.edu>
885 2005-05-12 Fernando Perez <fperez@colorado.edu>
861
886
862 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
887 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
863 which I'd broken (again) due to a changed regexp. In the process,
888 which I'd broken (again) due to a changed regexp. In the process,
864 added ';' as an escape to auto-quote the whole line without
889 added ';' as an escape to auto-quote the whole line without
865 splitting its arguments. Thanks to a report by Jerry McRae
890 splitting its arguments. Thanks to a report by Jerry McRae
866 <qrs0xyc02-AT-sneakemail.com>.
891 <qrs0xyc02-AT-sneakemail.com>.
867
892
868 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
893 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
869 possible crashes caused by a TokenError. Reported by Ed Schofield
894 possible crashes caused by a TokenError. Reported by Ed Schofield
870 <schofield-AT-ftw.at>.
895 <schofield-AT-ftw.at>.
871
896
872 2005-05-06 Fernando Perez <fperez@colorado.edu>
897 2005-05-06 Fernando Perez <fperez@colorado.edu>
873
898
874 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
899 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
875
900
876 2005-04-29 Fernando Perez <fperez@colorado.edu>
901 2005-04-29 Fernando Perez <fperez@colorado.edu>
877
902
878 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
903 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
879 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
904 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
880 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
905 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
881 which provides support for Qt interactive usage (similar to the
906 which provides support for Qt interactive usage (similar to the
882 existing one for WX and GTK). This had been often requested.
907 existing one for WX and GTK). This had been often requested.
883
908
884 2005-04-14 *** Released version 0.6.13
909 2005-04-14 *** Released version 0.6.13
885
910
886 2005-04-08 Fernando Perez <fperez@colorado.edu>
911 2005-04-08 Fernando Perez <fperez@colorado.edu>
887
912
888 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
913 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
889 from _ofind, which gets called on almost every input line. Now,
914 from _ofind, which gets called on almost every input line. Now,
890 we only try to get docstrings if they are actually going to be
915 we only try to get docstrings if they are actually going to be
891 used (the overhead of fetching unnecessary docstrings can be
916 used (the overhead of fetching unnecessary docstrings can be
892 noticeable for certain objects, such as Pyro proxies).
917 noticeable for certain objects, such as Pyro proxies).
893
918
894 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
919 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
895 for completers. For some reason I had been passing them the state
920 for completers. For some reason I had been passing them the state
896 variable, which completers never actually need, and was in
921 variable, which completers never actually need, and was in
897 conflict with the rlcompleter API. Custom completers ONLY need to
922 conflict with the rlcompleter API. Custom completers ONLY need to
898 take the text parameter.
923 take the text parameter.
899
924
900 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
925 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
901 work correctly in pysh. I've also moved all the logic which used
926 work correctly in pysh. I've also moved all the logic which used
902 to be in pysh.py here, which will prevent problems with future
927 to be in pysh.py here, which will prevent problems with future
903 upgrades. However, this time I must warn users to update their
928 upgrades. However, this time I must warn users to update their
904 pysh profile to include the line
929 pysh profile to include the line
905
930
906 import_all IPython.Extensions.InterpreterExec
931 import_all IPython.Extensions.InterpreterExec
907
932
908 because otherwise things won't work for them. They MUST also
933 because otherwise things won't work for them. They MUST also
909 delete pysh.py and the line
934 delete pysh.py and the line
910
935
911 execfile pysh.py
936 execfile pysh.py
912
937
913 from their ipythonrc-pysh.
938 from their ipythonrc-pysh.
914
939
915 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
940 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
916 robust in the face of objects whose dir() returns non-strings
941 robust in the face of objects whose dir() returns non-strings
917 (which it shouldn't, but some broken libs like ITK do). Thanks to
942 (which it shouldn't, but some broken libs like ITK do). Thanks to
918 a patch by John Hunter (implemented differently, though). Also
943 a patch by John Hunter (implemented differently, though). Also
919 minor improvements by using .extend instead of + on lists.
944 minor improvements by using .extend instead of + on lists.
920
945
921 * pysh.py:
946 * pysh.py:
922
947
923 2005-04-06 Fernando Perez <fperez@colorado.edu>
948 2005-04-06 Fernando Perez <fperez@colorado.edu>
924
949
925 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
950 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
926 by default, so that all users benefit from it. Those who don't
951 by default, so that all users benefit from it. Those who don't
927 want it can still turn it off.
952 want it can still turn it off.
928
953
929 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
954 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
930 config file, I'd forgotten about this, so users were getting it
955 config file, I'd forgotten about this, so users were getting it
931 off by default.
956 off by default.
932
957
933 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
958 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
934 consistency. Now magics can be called in multiline statements,
959 consistency. Now magics can be called in multiline statements,
935 and python variables can be expanded in magic calls via $var.
960 and python variables can be expanded in magic calls via $var.
936 This makes the magic system behave just like aliases or !system
961 This makes the magic system behave just like aliases or !system
937 calls.
962 calls.
938
963
939 2005-03-28 Fernando Perez <fperez@colorado.edu>
964 2005-03-28 Fernando Perez <fperez@colorado.edu>
940
965
941 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
966 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
942 expensive string additions for building command. Add support for
967 expensive string additions for building command. Add support for
943 trailing ';' when autocall is used.
968 trailing ';' when autocall is used.
944
969
945 2005-03-26 Fernando Perez <fperez@colorado.edu>
970 2005-03-26 Fernando Perez <fperez@colorado.edu>
946
971
947 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
972 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
948 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
973 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
949 ipython.el robust against prompts with any number of spaces
974 ipython.el robust against prompts with any number of spaces
950 (including 0) after the ':' character.
975 (including 0) after the ':' character.
951
976
952 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
977 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
953 continuation prompt, which misled users to think the line was
978 continuation prompt, which misled users to think the line was
954 already indented. Closes debian Bug#300847, reported to me by
979 already indented. Closes debian Bug#300847, reported to me by
955 Norbert Tretkowski <tretkowski-AT-inittab.de>.
980 Norbert Tretkowski <tretkowski-AT-inittab.de>.
956
981
957 2005-03-23 Fernando Perez <fperez@colorado.edu>
982 2005-03-23 Fernando Perez <fperez@colorado.edu>
958
983
959 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
984 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
960 properly aligned if they have embedded newlines.
985 properly aligned if they have embedded newlines.
961
986
962 * IPython/iplib.py (runlines): Add a public method to expose
987 * IPython/iplib.py (runlines): Add a public method to expose
963 IPython's code execution machinery, so that users can run strings
988 IPython's code execution machinery, so that users can run strings
964 as if they had been typed at the prompt interactively.
989 as if they had been typed at the prompt interactively.
965 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
990 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
966 methods which can call the system shell, but with python variable
991 methods which can call the system shell, but with python variable
967 expansion. The three such methods are: __IPYTHON__.system,
992 expansion. The three such methods are: __IPYTHON__.system,
968 .getoutput and .getoutputerror. These need to be documented in a
993 .getoutput and .getoutputerror. These need to be documented in a
969 'public API' section (to be written) of the manual.
994 'public API' section (to be written) of the manual.
970
995
971 2005-03-20 Fernando Perez <fperez@colorado.edu>
996 2005-03-20 Fernando Perez <fperez@colorado.edu>
972
997
973 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
998 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
974 for custom exception handling. This is quite powerful, and it
999 for custom exception handling. This is quite powerful, and it
975 allows for user-installable exception handlers which can trap
1000 allows for user-installable exception handlers which can trap
976 custom exceptions at runtime and treat them separately from
1001 custom exceptions at runtime and treat them separately from
977 IPython's default mechanisms. At the request of Frédéric
1002 IPython's default mechanisms. At the request of Frédéric
978 Mantegazza <mantegazza-AT-ill.fr>.
1003 Mantegazza <mantegazza-AT-ill.fr>.
979 (InteractiveShell.set_custom_completer): public API function to
1004 (InteractiveShell.set_custom_completer): public API function to
980 add new completers at runtime.
1005 add new completers at runtime.
981
1006
982 2005-03-19 Fernando Perez <fperez@colorado.edu>
1007 2005-03-19 Fernando Perez <fperez@colorado.edu>
983
1008
984 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1009 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
985 allow objects which provide their docstrings via non-standard
1010 allow objects which provide their docstrings via non-standard
986 mechanisms (like Pyro proxies) to still be inspected by ipython's
1011 mechanisms (like Pyro proxies) to still be inspected by ipython's
987 ? system.
1012 ? system.
988
1013
989 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1014 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
990 automatic capture system. I tried quite hard to make it work
1015 automatic capture system. I tried quite hard to make it work
991 reliably, and simply failed. I tried many combinations with the
1016 reliably, and simply failed. I tried many combinations with the
992 subprocess module, but eventually nothing worked in all needed
1017 subprocess module, but eventually nothing worked in all needed
993 cases (not blocking stdin for the child, duplicating stdout
1018 cases (not blocking stdin for the child, duplicating stdout
994 without blocking, etc). The new %sc/%sx still do capture to these
1019 without blocking, etc). The new %sc/%sx still do capture to these
995 magical list/string objects which make shell use much more
1020 magical list/string objects which make shell use much more
996 conveninent, so not all is lost.
1021 conveninent, so not all is lost.
997
1022
998 XXX - FIX MANUAL for the change above!
1023 XXX - FIX MANUAL for the change above!
999
1024
1000 (runsource): I copied code.py's runsource() into ipython to modify
1025 (runsource): I copied code.py's runsource() into ipython to modify
1001 it a bit. Now the code object and source to be executed are
1026 it a bit. Now the code object and source to be executed are
1002 stored in ipython. This makes this info accessible to third-party
1027 stored in ipython. This makes this info accessible to third-party
1003 tools, like custom exception handlers. After a request by Frédéric
1028 tools, like custom exception handlers. After a request by Frédéric
1004 Mantegazza <mantegazza-AT-ill.fr>.
1029 Mantegazza <mantegazza-AT-ill.fr>.
1005
1030
1006 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1031 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1007 history-search via readline (like C-p/C-n). I'd wanted this for a
1032 history-search via readline (like C-p/C-n). I'd wanted this for a
1008 long time, but only recently found out how to do it. For users
1033 long time, but only recently found out how to do it. For users
1009 who already have their ipythonrc files made and want this, just
1034 who already have their ipythonrc files made and want this, just
1010 add:
1035 add:
1011
1036
1012 readline_parse_and_bind "\e[A": history-search-backward
1037 readline_parse_and_bind "\e[A": history-search-backward
1013 readline_parse_and_bind "\e[B": history-search-forward
1038 readline_parse_and_bind "\e[B": history-search-forward
1014
1039
1015 2005-03-18 Fernando Perez <fperez@colorado.edu>
1040 2005-03-18 Fernando Perez <fperez@colorado.edu>
1016
1041
1017 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1042 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1018 LSString and SList classes which allow transparent conversions
1043 LSString and SList classes which allow transparent conversions
1019 between list mode and whitespace-separated string.
1044 between list mode and whitespace-separated string.
1020 (magic_r): Fix recursion problem in %r.
1045 (magic_r): Fix recursion problem in %r.
1021
1046
1022 * IPython/genutils.py (LSString): New class to be used for
1047 * IPython/genutils.py (LSString): New class to be used for
1023 automatic storage of the results of all alias/system calls in _o
1048 automatic storage of the results of all alias/system calls in _o
1024 and _e (stdout/err). These provide a .l/.list attribute which
1049 and _e (stdout/err). These provide a .l/.list attribute which
1025 does automatic splitting on newlines. This means that for most
1050 does automatic splitting on newlines. This means that for most
1026 uses, you'll never need to do capturing of output with %sc/%sx
1051 uses, you'll never need to do capturing of output with %sc/%sx
1027 anymore, since ipython keeps this always done for you. Note that
1052 anymore, since ipython keeps this always done for you. Note that
1028 only the LAST results are stored, the _o/e variables are
1053 only the LAST results are stored, the _o/e variables are
1029 overwritten on each call. If you need to save their contents
1054 overwritten on each call. If you need to save their contents
1030 further, simply bind them to any other name.
1055 further, simply bind them to any other name.
1031
1056
1032 2005-03-17 Fernando Perez <fperez@colorado.edu>
1057 2005-03-17 Fernando Perez <fperez@colorado.edu>
1033
1058
1034 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1059 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1035 prompt namespace handling.
1060 prompt namespace handling.
1036
1061
1037 2005-03-16 Fernando Perez <fperez@colorado.edu>
1062 2005-03-16 Fernando Perez <fperez@colorado.edu>
1038
1063
1039 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1064 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1040 classic prompts to be '>>> ' (final space was missing, and it
1065 classic prompts to be '>>> ' (final space was missing, and it
1041 trips the emacs python mode).
1066 trips the emacs python mode).
1042 (BasePrompt.__str__): Added safe support for dynamic prompt
1067 (BasePrompt.__str__): Added safe support for dynamic prompt
1043 strings. Now you can set your prompt string to be '$x', and the
1068 strings. Now you can set your prompt string to be '$x', and the
1044 value of x will be printed from your interactive namespace. The
1069 value of x will be printed from your interactive namespace. The
1045 interpolation syntax includes the full Itpl support, so
1070 interpolation syntax includes the full Itpl support, so
1046 ${foo()+x+bar()} is a valid prompt string now, and the function
1071 ${foo()+x+bar()} is a valid prompt string now, and the function
1047 calls will be made at runtime.
1072 calls will be made at runtime.
1048
1073
1049 2005-03-15 Fernando Perez <fperez@colorado.edu>
1074 2005-03-15 Fernando Perez <fperez@colorado.edu>
1050
1075
1051 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1076 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1052 avoid name clashes in pylab. %hist still works, it just forwards
1077 avoid name clashes in pylab. %hist still works, it just forwards
1053 the call to %history.
1078 the call to %history.
1054
1079
1055 2005-03-02 *** Released version 0.6.12
1080 2005-03-02 *** Released version 0.6.12
1056
1081
1057 2005-03-02 Fernando Perez <fperez@colorado.edu>
1082 2005-03-02 Fernando Perez <fperez@colorado.edu>
1058
1083
1059 * IPython/iplib.py (handle_magic): log magic calls properly as
1084 * IPython/iplib.py (handle_magic): log magic calls properly as
1060 ipmagic() function calls.
1085 ipmagic() function calls.
1061
1086
1062 * IPython/Magic.py (magic_time): Improved %time to support
1087 * IPython/Magic.py (magic_time): Improved %time to support
1063 statements and provide wall-clock as well as CPU time.
1088 statements and provide wall-clock as well as CPU time.
1064
1089
1065 2005-02-27 Fernando Perez <fperez@colorado.edu>
1090 2005-02-27 Fernando Perez <fperez@colorado.edu>
1066
1091
1067 * IPython/hooks.py: New hooks module, to expose user-modifiable
1092 * IPython/hooks.py: New hooks module, to expose user-modifiable
1068 IPython functionality in a clean manner. For now only the editor
1093 IPython functionality in a clean manner. For now only the editor
1069 hook is actually written, and other thigns which I intend to turn
1094 hook is actually written, and other thigns which I intend to turn
1070 into proper hooks aren't yet there. The display and prefilter
1095 into proper hooks aren't yet there. The display and prefilter
1071 stuff, for example, should be hooks. But at least now the
1096 stuff, for example, should be hooks. But at least now the
1072 framework is in place, and the rest can be moved here with more
1097 framework is in place, and the rest can be moved here with more
1073 time later. IPython had had a .hooks variable for a long time for
1098 time later. IPython had had a .hooks variable for a long time for
1074 this purpose, but I'd never actually used it for anything.
1099 this purpose, but I'd never actually used it for anything.
1075
1100
1076 2005-02-26 Fernando Perez <fperez@colorado.edu>
1101 2005-02-26 Fernando Perez <fperez@colorado.edu>
1077
1102
1078 * IPython/ipmaker.py (make_IPython): make the default ipython
1103 * IPython/ipmaker.py (make_IPython): make the default ipython
1079 directory be called _ipython under win32, to follow more the
1104 directory be called _ipython under win32, to follow more the
1080 naming peculiarities of that platform (where buggy software like
1105 naming peculiarities of that platform (where buggy software like
1081 Visual Sourcesafe breaks with .named directories). Reported by
1106 Visual Sourcesafe breaks with .named directories). Reported by
1082 Ville Vainio.
1107 Ville Vainio.
1083
1108
1084 2005-02-23 Fernando Perez <fperez@colorado.edu>
1109 2005-02-23 Fernando Perez <fperez@colorado.edu>
1085
1110
1086 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1111 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1087 auto_aliases for win32 which were causing problems. Users can
1112 auto_aliases for win32 which were causing problems. Users can
1088 define the ones they personally like.
1113 define the ones they personally like.
1089
1114
1090 2005-02-21 Fernando Perez <fperez@colorado.edu>
1115 2005-02-21 Fernando Perez <fperez@colorado.edu>
1091
1116
1092 * IPython/Magic.py (magic_time): new magic to time execution of
1117 * IPython/Magic.py (magic_time): new magic to time execution of
1093 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1118 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1094
1119
1095 2005-02-19 Fernando Perez <fperez@colorado.edu>
1120 2005-02-19 Fernando Perez <fperez@colorado.edu>
1096
1121
1097 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1122 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1098 into keys (for prompts, for example).
1123 into keys (for prompts, for example).
1099
1124
1100 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1125 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1101 prompts in case users want them. This introduces a small behavior
1126 prompts in case users want them. This introduces a small behavior
1102 change: ipython does not automatically add a space to all prompts
1127 change: ipython does not automatically add a space to all prompts
1103 anymore. To get the old prompts with a space, users should add it
1128 anymore. To get the old prompts with a space, users should add it
1104 manually to their ipythonrc file, so for example prompt_in1 should
1129 manually to their ipythonrc file, so for example prompt_in1 should
1105 now read 'In [\#]: ' instead of 'In [\#]:'.
1130 now read 'In [\#]: ' instead of 'In [\#]:'.
1106 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1131 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1107 file) to control left-padding of secondary prompts.
1132 file) to control left-padding of secondary prompts.
1108
1133
1109 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1134 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1110 the profiler can't be imported. Fix for Debian, which removed
1135 the profiler can't be imported. Fix for Debian, which removed
1111 profile.py because of License issues. I applied a slightly
1136 profile.py because of License issues. I applied a slightly
1112 modified version of the original Debian patch at
1137 modified version of the original Debian patch at
1113 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1138 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1114
1139
1115 2005-02-17 Fernando Perez <fperez@colorado.edu>
1140 2005-02-17 Fernando Perez <fperez@colorado.edu>
1116
1141
1117 * IPython/genutils.py (native_line_ends): Fix bug which would
1142 * IPython/genutils.py (native_line_ends): Fix bug which would
1118 cause improper line-ends under win32 b/c I was not opening files
1143 cause improper line-ends under win32 b/c I was not opening files
1119 in binary mode. Bug report and fix thanks to Ville.
1144 in binary mode. Bug report and fix thanks to Ville.
1120
1145
1121 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1146 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1122 trying to catch spurious foo[1] autocalls. My fix actually broke
1147 trying to catch spurious foo[1] autocalls. My fix actually broke
1123 ',/' autoquote/call with explicit escape (bad regexp).
1148 ',/' autoquote/call with explicit escape (bad regexp).
1124
1149
1125 2005-02-15 *** Released version 0.6.11
1150 2005-02-15 *** Released version 0.6.11
1126
1151
1127 2005-02-14 Fernando Perez <fperez@colorado.edu>
1152 2005-02-14 Fernando Perez <fperez@colorado.edu>
1128
1153
1129 * IPython/background_jobs.py: New background job management
1154 * IPython/background_jobs.py: New background job management
1130 subsystem. This is implemented via a new set of classes, and
1155 subsystem. This is implemented via a new set of classes, and
1131 IPython now provides a builtin 'jobs' object for background job
1156 IPython now provides a builtin 'jobs' object for background job
1132 execution. A convenience %bg magic serves as a lightweight
1157 execution. A convenience %bg magic serves as a lightweight
1133 frontend for starting the more common type of calls. This was
1158 frontend for starting the more common type of calls. This was
1134 inspired by discussions with B. Granger and the BackgroundCommand
1159 inspired by discussions with B. Granger and the BackgroundCommand
1135 class described in the book Python Scripting for Computational
1160 class described in the book Python Scripting for Computational
1136 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1161 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1137 (although ultimately no code from this text was used, as IPython's
1162 (although ultimately no code from this text was used, as IPython's
1138 system is a separate implementation).
1163 system is a separate implementation).
1139
1164
1140 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1165 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1141 to control the completion of single/double underscore names
1166 to control the completion of single/double underscore names
1142 separately. As documented in the example ipytonrc file, the
1167 separately. As documented in the example ipytonrc file, the
1143 readline_omit__names variable can now be set to 2, to omit even
1168 readline_omit__names variable can now be set to 2, to omit even
1144 single underscore names. Thanks to a patch by Brian Wong
1169 single underscore names. Thanks to a patch by Brian Wong
1145 <BrianWong-AT-AirgoNetworks.Com>.
1170 <BrianWong-AT-AirgoNetworks.Com>.
1146 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1171 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1147 be autocalled as foo([1]) if foo were callable. A problem for
1172 be autocalled as foo([1]) if foo were callable. A problem for
1148 things which are both callable and implement __getitem__.
1173 things which are both callable and implement __getitem__.
1149 (init_readline): Fix autoindentation for win32. Thanks to a patch
1174 (init_readline): Fix autoindentation for win32. Thanks to a patch
1150 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1175 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1151
1176
1152 2005-02-12 Fernando Perez <fperez@colorado.edu>
1177 2005-02-12 Fernando Perez <fperez@colorado.edu>
1153
1178
1154 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1179 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1155 which I had written long ago to sort out user error messages which
1180 which I had written long ago to sort out user error messages which
1156 may occur during startup. This seemed like a good idea initially,
1181 may occur during startup. This seemed like a good idea initially,
1157 but it has proven a disaster in retrospect. I don't want to
1182 but it has proven a disaster in retrospect. I don't want to
1158 change much code for now, so my fix is to set the internal 'debug'
1183 change much code for now, so my fix is to set the internal 'debug'
1159 flag to true everywhere, whose only job was precisely to control
1184 flag to true everywhere, whose only job was precisely to control
1160 this subsystem. This closes issue 28 (as well as avoiding all
1185 this subsystem. This closes issue 28 (as well as avoiding all
1161 sorts of strange hangups which occur from time to time).
1186 sorts of strange hangups which occur from time to time).
1162
1187
1163 2005-02-07 Fernando Perez <fperez@colorado.edu>
1188 2005-02-07 Fernando Perez <fperez@colorado.edu>
1164
1189
1165 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1190 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1166 previous call produced a syntax error.
1191 previous call produced a syntax error.
1167
1192
1168 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1193 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1169 classes without constructor.
1194 classes without constructor.
1170
1195
1171 2005-02-06 Fernando Perez <fperez@colorado.edu>
1196 2005-02-06 Fernando Perez <fperez@colorado.edu>
1172
1197
1173 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1198 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1174 completions with the results of each matcher, so we return results
1199 completions with the results of each matcher, so we return results
1175 to the user from all namespaces. This breaks with ipython
1200 to the user from all namespaces. This breaks with ipython
1176 tradition, but I think it's a nicer behavior. Now you get all
1201 tradition, but I think it's a nicer behavior. Now you get all
1177 possible completions listed, from all possible namespaces (python,
1202 possible completions listed, from all possible namespaces (python,
1178 filesystem, magics...) After a request by John Hunter
1203 filesystem, magics...) After a request by John Hunter
1179 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1204 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1180
1205
1181 2005-02-05 Fernando Perez <fperez@colorado.edu>
1206 2005-02-05 Fernando Perez <fperez@colorado.edu>
1182
1207
1183 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1208 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1184 the call had quote characters in it (the quotes were stripped).
1209 the call had quote characters in it (the quotes were stripped).
1185
1210
1186 2005-01-31 Fernando Perez <fperez@colorado.edu>
1211 2005-01-31 Fernando Perez <fperez@colorado.edu>
1187
1212
1188 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1213 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1189 Itpl.itpl() to make the code more robust against psyco
1214 Itpl.itpl() to make the code more robust against psyco
1190 optimizations.
1215 optimizations.
1191
1216
1192 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1217 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1193 of causing an exception. Quicker, cleaner.
1218 of causing an exception. Quicker, cleaner.
1194
1219
1195 2005-01-28 Fernando Perez <fperez@colorado.edu>
1220 2005-01-28 Fernando Perez <fperez@colorado.edu>
1196
1221
1197 * scripts/ipython_win_post_install.py (install): hardcode
1222 * scripts/ipython_win_post_install.py (install): hardcode
1198 sys.prefix+'python.exe' as the executable path. It turns out that
1223 sys.prefix+'python.exe' as the executable path. It turns out that
1199 during the post-installation run, sys.executable resolves to the
1224 during the post-installation run, sys.executable resolves to the
1200 name of the binary installer! I should report this as a distutils
1225 name of the binary installer! I should report this as a distutils
1201 bug, I think. I updated the .10 release with this tiny fix, to
1226 bug, I think. I updated the .10 release with this tiny fix, to
1202 avoid annoying the lists further.
1227 avoid annoying the lists further.
1203
1228
1204 2005-01-27 *** Released version 0.6.10
1229 2005-01-27 *** Released version 0.6.10
1205
1230
1206 2005-01-27 Fernando Perez <fperez@colorado.edu>
1231 2005-01-27 Fernando Perez <fperez@colorado.edu>
1207
1232
1208 * IPython/numutils.py (norm): Added 'inf' as optional name for
1233 * IPython/numutils.py (norm): Added 'inf' as optional name for
1209 L-infinity norm, included references to mathworld.com for vector
1234 L-infinity norm, included references to mathworld.com for vector
1210 norm definitions.
1235 norm definitions.
1211 (amin/amax): added amin/amax for array min/max. Similar to what
1236 (amin/amax): added amin/amax for array min/max. Similar to what
1212 pylab ships with after the recent reorganization of names.
1237 pylab ships with after the recent reorganization of names.
1213 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1238 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1214
1239
1215 * ipython.el: committed Alex's recent fixes and improvements.
1240 * ipython.el: committed Alex's recent fixes and improvements.
1216 Tested with python-mode from CVS, and it looks excellent. Since
1241 Tested with python-mode from CVS, and it looks excellent. Since
1217 python-mode hasn't released anything in a while, I'm temporarily
1242 python-mode hasn't released anything in a while, I'm temporarily
1218 putting a copy of today's CVS (v 4.70) of python-mode in:
1243 putting a copy of today's CVS (v 4.70) of python-mode in:
1219 http://ipython.scipy.org/tmp/python-mode.el
1244 http://ipython.scipy.org/tmp/python-mode.el
1220
1245
1221 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1246 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1222 sys.executable for the executable name, instead of assuming it's
1247 sys.executable for the executable name, instead of assuming it's
1223 called 'python.exe' (the post-installer would have produced broken
1248 called 'python.exe' (the post-installer would have produced broken
1224 setups on systems with a differently named python binary).
1249 setups on systems with a differently named python binary).
1225
1250
1226 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1251 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1227 references to os.linesep, to make the code more
1252 references to os.linesep, to make the code more
1228 platform-independent. This is also part of the win32 coloring
1253 platform-independent. This is also part of the win32 coloring
1229 fixes.
1254 fixes.
1230
1255
1231 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1256 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1232 lines, which actually cause coloring bugs because the length of
1257 lines, which actually cause coloring bugs because the length of
1233 the line is very difficult to correctly compute with embedded
1258 the line is very difficult to correctly compute with embedded
1234 escapes. This was the source of all the coloring problems under
1259 escapes. This was the source of all the coloring problems under
1235 Win32. I think that _finally_, Win32 users have a properly
1260 Win32. I think that _finally_, Win32 users have a properly
1236 working ipython in all respects. This would never have happened
1261 working ipython in all respects. This would never have happened
1237 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1262 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1238
1263
1239 2005-01-26 *** Released version 0.6.9
1264 2005-01-26 *** Released version 0.6.9
1240
1265
1241 2005-01-25 Fernando Perez <fperez@colorado.edu>
1266 2005-01-25 Fernando Perez <fperez@colorado.edu>
1242
1267
1243 * setup.py: finally, we have a true Windows installer, thanks to
1268 * setup.py: finally, we have a true Windows installer, thanks to
1244 the excellent work of Viktor Ransmayr
1269 the excellent work of Viktor Ransmayr
1245 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1270 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1246 Windows users. The setup routine is quite a bit cleaner thanks to
1271 Windows users. The setup routine is quite a bit cleaner thanks to
1247 this, and the post-install script uses the proper functions to
1272 this, and the post-install script uses the proper functions to
1248 allow a clean de-installation using the standard Windows Control
1273 allow a clean de-installation using the standard Windows Control
1249 Panel.
1274 Panel.
1250
1275
1251 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1276 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1252 environment variable under all OSes (including win32) if
1277 environment variable under all OSes (including win32) if
1253 available. This will give consistency to win32 users who have set
1278 available. This will give consistency to win32 users who have set
1254 this variable for any reason. If os.environ['HOME'] fails, the
1279 this variable for any reason. If os.environ['HOME'] fails, the
1255 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1280 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1256
1281
1257 2005-01-24 Fernando Perez <fperez@colorado.edu>
1282 2005-01-24 Fernando Perez <fperez@colorado.edu>
1258
1283
1259 * IPython/numutils.py (empty_like): add empty_like(), similar to
1284 * IPython/numutils.py (empty_like): add empty_like(), similar to
1260 zeros_like() but taking advantage of the new empty() Numeric routine.
1285 zeros_like() but taking advantage of the new empty() Numeric routine.
1261
1286
1262 2005-01-23 *** Released version 0.6.8
1287 2005-01-23 *** Released version 0.6.8
1263
1288
1264 2005-01-22 Fernando Perez <fperez@colorado.edu>
1289 2005-01-22 Fernando Perez <fperez@colorado.edu>
1265
1290
1266 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1291 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1267 automatic show() calls. After discussing things with JDH, it
1292 automatic show() calls. After discussing things with JDH, it
1268 turns out there are too many corner cases where this can go wrong.
1293 turns out there are too many corner cases where this can go wrong.
1269 It's best not to try to be 'too smart', and simply have ipython
1294 It's best not to try to be 'too smart', and simply have ipython
1270 reproduce as much as possible the default behavior of a normal
1295 reproduce as much as possible the default behavior of a normal
1271 python shell.
1296 python shell.
1272
1297
1273 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1298 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1274 line-splitting regexp and _prefilter() to avoid calling getattr()
1299 line-splitting regexp and _prefilter() to avoid calling getattr()
1275 on assignments. This closes
1300 on assignments. This closes
1276 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1301 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1277 readline uses getattr(), so a simple <TAB> keypress is still
1302 readline uses getattr(), so a simple <TAB> keypress is still
1278 enough to trigger getattr() calls on an object.
1303 enough to trigger getattr() calls on an object.
1279
1304
1280 2005-01-21 Fernando Perez <fperez@colorado.edu>
1305 2005-01-21 Fernando Perez <fperez@colorado.edu>
1281
1306
1282 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1307 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1283 docstring under pylab so it doesn't mask the original.
1308 docstring under pylab so it doesn't mask the original.
1284
1309
1285 2005-01-21 *** Released version 0.6.7
1310 2005-01-21 *** Released version 0.6.7
1286
1311
1287 2005-01-21 Fernando Perez <fperez@colorado.edu>
1312 2005-01-21 Fernando Perez <fperez@colorado.edu>
1288
1313
1289 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1314 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1290 signal handling for win32 users in multithreaded mode.
1315 signal handling for win32 users in multithreaded mode.
1291
1316
1292 2005-01-17 Fernando Perez <fperez@colorado.edu>
1317 2005-01-17 Fernando Perez <fperez@colorado.edu>
1293
1318
1294 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1319 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1295 instances with no __init__. After a crash report by Norbert Nemec
1320 instances with no __init__. After a crash report by Norbert Nemec
1296 <Norbert-AT-nemec-online.de>.
1321 <Norbert-AT-nemec-online.de>.
1297
1322
1298 2005-01-14 Fernando Perez <fperez@colorado.edu>
1323 2005-01-14 Fernando Perez <fperez@colorado.edu>
1299
1324
1300 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1325 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1301 names for verbose exceptions, when multiple dotted names and the
1326 names for verbose exceptions, when multiple dotted names and the
1302 'parent' object were present on the same line.
1327 'parent' object were present on the same line.
1303
1328
1304 2005-01-11 Fernando Perez <fperez@colorado.edu>
1329 2005-01-11 Fernando Perez <fperez@colorado.edu>
1305
1330
1306 * IPython/genutils.py (flag_calls): new utility to trap and flag
1331 * IPython/genutils.py (flag_calls): new utility to trap and flag
1307 calls in functions. I need it to clean up matplotlib support.
1332 calls in functions. I need it to clean up matplotlib support.
1308 Also removed some deprecated code in genutils.
1333 Also removed some deprecated code in genutils.
1309
1334
1310 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1335 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1311 that matplotlib scripts called with %run, which don't call show()
1336 that matplotlib scripts called with %run, which don't call show()
1312 themselves, still have their plotting windows open.
1337 themselves, still have their plotting windows open.
1313
1338
1314 2005-01-05 Fernando Perez <fperez@colorado.edu>
1339 2005-01-05 Fernando Perez <fperez@colorado.edu>
1315
1340
1316 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1341 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1317 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1342 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1318
1343
1319 2004-12-19 Fernando Perez <fperez@colorado.edu>
1344 2004-12-19 Fernando Perez <fperez@colorado.edu>
1320
1345
1321 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1346 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1322 parent_runcode, which was an eyesore. The same result can be
1347 parent_runcode, which was an eyesore. The same result can be
1323 obtained with Python's regular superclass mechanisms.
1348 obtained with Python's regular superclass mechanisms.
1324
1349
1325 2004-12-17 Fernando Perez <fperez@colorado.edu>
1350 2004-12-17 Fernando Perez <fperez@colorado.edu>
1326
1351
1327 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1352 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1328 reported by Prabhu.
1353 reported by Prabhu.
1329 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1354 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1330 sys.stderr) instead of explicitly calling sys.stderr. This helps
1355 sys.stderr) instead of explicitly calling sys.stderr. This helps
1331 maintain our I/O abstractions clean, for future GUI embeddings.
1356 maintain our I/O abstractions clean, for future GUI embeddings.
1332
1357
1333 * IPython/genutils.py (info): added new utility for sys.stderr
1358 * IPython/genutils.py (info): added new utility for sys.stderr
1334 unified info message handling (thin wrapper around warn()).
1359 unified info message handling (thin wrapper around warn()).
1335
1360
1336 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1361 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1337 composite (dotted) names on verbose exceptions.
1362 composite (dotted) names on verbose exceptions.
1338 (VerboseTB.nullrepr): harden against another kind of errors which
1363 (VerboseTB.nullrepr): harden against another kind of errors which
1339 Python's inspect module can trigger, and which were crashing
1364 Python's inspect module can trigger, and which were crashing
1340 IPython. Thanks to a report by Marco Lombardi
1365 IPython. Thanks to a report by Marco Lombardi
1341 <mlombard-AT-ma010192.hq.eso.org>.
1366 <mlombard-AT-ma010192.hq.eso.org>.
1342
1367
1343 2004-12-13 *** Released version 0.6.6
1368 2004-12-13 *** Released version 0.6.6
1344
1369
1345 2004-12-12 Fernando Perez <fperez@colorado.edu>
1370 2004-12-12 Fernando Perez <fperez@colorado.edu>
1346
1371
1347 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1372 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1348 generated by pygtk upon initialization if it was built without
1373 generated by pygtk upon initialization if it was built without
1349 threads (for matplotlib users). After a crash reported by
1374 threads (for matplotlib users). After a crash reported by
1350 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1375 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1351
1376
1352 * IPython/ipmaker.py (make_IPython): fix small bug in the
1377 * IPython/ipmaker.py (make_IPython): fix small bug in the
1353 import_some parameter for multiple imports.
1378 import_some parameter for multiple imports.
1354
1379
1355 * IPython/iplib.py (ipmagic): simplified the interface of
1380 * IPython/iplib.py (ipmagic): simplified the interface of
1356 ipmagic() to take a single string argument, just as it would be
1381 ipmagic() to take a single string argument, just as it would be
1357 typed at the IPython cmd line.
1382 typed at the IPython cmd line.
1358 (ipalias): Added new ipalias() with an interface identical to
1383 (ipalias): Added new ipalias() with an interface identical to
1359 ipmagic(). This completes exposing a pure python interface to the
1384 ipmagic(). This completes exposing a pure python interface to the
1360 alias and magic system, which can be used in loops or more complex
1385 alias and magic system, which can be used in loops or more complex
1361 code where IPython's automatic line mangling is not active.
1386 code where IPython's automatic line mangling is not active.
1362
1387
1363 * IPython/genutils.py (timing): changed interface of timing to
1388 * IPython/genutils.py (timing): changed interface of timing to
1364 simply run code once, which is the most common case. timings()
1389 simply run code once, which is the most common case. timings()
1365 remains unchanged, for the cases where you want multiple runs.
1390 remains unchanged, for the cases where you want multiple runs.
1366
1391
1367 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1392 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1368 bug where Python2.2 crashes with exec'ing code which does not end
1393 bug where Python2.2 crashes with exec'ing code which does not end
1369 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1394 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1370 before.
1395 before.
1371
1396
1372 2004-12-10 Fernando Perez <fperez@colorado.edu>
1397 2004-12-10 Fernando Perez <fperez@colorado.edu>
1373
1398
1374 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1399 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1375 -t to -T, to accomodate the new -t flag in %run (the %run and
1400 -t to -T, to accomodate the new -t flag in %run (the %run and
1376 %prun options are kind of intermixed, and it's not easy to change
1401 %prun options are kind of intermixed, and it's not easy to change
1377 this with the limitations of python's getopt).
1402 this with the limitations of python's getopt).
1378
1403
1379 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1404 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1380 the execution of scripts. It's not as fine-tuned as timeit.py,
1405 the execution of scripts. It's not as fine-tuned as timeit.py,
1381 but it works from inside ipython (and under 2.2, which lacks
1406 but it works from inside ipython (and under 2.2, which lacks
1382 timeit.py). Optionally a number of runs > 1 can be given for
1407 timeit.py). Optionally a number of runs > 1 can be given for
1383 timing very short-running code.
1408 timing very short-running code.
1384
1409
1385 * IPython/genutils.py (uniq_stable): new routine which returns a
1410 * IPython/genutils.py (uniq_stable): new routine which returns a
1386 list of unique elements in any iterable, but in stable order of
1411 list of unique elements in any iterable, but in stable order of
1387 appearance. I needed this for the ultraTB fixes, and it's a handy
1412 appearance. I needed this for the ultraTB fixes, and it's a handy
1388 utility.
1413 utility.
1389
1414
1390 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1415 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1391 dotted names in Verbose exceptions. This had been broken since
1416 dotted names in Verbose exceptions. This had been broken since
1392 the very start, now x.y will properly be printed in a Verbose
1417 the very start, now x.y will properly be printed in a Verbose
1393 traceback, instead of x being shown and y appearing always as an
1418 traceback, instead of x being shown and y appearing always as an
1394 'undefined global'. Getting this to work was a bit tricky,
1419 'undefined global'. Getting this to work was a bit tricky,
1395 because by default python tokenizers are stateless. Saved by
1420 because by default python tokenizers are stateless. Saved by
1396 python's ability to easily add a bit of state to an arbitrary
1421 python's ability to easily add a bit of state to an arbitrary
1397 function (without needing to build a full-blown callable object).
1422 function (without needing to build a full-blown callable object).
1398
1423
1399 Also big cleanup of this code, which had horrendous runtime
1424 Also big cleanup of this code, which had horrendous runtime
1400 lookups of zillions of attributes for colorization. Moved all
1425 lookups of zillions of attributes for colorization. Moved all
1401 this code into a few templates, which make it cleaner and quicker.
1426 this code into a few templates, which make it cleaner and quicker.
1402
1427
1403 Printout quality was also improved for Verbose exceptions: one
1428 Printout quality was also improved for Verbose exceptions: one
1404 variable per line, and memory addresses are printed (this can be
1429 variable per line, and memory addresses are printed (this can be
1405 quite handy in nasty debugging situations, which is what Verbose
1430 quite handy in nasty debugging situations, which is what Verbose
1406 is for).
1431 is for).
1407
1432
1408 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1433 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1409 the command line as scripts to be loaded by embedded instances.
1434 the command line as scripts to be loaded by embedded instances.
1410 Doing so has the potential for an infinite recursion if there are
1435 Doing so has the potential for an infinite recursion if there are
1411 exceptions thrown in the process. This fixes a strange crash
1436 exceptions thrown in the process. This fixes a strange crash
1412 reported by Philippe MULLER <muller-AT-irit.fr>.
1437 reported by Philippe MULLER <muller-AT-irit.fr>.
1413
1438
1414 2004-12-09 Fernando Perez <fperez@colorado.edu>
1439 2004-12-09 Fernando Perez <fperez@colorado.edu>
1415
1440
1416 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1441 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1417 to reflect new names in matplotlib, which now expose the
1442 to reflect new names in matplotlib, which now expose the
1418 matlab-compatible interface via a pylab module instead of the
1443 matlab-compatible interface via a pylab module instead of the
1419 'matlab' name. The new code is backwards compatible, so users of
1444 'matlab' name. The new code is backwards compatible, so users of
1420 all matplotlib versions are OK. Patch by J. Hunter.
1445 all matplotlib versions are OK. Patch by J. Hunter.
1421
1446
1422 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1447 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1423 of __init__ docstrings for instances (class docstrings are already
1448 of __init__ docstrings for instances (class docstrings are already
1424 automatically printed). Instances with customized docstrings
1449 automatically printed). Instances with customized docstrings
1425 (indep. of the class) are also recognized and all 3 separate
1450 (indep. of the class) are also recognized and all 3 separate
1426 docstrings are printed (instance, class, constructor). After some
1451 docstrings are printed (instance, class, constructor). After some
1427 comments/suggestions by J. Hunter.
1452 comments/suggestions by J. Hunter.
1428
1453
1429 2004-12-05 Fernando Perez <fperez@colorado.edu>
1454 2004-12-05 Fernando Perez <fperez@colorado.edu>
1430
1455
1431 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1456 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1432 warnings when tab-completion fails and triggers an exception.
1457 warnings when tab-completion fails and triggers an exception.
1433
1458
1434 2004-12-03 Fernando Perez <fperez@colorado.edu>
1459 2004-12-03 Fernando Perez <fperez@colorado.edu>
1435
1460
1436 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1461 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1437 be triggered when using 'run -p'. An incorrect option flag was
1462 be triggered when using 'run -p'. An incorrect option flag was
1438 being set ('d' instead of 'D').
1463 being set ('d' instead of 'D').
1439 (manpage): fix missing escaped \- sign.
1464 (manpage): fix missing escaped \- sign.
1440
1465
1441 2004-11-30 *** Released version 0.6.5
1466 2004-11-30 *** Released version 0.6.5
1442
1467
1443 2004-11-30 Fernando Perez <fperez@colorado.edu>
1468 2004-11-30 Fernando Perez <fperez@colorado.edu>
1444
1469
1445 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1470 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1446 setting with -d option.
1471 setting with -d option.
1447
1472
1448 * setup.py (docfiles): Fix problem where the doc glob I was using
1473 * setup.py (docfiles): Fix problem where the doc glob I was using
1449 was COMPLETELY BROKEN. It was giving the right files by pure
1474 was COMPLETELY BROKEN. It was giving the right files by pure
1450 accident, but failed once I tried to include ipython.el. Note:
1475 accident, but failed once I tried to include ipython.el. Note:
1451 glob() does NOT allow you to do exclusion on multiple endings!
1476 glob() does NOT allow you to do exclusion on multiple endings!
1452
1477
1453 2004-11-29 Fernando Perez <fperez@colorado.edu>
1478 2004-11-29 Fernando Perez <fperez@colorado.edu>
1454
1479
1455 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1480 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1456 the manpage as the source. Better formatting & consistency.
1481 the manpage as the source. Better formatting & consistency.
1457
1482
1458 * IPython/Magic.py (magic_run): Added new -d option, to run
1483 * IPython/Magic.py (magic_run): Added new -d option, to run
1459 scripts under the control of the python pdb debugger. Note that
1484 scripts under the control of the python pdb debugger. Note that
1460 this required changing the %prun option -d to -D, to avoid a clash
1485 this required changing the %prun option -d to -D, to avoid a clash
1461 (since %run must pass options to %prun, and getopt is too dumb to
1486 (since %run must pass options to %prun, and getopt is too dumb to
1462 handle options with string values with embedded spaces). Thanks
1487 handle options with string values with embedded spaces). Thanks
1463 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1488 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1464 (magic_who_ls): added type matching to %who and %whos, so that one
1489 (magic_who_ls): added type matching to %who and %whos, so that one
1465 can filter their output to only include variables of certain
1490 can filter their output to only include variables of certain
1466 types. Another suggestion by Matthew.
1491 types. Another suggestion by Matthew.
1467 (magic_whos): Added memory summaries in kb and Mb for arrays.
1492 (magic_whos): Added memory summaries in kb and Mb for arrays.
1468 (magic_who): Improve formatting (break lines every 9 vars).
1493 (magic_who): Improve formatting (break lines every 9 vars).
1469
1494
1470 2004-11-28 Fernando Perez <fperez@colorado.edu>
1495 2004-11-28 Fernando Perez <fperez@colorado.edu>
1471
1496
1472 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1497 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1473 cache when empty lines were present.
1498 cache when empty lines were present.
1474
1499
1475 2004-11-24 Fernando Perez <fperez@colorado.edu>
1500 2004-11-24 Fernando Perez <fperez@colorado.edu>
1476
1501
1477 * IPython/usage.py (__doc__): document the re-activated threading
1502 * IPython/usage.py (__doc__): document the re-activated threading
1478 options for WX and GTK.
1503 options for WX and GTK.
1479
1504
1480 2004-11-23 Fernando Perez <fperez@colorado.edu>
1505 2004-11-23 Fernando Perez <fperez@colorado.edu>
1481
1506
1482 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1507 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1483 the -wthread and -gthread options, along with a new -tk one to try
1508 the -wthread and -gthread options, along with a new -tk one to try
1484 and coordinate Tk threading with wx/gtk. The tk support is very
1509 and coordinate Tk threading with wx/gtk. The tk support is very
1485 platform dependent, since it seems to require Tcl and Tk to be
1510 platform dependent, since it seems to require Tcl and Tk to be
1486 built with threads (Fedora1/2 appears NOT to have it, but in
1511 built with threads (Fedora1/2 appears NOT to have it, but in
1487 Prabhu's Debian boxes it works OK). But even with some Tk
1512 Prabhu's Debian boxes it works OK). But even with some Tk
1488 limitations, this is a great improvement.
1513 limitations, this is a great improvement.
1489
1514
1490 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1515 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1491 info in user prompts. Patch by Prabhu.
1516 info in user prompts. Patch by Prabhu.
1492
1517
1493 2004-11-18 Fernando Perez <fperez@colorado.edu>
1518 2004-11-18 Fernando Perez <fperez@colorado.edu>
1494
1519
1495 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1520 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1496 EOFErrors and bail, to avoid infinite loops if a non-terminating
1521 EOFErrors and bail, to avoid infinite loops if a non-terminating
1497 file is fed into ipython. Patch submitted in issue 19 by user,
1522 file is fed into ipython. Patch submitted in issue 19 by user,
1498 many thanks.
1523 many thanks.
1499
1524
1500 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1525 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1501 autoquote/parens in continuation prompts, which can cause lots of
1526 autoquote/parens in continuation prompts, which can cause lots of
1502 problems. Closes roundup issue 20.
1527 problems. Closes roundup issue 20.
1503
1528
1504 2004-11-17 Fernando Perez <fperez@colorado.edu>
1529 2004-11-17 Fernando Perez <fperez@colorado.edu>
1505
1530
1506 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1531 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1507 reported as debian bug #280505. I'm not sure my local changelog
1532 reported as debian bug #280505. I'm not sure my local changelog
1508 entry has the proper debian format (Jack?).
1533 entry has the proper debian format (Jack?).
1509
1534
1510 2004-11-08 *** Released version 0.6.4
1535 2004-11-08 *** Released version 0.6.4
1511
1536
1512 2004-11-08 Fernando Perez <fperez@colorado.edu>
1537 2004-11-08 Fernando Perez <fperez@colorado.edu>
1513
1538
1514 * IPython/iplib.py (init_readline): Fix exit message for Windows
1539 * IPython/iplib.py (init_readline): Fix exit message for Windows
1515 when readline is active. Thanks to a report by Eric Jones
1540 when readline is active. Thanks to a report by Eric Jones
1516 <eric-AT-enthought.com>.
1541 <eric-AT-enthought.com>.
1517
1542
1518 2004-11-07 Fernando Perez <fperez@colorado.edu>
1543 2004-11-07 Fernando Perez <fperez@colorado.edu>
1519
1544
1520 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1545 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1521 sometimes seen by win2k/cygwin users.
1546 sometimes seen by win2k/cygwin users.
1522
1547
1523 2004-11-06 Fernando Perez <fperez@colorado.edu>
1548 2004-11-06 Fernando Perez <fperez@colorado.edu>
1524
1549
1525 * IPython/iplib.py (interact): Change the handling of %Exit from
1550 * IPython/iplib.py (interact): Change the handling of %Exit from
1526 trying to propagate a SystemExit to an internal ipython flag.
1551 trying to propagate a SystemExit to an internal ipython flag.
1527 This is less elegant than using Python's exception mechanism, but
1552 This is less elegant than using Python's exception mechanism, but
1528 I can't get that to work reliably with threads, so under -pylab
1553 I can't get that to work reliably with threads, so under -pylab
1529 %Exit was hanging IPython. Cross-thread exception handling is
1554 %Exit was hanging IPython. Cross-thread exception handling is
1530 really a bitch. Thaks to a bug report by Stephen Walton
1555 really a bitch. Thaks to a bug report by Stephen Walton
1531 <stephen.walton-AT-csun.edu>.
1556 <stephen.walton-AT-csun.edu>.
1532
1557
1533 2004-11-04 Fernando Perez <fperez@colorado.edu>
1558 2004-11-04 Fernando Perez <fperez@colorado.edu>
1534
1559
1535 * IPython/iplib.py (raw_input_original): store a pointer to the
1560 * IPython/iplib.py (raw_input_original): store a pointer to the
1536 true raw_input to harden against code which can modify it
1561 true raw_input to harden against code which can modify it
1537 (wx.py.PyShell does this and would otherwise crash ipython).
1562 (wx.py.PyShell does this and would otherwise crash ipython).
1538 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1563 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1539
1564
1540 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1565 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1541 Ctrl-C problem, which does not mess up the input line.
1566 Ctrl-C problem, which does not mess up the input line.
1542
1567
1543 2004-11-03 Fernando Perez <fperez@colorado.edu>
1568 2004-11-03 Fernando Perez <fperez@colorado.edu>
1544
1569
1545 * IPython/Release.py: Changed licensing to BSD, in all files.
1570 * IPython/Release.py: Changed licensing to BSD, in all files.
1546 (name): lowercase name for tarball/RPM release.
1571 (name): lowercase name for tarball/RPM release.
1547
1572
1548 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1573 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1549 use throughout ipython.
1574 use throughout ipython.
1550
1575
1551 * IPython/Magic.py (Magic._ofind): Switch to using the new
1576 * IPython/Magic.py (Magic._ofind): Switch to using the new
1552 OInspect.getdoc() function.
1577 OInspect.getdoc() function.
1553
1578
1554 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1579 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1555 of the line currently being canceled via Ctrl-C. It's extremely
1580 of the line currently being canceled via Ctrl-C. It's extremely
1556 ugly, but I don't know how to do it better (the problem is one of
1581 ugly, but I don't know how to do it better (the problem is one of
1557 handling cross-thread exceptions).
1582 handling cross-thread exceptions).
1558
1583
1559 2004-10-28 Fernando Perez <fperez@colorado.edu>
1584 2004-10-28 Fernando Perez <fperez@colorado.edu>
1560
1585
1561 * IPython/Shell.py (signal_handler): add signal handlers to trap
1586 * IPython/Shell.py (signal_handler): add signal handlers to trap
1562 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1587 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1563 report by Francesc Alted.
1588 report by Francesc Alted.
1564
1589
1565 2004-10-21 Fernando Perez <fperez@colorado.edu>
1590 2004-10-21 Fernando Perez <fperez@colorado.edu>
1566
1591
1567 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1592 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1568 to % for pysh syntax extensions.
1593 to % for pysh syntax extensions.
1569
1594
1570 2004-10-09 Fernando Perez <fperez@colorado.edu>
1595 2004-10-09 Fernando Perez <fperez@colorado.edu>
1571
1596
1572 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1597 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1573 arrays to print a more useful summary, without calling str(arr).
1598 arrays to print a more useful summary, without calling str(arr).
1574 This avoids the problem of extremely lengthy computations which
1599 This avoids the problem of extremely lengthy computations which
1575 occur if arr is large, and appear to the user as a system lockup
1600 occur if arr is large, and appear to the user as a system lockup
1576 with 100% cpu activity. After a suggestion by Kristian Sandberg
1601 with 100% cpu activity. After a suggestion by Kristian Sandberg
1577 <Kristian.Sandberg@colorado.edu>.
1602 <Kristian.Sandberg@colorado.edu>.
1578 (Magic.__init__): fix bug in global magic escapes not being
1603 (Magic.__init__): fix bug in global magic escapes not being
1579 correctly set.
1604 correctly set.
1580
1605
1581 2004-10-08 Fernando Perez <fperez@colorado.edu>
1606 2004-10-08 Fernando Perez <fperez@colorado.edu>
1582
1607
1583 * IPython/Magic.py (__license__): change to absolute imports of
1608 * IPython/Magic.py (__license__): change to absolute imports of
1584 ipython's own internal packages, to start adapting to the absolute
1609 ipython's own internal packages, to start adapting to the absolute
1585 import requirement of PEP-328.
1610 import requirement of PEP-328.
1586
1611
1587 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1612 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1588 files, and standardize author/license marks through the Release
1613 files, and standardize author/license marks through the Release
1589 module instead of having per/file stuff (except for files with
1614 module instead of having per/file stuff (except for files with
1590 particular licenses, like the MIT/PSF-licensed codes).
1615 particular licenses, like the MIT/PSF-licensed codes).
1591
1616
1592 * IPython/Debugger.py: remove dead code for python 2.1
1617 * IPython/Debugger.py: remove dead code for python 2.1
1593
1618
1594 2004-10-04 Fernando Perez <fperez@colorado.edu>
1619 2004-10-04 Fernando Perez <fperez@colorado.edu>
1595
1620
1596 * IPython/iplib.py (ipmagic): New function for accessing magics
1621 * IPython/iplib.py (ipmagic): New function for accessing magics
1597 via a normal python function call.
1622 via a normal python function call.
1598
1623
1599 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1624 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1600 from '@' to '%', to accomodate the new @decorator syntax of python
1625 from '@' to '%', to accomodate the new @decorator syntax of python
1601 2.4.
1626 2.4.
1602
1627
1603 2004-09-29 Fernando Perez <fperez@colorado.edu>
1628 2004-09-29 Fernando Perez <fperez@colorado.edu>
1604
1629
1605 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1630 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1606 matplotlib.use to prevent running scripts which try to switch
1631 matplotlib.use to prevent running scripts which try to switch
1607 interactive backends from within ipython. This will just crash
1632 interactive backends from within ipython. This will just crash
1608 the python interpreter, so we can't allow it (but a detailed error
1633 the python interpreter, so we can't allow it (but a detailed error
1609 is given to the user).
1634 is given to the user).
1610
1635
1611 2004-09-28 Fernando Perez <fperez@colorado.edu>
1636 2004-09-28 Fernando Perez <fperez@colorado.edu>
1612
1637
1613 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1638 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1614 matplotlib-related fixes so that using @run with non-matplotlib
1639 matplotlib-related fixes so that using @run with non-matplotlib
1615 scripts doesn't pop up spurious plot windows. This requires
1640 scripts doesn't pop up spurious plot windows. This requires
1616 matplotlib >= 0.63, where I had to make some changes as well.
1641 matplotlib >= 0.63, where I had to make some changes as well.
1617
1642
1618 * IPython/ipmaker.py (make_IPython): update version requirement to
1643 * IPython/ipmaker.py (make_IPython): update version requirement to
1619 python 2.2.
1644 python 2.2.
1620
1645
1621 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1646 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1622 banner arg for embedded customization.
1647 banner arg for embedded customization.
1623
1648
1624 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1649 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1625 explicit uses of __IP as the IPython's instance name. Now things
1650 explicit uses of __IP as the IPython's instance name. Now things
1626 are properly handled via the shell.name value. The actual code
1651 are properly handled via the shell.name value. The actual code
1627 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1652 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1628 is much better than before. I'll clean things completely when the
1653 is much better than before. I'll clean things completely when the
1629 magic stuff gets a real overhaul.
1654 magic stuff gets a real overhaul.
1630
1655
1631 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1656 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1632 minor changes to debian dir.
1657 minor changes to debian dir.
1633
1658
1634 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1659 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1635 pointer to the shell itself in the interactive namespace even when
1660 pointer to the shell itself in the interactive namespace even when
1636 a user-supplied dict is provided. This is needed for embedding
1661 a user-supplied dict is provided. This is needed for embedding
1637 purposes (found by tests with Michel Sanner).
1662 purposes (found by tests with Michel Sanner).
1638
1663
1639 2004-09-27 Fernando Perez <fperez@colorado.edu>
1664 2004-09-27 Fernando Perez <fperez@colorado.edu>
1640
1665
1641 * IPython/UserConfig/ipythonrc: remove []{} from
1666 * IPython/UserConfig/ipythonrc: remove []{} from
1642 readline_remove_delims, so that things like [modname.<TAB> do
1667 readline_remove_delims, so that things like [modname.<TAB> do
1643 proper completion. This disables [].TAB, but that's a less common
1668 proper completion. This disables [].TAB, but that's a less common
1644 case than module names in list comprehensions, for example.
1669 case than module names in list comprehensions, for example.
1645 Thanks to a report by Andrea Riciputi.
1670 Thanks to a report by Andrea Riciputi.
1646
1671
1647 2004-09-09 Fernando Perez <fperez@colorado.edu>
1672 2004-09-09 Fernando Perez <fperez@colorado.edu>
1648
1673
1649 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1674 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1650 blocking problems in win32 and osx. Fix by John.
1675 blocking problems in win32 and osx. Fix by John.
1651
1676
1652 2004-09-08 Fernando Perez <fperez@colorado.edu>
1677 2004-09-08 Fernando Perez <fperez@colorado.edu>
1653
1678
1654 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1679 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1655 for Win32 and OSX. Fix by John Hunter.
1680 for Win32 and OSX. Fix by John Hunter.
1656
1681
1657 2004-08-30 *** Released version 0.6.3
1682 2004-08-30 *** Released version 0.6.3
1658
1683
1659 2004-08-30 Fernando Perez <fperez@colorado.edu>
1684 2004-08-30 Fernando Perez <fperez@colorado.edu>
1660
1685
1661 * setup.py (isfile): Add manpages to list of dependent files to be
1686 * setup.py (isfile): Add manpages to list of dependent files to be
1662 updated.
1687 updated.
1663
1688
1664 2004-08-27 Fernando Perez <fperez@colorado.edu>
1689 2004-08-27 Fernando Perez <fperez@colorado.edu>
1665
1690
1666 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1691 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1667 for now. They don't really work with standalone WX/GTK code
1692 for now. They don't really work with standalone WX/GTK code
1668 (though matplotlib IS working fine with both of those backends).
1693 (though matplotlib IS working fine with both of those backends).
1669 This will neeed much more testing. I disabled most things with
1694 This will neeed much more testing. I disabled most things with
1670 comments, so turning it back on later should be pretty easy.
1695 comments, so turning it back on later should be pretty easy.
1671
1696
1672 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1697 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1673 autocalling of expressions like r'foo', by modifying the line
1698 autocalling of expressions like r'foo', by modifying the line
1674 split regexp. Closes
1699 split regexp. Closes
1675 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1700 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1676 Riley <ipythonbugs-AT-sabi.net>.
1701 Riley <ipythonbugs-AT-sabi.net>.
1677 (InteractiveShell.mainloop): honor --nobanner with banner
1702 (InteractiveShell.mainloop): honor --nobanner with banner
1678 extensions.
1703 extensions.
1679
1704
1680 * IPython/Shell.py: Significant refactoring of all classes, so
1705 * IPython/Shell.py: Significant refactoring of all classes, so
1681 that we can really support ALL matplotlib backends and threading
1706 that we can really support ALL matplotlib backends and threading
1682 models (John spotted a bug with Tk which required this). Now we
1707 models (John spotted a bug with Tk which required this). Now we
1683 should support single-threaded, WX-threads and GTK-threads, both
1708 should support single-threaded, WX-threads and GTK-threads, both
1684 for generic code and for matplotlib.
1709 for generic code and for matplotlib.
1685
1710
1686 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1711 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1687 -pylab, to simplify things for users. Will also remove the pylab
1712 -pylab, to simplify things for users. Will also remove the pylab
1688 profile, since now all of matplotlib configuration is directly
1713 profile, since now all of matplotlib configuration is directly
1689 handled here. This also reduces startup time.
1714 handled here. This also reduces startup time.
1690
1715
1691 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1716 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1692 shell wasn't being correctly called. Also in IPShellWX.
1717 shell wasn't being correctly called. Also in IPShellWX.
1693
1718
1694 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1719 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1695 fine-tune banner.
1720 fine-tune banner.
1696
1721
1697 * IPython/numutils.py (spike): Deprecate these spike functions,
1722 * IPython/numutils.py (spike): Deprecate these spike functions,
1698 delete (long deprecated) gnuplot_exec handler.
1723 delete (long deprecated) gnuplot_exec handler.
1699
1724
1700 2004-08-26 Fernando Perez <fperez@colorado.edu>
1725 2004-08-26 Fernando Perez <fperez@colorado.edu>
1701
1726
1702 * ipython.1: Update for threading options, plus some others which
1727 * ipython.1: Update for threading options, plus some others which
1703 were missing.
1728 were missing.
1704
1729
1705 * IPython/ipmaker.py (__call__): Added -wthread option for
1730 * IPython/ipmaker.py (__call__): Added -wthread option for
1706 wxpython thread handling. Make sure threading options are only
1731 wxpython thread handling. Make sure threading options are only
1707 valid at the command line.
1732 valid at the command line.
1708
1733
1709 * scripts/ipython: moved shell selection into a factory function
1734 * scripts/ipython: moved shell selection into a factory function
1710 in Shell.py, to keep the starter script to a minimum.
1735 in Shell.py, to keep the starter script to a minimum.
1711
1736
1712 2004-08-25 Fernando Perez <fperez@colorado.edu>
1737 2004-08-25 Fernando Perez <fperez@colorado.edu>
1713
1738
1714 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1739 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1715 John. Along with some recent changes he made to matplotlib, the
1740 John. Along with some recent changes he made to matplotlib, the
1716 next versions of both systems should work very well together.
1741 next versions of both systems should work very well together.
1717
1742
1718 2004-08-24 Fernando Perez <fperez@colorado.edu>
1743 2004-08-24 Fernando Perez <fperez@colorado.edu>
1719
1744
1720 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1745 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1721 tried to switch the profiling to using hotshot, but I'm getting
1746 tried to switch the profiling to using hotshot, but I'm getting
1722 strange errors from prof.runctx() there. I may be misreading the
1747 strange errors from prof.runctx() there. I may be misreading the
1723 docs, but it looks weird. For now the profiling code will
1748 docs, but it looks weird. For now the profiling code will
1724 continue to use the standard profiler.
1749 continue to use the standard profiler.
1725
1750
1726 2004-08-23 Fernando Perez <fperez@colorado.edu>
1751 2004-08-23 Fernando Perez <fperez@colorado.edu>
1727
1752
1728 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1753 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1729 threaded shell, by John Hunter. It's not quite ready yet, but
1754 threaded shell, by John Hunter. It's not quite ready yet, but
1730 close.
1755 close.
1731
1756
1732 2004-08-22 Fernando Perez <fperez@colorado.edu>
1757 2004-08-22 Fernando Perez <fperez@colorado.edu>
1733
1758
1734 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1759 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1735 in Magic and ultraTB.
1760 in Magic and ultraTB.
1736
1761
1737 * ipython.1: document threading options in manpage.
1762 * ipython.1: document threading options in manpage.
1738
1763
1739 * scripts/ipython: Changed name of -thread option to -gthread,
1764 * scripts/ipython: Changed name of -thread option to -gthread,
1740 since this is GTK specific. I want to leave the door open for a
1765 since this is GTK specific. I want to leave the door open for a
1741 -wthread option for WX, which will most likely be necessary. This
1766 -wthread option for WX, which will most likely be necessary. This
1742 change affects usage and ipmaker as well.
1767 change affects usage and ipmaker as well.
1743
1768
1744 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1769 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1745 handle the matplotlib shell issues. Code by John Hunter
1770 handle the matplotlib shell issues. Code by John Hunter
1746 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1771 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1747 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1772 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1748 broken (and disabled for end users) for now, but it puts the
1773 broken (and disabled for end users) for now, but it puts the
1749 infrastructure in place.
1774 infrastructure in place.
1750
1775
1751 2004-08-21 Fernando Perez <fperez@colorado.edu>
1776 2004-08-21 Fernando Perez <fperez@colorado.edu>
1752
1777
1753 * ipythonrc-pylab: Add matplotlib support.
1778 * ipythonrc-pylab: Add matplotlib support.
1754
1779
1755 * matplotlib_config.py: new files for matplotlib support, part of
1780 * matplotlib_config.py: new files for matplotlib support, part of
1756 the pylab profile.
1781 the pylab profile.
1757
1782
1758 * IPython/usage.py (__doc__): documented the threading options.
1783 * IPython/usage.py (__doc__): documented the threading options.
1759
1784
1760 2004-08-20 Fernando Perez <fperez@colorado.edu>
1785 2004-08-20 Fernando Perez <fperez@colorado.edu>
1761
1786
1762 * ipython: Modified the main calling routine to handle the -thread
1787 * ipython: Modified the main calling routine to handle the -thread
1763 and -mpthread options. This needs to be done as a top-level hack,
1788 and -mpthread options. This needs to be done as a top-level hack,
1764 because it determines which class to instantiate for IPython
1789 because it determines which class to instantiate for IPython
1765 itself.
1790 itself.
1766
1791
1767 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1792 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1768 classes to support multithreaded GTK operation without blocking,
1793 classes to support multithreaded GTK operation without blocking,
1769 and matplotlib with all backends. This is a lot of still very
1794 and matplotlib with all backends. This is a lot of still very
1770 experimental code, and threads are tricky. So it may still have a
1795 experimental code, and threads are tricky. So it may still have a
1771 few rough edges... This code owes a lot to
1796 few rough edges... This code owes a lot to
1772 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1797 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1773 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1798 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1774 to John Hunter for all the matplotlib work.
1799 to John Hunter for all the matplotlib work.
1775
1800
1776 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1801 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1777 options for gtk thread and matplotlib support.
1802 options for gtk thread and matplotlib support.
1778
1803
1779 2004-08-16 Fernando Perez <fperez@colorado.edu>
1804 2004-08-16 Fernando Perez <fperez@colorado.edu>
1780
1805
1781 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1806 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1782 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1807 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1783 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1808 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1784
1809
1785 2004-08-11 Fernando Perez <fperez@colorado.edu>
1810 2004-08-11 Fernando Perez <fperez@colorado.edu>
1786
1811
1787 * setup.py (isfile): Fix build so documentation gets updated for
1812 * setup.py (isfile): Fix build so documentation gets updated for
1788 rpms (it was only done for .tgz builds).
1813 rpms (it was only done for .tgz builds).
1789
1814
1790 2004-08-10 Fernando Perez <fperez@colorado.edu>
1815 2004-08-10 Fernando Perez <fperez@colorado.edu>
1791
1816
1792 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1817 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1793
1818
1794 * iplib.py : Silence syntax error exceptions in tab-completion.
1819 * iplib.py : Silence syntax error exceptions in tab-completion.
1795
1820
1796 2004-08-05 Fernando Perez <fperez@colorado.edu>
1821 2004-08-05 Fernando Perez <fperez@colorado.edu>
1797
1822
1798 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1823 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1799 'color off' mark for continuation prompts. This was causing long
1824 'color off' mark for continuation prompts. This was causing long
1800 continuation lines to mis-wrap.
1825 continuation lines to mis-wrap.
1801
1826
1802 2004-08-01 Fernando Perez <fperez@colorado.edu>
1827 2004-08-01 Fernando Perez <fperez@colorado.edu>
1803
1828
1804 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1829 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1805 for building ipython to be a parameter. All this is necessary
1830 for building ipython to be a parameter. All this is necessary
1806 right now to have a multithreaded version, but this insane
1831 right now to have a multithreaded version, but this insane
1807 non-design will be cleaned up soon. For now, it's a hack that
1832 non-design will be cleaned up soon. For now, it's a hack that
1808 works.
1833 works.
1809
1834
1810 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1835 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1811 args in various places. No bugs so far, but it's a dangerous
1836 args in various places. No bugs so far, but it's a dangerous
1812 practice.
1837 practice.
1813
1838
1814 2004-07-31 Fernando Perez <fperez@colorado.edu>
1839 2004-07-31 Fernando Perez <fperez@colorado.edu>
1815
1840
1816 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1841 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1817 fix completion of files with dots in their names under most
1842 fix completion of files with dots in their names under most
1818 profiles (pysh was OK because the completion order is different).
1843 profiles (pysh was OK because the completion order is different).
1819
1844
1820 2004-07-27 Fernando Perez <fperez@colorado.edu>
1845 2004-07-27 Fernando Perez <fperez@colorado.edu>
1821
1846
1822 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1847 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1823 keywords manually, b/c the one in keyword.py was removed in python
1848 keywords manually, b/c the one in keyword.py was removed in python
1824 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1849 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1825 This is NOT a bug under python 2.3 and earlier.
1850 This is NOT a bug under python 2.3 and earlier.
1826
1851
1827 2004-07-26 Fernando Perez <fperez@colorado.edu>
1852 2004-07-26 Fernando Perez <fperez@colorado.edu>
1828
1853
1829 * IPython/ultraTB.py (VerboseTB.text): Add another
1854 * IPython/ultraTB.py (VerboseTB.text): Add another
1830 linecache.checkcache() call to try to prevent inspect.py from
1855 linecache.checkcache() call to try to prevent inspect.py from
1831 crashing under python 2.3. I think this fixes
1856 crashing under python 2.3. I think this fixes
1832 http://www.scipy.net/roundup/ipython/issue17.
1857 http://www.scipy.net/roundup/ipython/issue17.
1833
1858
1834 2004-07-26 *** Released version 0.6.2
1859 2004-07-26 *** Released version 0.6.2
1835
1860
1836 2004-07-26 Fernando Perez <fperez@colorado.edu>
1861 2004-07-26 Fernando Perez <fperez@colorado.edu>
1837
1862
1838 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1863 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1839 fail for any number.
1864 fail for any number.
1840 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1865 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1841 empty bookmarks.
1866 empty bookmarks.
1842
1867
1843 2004-07-26 *** Released version 0.6.1
1868 2004-07-26 *** Released version 0.6.1
1844
1869
1845 2004-07-26 Fernando Perez <fperez@colorado.edu>
1870 2004-07-26 Fernando Perez <fperez@colorado.edu>
1846
1871
1847 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1872 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1848
1873
1849 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1874 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1850 escaping '()[]{}' in filenames.
1875 escaping '()[]{}' in filenames.
1851
1876
1852 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1877 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1853 Python 2.2 users who lack a proper shlex.split.
1878 Python 2.2 users who lack a proper shlex.split.
1854
1879
1855 2004-07-19 Fernando Perez <fperez@colorado.edu>
1880 2004-07-19 Fernando Perez <fperez@colorado.edu>
1856
1881
1857 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1882 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1858 for reading readline's init file. I follow the normal chain:
1883 for reading readline's init file. I follow the normal chain:
1859 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1884 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1860 report by Mike Heeter. This closes
1885 report by Mike Heeter. This closes
1861 http://www.scipy.net/roundup/ipython/issue16.
1886 http://www.scipy.net/roundup/ipython/issue16.
1862
1887
1863 2004-07-18 Fernando Perez <fperez@colorado.edu>
1888 2004-07-18 Fernando Perez <fperez@colorado.edu>
1864
1889
1865 * IPython/iplib.py (__init__): Add better handling of '\' under
1890 * IPython/iplib.py (__init__): Add better handling of '\' under
1866 Win32 for filenames. After a patch by Ville.
1891 Win32 for filenames. After a patch by Ville.
1867
1892
1868 2004-07-17 Fernando Perez <fperez@colorado.edu>
1893 2004-07-17 Fernando Perez <fperez@colorado.edu>
1869
1894
1870 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1895 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1871 autocalling would be triggered for 'foo is bar' if foo is
1896 autocalling would be triggered for 'foo is bar' if foo is
1872 callable. I also cleaned up the autocall detection code to use a
1897 callable. I also cleaned up the autocall detection code to use a
1873 regexp, which is faster. Bug reported by Alexander Schmolck.
1898 regexp, which is faster. Bug reported by Alexander Schmolck.
1874
1899
1875 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1900 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1876 '?' in them would confuse the help system. Reported by Alex
1901 '?' in them would confuse the help system. Reported by Alex
1877 Schmolck.
1902 Schmolck.
1878
1903
1879 2004-07-16 Fernando Perez <fperez@colorado.edu>
1904 2004-07-16 Fernando Perez <fperez@colorado.edu>
1880
1905
1881 * IPython/GnuplotInteractive.py (__all__): added plot2.
1906 * IPython/GnuplotInteractive.py (__all__): added plot2.
1882
1907
1883 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1908 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1884 plotting dictionaries, lists or tuples of 1d arrays.
1909 plotting dictionaries, lists or tuples of 1d arrays.
1885
1910
1886 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1911 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1887 optimizations.
1912 optimizations.
1888
1913
1889 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1914 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1890 the information which was there from Janko's original IPP code:
1915 the information which was there from Janko's original IPP code:
1891
1916
1892 03.05.99 20:53 porto.ifm.uni-kiel.de
1917 03.05.99 20:53 porto.ifm.uni-kiel.de
1893 --Started changelog.
1918 --Started changelog.
1894 --make clear do what it say it does
1919 --make clear do what it say it does
1895 --added pretty output of lines from inputcache
1920 --added pretty output of lines from inputcache
1896 --Made Logger a mixin class, simplifies handling of switches
1921 --Made Logger a mixin class, simplifies handling of switches
1897 --Added own completer class. .string<TAB> expands to last history
1922 --Added own completer class. .string<TAB> expands to last history
1898 line which starts with string. The new expansion is also present
1923 line which starts with string. The new expansion is also present
1899 with Ctrl-r from the readline library. But this shows, who this
1924 with Ctrl-r from the readline library. But this shows, who this
1900 can be done for other cases.
1925 can be done for other cases.
1901 --Added convention that all shell functions should accept a
1926 --Added convention that all shell functions should accept a
1902 parameter_string This opens the door for different behaviour for
1927 parameter_string This opens the door for different behaviour for
1903 each function. @cd is a good example of this.
1928 each function. @cd is a good example of this.
1904
1929
1905 04.05.99 12:12 porto.ifm.uni-kiel.de
1930 04.05.99 12:12 porto.ifm.uni-kiel.de
1906 --added logfile rotation
1931 --added logfile rotation
1907 --added new mainloop method which freezes first the namespace
1932 --added new mainloop method which freezes first the namespace
1908
1933
1909 07.05.99 21:24 porto.ifm.uni-kiel.de
1934 07.05.99 21:24 porto.ifm.uni-kiel.de
1910 --added the docreader classes. Now there is a help system.
1935 --added the docreader classes. Now there is a help system.
1911 -This is only a first try. Currently it's not easy to put new
1936 -This is only a first try. Currently it's not easy to put new
1912 stuff in the indices. But this is the way to go. Info would be
1937 stuff in the indices. But this is the way to go. Info would be
1913 better, but HTML is every where and not everybody has an info
1938 better, but HTML is every where and not everybody has an info
1914 system installed and it's not so easy to change html-docs to info.
1939 system installed and it's not so easy to change html-docs to info.
1915 --added global logfile option
1940 --added global logfile option
1916 --there is now a hook for object inspection method pinfo needs to
1941 --there is now a hook for object inspection method pinfo needs to
1917 be provided for this. Can be reached by two '??'.
1942 be provided for this. Can be reached by two '??'.
1918
1943
1919 08.05.99 20:51 porto.ifm.uni-kiel.de
1944 08.05.99 20:51 porto.ifm.uni-kiel.de
1920 --added a README
1945 --added a README
1921 --bug in rc file. Something has changed so functions in the rc
1946 --bug in rc file. Something has changed so functions in the rc
1922 file need to reference the shell and not self. Not clear if it's a
1947 file need to reference the shell and not self. Not clear if it's a
1923 bug or feature.
1948 bug or feature.
1924 --changed rc file for new behavior
1949 --changed rc file for new behavior
1925
1950
1926 2004-07-15 Fernando Perez <fperez@colorado.edu>
1951 2004-07-15 Fernando Perez <fperez@colorado.edu>
1927
1952
1928 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1953 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1929 cache was falling out of sync in bizarre manners when multi-line
1954 cache was falling out of sync in bizarre manners when multi-line
1930 input was present. Minor optimizations and cleanup.
1955 input was present. Minor optimizations and cleanup.
1931
1956
1932 (Logger): Remove old Changelog info for cleanup. This is the
1957 (Logger): Remove old Changelog info for cleanup. This is the
1933 information which was there from Janko's original code:
1958 information which was there from Janko's original code:
1934
1959
1935 Changes to Logger: - made the default log filename a parameter
1960 Changes to Logger: - made the default log filename a parameter
1936
1961
1937 - put a check for lines beginning with !@? in log(). Needed
1962 - put a check for lines beginning with !@? in log(). Needed
1938 (even if the handlers properly log their lines) for mid-session
1963 (even if the handlers properly log their lines) for mid-session
1939 logging activation to work properly. Without this, lines logged
1964 logging activation to work properly. Without this, lines logged
1940 in mid session, which get read from the cache, would end up
1965 in mid session, which get read from the cache, would end up
1941 'bare' (with !@? in the open) in the log. Now they are caught
1966 'bare' (with !@? in the open) in the log. Now they are caught
1942 and prepended with a #.
1967 and prepended with a #.
1943
1968
1944 * IPython/iplib.py (InteractiveShell.init_readline): added check
1969 * IPython/iplib.py (InteractiveShell.init_readline): added check
1945 in case MagicCompleter fails to be defined, so we don't crash.
1970 in case MagicCompleter fails to be defined, so we don't crash.
1946
1971
1947 2004-07-13 Fernando Perez <fperez@colorado.edu>
1972 2004-07-13 Fernando Perez <fperez@colorado.edu>
1948
1973
1949 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1974 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1950 of EPS if the requested filename ends in '.eps'.
1975 of EPS if the requested filename ends in '.eps'.
1951
1976
1952 2004-07-04 Fernando Perez <fperez@colorado.edu>
1977 2004-07-04 Fernando Perez <fperez@colorado.edu>
1953
1978
1954 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1979 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1955 escaping of quotes when calling the shell.
1980 escaping of quotes when calling the shell.
1956
1981
1957 2004-07-02 Fernando Perez <fperez@colorado.edu>
1982 2004-07-02 Fernando Perez <fperez@colorado.edu>
1958
1983
1959 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1984 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1960 gettext not working because we were clobbering '_'. Fixes
1985 gettext not working because we were clobbering '_'. Fixes
1961 http://www.scipy.net/roundup/ipython/issue6.
1986 http://www.scipy.net/roundup/ipython/issue6.
1962
1987
1963 2004-07-01 Fernando Perez <fperez@colorado.edu>
1988 2004-07-01 Fernando Perez <fperez@colorado.edu>
1964
1989
1965 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1990 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1966 into @cd. Patch by Ville.
1991 into @cd. Patch by Ville.
1967
1992
1968 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1993 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1969 new function to store things after ipmaker runs. Patch by Ville.
1994 new function to store things after ipmaker runs. Patch by Ville.
1970 Eventually this will go away once ipmaker is removed and the class
1995 Eventually this will go away once ipmaker is removed and the class
1971 gets cleaned up, but for now it's ok. Key functionality here is
1996 gets cleaned up, but for now it's ok. Key functionality here is
1972 the addition of the persistent storage mechanism, a dict for
1997 the addition of the persistent storage mechanism, a dict for
1973 keeping data across sessions (for now just bookmarks, but more can
1998 keeping data across sessions (for now just bookmarks, but more can
1974 be implemented later).
1999 be implemented later).
1975
2000
1976 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2001 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1977 persistent across sections. Patch by Ville, I modified it
2002 persistent across sections. Patch by Ville, I modified it
1978 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2003 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1979 added a '-l' option to list all bookmarks.
2004 added a '-l' option to list all bookmarks.
1980
2005
1981 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2006 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1982 center for cleanup. Registered with atexit.register(). I moved
2007 center for cleanup. Registered with atexit.register(). I moved
1983 here the old exit_cleanup(). After a patch by Ville.
2008 here the old exit_cleanup(). After a patch by Ville.
1984
2009
1985 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2010 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1986 characters in the hacked shlex_split for python 2.2.
2011 characters in the hacked shlex_split for python 2.2.
1987
2012
1988 * IPython/iplib.py (file_matches): more fixes to filenames with
2013 * IPython/iplib.py (file_matches): more fixes to filenames with
1989 whitespace in them. It's not perfect, but limitations in python's
2014 whitespace in them. It's not perfect, but limitations in python's
1990 readline make it impossible to go further.
2015 readline make it impossible to go further.
1991
2016
1992 2004-06-29 Fernando Perez <fperez@colorado.edu>
2017 2004-06-29 Fernando Perez <fperez@colorado.edu>
1993
2018
1994 * IPython/iplib.py (file_matches): escape whitespace correctly in
2019 * IPython/iplib.py (file_matches): escape whitespace correctly in
1995 filename completions. Bug reported by Ville.
2020 filename completions. Bug reported by Ville.
1996
2021
1997 2004-06-28 Fernando Perez <fperez@colorado.edu>
2022 2004-06-28 Fernando Perez <fperez@colorado.edu>
1998
2023
1999 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2024 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2000 the history file will be called 'history-PROFNAME' (or just
2025 the history file will be called 'history-PROFNAME' (or just
2001 'history' if no profile is loaded). I was getting annoyed at
2026 'history' if no profile is loaded). I was getting annoyed at
2002 getting my Numerical work history clobbered by pysh sessions.
2027 getting my Numerical work history clobbered by pysh sessions.
2003
2028
2004 * IPython/iplib.py (InteractiveShell.__init__): Internal
2029 * IPython/iplib.py (InteractiveShell.__init__): Internal
2005 getoutputerror() function so that we can honor the system_verbose
2030 getoutputerror() function so that we can honor the system_verbose
2006 flag for _all_ system calls. I also added escaping of #
2031 flag for _all_ system calls. I also added escaping of #
2007 characters here to avoid confusing Itpl.
2032 characters here to avoid confusing Itpl.
2008
2033
2009 * IPython/Magic.py (shlex_split): removed call to shell in
2034 * IPython/Magic.py (shlex_split): removed call to shell in
2010 parse_options and replaced it with shlex.split(). The annoying
2035 parse_options and replaced it with shlex.split(). The annoying
2011 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2036 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2012 to backport it from 2.3, with several frail hacks (the shlex
2037 to backport it from 2.3, with several frail hacks (the shlex
2013 module is rather limited in 2.2). Thanks to a suggestion by Ville
2038 module is rather limited in 2.2). Thanks to a suggestion by Ville
2014 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2039 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2015 problem.
2040 problem.
2016
2041
2017 (Magic.magic_system_verbose): new toggle to print the actual
2042 (Magic.magic_system_verbose): new toggle to print the actual
2018 system calls made by ipython. Mainly for debugging purposes.
2043 system calls made by ipython. Mainly for debugging purposes.
2019
2044
2020 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2045 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2021 doesn't support persistence. Reported (and fix suggested) by
2046 doesn't support persistence. Reported (and fix suggested) by
2022 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2047 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2023
2048
2024 2004-06-26 Fernando Perez <fperez@colorado.edu>
2049 2004-06-26 Fernando Perez <fperez@colorado.edu>
2025
2050
2026 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2051 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2027 continue prompts.
2052 continue prompts.
2028
2053
2029 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2054 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2030 function (basically a big docstring) and a few more things here to
2055 function (basically a big docstring) and a few more things here to
2031 speedup startup. pysh.py is now very lightweight. We want because
2056 speedup startup. pysh.py is now very lightweight. We want because
2032 it gets execfile'd, while InterpreterExec gets imported, so
2057 it gets execfile'd, while InterpreterExec gets imported, so
2033 byte-compilation saves time.
2058 byte-compilation saves time.
2034
2059
2035 2004-06-25 Fernando Perez <fperez@colorado.edu>
2060 2004-06-25 Fernando Perez <fperez@colorado.edu>
2036
2061
2037 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2062 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2038 -NUM', which was recently broken.
2063 -NUM', which was recently broken.
2039
2064
2040 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2065 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2041 in multi-line input (but not !!, which doesn't make sense there).
2066 in multi-line input (but not !!, which doesn't make sense there).
2042
2067
2043 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2068 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2044 It's just too useful, and people can turn it off in the less
2069 It's just too useful, and people can turn it off in the less
2045 common cases where it's a problem.
2070 common cases where it's a problem.
2046
2071
2047 2004-06-24 Fernando Perez <fperez@colorado.edu>
2072 2004-06-24 Fernando Perez <fperez@colorado.edu>
2048
2073
2049 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2074 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2050 special syntaxes (like alias calling) is now allied in multi-line
2075 special syntaxes (like alias calling) is now allied in multi-line
2051 input. This is still _very_ experimental, but it's necessary for
2076 input. This is still _very_ experimental, but it's necessary for
2052 efficient shell usage combining python looping syntax with system
2077 efficient shell usage combining python looping syntax with system
2053 calls. For now it's restricted to aliases, I don't think it
2078 calls. For now it's restricted to aliases, I don't think it
2054 really even makes sense to have this for magics.
2079 really even makes sense to have this for magics.
2055
2080
2056 2004-06-23 Fernando Perez <fperez@colorado.edu>
2081 2004-06-23 Fernando Perez <fperez@colorado.edu>
2057
2082
2058 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2083 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2059 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2084 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2060
2085
2061 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2086 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2062 extensions under Windows (after code sent by Gary Bishop). The
2087 extensions under Windows (after code sent by Gary Bishop). The
2063 extensions considered 'executable' are stored in IPython's rc
2088 extensions considered 'executable' are stored in IPython's rc
2064 structure as win_exec_ext.
2089 structure as win_exec_ext.
2065
2090
2066 * IPython/genutils.py (shell): new function, like system() but
2091 * IPython/genutils.py (shell): new function, like system() but
2067 without return value. Very useful for interactive shell work.
2092 without return value. Very useful for interactive shell work.
2068
2093
2069 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2094 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2070 delete aliases.
2095 delete aliases.
2071
2096
2072 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2097 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2073 sure that the alias table doesn't contain python keywords.
2098 sure that the alias table doesn't contain python keywords.
2074
2099
2075 2004-06-21 Fernando Perez <fperez@colorado.edu>
2100 2004-06-21 Fernando Perez <fperez@colorado.edu>
2076
2101
2077 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2102 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2078 non-existent items are found in $PATH. Reported by Thorsten.
2103 non-existent items are found in $PATH. Reported by Thorsten.
2079
2104
2080 2004-06-20 Fernando Perez <fperez@colorado.edu>
2105 2004-06-20 Fernando Perez <fperez@colorado.edu>
2081
2106
2082 * IPython/iplib.py (complete): modified the completer so that the
2107 * IPython/iplib.py (complete): modified the completer so that the
2083 order of priorities can be easily changed at runtime.
2108 order of priorities can be easily changed at runtime.
2084
2109
2085 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2110 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2086 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2111 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2087
2112
2088 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2113 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2089 expand Python variables prepended with $ in all system calls. The
2114 expand Python variables prepended with $ in all system calls. The
2090 same was done to InteractiveShell.handle_shell_escape. Now all
2115 same was done to InteractiveShell.handle_shell_escape. Now all
2091 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2116 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2092 expansion of python variables and expressions according to the
2117 expansion of python variables and expressions according to the
2093 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2118 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2094
2119
2095 Though PEP-215 has been rejected, a similar (but simpler) one
2120 Though PEP-215 has been rejected, a similar (but simpler) one
2096 seems like it will go into Python 2.4, PEP-292 -
2121 seems like it will go into Python 2.4, PEP-292 -
2097 http://www.python.org/peps/pep-0292.html.
2122 http://www.python.org/peps/pep-0292.html.
2098
2123
2099 I'll keep the full syntax of PEP-215, since IPython has since the
2124 I'll keep the full syntax of PEP-215, since IPython has since the
2100 start used Ka-Ping Yee's reference implementation discussed there
2125 start used Ka-Ping Yee's reference implementation discussed there
2101 (Itpl), and I actually like the powerful semantics it offers.
2126 (Itpl), and I actually like the powerful semantics it offers.
2102
2127
2103 In order to access normal shell variables, the $ has to be escaped
2128 In order to access normal shell variables, the $ has to be escaped
2104 via an extra $. For example:
2129 via an extra $. For example:
2105
2130
2106 In [7]: PATH='a python variable'
2131 In [7]: PATH='a python variable'
2107
2132
2108 In [8]: !echo $PATH
2133 In [8]: !echo $PATH
2109 a python variable
2134 a python variable
2110
2135
2111 In [9]: !echo $$PATH
2136 In [9]: !echo $$PATH
2112 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2137 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2113
2138
2114 (Magic.parse_options): escape $ so the shell doesn't evaluate
2139 (Magic.parse_options): escape $ so the shell doesn't evaluate
2115 things prematurely.
2140 things prematurely.
2116
2141
2117 * IPython/iplib.py (InteractiveShell.call_alias): added the
2142 * IPython/iplib.py (InteractiveShell.call_alias): added the
2118 ability for aliases to expand python variables via $.
2143 ability for aliases to expand python variables via $.
2119
2144
2120 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2145 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2121 system, now there's a @rehash/@rehashx pair of magics. These work
2146 system, now there's a @rehash/@rehashx pair of magics. These work
2122 like the csh rehash command, and can be invoked at any time. They
2147 like the csh rehash command, and can be invoked at any time. They
2123 build a table of aliases to everything in the user's $PATH
2148 build a table of aliases to everything in the user's $PATH
2124 (@rehash uses everything, @rehashx is slower but only adds
2149 (@rehash uses everything, @rehashx is slower but only adds
2125 executable files). With this, the pysh.py-based shell profile can
2150 executable files). With this, the pysh.py-based shell profile can
2126 now simply call rehash upon startup, and full access to all
2151 now simply call rehash upon startup, and full access to all
2127 programs in the user's path is obtained.
2152 programs in the user's path is obtained.
2128
2153
2129 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2154 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2130 functionality is now fully in place. I removed the old dynamic
2155 functionality is now fully in place. I removed the old dynamic
2131 code generation based approach, in favor of a much lighter one
2156 code generation based approach, in favor of a much lighter one
2132 based on a simple dict. The advantage is that this allows me to
2157 based on a simple dict. The advantage is that this allows me to
2133 now have thousands of aliases with negligible cost (unthinkable
2158 now have thousands of aliases with negligible cost (unthinkable
2134 with the old system).
2159 with the old system).
2135
2160
2136 2004-06-19 Fernando Perez <fperez@colorado.edu>
2161 2004-06-19 Fernando Perez <fperez@colorado.edu>
2137
2162
2138 * IPython/iplib.py (__init__): extended MagicCompleter class to
2163 * IPython/iplib.py (__init__): extended MagicCompleter class to
2139 also complete (last in priority) on user aliases.
2164 also complete (last in priority) on user aliases.
2140
2165
2141 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2166 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2142 call to eval.
2167 call to eval.
2143 (ItplNS.__init__): Added a new class which functions like Itpl,
2168 (ItplNS.__init__): Added a new class which functions like Itpl,
2144 but allows configuring the namespace for the evaluation to occur
2169 but allows configuring the namespace for the evaluation to occur
2145 in.
2170 in.
2146
2171
2147 2004-06-18 Fernando Perez <fperez@colorado.edu>
2172 2004-06-18 Fernando Perez <fperez@colorado.edu>
2148
2173
2149 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2174 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2150 better message when 'exit' or 'quit' are typed (a common newbie
2175 better message when 'exit' or 'quit' are typed (a common newbie
2151 confusion).
2176 confusion).
2152
2177
2153 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2178 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2154 check for Windows users.
2179 check for Windows users.
2155
2180
2156 * IPython/iplib.py (InteractiveShell.user_setup): removed
2181 * IPython/iplib.py (InteractiveShell.user_setup): removed
2157 disabling of colors for Windows. I'll test at runtime and issue a
2182 disabling of colors for Windows. I'll test at runtime and issue a
2158 warning if Gary's readline isn't found, as to nudge users to
2183 warning if Gary's readline isn't found, as to nudge users to
2159 download it.
2184 download it.
2160
2185
2161 2004-06-16 Fernando Perez <fperez@colorado.edu>
2186 2004-06-16 Fernando Perez <fperez@colorado.edu>
2162
2187
2163 * IPython/genutils.py (Stream.__init__): changed to print errors
2188 * IPython/genutils.py (Stream.__init__): changed to print errors
2164 to sys.stderr. I had a circular dependency here. Now it's
2189 to sys.stderr. I had a circular dependency here. Now it's
2165 possible to run ipython as IDLE's shell (consider this pre-alpha,
2190 possible to run ipython as IDLE's shell (consider this pre-alpha,
2166 since true stdout things end up in the starting terminal instead
2191 since true stdout things end up in the starting terminal instead
2167 of IDLE's out).
2192 of IDLE's out).
2168
2193
2169 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2194 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2170 users who haven't # updated their prompt_in2 definitions. Remove
2195 users who haven't # updated their prompt_in2 definitions. Remove
2171 eventually.
2196 eventually.
2172 (multiple_replace): added credit to original ASPN recipe.
2197 (multiple_replace): added credit to original ASPN recipe.
2173
2198
2174 2004-06-15 Fernando Perez <fperez@colorado.edu>
2199 2004-06-15 Fernando Perez <fperez@colorado.edu>
2175
2200
2176 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2201 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2177 list of auto-defined aliases.
2202 list of auto-defined aliases.
2178
2203
2179 2004-06-13 Fernando Perez <fperez@colorado.edu>
2204 2004-06-13 Fernando Perez <fperez@colorado.edu>
2180
2205
2181 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2206 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2182 install was really requested (so setup.py can be used for other
2207 install was really requested (so setup.py can be used for other
2183 things under Windows).
2208 things under Windows).
2184
2209
2185 2004-06-10 Fernando Perez <fperez@colorado.edu>
2210 2004-06-10 Fernando Perez <fperez@colorado.edu>
2186
2211
2187 * IPython/Logger.py (Logger.create_log): Manually remove any old
2212 * IPython/Logger.py (Logger.create_log): Manually remove any old
2188 backup, since os.remove may fail under Windows. Fixes bug
2213 backup, since os.remove may fail under Windows. Fixes bug
2189 reported by Thorsten.
2214 reported by Thorsten.
2190
2215
2191 2004-06-09 Fernando Perez <fperez@colorado.edu>
2216 2004-06-09 Fernando Perez <fperez@colorado.edu>
2192
2217
2193 * examples/example-embed.py: fixed all references to %n (replaced
2218 * examples/example-embed.py: fixed all references to %n (replaced
2194 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2219 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2195 for all examples and the manual as well.
2220 for all examples and the manual as well.
2196
2221
2197 2004-06-08 Fernando Perez <fperez@colorado.edu>
2222 2004-06-08 Fernando Perez <fperez@colorado.edu>
2198
2223
2199 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2224 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2200 alignment and color management. All 3 prompt subsystems now
2225 alignment and color management. All 3 prompt subsystems now
2201 inherit from BasePrompt.
2226 inherit from BasePrompt.
2202
2227
2203 * tools/release: updates for windows installer build and tag rpms
2228 * tools/release: updates for windows installer build and tag rpms
2204 with python version (since paths are fixed).
2229 with python version (since paths are fixed).
2205
2230
2206 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2231 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2207 which will become eventually obsolete. Also fixed the default
2232 which will become eventually obsolete. Also fixed the default
2208 prompt_in2 to use \D, so at least new users start with the correct
2233 prompt_in2 to use \D, so at least new users start with the correct
2209 defaults.
2234 defaults.
2210 WARNING: Users with existing ipythonrc files will need to apply
2235 WARNING: Users with existing ipythonrc files will need to apply
2211 this fix manually!
2236 this fix manually!
2212
2237
2213 * setup.py: make windows installer (.exe). This is finally the
2238 * setup.py: make windows installer (.exe). This is finally the
2214 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2239 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2215 which I hadn't included because it required Python 2.3 (or recent
2240 which I hadn't included because it required Python 2.3 (or recent
2216 distutils).
2241 distutils).
2217
2242
2218 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2243 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2219 usage of new '\D' escape.
2244 usage of new '\D' escape.
2220
2245
2221 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2246 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2222 lacks os.getuid())
2247 lacks os.getuid())
2223 (CachedOutput.set_colors): Added the ability to turn coloring
2248 (CachedOutput.set_colors): Added the ability to turn coloring
2224 on/off with @colors even for manually defined prompt colors. It
2249 on/off with @colors even for manually defined prompt colors. It
2225 uses a nasty global, but it works safely and via the generic color
2250 uses a nasty global, but it works safely and via the generic color
2226 handling mechanism.
2251 handling mechanism.
2227 (Prompt2.__init__): Introduced new escape '\D' for continuation
2252 (Prompt2.__init__): Introduced new escape '\D' for continuation
2228 prompts. It represents the counter ('\#') as dots.
2253 prompts. It represents the counter ('\#') as dots.
2229 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2254 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2230 need to update their ipythonrc files and replace '%n' with '\D' in
2255 need to update their ipythonrc files and replace '%n' with '\D' in
2231 their prompt_in2 settings everywhere. Sorry, but there's
2256 their prompt_in2 settings everywhere. Sorry, but there's
2232 otherwise no clean way to get all prompts to properly align. The
2257 otherwise no clean way to get all prompts to properly align. The
2233 ipythonrc shipped with IPython has been updated.
2258 ipythonrc shipped with IPython has been updated.
2234
2259
2235 2004-06-07 Fernando Perez <fperez@colorado.edu>
2260 2004-06-07 Fernando Perez <fperez@colorado.edu>
2236
2261
2237 * setup.py (isfile): Pass local_icons option to latex2html, so the
2262 * setup.py (isfile): Pass local_icons option to latex2html, so the
2238 resulting HTML file is self-contained. Thanks to
2263 resulting HTML file is self-contained. Thanks to
2239 dryice-AT-liu.com.cn for the tip.
2264 dryice-AT-liu.com.cn for the tip.
2240
2265
2241 * pysh.py: I created a new profile 'shell', which implements a
2266 * pysh.py: I created a new profile 'shell', which implements a
2242 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2267 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2243 system shell, nor will it become one anytime soon. It's mainly
2268 system shell, nor will it become one anytime soon. It's mainly
2244 meant to illustrate the use of the new flexible bash-like prompts.
2269 meant to illustrate the use of the new flexible bash-like prompts.
2245 I guess it could be used by hardy souls for true shell management,
2270 I guess it could be used by hardy souls for true shell management,
2246 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2271 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2247 profile. This uses the InterpreterExec extension provided by
2272 profile. This uses the InterpreterExec extension provided by
2248 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2273 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2249
2274
2250 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2275 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2251 auto-align itself with the length of the previous input prompt
2276 auto-align itself with the length of the previous input prompt
2252 (taking into account the invisible color escapes).
2277 (taking into account the invisible color escapes).
2253 (CachedOutput.__init__): Large restructuring of this class. Now
2278 (CachedOutput.__init__): Large restructuring of this class. Now
2254 all three prompts (primary1, primary2, output) are proper objects,
2279 all three prompts (primary1, primary2, output) are proper objects,
2255 managed by the 'parent' CachedOutput class. The code is still a
2280 managed by the 'parent' CachedOutput class. The code is still a
2256 bit hackish (all prompts share state via a pointer to the cache),
2281 bit hackish (all prompts share state via a pointer to the cache),
2257 but it's overall far cleaner than before.
2282 but it's overall far cleaner than before.
2258
2283
2259 * IPython/genutils.py (getoutputerror): modified to add verbose,
2284 * IPython/genutils.py (getoutputerror): modified to add verbose,
2260 debug and header options. This makes the interface of all getout*
2285 debug and header options. This makes the interface of all getout*
2261 functions uniform.
2286 functions uniform.
2262 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2287 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2263
2288
2264 * IPython/Magic.py (Magic.default_option): added a function to
2289 * IPython/Magic.py (Magic.default_option): added a function to
2265 allow registering default options for any magic command. This
2290 allow registering default options for any magic command. This
2266 makes it easy to have profiles which customize the magics globally
2291 makes it easy to have profiles which customize the magics globally
2267 for a certain use. The values set through this function are
2292 for a certain use. The values set through this function are
2268 picked up by the parse_options() method, which all magics should
2293 picked up by the parse_options() method, which all magics should
2269 use to parse their options.
2294 use to parse their options.
2270
2295
2271 * IPython/genutils.py (warn): modified the warnings framework to
2296 * IPython/genutils.py (warn): modified the warnings framework to
2272 use the Term I/O class. I'm trying to slowly unify all of
2297 use the Term I/O class. I'm trying to slowly unify all of
2273 IPython's I/O operations to pass through Term.
2298 IPython's I/O operations to pass through Term.
2274
2299
2275 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2300 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2276 the secondary prompt to correctly match the length of the primary
2301 the secondary prompt to correctly match the length of the primary
2277 one for any prompt. Now multi-line code will properly line up
2302 one for any prompt. Now multi-line code will properly line up
2278 even for path dependent prompts, such as the new ones available
2303 even for path dependent prompts, such as the new ones available
2279 via the prompt_specials.
2304 via the prompt_specials.
2280
2305
2281 2004-06-06 Fernando Perez <fperez@colorado.edu>
2306 2004-06-06 Fernando Perez <fperez@colorado.edu>
2282
2307
2283 * IPython/Prompts.py (prompt_specials): Added the ability to have
2308 * IPython/Prompts.py (prompt_specials): Added the ability to have
2284 bash-like special sequences in the prompts, which get
2309 bash-like special sequences in the prompts, which get
2285 automatically expanded. Things like hostname, current working
2310 automatically expanded. Things like hostname, current working
2286 directory and username are implemented already, but it's easy to
2311 directory and username are implemented already, but it's easy to
2287 add more in the future. Thanks to a patch by W.J. van der Laan
2312 add more in the future. Thanks to a patch by W.J. van der Laan
2288 <gnufnork-AT-hetdigitalegat.nl>
2313 <gnufnork-AT-hetdigitalegat.nl>
2289 (prompt_specials): Added color support for prompt strings, so
2314 (prompt_specials): Added color support for prompt strings, so
2290 users can define arbitrary color setups for their prompts.
2315 users can define arbitrary color setups for their prompts.
2291
2316
2292 2004-06-05 Fernando Perez <fperez@colorado.edu>
2317 2004-06-05 Fernando Perez <fperez@colorado.edu>
2293
2318
2294 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2319 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2295 code to load Gary Bishop's readline and configure it
2320 code to load Gary Bishop's readline and configure it
2296 automatically. Thanks to Gary for help on this.
2321 automatically. Thanks to Gary for help on this.
2297
2322
2298 2004-06-01 Fernando Perez <fperez@colorado.edu>
2323 2004-06-01 Fernando Perez <fperez@colorado.edu>
2299
2324
2300 * IPython/Logger.py (Logger.create_log): fix bug for logging
2325 * IPython/Logger.py (Logger.create_log): fix bug for logging
2301 with no filename (previous fix was incomplete).
2326 with no filename (previous fix was incomplete).
2302
2327
2303 2004-05-25 Fernando Perez <fperez@colorado.edu>
2328 2004-05-25 Fernando Perez <fperez@colorado.edu>
2304
2329
2305 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2330 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2306 parens would get passed to the shell.
2331 parens would get passed to the shell.
2307
2332
2308 2004-05-20 Fernando Perez <fperez@colorado.edu>
2333 2004-05-20 Fernando Perez <fperez@colorado.edu>
2309
2334
2310 * IPython/Magic.py (Magic.magic_prun): changed default profile
2335 * IPython/Magic.py (Magic.magic_prun): changed default profile
2311 sort order to 'time' (the more common profiling need).
2336 sort order to 'time' (the more common profiling need).
2312
2337
2313 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2338 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2314 so that source code shown is guaranteed in sync with the file on
2339 so that source code shown is guaranteed in sync with the file on
2315 disk (also changed in psource). Similar fix to the one for
2340 disk (also changed in psource). Similar fix to the one for
2316 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2341 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2317 <yann.ledu-AT-noos.fr>.
2342 <yann.ledu-AT-noos.fr>.
2318
2343
2319 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2344 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2320 with a single option would not be correctly parsed. Closes
2345 with a single option would not be correctly parsed. Closes
2321 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2346 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2322 introduced in 0.6.0 (on 2004-05-06).
2347 introduced in 0.6.0 (on 2004-05-06).
2323
2348
2324 2004-05-13 *** Released version 0.6.0
2349 2004-05-13 *** Released version 0.6.0
2325
2350
2326 2004-05-13 Fernando Perez <fperez@colorado.edu>
2351 2004-05-13 Fernando Perez <fperez@colorado.edu>
2327
2352
2328 * debian/: Added debian/ directory to CVS, so that debian support
2353 * debian/: Added debian/ directory to CVS, so that debian support
2329 is publicly accessible. The debian package is maintained by Jack
2354 is publicly accessible. The debian package is maintained by Jack
2330 Moffit <jack-AT-xiph.org>.
2355 Moffit <jack-AT-xiph.org>.
2331
2356
2332 * Documentation: included the notes about an ipython-based system
2357 * Documentation: included the notes about an ipython-based system
2333 shell (the hypothetical 'pysh') into the new_design.pdf document,
2358 shell (the hypothetical 'pysh') into the new_design.pdf document,
2334 so that these ideas get distributed to users along with the
2359 so that these ideas get distributed to users along with the
2335 official documentation.
2360 official documentation.
2336
2361
2337 2004-05-10 Fernando Perez <fperez@colorado.edu>
2362 2004-05-10 Fernando Perez <fperez@colorado.edu>
2338
2363
2339 * IPython/Logger.py (Logger.create_log): fix recently introduced
2364 * IPython/Logger.py (Logger.create_log): fix recently introduced
2340 bug (misindented line) where logstart would fail when not given an
2365 bug (misindented line) where logstart would fail when not given an
2341 explicit filename.
2366 explicit filename.
2342
2367
2343 2004-05-09 Fernando Perez <fperez@colorado.edu>
2368 2004-05-09 Fernando Perez <fperez@colorado.edu>
2344
2369
2345 * IPython/Magic.py (Magic.parse_options): skip system call when
2370 * IPython/Magic.py (Magic.parse_options): skip system call when
2346 there are no options to look for. Faster, cleaner for the common
2371 there are no options to look for. Faster, cleaner for the common
2347 case.
2372 case.
2348
2373
2349 * Documentation: many updates to the manual: describing Windows
2374 * Documentation: many updates to the manual: describing Windows
2350 support better, Gnuplot updates, credits, misc small stuff. Also
2375 support better, Gnuplot updates, credits, misc small stuff. Also
2351 updated the new_design doc a bit.
2376 updated the new_design doc a bit.
2352
2377
2353 2004-05-06 *** Released version 0.6.0.rc1
2378 2004-05-06 *** Released version 0.6.0.rc1
2354
2379
2355 2004-05-06 Fernando Perez <fperez@colorado.edu>
2380 2004-05-06 Fernando Perez <fperez@colorado.edu>
2356
2381
2357 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2382 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2358 operations to use the vastly more efficient list/''.join() method.
2383 operations to use the vastly more efficient list/''.join() method.
2359 (FormattedTB.text): Fix
2384 (FormattedTB.text): Fix
2360 http://www.scipy.net/roundup/ipython/issue12 - exception source
2385 http://www.scipy.net/roundup/ipython/issue12 - exception source
2361 extract not updated after reload. Thanks to Mike Salib
2386 extract not updated after reload. Thanks to Mike Salib
2362 <msalib-AT-mit.edu> for pinning the source of the problem.
2387 <msalib-AT-mit.edu> for pinning the source of the problem.
2363 Fortunately, the solution works inside ipython and doesn't require
2388 Fortunately, the solution works inside ipython and doesn't require
2364 any changes to python proper.
2389 any changes to python proper.
2365
2390
2366 * IPython/Magic.py (Magic.parse_options): Improved to process the
2391 * IPython/Magic.py (Magic.parse_options): Improved to process the
2367 argument list as a true shell would (by actually using the
2392 argument list as a true shell would (by actually using the
2368 underlying system shell). This way, all @magics automatically get
2393 underlying system shell). This way, all @magics automatically get
2369 shell expansion for variables. Thanks to a comment by Alex
2394 shell expansion for variables. Thanks to a comment by Alex
2370 Schmolck.
2395 Schmolck.
2371
2396
2372 2004-04-04 Fernando Perez <fperez@colorado.edu>
2397 2004-04-04 Fernando Perez <fperez@colorado.edu>
2373
2398
2374 * IPython/iplib.py (InteractiveShell.interact): Added a special
2399 * IPython/iplib.py (InteractiveShell.interact): Added a special
2375 trap for a debugger quit exception, which is basically impossible
2400 trap for a debugger quit exception, which is basically impossible
2376 to handle by normal mechanisms, given what pdb does to the stack.
2401 to handle by normal mechanisms, given what pdb does to the stack.
2377 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2402 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2378
2403
2379 2004-04-03 Fernando Perez <fperez@colorado.edu>
2404 2004-04-03 Fernando Perez <fperez@colorado.edu>
2380
2405
2381 * IPython/genutils.py (Term): Standardized the names of the Term
2406 * IPython/genutils.py (Term): Standardized the names of the Term
2382 class streams to cin/cout/cerr, following C++ naming conventions
2407 class streams to cin/cout/cerr, following C++ naming conventions
2383 (I can't use in/out/err because 'in' is not a valid attribute
2408 (I can't use in/out/err because 'in' is not a valid attribute
2384 name).
2409 name).
2385
2410
2386 * IPython/iplib.py (InteractiveShell.interact): don't increment
2411 * IPython/iplib.py (InteractiveShell.interact): don't increment
2387 the prompt if there's no user input. By Daniel 'Dang' Griffith
2412 the prompt if there's no user input. By Daniel 'Dang' Griffith
2388 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2413 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2389 Francois Pinard.
2414 Francois Pinard.
2390
2415
2391 2004-04-02 Fernando Perez <fperez@colorado.edu>
2416 2004-04-02 Fernando Perez <fperez@colorado.edu>
2392
2417
2393 * IPython/genutils.py (Stream.__init__): Modified to survive at
2418 * IPython/genutils.py (Stream.__init__): Modified to survive at
2394 least importing in contexts where stdin/out/err aren't true file
2419 least importing in contexts where stdin/out/err aren't true file
2395 objects, such as PyCrust (they lack fileno() and mode). However,
2420 objects, such as PyCrust (they lack fileno() and mode). However,
2396 the recovery facilities which rely on these things existing will
2421 the recovery facilities which rely on these things existing will
2397 not work.
2422 not work.
2398
2423
2399 2004-04-01 Fernando Perez <fperez@colorado.edu>
2424 2004-04-01 Fernando Perez <fperez@colorado.edu>
2400
2425
2401 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2426 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2402 use the new getoutputerror() function, so it properly
2427 use the new getoutputerror() function, so it properly
2403 distinguishes stdout/err.
2428 distinguishes stdout/err.
2404
2429
2405 * IPython/genutils.py (getoutputerror): added a function to
2430 * IPython/genutils.py (getoutputerror): added a function to
2406 capture separately the standard output and error of a command.
2431 capture separately the standard output and error of a command.
2407 After a comment from dang on the mailing lists. This code is
2432 After a comment from dang on the mailing lists. This code is
2408 basically a modified version of commands.getstatusoutput(), from
2433 basically a modified version of commands.getstatusoutput(), from
2409 the standard library.
2434 the standard library.
2410
2435
2411 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2436 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2412 '!!' as a special syntax (shorthand) to access @sx.
2437 '!!' as a special syntax (shorthand) to access @sx.
2413
2438
2414 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2439 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2415 command and return its output as a list split on '\n'.
2440 command and return its output as a list split on '\n'.
2416
2441
2417 2004-03-31 Fernando Perez <fperez@colorado.edu>
2442 2004-03-31 Fernando Perez <fperez@colorado.edu>
2418
2443
2419 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2444 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2420 method to dictionaries used as FakeModule instances if they lack
2445 method to dictionaries used as FakeModule instances if they lack
2421 it. At least pydoc in python2.3 breaks for runtime-defined
2446 it. At least pydoc in python2.3 breaks for runtime-defined
2422 functions without this hack. At some point I need to _really_
2447 functions without this hack. At some point I need to _really_
2423 understand what FakeModule is doing, because it's a gross hack.
2448 understand what FakeModule is doing, because it's a gross hack.
2424 But it solves Arnd's problem for now...
2449 But it solves Arnd's problem for now...
2425
2450
2426 2004-02-27 Fernando Perez <fperez@colorado.edu>
2451 2004-02-27 Fernando Perez <fperez@colorado.edu>
2427
2452
2428 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2453 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2429 mode would behave erratically. Also increased the number of
2454 mode would behave erratically. Also increased the number of
2430 possible logs in rotate mod to 999. Thanks to Rod Holland
2455 possible logs in rotate mod to 999. Thanks to Rod Holland
2431 <rhh@StructureLABS.com> for the report and fixes.
2456 <rhh@StructureLABS.com> for the report and fixes.
2432
2457
2433 2004-02-26 Fernando Perez <fperez@colorado.edu>
2458 2004-02-26 Fernando Perez <fperez@colorado.edu>
2434
2459
2435 * IPython/genutils.py (page): Check that the curses module really
2460 * IPython/genutils.py (page): Check that the curses module really
2436 has the initscr attribute before trying to use it. For some
2461 has the initscr attribute before trying to use it. For some
2437 reason, the Solaris curses module is missing this. I think this
2462 reason, the Solaris curses module is missing this. I think this
2438 should be considered a Solaris python bug, but I'm not sure.
2463 should be considered a Solaris python bug, but I'm not sure.
2439
2464
2440 2004-01-17 Fernando Perez <fperez@colorado.edu>
2465 2004-01-17 Fernando Perez <fperez@colorado.edu>
2441
2466
2442 * IPython/genutils.py (Stream.__init__): Changes to try to make
2467 * IPython/genutils.py (Stream.__init__): Changes to try to make
2443 ipython robust against stdin/out/err being closed by the user.
2468 ipython robust against stdin/out/err being closed by the user.
2444 This is 'user error' (and blocks a normal python session, at least
2469 This is 'user error' (and blocks a normal python session, at least
2445 the stdout case). However, Ipython should be able to survive such
2470 the stdout case). However, Ipython should be able to survive such
2446 instances of abuse as gracefully as possible. To simplify the
2471 instances of abuse as gracefully as possible. To simplify the
2447 coding and maintain compatibility with Gary Bishop's Term
2472 coding and maintain compatibility with Gary Bishop's Term
2448 contributions, I've made use of classmethods for this. I think
2473 contributions, I've made use of classmethods for this. I think
2449 this introduces a dependency on python 2.2.
2474 this introduces a dependency on python 2.2.
2450
2475
2451 2004-01-13 Fernando Perez <fperez@colorado.edu>
2476 2004-01-13 Fernando Perez <fperez@colorado.edu>
2452
2477
2453 * IPython/numutils.py (exp_safe): simplified the code a bit and
2478 * IPython/numutils.py (exp_safe): simplified the code a bit and
2454 removed the need for importing the kinds module altogether.
2479 removed the need for importing the kinds module altogether.
2455
2480
2456 2004-01-06 Fernando Perez <fperez@colorado.edu>
2481 2004-01-06 Fernando Perez <fperez@colorado.edu>
2457
2482
2458 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2483 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2459 a magic function instead, after some community feedback. No
2484 a magic function instead, after some community feedback. No
2460 special syntax will exist for it, but its name is deliberately
2485 special syntax will exist for it, but its name is deliberately
2461 very short.
2486 very short.
2462
2487
2463 2003-12-20 Fernando Perez <fperez@colorado.edu>
2488 2003-12-20 Fernando Perez <fperez@colorado.edu>
2464
2489
2465 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2490 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2466 new functionality, to automagically assign the result of a shell
2491 new functionality, to automagically assign the result of a shell
2467 command to a variable. I'll solicit some community feedback on
2492 command to a variable. I'll solicit some community feedback on
2468 this before making it permanent.
2493 this before making it permanent.
2469
2494
2470 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2495 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2471 requested about callables for which inspect couldn't obtain a
2496 requested about callables for which inspect couldn't obtain a
2472 proper argspec. Thanks to a crash report sent by Etienne
2497 proper argspec. Thanks to a crash report sent by Etienne
2473 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2498 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2474
2499
2475 2003-12-09 Fernando Perez <fperez@colorado.edu>
2500 2003-12-09 Fernando Perez <fperez@colorado.edu>
2476
2501
2477 * IPython/genutils.py (page): patch for the pager to work across
2502 * IPython/genutils.py (page): patch for the pager to work across
2478 various versions of Windows. By Gary Bishop.
2503 various versions of Windows. By Gary Bishop.
2479
2504
2480 2003-12-04 Fernando Perez <fperez@colorado.edu>
2505 2003-12-04 Fernando Perez <fperez@colorado.edu>
2481
2506
2482 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2507 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2483 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2508 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2484 While I tested this and it looks ok, there may still be corner
2509 While I tested this and it looks ok, there may still be corner
2485 cases I've missed.
2510 cases I've missed.
2486
2511
2487 2003-12-01 Fernando Perez <fperez@colorado.edu>
2512 2003-12-01 Fernando Perez <fperez@colorado.edu>
2488
2513
2489 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2514 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2490 where a line like 'p,q=1,2' would fail because the automagic
2515 where a line like 'p,q=1,2' would fail because the automagic
2491 system would be triggered for @p.
2516 system would be triggered for @p.
2492
2517
2493 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2518 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2494 cleanups, code unmodified.
2519 cleanups, code unmodified.
2495
2520
2496 * IPython/genutils.py (Term): added a class for IPython to handle
2521 * IPython/genutils.py (Term): added a class for IPython to handle
2497 output. In most cases it will just be a proxy for stdout/err, but
2522 output. In most cases it will just be a proxy for stdout/err, but
2498 having this allows modifications to be made for some platforms,
2523 having this allows modifications to be made for some platforms,
2499 such as handling color escapes under Windows. All of this code
2524 such as handling color escapes under Windows. All of this code
2500 was contributed by Gary Bishop, with minor modifications by me.
2525 was contributed by Gary Bishop, with minor modifications by me.
2501 The actual changes affect many files.
2526 The actual changes affect many files.
2502
2527
2503 2003-11-30 Fernando Perez <fperez@colorado.edu>
2528 2003-11-30 Fernando Perez <fperez@colorado.edu>
2504
2529
2505 * IPython/iplib.py (file_matches): new completion code, courtesy
2530 * IPython/iplib.py (file_matches): new completion code, courtesy
2506 of Jeff Collins. This enables filename completion again under
2531 of Jeff Collins. This enables filename completion again under
2507 python 2.3, which disabled it at the C level.
2532 python 2.3, which disabled it at the C level.
2508
2533
2509 2003-11-11 Fernando Perez <fperez@colorado.edu>
2534 2003-11-11 Fernando Perez <fperez@colorado.edu>
2510
2535
2511 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2536 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2512 for Numeric.array(map(...)), but often convenient.
2537 for Numeric.array(map(...)), but often convenient.
2513
2538
2514 2003-11-05 Fernando Perez <fperez@colorado.edu>
2539 2003-11-05 Fernando Perez <fperez@colorado.edu>
2515
2540
2516 * IPython/numutils.py (frange): Changed a call from int() to
2541 * IPython/numutils.py (frange): Changed a call from int() to
2517 int(round()) to prevent a problem reported with arange() in the
2542 int(round()) to prevent a problem reported with arange() in the
2518 numpy list.
2543 numpy list.
2519
2544
2520 2003-10-06 Fernando Perez <fperez@colorado.edu>
2545 2003-10-06 Fernando Perez <fperez@colorado.edu>
2521
2546
2522 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2547 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2523 prevent crashes if sys lacks an argv attribute (it happens with
2548 prevent crashes if sys lacks an argv attribute (it happens with
2524 embedded interpreters which build a bare-bones sys module).
2549 embedded interpreters which build a bare-bones sys module).
2525 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2550 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2526
2551
2527 2003-09-24 Fernando Perez <fperez@colorado.edu>
2552 2003-09-24 Fernando Perez <fperez@colorado.edu>
2528
2553
2529 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2554 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2530 to protect against poorly written user objects where __getattr__
2555 to protect against poorly written user objects where __getattr__
2531 raises exceptions other than AttributeError. Thanks to a bug
2556 raises exceptions other than AttributeError. Thanks to a bug
2532 report by Oliver Sander <osander-AT-gmx.de>.
2557 report by Oliver Sander <osander-AT-gmx.de>.
2533
2558
2534 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2559 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2535 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2560 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2536
2561
2537 2003-09-09 Fernando Perez <fperez@colorado.edu>
2562 2003-09-09 Fernando Perez <fperez@colorado.edu>
2538
2563
2539 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2564 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2540 unpacking a list whith a callable as first element would
2565 unpacking a list whith a callable as first element would
2541 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2566 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2542 Collins.
2567 Collins.
2543
2568
2544 2003-08-25 *** Released version 0.5.0
2569 2003-08-25 *** Released version 0.5.0
2545
2570
2546 2003-08-22 Fernando Perez <fperez@colorado.edu>
2571 2003-08-22 Fernando Perez <fperez@colorado.edu>
2547
2572
2548 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2573 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2549 improperly defined user exceptions. Thanks to feedback from Mark
2574 improperly defined user exceptions. Thanks to feedback from Mark
2550 Russell <mrussell-AT-verio.net>.
2575 Russell <mrussell-AT-verio.net>.
2551
2576
2552 2003-08-20 Fernando Perez <fperez@colorado.edu>
2577 2003-08-20 Fernando Perez <fperez@colorado.edu>
2553
2578
2554 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2579 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2555 printing so that it would print multi-line string forms starting
2580 printing so that it would print multi-line string forms starting
2556 with a new line. This way the formatting is better respected for
2581 with a new line. This way the formatting is better respected for
2557 objects which work hard to make nice string forms.
2582 objects which work hard to make nice string forms.
2558
2583
2559 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2584 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2560 autocall would overtake data access for objects with both
2585 autocall would overtake data access for objects with both
2561 __getitem__ and __call__.
2586 __getitem__ and __call__.
2562
2587
2563 2003-08-19 *** Released version 0.5.0-rc1
2588 2003-08-19 *** Released version 0.5.0-rc1
2564
2589
2565 2003-08-19 Fernando Perez <fperez@colorado.edu>
2590 2003-08-19 Fernando Perez <fperez@colorado.edu>
2566
2591
2567 * IPython/deep_reload.py (load_tail): single tiny change here
2592 * IPython/deep_reload.py (load_tail): single tiny change here
2568 seems to fix the long-standing bug of dreload() failing to work
2593 seems to fix the long-standing bug of dreload() failing to work
2569 for dotted names. But this module is pretty tricky, so I may have
2594 for dotted names. But this module is pretty tricky, so I may have
2570 missed some subtlety. Needs more testing!.
2595 missed some subtlety. Needs more testing!.
2571
2596
2572 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2597 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2573 exceptions which have badly implemented __str__ methods.
2598 exceptions which have badly implemented __str__ methods.
2574 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2599 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2575 which I've been getting reports about from Python 2.3 users. I
2600 which I've been getting reports about from Python 2.3 users. I
2576 wish I had a simple test case to reproduce the problem, so I could
2601 wish I had a simple test case to reproduce the problem, so I could
2577 either write a cleaner workaround or file a bug report if
2602 either write a cleaner workaround or file a bug report if
2578 necessary.
2603 necessary.
2579
2604
2580 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2605 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2581 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2606 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2582 a bug report by Tjabo Kloppenburg.
2607 a bug report by Tjabo Kloppenburg.
2583
2608
2584 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2609 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2585 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2610 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2586 seems rather unstable. Thanks to a bug report by Tjabo
2611 seems rather unstable. Thanks to a bug report by Tjabo
2587 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2612 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2588
2613
2589 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2614 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2590 this out soon because of the critical fixes in the inner loop for
2615 this out soon because of the critical fixes in the inner loop for
2591 generators.
2616 generators.
2592
2617
2593 * IPython/Magic.py (Magic.getargspec): removed. This (and
2618 * IPython/Magic.py (Magic.getargspec): removed. This (and
2594 _get_def) have been obsoleted by OInspect for a long time, I
2619 _get_def) have been obsoleted by OInspect for a long time, I
2595 hadn't noticed that they were dead code.
2620 hadn't noticed that they were dead code.
2596 (Magic._ofind): restored _ofind functionality for a few literals
2621 (Magic._ofind): restored _ofind functionality for a few literals
2597 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2622 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2598 for things like "hello".capitalize?, since that would require a
2623 for things like "hello".capitalize?, since that would require a
2599 potentially dangerous eval() again.
2624 potentially dangerous eval() again.
2600
2625
2601 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2626 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2602 logic a bit more to clean up the escapes handling and minimize the
2627 logic a bit more to clean up the escapes handling and minimize the
2603 use of _ofind to only necessary cases. The interactive 'feel' of
2628 use of _ofind to only necessary cases. The interactive 'feel' of
2604 IPython should have improved quite a bit with the changes in
2629 IPython should have improved quite a bit with the changes in
2605 _prefilter and _ofind (besides being far safer than before).
2630 _prefilter and _ofind (besides being far safer than before).
2606
2631
2607 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2632 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2608 obscure, never reported). Edit would fail to find the object to
2633 obscure, never reported). Edit would fail to find the object to
2609 edit under some circumstances.
2634 edit under some circumstances.
2610 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2635 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2611 which were causing double-calling of generators. Those eval calls
2636 which were causing double-calling of generators. Those eval calls
2612 were _very_ dangerous, since code with side effects could be
2637 were _very_ dangerous, since code with side effects could be
2613 triggered. As they say, 'eval is evil'... These were the
2638 triggered. As they say, 'eval is evil'... These were the
2614 nastiest evals in IPython. Besides, _ofind is now far simpler,
2639 nastiest evals in IPython. Besides, _ofind is now far simpler,
2615 and it should also be quite a bit faster. Its use of inspect is
2640 and it should also be quite a bit faster. Its use of inspect is
2616 also safer, so perhaps some of the inspect-related crashes I've
2641 also safer, so perhaps some of the inspect-related crashes I've
2617 seen lately with Python 2.3 might be taken care of. That will
2642 seen lately with Python 2.3 might be taken care of. That will
2618 need more testing.
2643 need more testing.
2619
2644
2620 2003-08-17 Fernando Perez <fperez@colorado.edu>
2645 2003-08-17 Fernando Perez <fperez@colorado.edu>
2621
2646
2622 * IPython/iplib.py (InteractiveShell._prefilter): significant
2647 * IPython/iplib.py (InteractiveShell._prefilter): significant
2623 simplifications to the logic for handling user escapes. Faster
2648 simplifications to the logic for handling user escapes. Faster
2624 and simpler code.
2649 and simpler code.
2625
2650
2626 2003-08-14 Fernando Perez <fperez@colorado.edu>
2651 2003-08-14 Fernando Perez <fperez@colorado.edu>
2627
2652
2628 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2653 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2629 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2654 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2630 but it should be quite a bit faster. And the recursive version
2655 but it should be quite a bit faster. And the recursive version
2631 generated O(log N) intermediate storage for all rank>1 arrays,
2656 generated O(log N) intermediate storage for all rank>1 arrays,
2632 even if they were contiguous.
2657 even if they were contiguous.
2633 (l1norm): Added this function.
2658 (l1norm): Added this function.
2634 (norm): Added this function for arbitrary norms (including
2659 (norm): Added this function for arbitrary norms (including
2635 l-infinity). l1 and l2 are still special cases for convenience
2660 l-infinity). l1 and l2 are still special cases for convenience
2636 and speed.
2661 and speed.
2637
2662
2638 2003-08-03 Fernando Perez <fperez@colorado.edu>
2663 2003-08-03 Fernando Perez <fperez@colorado.edu>
2639
2664
2640 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2665 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2641 exceptions, which now raise PendingDeprecationWarnings in Python
2666 exceptions, which now raise PendingDeprecationWarnings in Python
2642 2.3. There were some in Magic and some in Gnuplot2.
2667 2.3. There were some in Magic and some in Gnuplot2.
2643
2668
2644 2003-06-30 Fernando Perez <fperez@colorado.edu>
2669 2003-06-30 Fernando Perez <fperez@colorado.edu>
2645
2670
2646 * IPython/genutils.py (page): modified to call curses only for
2671 * IPython/genutils.py (page): modified to call curses only for
2647 terminals where TERM=='xterm'. After problems under many other
2672 terminals where TERM=='xterm'. After problems under many other
2648 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2673 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2649
2674
2650 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2675 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2651 would be triggered when readline was absent. This was just an old
2676 would be triggered when readline was absent. This was just an old
2652 debugging statement I'd forgotten to take out.
2677 debugging statement I'd forgotten to take out.
2653
2678
2654 2003-06-20 Fernando Perez <fperez@colorado.edu>
2679 2003-06-20 Fernando Perez <fperez@colorado.edu>
2655
2680
2656 * IPython/genutils.py (clock): modified to return only user time
2681 * IPython/genutils.py (clock): modified to return only user time
2657 (not counting system time), after a discussion on scipy. While
2682 (not counting system time), after a discussion on scipy. While
2658 system time may be a useful quantity occasionally, it may much
2683 system time may be a useful quantity occasionally, it may much
2659 more easily be skewed by occasional swapping or other similar
2684 more easily be skewed by occasional swapping or other similar
2660 activity.
2685 activity.
2661
2686
2662 2003-06-05 Fernando Perez <fperez@colorado.edu>
2687 2003-06-05 Fernando Perez <fperez@colorado.edu>
2663
2688
2664 * IPython/numutils.py (identity): new function, for building
2689 * IPython/numutils.py (identity): new function, for building
2665 arbitrary rank Kronecker deltas (mostly backwards compatible with
2690 arbitrary rank Kronecker deltas (mostly backwards compatible with
2666 Numeric.identity)
2691 Numeric.identity)
2667
2692
2668 2003-06-03 Fernando Perez <fperez@colorado.edu>
2693 2003-06-03 Fernando Perez <fperez@colorado.edu>
2669
2694
2670 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2695 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2671 arguments passed to magics with spaces, to allow trailing '\' to
2696 arguments passed to magics with spaces, to allow trailing '\' to
2672 work normally (mainly for Windows users).
2697 work normally (mainly for Windows users).
2673
2698
2674 2003-05-29 Fernando Perez <fperez@colorado.edu>
2699 2003-05-29 Fernando Perez <fperez@colorado.edu>
2675
2700
2676 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2701 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2677 instead of pydoc.help. This fixes a bizarre behavior where
2702 instead of pydoc.help. This fixes a bizarre behavior where
2678 printing '%s' % locals() would trigger the help system. Now
2703 printing '%s' % locals() would trigger the help system. Now
2679 ipython behaves like normal python does.
2704 ipython behaves like normal python does.
2680
2705
2681 Note that if one does 'from pydoc import help', the bizarre
2706 Note that if one does 'from pydoc import help', the bizarre
2682 behavior returns, but this will also happen in normal python, so
2707 behavior returns, but this will also happen in normal python, so
2683 it's not an ipython bug anymore (it has to do with how pydoc.help
2708 it's not an ipython bug anymore (it has to do with how pydoc.help
2684 is implemented).
2709 is implemented).
2685
2710
2686 2003-05-22 Fernando Perez <fperez@colorado.edu>
2711 2003-05-22 Fernando Perez <fperez@colorado.edu>
2687
2712
2688 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2713 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2689 return [] instead of None when nothing matches, also match to end
2714 return [] instead of None when nothing matches, also match to end
2690 of line. Patch by Gary Bishop.
2715 of line. Patch by Gary Bishop.
2691
2716
2692 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2717 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2693 protection as before, for files passed on the command line. This
2718 protection as before, for files passed on the command line. This
2694 prevents the CrashHandler from kicking in if user files call into
2719 prevents the CrashHandler from kicking in if user files call into
2695 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2720 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2696 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2721 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2697
2722
2698 2003-05-20 *** Released version 0.4.0
2723 2003-05-20 *** Released version 0.4.0
2699
2724
2700 2003-05-20 Fernando Perez <fperez@colorado.edu>
2725 2003-05-20 Fernando Perez <fperez@colorado.edu>
2701
2726
2702 * setup.py: added support for manpages. It's a bit hackish b/c of
2727 * setup.py: added support for manpages. It's a bit hackish b/c of
2703 a bug in the way the bdist_rpm distutils target handles gzipped
2728 a bug in the way the bdist_rpm distutils target handles gzipped
2704 manpages, but it works. After a patch by Jack.
2729 manpages, but it works. After a patch by Jack.
2705
2730
2706 2003-05-19 Fernando Perez <fperez@colorado.edu>
2731 2003-05-19 Fernando Perez <fperez@colorado.edu>
2707
2732
2708 * IPython/numutils.py: added a mockup of the kinds module, since
2733 * IPython/numutils.py: added a mockup of the kinds module, since
2709 it was recently removed from Numeric. This way, numutils will
2734 it was recently removed from Numeric. This way, numutils will
2710 work for all users even if they are missing kinds.
2735 work for all users even if they are missing kinds.
2711
2736
2712 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2737 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2713 failure, which can occur with SWIG-wrapped extensions. After a
2738 failure, which can occur with SWIG-wrapped extensions. After a
2714 crash report from Prabhu.
2739 crash report from Prabhu.
2715
2740
2716 2003-05-16 Fernando Perez <fperez@colorado.edu>
2741 2003-05-16 Fernando Perez <fperez@colorado.edu>
2717
2742
2718 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2743 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2719 protect ipython from user code which may call directly
2744 protect ipython from user code which may call directly
2720 sys.excepthook (this looks like an ipython crash to the user, even
2745 sys.excepthook (this looks like an ipython crash to the user, even
2721 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2746 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2722 This is especially important to help users of WxWindows, but may
2747 This is especially important to help users of WxWindows, but may
2723 also be useful in other cases.
2748 also be useful in other cases.
2724
2749
2725 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2750 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2726 an optional tb_offset to be specified, and to preserve exception
2751 an optional tb_offset to be specified, and to preserve exception
2727 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2752 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2728
2753
2729 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2754 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2730
2755
2731 2003-05-15 Fernando Perez <fperez@colorado.edu>
2756 2003-05-15 Fernando Perez <fperez@colorado.edu>
2732
2757
2733 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2758 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2734 installing for a new user under Windows.
2759 installing for a new user under Windows.
2735
2760
2736 2003-05-12 Fernando Perez <fperez@colorado.edu>
2761 2003-05-12 Fernando Perez <fperez@colorado.edu>
2737
2762
2738 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2763 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2739 handler for Emacs comint-based lines. Currently it doesn't do
2764 handler for Emacs comint-based lines. Currently it doesn't do
2740 much (but importantly, it doesn't update the history cache). In
2765 much (but importantly, it doesn't update the history cache). In
2741 the future it may be expanded if Alex needs more functionality
2766 the future it may be expanded if Alex needs more functionality
2742 there.
2767 there.
2743
2768
2744 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2769 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2745 info to crash reports.
2770 info to crash reports.
2746
2771
2747 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2772 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2748 just like Python's -c. Also fixed crash with invalid -color
2773 just like Python's -c. Also fixed crash with invalid -color
2749 option value at startup. Thanks to Will French
2774 option value at startup. Thanks to Will French
2750 <wfrench-AT-bestweb.net> for the bug report.
2775 <wfrench-AT-bestweb.net> for the bug report.
2751
2776
2752 2003-05-09 Fernando Perez <fperez@colorado.edu>
2777 2003-05-09 Fernando Perez <fperez@colorado.edu>
2753
2778
2754 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2779 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2755 to EvalDict (it's a mapping, after all) and simplified its code
2780 to EvalDict (it's a mapping, after all) and simplified its code
2756 quite a bit, after a nice discussion on c.l.py where Gustavo
2781 quite a bit, after a nice discussion on c.l.py where Gustavo
2757 Córdova <gcordova-AT-sismex.com> suggested the new version.
2782 Córdova <gcordova-AT-sismex.com> suggested the new version.
2758
2783
2759 2003-04-30 Fernando Perez <fperez@colorado.edu>
2784 2003-04-30 Fernando Perez <fperez@colorado.edu>
2760
2785
2761 * IPython/genutils.py (timings_out): modified it to reduce its
2786 * IPython/genutils.py (timings_out): modified it to reduce its
2762 overhead in the common reps==1 case.
2787 overhead in the common reps==1 case.
2763
2788
2764 2003-04-29 Fernando Perez <fperez@colorado.edu>
2789 2003-04-29 Fernando Perez <fperez@colorado.edu>
2765
2790
2766 * IPython/genutils.py (timings_out): Modified to use the resource
2791 * IPython/genutils.py (timings_out): Modified to use the resource
2767 module, which avoids the wraparound problems of time.clock().
2792 module, which avoids the wraparound problems of time.clock().
2768
2793
2769 2003-04-17 *** Released version 0.2.15pre4
2794 2003-04-17 *** Released version 0.2.15pre4
2770
2795
2771 2003-04-17 Fernando Perez <fperez@colorado.edu>
2796 2003-04-17 Fernando Perez <fperez@colorado.edu>
2772
2797
2773 * setup.py (scriptfiles): Split windows-specific stuff over to a
2798 * setup.py (scriptfiles): Split windows-specific stuff over to a
2774 separate file, in an attempt to have a Windows GUI installer.
2799 separate file, in an attempt to have a Windows GUI installer.
2775 That didn't work, but part of the groundwork is done.
2800 That didn't work, but part of the groundwork is done.
2776
2801
2777 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2802 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2778 indent/unindent with 4 spaces. Particularly useful in combination
2803 indent/unindent with 4 spaces. Particularly useful in combination
2779 with the new auto-indent option.
2804 with the new auto-indent option.
2780
2805
2781 2003-04-16 Fernando Perez <fperez@colorado.edu>
2806 2003-04-16 Fernando Perez <fperez@colorado.edu>
2782
2807
2783 * IPython/Magic.py: various replacements of self.rc for
2808 * IPython/Magic.py: various replacements of self.rc for
2784 self.shell.rc. A lot more remains to be done to fully disentangle
2809 self.shell.rc. A lot more remains to be done to fully disentangle
2785 this class from the main Shell class.
2810 this class from the main Shell class.
2786
2811
2787 * IPython/GnuplotRuntime.py: added checks for mouse support so
2812 * IPython/GnuplotRuntime.py: added checks for mouse support so
2788 that we don't try to enable it if the current gnuplot doesn't
2813 that we don't try to enable it if the current gnuplot doesn't
2789 really support it. Also added checks so that we don't try to
2814 really support it. Also added checks so that we don't try to
2790 enable persist under Windows (where Gnuplot doesn't recognize the
2815 enable persist under Windows (where Gnuplot doesn't recognize the
2791 option).
2816 option).
2792
2817
2793 * IPython/iplib.py (InteractiveShell.interact): Added optional
2818 * IPython/iplib.py (InteractiveShell.interact): Added optional
2794 auto-indenting code, after a patch by King C. Shu
2819 auto-indenting code, after a patch by King C. Shu
2795 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2820 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2796 get along well with pasting indented code. If I ever figure out
2821 get along well with pasting indented code. If I ever figure out
2797 how to make that part go well, it will become on by default.
2822 how to make that part go well, it will become on by default.
2798
2823
2799 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2824 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2800 crash ipython if there was an unmatched '%' in the user's prompt
2825 crash ipython if there was an unmatched '%' in the user's prompt
2801 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2826 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2802
2827
2803 * IPython/iplib.py (InteractiveShell.interact): removed the
2828 * IPython/iplib.py (InteractiveShell.interact): removed the
2804 ability to ask the user whether he wants to crash or not at the
2829 ability to ask the user whether he wants to crash or not at the
2805 'last line' exception handler. Calling functions at that point
2830 'last line' exception handler. Calling functions at that point
2806 changes the stack, and the error reports would have incorrect
2831 changes the stack, and the error reports would have incorrect
2807 tracebacks.
2832 tracebacks.
2808
2833
2809 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2834 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2810 pass through a peger a pretty-printed form of any object. After a
2835 pass through a peger a pretty-printed form of any object. After a
2811 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2836 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2812
2837
2813 2003-04-14 Fernando Perez <fperez@colorado.edu>
2838 2003-04-14 Fernando Perez <fperez@colorado.edu>
2814
2839
2815 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2840 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2816 all files in ~ would be modified at first install (instead of
2841 all files in ~ would be modified at first install (instead of
2817 ~/.ipython). This could be potentially disastrous, as the
2842 ~/.ipython). This could be potentially disastrous, as the
2818 modification (make line-endings native) could damage binary files.
2843 modification (make line-endings native) could damage binary files.
2819
2844
2820 2003-04-10 Fernando Perez <fperez@colorado.edu>
2845 2003-04-10 Fernando Perez <fperez@colorado.edu>
2821
2846
2822 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2847 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2823 handle only lines which are invalid python. This now means that
2848 handle only lines which are invalid python. This now means that
2824 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2849 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2825 for the bug report.
2850 for the bug report.
2826
2851
2827 2003-04-01 Fernando Perez <fperez@colorado.edu>
2852 2003-04-01 Fernando Perez <fperez@colorado.edu>
2828
2853
2829 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2854 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2830 where failing to set sys.last_traceback would crash pdb.pm().
2855 where failing to set sys.last_traceback would crash pdb.pm().
2831 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2856 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2832 report.
2857 report.
2833
2858
2834 2003-03-25 Fernando Perez <fperez@colorado.edu>
2859 2003-03-25 Fernando Perez <fperez@colorado.edu>
2835
2860
2836 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2861 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2837 before printing it (it had a lot of spurious blank lines at the
2862 before printing it (it had a lot of spurious blank lines at the
2838 end).
2863 end).
2839
2864
2840 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2865 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2841 output would be sent 21 times! Obviously people don't use this
2866 output would be sent 21 times! Obviously people don't use this
2842 too often, or I would have heard about it.
2867 too often, or I would have heard about it.
2843
2868
2844 2003-03-24 Fernando Perez <fperez@colorado.edu>
2869 2003-03-24 Fernando Perez <fperez@colorado.edu>
2845
2870
2846 * setup.py (scriptfiles): renamed the data_files parameter from
2871 * setup.py (scriptfiles): renamed the data_files parameter from
2847 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2872 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2848 for the patch.
2873 for the patch.
2849
2874
2850 2003-03-20 Fernando Perez <fperez@colorado.edu>
2875 2003-03-20 Fernando Perez <fperez@colorado.edu>
2851
2876
2852 * IPython/genutils.py (error): added error() and fatal()
2877 * IPython/genutils.py (error): added error() and fatal()
2853 functions.
2878 functions.
2854
2879
2855 2003-03-18 *** Released version 0.2.15pre3
2880 2003-03-18 *** Released version 0.2.15pre3
2856
2881
2857 2003-03-18 Fernando Perez <fperez@colorado.edu>
2882 2003-03-18 Fernando Perez <fperez@colorado.edu>
2858
2883
2859 * setupext/install_data_ext.py
2884 * setupext/install_data_ext.py
2860 (install_data_ext.initialize_options): Class contributed by Jack
2885 (install_data_ext.initialize_options): Class contributed by Jack
2861 Moffit for fixing the old distutils hack. He is sending this to
2886 Moffit for fixing the old distutils hack. He is sending this to
2862 the distutils folks so in the future we may not need it as a
2887 the distutils folks so in the future we may not need it as a
2863 private fix.
2888 private fix.
2864
2889
2865 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2890 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2866 changes for Debian packaging. See his patch for full details.
2891 changes for Debian packaging. See his patch for full details.
2867 The old distutils hack of making the ipythonrc* files carry a
2892 The old distutils hack of making the ipythonrc* files carry a
2868 bogus .py extension is gone, at last. Examples were moved to a
2893 bogus .py extension is gone, at last. Examples were moved to a
2869 separate subdir under doc/, and the separate executable scripts
2894 separate subdir under doc/, and the separate executable scripts
2870 now live in their own directory. Overall a great cleanup. The
2895 now live in their own directory. Overall a great cleanup. The
2871 manual was updated to use the new files, and setup.py has been
2896 manual was updated to use the new files, and setup.py has been
2872 fixed for this setup.
2897 fixed for this setup.
2873
2898
2874 * IPython/PyColorize.py (Parser.usage): made non-executable and
2899 * IPython/PyColorize.py (Parser.usage): made non-executable and
2875 created a pycolor wrapper around it to be included as a script.
2900 created a pycolor wrapper around it to be included as a script.
2876
2901
2877 2003-03-12 *** Released version 0.2.15pre2
2902 2003-03-12 *** Released version 0.2.15pre2
2878
2903
2879 2003-03-12 Fernando Perez <fperez@colorado.edu>
2904 2003-03-12 Fernando Perez <fperez@colorado.edu>
2880
2905
2881 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2906 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2882 long-standing problem with garbage characters in some terminals.
2907 long-standing problem with garbage characters in some terminals.
2883 The issue was really that the \001 and \002 escapes must _only_ be
2908 The issue was really that the \001 and \002 escapes must _only_ be
2884 passed to input prompts (which call readline), but _never_ to
2909 passed to input prompts (which call readline), but _never_ to
2885 normal text to be printed on screen. I changed ColorANSI to have
2910 normal text to be printed on screen. I changed ColorANSI to have
2886 two classes: TermColors and InputTermColors, each with the
2911 two classes: TermColors and InputTermColors, each with the
2887 appropriate escapes for input prompts or normal text. The code in
2912 appropriate escapes for input prompts or normal text. The code in
2888 Prompts.py got slightly more complicated, but this very old and
2913 Prompts.py got slightly more complicated, but this very old and
2889 annoying bug is finally fixed.
2914 annoying bug is finally fixed.
2890
2915
2891 All the credit for nailing down the real origin of this problem
2916 All the credit for nailing down the real origin of this problem
2892 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2917 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2893 *Many* thanks to him for spending quite a bit of effort on this.
2918 *Many* thanks to him for spending quite a bit of effort on this.
2894
2919
2895 2003-03-05 *** Released version 0.2.15pre1
2920 2003-03-05 *** Released version 0.2.15pre1
2896
2921
2897 2003-03-03 Fernando Perez <fperez@colorado.edu>
2922 2003-03-03 Fernando Perez <fperez@colorado.edu>
2898
2923
2899 * IPython/FakeModule.py: Moved the former _FakeModule to a
2924 * IPython/FakeModule.py: Moved the former _FakeModule to a
2900 separate file, because it's also needed by Magic (to fix a similar
2925 separate file, because it's also needed by Magic (to fix a similar
2901 pickle-related issue in @run).
2926 pickle-related issue in @run).
2902
2927
2903 2003-03-02 Fernando Perez <fperez@colorado.edu>
2928 2003-03-02 Fernando Perez <fperez@colorado.edu>
2904
2929
2905 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2930 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2906 the autocall option at runtime.
2931 the autocall option at runtime.
2907 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2932 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2908 across Magic.py to start separating Magic from InteractiveShell.
2933 across Magic.py to start separating Magic from InteractiveShell.
2909 (Magic._ofind): Fixed to return proper namespace for dotted
2934 (Magic._ofind): Fixed to return proper namespace for dotted
2910 names. Before, a dotted name would always return 'not currently
2935 names. Before, a dotted name would always return 'not currently
2911 defined', because it would find the 'parent'. s.x would be found,
2936 defined', because it would find the 'parent'. s.x would be found,
2912 but since 'x' isn't defined by itself, it would get confused.
2937 but since 'x' isn't defined by itself, it would get confused.
2913 (Magic.magic_run): Fixed pickling problems reported by Ralf
2938 (Magic.magic_run): Fixed pickling problems reported by Ralf
2914 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2939 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2915 that I'd used when Mike Heeter reported similar issues at the
2940 that I'd used when Mike Heeter reported similar issues at the
2916 top-level, but now for @run. It boils down to injecting the
2941 top-level, but now for @run. It boils down to injecting the
2917 namespace where code is being executed with something that looks
2942 namespace where code is being executed with something that looks
2918 enough like a module to fool pickle.dump(). Since a pickle stores
2943 enough like a module to fool pickle.dump(). Since a pickle stores
2919 a named reference to the importing module, we need this for
2944 a named reference to the importing module, we need this for
2920 pickles to save something sensible.
2945 pickles to save something sensible.
2921
2946
2922 * IPython/ipmaker.py (make_IPython): added an autocall option.
2947 * IPython/ipmaker.py (make_IPython): added an autocall option.
2923
2948
2924 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2949 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2925 the auto-eval code. Now autocalling is an option, and the code is
2950 the auto-eval code. Now autocalling is an option, and the code is
2926 also vastly safer. There is no more eval() involved at all.
2951 also vastly safer. There is no more eval() involved at all.
2927
2952
2928 2003-03-01 Fernando Perez <fperez@colorado.edu>
2953 2003-03-01 Fernando Perez <fperez@colorado.edu>
2929
2954
2930 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2955 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2931 dict with named keys instead of a tuple.
2956 dict with named keys instead of a tuple.
2932
2957
2933 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2958 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2934
2959
2935 * setup.py (make_shortcut): Fixed message about directories
2960 * setup.py (make_shortcut): Fixed message about directories
2936 created during Windows installation (the directories were ok, just
2961 created during Windows installation (the directories were ok, just
2937 the printed message was misleading). Thanks to Chris Liechti
2962 the printed message was misleading). Thanks to Chris Liechti
2938 <cliechti-AT-gmx.net> for the heads up.
2963 <cliechti-AT-gmx.net> for the heads up.
2939
2964
2940 2003-02-21 Fernando Perez <fperez@colorado.edu>
2965 2003-02-21 Fernando Perez <fperez@colorado.edu>
2941
2966
2942 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2967 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2943 of ValueError exception when checking for auto-execution. This
2968 of ValueError exception when checking for auto-execution. This
2944 one is raised by things like Numeric arrays arr.flat when the
2969 one is raised by things like Numeric arrays arr.flat when the
2945 array is non-contiguous.
2970 array is non-contiguous.
2946
2971
2947 2003-01-31 Fernando Perez <fperez@colorado.edu>
2972 2003-01-31 Fernando Perez <fperez@colorado.edu>
2948
2973
2949 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2974 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2950 not return any value at all (even though the command would get
2975 not return any value at all (even though the command would get
2951 executed).
2976 executed).
2952 (xsys): Flush stdout right after printing the command to ensure
2977 (xsys): Flush stdout right after printing the command to ensure
2953 proper ordering of commands and command output in the total
2978 proper ordering of commands and command output in the total
2954 output.
2979 output.
2955 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2980 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2956 system/getoutput as defaults. The old ones are kept for
2981 system/getoutput as defaults. The old ones are kept for
2957 compatibility reasons, so no code which uses this library needs
2982 compatibility reasons, so no code which uses this library needs
2958 changing.
2983 changing.
2959
2984
2960 2003-01-27 *** Released version 0.2.14
2985 2003-01-27 *** Released version 0.2.14
2961
2986
2962 2003-01-25 Fernando Perez <fperez@colorado.edu>
2987 2003-01-25 Fernando Perez <fperez@colorado.edu>
2963
2988
2964 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2989 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2965 functions defined in previous edit sessions could not be re-edited
2990 functions defined in previous edit sessions could not be re-edited
2966 (because the temp files were immediately removed). Now temp files
2991 (because the temp files were immediately removed). Now temp files
2967 are removed only at IPython's exit.
2992 are removed only at IPython's exit.
2968 (Magic.magic_run): Improved @run to perform shell-like expansions
2993 (Magic.magic_run): Improved @run to perform shell-like expansions
2969 on its arguments (~users and $VARS). With this, @run becomes more
2994 on its arguments (~users and $VARS). With this, @run becomes more
2970 like a normal command-line.
2995 like a normal command-line.
2971
2996
2972 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2997 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2973 bugs related to embedding and cleaned up that code. A fairly
2998 bugs related to embedding and cleaned up that code. A fairly
2974 important one was the impossibility to access the global namespace
2999 important one was the impossibility to access the global namespace
2975 through the embedded IPython (only local variables were visible).
3000 through the embedded IPython (only local variables were visible).
2976
3001
2977 2003-01-14 Fernando Perez <fperez@colorado.edu>
3002 2003-01-14 Fernando Perez <fperez@colorado.edu>
2978
3003
2979 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3004 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2980 auto-calling to be a bit more conservative. Now it doesn't get
3005 auto-calling to be a bit more conservative. Now it doesn't get
2981 triggered if any of '!=()<>' are in the rest of the input line, to
3006 triggered if any of '!=()<>' are in the rest of the input line, to
2982 allow comparing callables. Thanks to Alex for the heads up.
3007 allow comparing callables. Thanks to Alex for the heads up.
2983
3008
2984 2003-01-07 Fernando Perez <fperez@colorado.edu>
3009 2003-01-07 Fernando Perez <fperez@colorado.edu>
2985
3010
2986 * IPython/genutils.py (page): fixed estimation of the number of
3011 * IPython/genutils.py (page): fixed estimation of the number of
2987 lines in a string to be paged to simply count newlines. This
3012 lines in a string to be paged to simply count newlines. This
2988 prevents over-guessing due to embedded escape sequences. A better
3013 prevents over-guessing due to embedded escape sequences. A better
2989 long-term solution would involve stripping out the control chars
3014 long-term solution would involve stripping out the control chars
2990 for the count, but it's potentially so expensive I just don't
3015 for the count, but it's potentially so expensive I just don't
2991 think it's worth doing.
3016 think it's worth doing.
2992
3017
2993 2002-12-19 *** Released version 0.2.14pre50
3018 2002-12-19 *** Released version 0.2.14pre50
2994
3019
2995 2002-12-19 Fernando Perez <fperez@colorado.edu>
3020 2002-12-19 Fernando Perez <fperez@colorado.edu>
2996
3021
2997 * tools/release (version): Changed release scripts to inform
3022 * tools/release (version): Changed release scripts to inform
2998 Andrea and build a NEWS file with a list of recent changes.
3023 Andrea and build a NEWS file with a list of recent changes.
2999
3024
3000 * IPython/ColorANSI.py (__all__): changed terminal detection
3025 * IPython/ColorANSI.py (__all__): changed terminal detection
3001 code. Seems to work better for xterms without breaking
3026 code. Seems to work better for xterms without breaking
3002 konsole. Will need more testing to determine if WinXP and Mac OSX
3027 konsole. Will need more testing to determine if WinXP and Mac OSX
3003 also work ok.
3028 also work ok.
3004
3029
3005 2002-12-18 *** Released version 0.2.14pre49
3030 2002-12-18 *** Released version 0.2.14pre49
3006
3031
3007 2002-12-18 Fernando Perez <fperez@colorado.edu>
3032 2002-12-18 Fernando Perez <fperez@colorado.edu>
3008
3033
3009 * Docs: added new info about Mac OSX, from Andrea.
3034 * Docs: added new info about Mac OSX, from Andrea.
3010
3035
3011 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3036 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3012 allow direct plotting of python strings whose format is the same
3037 allow direct plotting of python strings whose format is the same
3013 of gnuplot data files.
3038 of gnuplot data files.
3014
3039
3015 2002-12-16 Fernando Perez <fperez@colorado.edu>
3040 2002-12-16 Fernando Perez <fperez@colorado.edu>
3016
3041
3017 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3042 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3018 value of exit question to be acknowledged.
3043 value of exit question to be acknowledged.
3019
3044
3020 2002-12-03 Fernando Perez <fperez@colorado.edu>
3045 2002-12-03 Fernando Perez <fperez@colorado.edu>
3021
3046
3022 * IPython/ipmaker.py: removed generators, which had been added
3047 * IPython/ipmaker.py: removed generators, which had been added
3023 by mistake in an earlier debugging run. This was causing trouble
3048 by mistake in an earlier debugging run. This was causing trouble
3024 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3049 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3025 for pointing this out.
3050 for pointing this out.
3026
3051
3027 2002-11-17 Fernando Perez <fperez@colorado.edu>
3052 2002-11-17 Fernando Perez <fperez@colorado.edu>
3028
3053
3029 * Manual: updated the Gnuplot section.
3054 * Manual: updated the Gnuplot section.
3030
3055
3031 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3056 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3032 a much better split of what goes in Runtime and what goes in
3057 a much better split of what goes in Runtime and what goes in
3033 Interactive.
3058 Interactive.
3034
3059
3035 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3060 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3036 being imported from iplib.
3061 being imported from iplib.
3037
3062
3038 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3063 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3039 for command-passing. Now the global Gnuplot instance is called
3064 for command-passing. Now the global Gnuplot instance is called
3040 'gp' instead of 'g', which was really a far too fragile and
3065 'gp' instead of 'g', which was really a far too fragile and
3041 common name.
3066 common name.
3042
3067
3043 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3068 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3044 bounding boxes generated by Gnuplot for square plots.
3069 bounding boxes generated by Gnuplot for square plots.
3045
3070
3046 * IPython/genutils.py (popkey): new function added. I should
3071 * IPython/genutils.py (popkey): new function added. I should
3047 suggest this on c.l.py as a dict method, it seems useful.
3072 suggest this on c.l.py as a dict method, it seems useful.
3048
3073
3049 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3074 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3050 to transparently handle PostScript generation. MUCH better than
3075 to transparently handle PostScript generation. MUCH better than
3051 the previous plot_eps/replot_eps (which I removed now). The code
3076 the previous plot_eps/replot_eps (which I removed now). The code
3052 is also fairly clean and well documented now (including
3077 is also fairly clean and well documented now (including
3053 docstrings).
3078 docstrings).
3054
3079
3055 2002-11-13 Fernando Perez <fperez@colorado.edu>
3080 2002-11-13 Fernando Perez <fperez@colorado.edu>
3056
3081
3057 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3082 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3058 (inconsistent with options).
3083 (inconsistent with options).
3059
3084
3060 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3085 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3061 manually disabled, I don't know why. Fixed it.
3086 manually disabled, I don't know why. Fixed it.
3062 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3087 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3063 eps output.
3088 eps output.
3064
3089
3065 2002-11-12 Fernando Perez <fperez@colorado.edu>
3090 2002-11-12 Fernando Perez <fperez@colorado.edu>
3066
3091
3067 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3092 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3068 don't propagate up to caller. Fixes crash reported by François
3093 don't propagate up to caller. Fixes crash reported by François
3069 Pinard.
3094 Pinard.
3070
3095
3071 2002-11-09 Fernando Perez <fperez@colorado.edu>
3096 2002-11-09 Fernando Perez <fperez@colorado.edu>
3072
3097
3073 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3098 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3074 history file for new users.
3099 history file for new users.
3075 (make_IPython): fixed bug where initial install would leave the
3100 (make_IPython): fixed bug where initial install would leave the
3076 user running in the .ipython dir.
3101 user running in the .ipython dir.
3077 (make_IPython): fixed bug where config dir .ipython would be
3102 (make_IPython): fixed bug where config dir .ipython would be
3078 created regardless of the given -ipythondir option. Thanks to Cory
3103 created regardless of the given -ipythondir option. Thanks to Cory
3079 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3104 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3080
3105
3081 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3106 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3082 type confirmations. Will need to use it in all of IPython's code
3107 type confirmations. Will need to use it in all of IPython's code
3083 consistently.
3108 consistently.
3084
3109
3085 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3110 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3086 context to print 31 lines instead of the default 5. This will make
3111 context to print 31 lines instead of the default 5. This will make
3087 the crash reports extremely detailed in case the problem is in
3112 the crash reports extremely detailed in case the problem is in
3088 libraries I don't have access to.
3113 libraries I don't have access to.
3089
3114
3090 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3115 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3091 line of defense' code to still crash, but giving users fair
3116 line of defense' code to still crash, but giving users fair
3092 warning. I don't want internal errors to go unreported: if there's
3117 warning. I don't want internal errors to go unreported: if there's
3093 an internal problem, IPython should crash and generate a full
3118 an internal problem, IPython should crash and generate a full
3094 report.
3119 report.
3095
3120
3096 2002-11-08 Fernando Perez <fperez@colorado.edu>
3121 2002-11-08 Fernando Perez <fperez@colorado.edu>
3097
3122
3098 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3123 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3099 otherwise uncaught exceptions which can appear if people set
3124 otherwise uncaught exceptions which can appear if people set
3100 sys.stdout to something badly broken. Thanks to a crash report
3125 sys.stdout to something badly broken. Thanks to a crash report
3101 from henni-AT-mail.brainbot.com.
3126 from henni-AT-mail.brainbot.com.
3102
3127
3103 2002-11-04 Fernando Perez <fperez@colorado.edu>
3128 2002-11-04 Fernando Perez <fperez@colorado.edu>
3104
3129
3105 * IPython/iplib.py (InteractiveShell.interact): added
3130 * IPython/iplib.py (InteractiveShell.interact): added
3106 __IPYTHON__active to the builtins. It's a flag which goes on when
3131 __IPYTHON__active to the builtins. It's a flag which goes on when
3107 the interaction starts and goes off again when it stops. This
3132 the interaction starts and goes off again when it stops. This
3108 allows embedding code to detect being inside IPython. Before this
3133 allows embedding code to detect being inside IPython. Before this
3109 was done via __IPYTHON__, but that only shows that an IPython
3134 was done via __IPYTHON__, but that only shows that an IPython
3110 instance has been created.
3135 instance has been created.
3111
3136
3112 * IPython/Magic.py (Magic.magic_env): I realized that in a
3137 * IPython/Magic.py (Magic.magic_env): I realized that in a
3113 UserDict, instance.data holds the data as a normal dict. So I
3138 UserDict, instance.data holds the data as a normal dict. So I
3114 modified @env to return os.environ.data instead of rebuilding a
3139 modified @env to return os.environ.data instead of rebuilding a
3115 dict by hand.
3140 dict by hand.
3116
3141
3117 2002-11-02 Fernando Perez <fperez@colorado.edu>
3142 2002-11-02 Fernando Perez <fperez@colorado.edu>
3118
3143
3119 * IPython/genutils.py (warn): changed so that level 1 prints no
3144 * IPython/genutils.py (warn): changed so that level 1 prints no
3120 header. Level 2 is now the default (with 'WARNING' header, as
3145 header. Level 2 is now the default (with 'WARNING' header, as
3121 before). I think I tracked all places where changes were needed in
3146 before). I think I tracked all places where changes were needed in
3122 IPython, but outside code using the old level numbering may have
3147 IPython, but outside code using the old level numbering may have
3123 broken.
3148 broken.
3124
3149
3125 * IPython/iplib.py (InteractiveShell.runcode): added this to
3150 * IPython/iplib.py (InteractiveShell.runcode): added this to
3126 handle the tracebacks in SystemExit traps correctly. The previous
3151 handle the tracebacks in SystemExit traps correctly. The previous
3127 code (through interact) was printing more of the stack than
3152 code (through interact) was printing more of the stack than
3128 necessary, showing IPython internal code to the user.
3153 necessary, showing IPython internal code to the user.
3129
3154
3130 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3155 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3131 default. Now that the default at the confirmation prompt is yes,
3156 default. Now that the default at the confirmation prompt is yes,
3132 it's not so intrusive. François' argument that ipython sessions
3157 it's not so intrusive. François' argument that ipython sessions
3133 tend to be complex enough not to lose them from an accidental C-d,
3158 tend to be complex enough not to lose them from an accidental C-d,
3134 is a valid one.
3159 is a valid one.
3135
3160
3136 * IPython/iplib.py (InteractiveShell.interact): added a
3161 * IPython/iplib.py (InteractiveShell.interact): added a
3137 showtraceback() call to the SystemExit trap, and modified the exit
3162 showtraceback() call to the SystemExit trap, and modified the exit
3138 confirmation to have yes as the default.
3163 confirmation to have yes as the default.
3139
3164
3140 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3165 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3141 this file. It's been gone from the code for a long time, this was
3166 this file. It's been gone from the code for a long time, this was
3142 simply leftover junk.
3167 simply leftover junk.
3143
3168
3144 2002-11-01 Fernando Perez <fperez@colorado.edu>
3169 2002-11-01 Fernando Perez <fperez@colorado.edu>
3145
3170
3146 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3171 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3147 added. If set, IPython now traps EOF and asks for
3172 added. If set, IPython now traps EOF and asks for
3148 confirmation. After a request by François Pinard.
3173 confirmation. After a request by François Pinard.
3149
3174
3150 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3175 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3151 of @abort, and with a new (better) mechanism for handling the
3176 of @abort, and with a new (better) mechanism for handling the
3152 exceptions.
3177 exceptions.
3153
3178
3154 2002-10-27 Fernando Perez <fperez@colorado.edu>
3179 2002-10-27 Fernando Perez <fperez@colorado.edu>
3155
3180
3156 * IPython/usage.py (__doc__): updated the --help information and
3181 * IPython/usage.py (__doc__): updated the --help information and
3157 the ipythonrc file to indicate that -log generates
3182 the ipythonrc file to indicate that -log generates
3158 ./ipython.log. Also fixed the corresponding info in @logstart.
3183 ./ipython.log. Also fixed the corresponding info in @logstart.
3159 This and several other fixes in the manuals thanks to reports by
3184 This and several other fixes in the manuals thanks to reports by
3160 François Pinard <pinard-AT-iro.umontreal.ca>.
3185 François Pinard <pinard-AT-iro.umontreal.ca>.
3161
3186
3162 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3187 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3163 refer to @logstart (instead of @log, which doesn't exist).
3188 refer to @logstart (instead of @log, which doesn't exist).
3164
3189
3165 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3190 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3166 AttributeError crash. Thanks to Christopher Armstrong
3191 AttributeError crash. Thanks to Christopher Armstrong
3167 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3192 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3168 introduced recently (in 0.2.14pre37) with the fix to the eval
3193 introduced recently (in 0.2.14pre37) with the fix to the eval
3169 problem mentioned below.
3194 problem mentioned below.
3170
3195
3171 2002-10-17 Fernando Perez <fperez@colorado.edu>
3196 2002-10-17 Fernando Perez <fperez@colorado.edu>
3172
3197
3173 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3198 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3174 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3199 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3175
3200
3176 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3201 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3177 this function to fix a problem reported by Alex Schmolck. He saw
3202 this function to fix a problem reported by Alex Schmolck. He saw
3178 it with list comprehensions and generators, which were getting
3203 it with list comprehensions and generators, which were getting
3179 called twice. The real problem was an 'eval' call in testing for
3204 called twice. The real problem was an 'eval' call in testing for
3180 automagic which was evaluating the input line silently.
3205 automagic which was evaluating the input line silently.
3181
3206
3182 This is a potentially very nasty bug, if the input has side
3207 This is a potentially very nasty bug, if the input has side
3183 effects which must not be repeated. The code is much cleaner now,
3208 effects which must not be repeated. The code is much cleaner now,
3184 without any blanket 'except' left and with a regexp test for
3209 without any blanket 'except' left and with a regexp test for
3185 actual function names.
3210 actual function names.
3186
3211
3187 But an eval remains, which I'm not fully comfortable with. I just
3212 But an eval remains, which I'm not fully comfortable with. I just
3188 don't know how to find out if an expression could be a callable in
3213 don't know how to find out if an expression could be a callable in
3189 the user's namespace without doing an eval on the string. However
3214 the user's namespace without doing an eval on the string. However
3190 that string is now much more strictly checked so that no code
3215 that string is now much more strictly checked so that no code
3191 slips by, so the eval should only happen for things that can
3216 slips by, so the eval should only happen for things that can
3192 really be only function/method names.
3217 really be only function/method names.
3193
3218
3194 2002-10-15 Fernando Perez <fperez@colorado.edu>
3219 2002-10-15 Fernando Perez <fperez@colorado.edu>
3195
3220
3196 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3221 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3197 OSX information to main manual, removed README_Mac_OSX file from
3222 OSX information to main manual, removed README_Mac_OSX file from
3198 distribution. Also updated credits for recent additions.
3223 distribution. Also updated credits for recent additions.
3199
3224
3200 2002-10-10 Fernando Perez <fperez@colorado.edu>
3225 2002-10-10 Fernando Perez <fperez@colorado.edu>
3201
3226
3202 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3227 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3203 terminal-related issues. Many thanks to Andrea Riciputi
3228 terminal-related issues. Many thanks to Andrea Riciputi
3204 <andrea.riciputi-AT-libero.it> for writing it.
3229 <andrea.riciputi-AT-libero.it> for writing it.
3205
3230
3206 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3231 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3207 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3232 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3208
3233
3209 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3234 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3210 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3235 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3211 <syver-en-AT-online.no> who both submitted patches for this problem.
3236 <syver-en-AT-online.no> who both submitted patches for this problem.
3212
3237
3213 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3238 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3214 global embedding to make sure that things don't overwrite user
3239 global embedding to make sure that things don't overwrite user
3215 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3240 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3216
3241
3217 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3242 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3218 compatibility. Thanks to Hayden Callow
3243 compatibility. Thanks to Hayden Callow
3219 <h.callow-AT-elec.canterbury.ac.nz>
3244 <h.callow-AT-elec.canterbury.ac.nz>
3220
3245
3221 2002-10-04 Fernando Perez <fperez@colorado.edu>
3246 2002-10-04 Fernando Perez <fperez@colorado.edu>
3222
3247
3223 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3248 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3224 Gnuplot.File objects.
3249 Gnuplot.File objects.
3225
3250
3226 2002-07-23 Fernando Perez <fperez@colorado.edu>
3251 2002-07-23 Fernando Perez <fperez@colorado.edu>
3227
3252
3228 * IPython/genutils.py (timing): Added timings() and timing() for
3253 * IPython/genutils.py (timing): Added timings() and timing() for
3229 quick access to the most commonly needed data, the execution
3254 quick access to the most commonly needed data, the execution
3230 times. Old timing() renamed to timings_out().
3255 times. Old timing() renamed to timings_out().
3231
3256
3232 2002-07-18 Fernando Perez <fperez@colorado.edu>
3257 2002-07-18 Fernando Perez <fperez@colorado.edu>
3233
3258
3234 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3259 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3235 bug with nested instances disrupting the parent's tab completion.
3260 bug with nested instances disrupting the parent's tab completion.
3236
3261
3237 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3262 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3238 all_completions code to begin the emacs integration.
3263 all_completions code to begin the emacs integration.
3239
3264
3240 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3265 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3241 argument to allow titling individual arrays when plotting.
3266 argument to allow titling individual arrays when plotting.
3242
3267
3243 2002-07-15 Fernando Perez <fperez@colorado.edu>
3268 2002-07-15 Fernando Perez <fperez@colorado.edu>
3244
3269
3245 * setup.py (make_shortcut): changed to retrieve the value of
3270 * setup.py (make_shortcut): changed to retrieve the value of
3246 'Program Files' directory from the registry (this value changes in
3271 'Program Files' directory from the registry (this value changes in
3247 non-english versions of Windows). Thanks to Thomas Fanslau
3272 non-english versions of Windows). Thanks to Thomas Fanslau
3248 <tfanslau-AT-gmx.de> for the report.
3273 <tfanslau-AT-gmx.de> for the report.
3249
3274
3250 2002-07-10 Fernando Perez <fperez@colorado.edu>
3275 2002-07-10 Fernando Perez <fperez@colorado.edu>
3251
3276
3252 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3277 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3253 a bug in pdb, which crashes if a line with only whitespace is
3278 a bug in pdb, which crashes if a line with only whitespace is
3254 entered. Bug report submitted to sourceforge.
3279 entered. Bug report submitted to sourceforge.
3255
3280
3256 2002-07-09 Fernando Perez <fperez@colorado.edu>
3281 2002-07-09 Fernando Perez <fperez@colorado.edu>
3257
3282
3258 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3283 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3259 reporting exceptions (it's a bug in inspect.py, I just set a
3284 reporting exceptions (it's a bug in inspect.py, I just set a
3260 workaround).
3285 workaround).
3261
3286
3262 2002-07-08 Fernando Perez <fperez@colorado.edu>
3287 2002-07-08 Fernando Perez <fperez@colorado.edu>
3263
3288
3264 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3289 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3265 __IPYTHON__ in __builtins__ to show up in user_ns.
3290 __IPYTHON__ in __builtins__ to show up in user_ns.
3266
3291
3267 2002-07-03 Fernando Perez <fperez@colorado.edu>
3292 2002-07-03 Fernando Perez <fperez@colorado.edu>
3268
3293
3269 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3294 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3270 name from @gp_set_instance to @gp_set_default.
3295 name from @gp_set_instance to @gp_set_default.
3271
3296
3272 * IPython/ipmaker.py (make_IPython): default editor value set to
3297 * IPython/ipmaker.py (make_IPython): default editor value set to
3273 '0' (a string), to match the rc file. Otherwise will crash when
3298 '0' (a string), to match the rc file. Otherwise will crash when
3274 .strip() is called on it.
3299 .strip() is called on it.
3275
3300
3276
3301
3277 2002-06-28 Fernando Perez <fperez@colorado.edu>
3302 2002-06-28 Fernando Perez <fperez@colorado.edu>
3278
3303
3279 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3304 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3280 of files in current directory when a file is executed via
3305 of files in current directory when a file is executed via
3281 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3306 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3282
3307
3283 * setup.py (manfiles): fix for rpm builds, submitted by RA
3308 * setup.py (manfiles): fix for rpm builds, submitted by RA
3284 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3309 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3285
3310
3286 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3311 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3287 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3312 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3288 string!). A. Schmolck caught this one.
3313 string!). A. Schmolck caught this one.
3289
3314
3290 2002-06-27 Fernando Perez <fperez@colorado.edu>
3315 2002-06-27 Fernando Perez <fperez@colorado.edu>
3291
3316
3292 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3317 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3293 defined files at the cmd line. __name__ wasn't being set to
3318 defined files at the cmd line. __name__ wasn't being set to
3294 __main__.
3319 __main__.
3295
3320
3296 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3321 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3297 regular lists and tuples besides Numeric arrays.
3322 regular lists and tuples besides Numeric arrays.
3298
3323
3299 * IPython/Prompts.py (CachedOutput.__call__): Added output
3324 * IPython/Prompts.py (CachedOutput.__call__): Added output
3300 supression for input ending with ';'. Similar to Mathematica and
3325 supression for input ending with ';'. Similar to Mathematica and
3301 Matlab. The _* vars and Out[] list are still updated, just like
3326 Matlab. The _* vars and Out[] list are still updated, just like
3302 Mathematica behaves.
3327 Mathematica behaves.
3303
3328
3304 2002-06-25 Fernando Perez <fperez@colorado.edu>
3329 2002-06-25 Fernando Perez <fperez@colorado.edu>
3305
3330
3306 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3331 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3307 .ini extensions for profiels under Windows.
3332 .ini extensions for profiels under Windows.
3308
3333
3309 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3334 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3310 string form. Fix contributed by Alexander Schmolck
3335 string form. Fix contributed by Alexander Schmolck
3311 <a.schmolck-AT-gmx.net>
3336 <a.schmolck-AT-gmx.net>
3312
3337
3313 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3338 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3314 pre-configured Gnuplot instance.
3339 pre-configured Gnuplot instance.
3315
3340
3316 2002-06-21 Fernando Perez <fperez@colorado.edu>
3341 2002-06-21 Fernando Perez <fperez@colorado.edu>
3317
3342
3318 * IPython/numutils.py (exp_safe): new function, works around the
3343 * IPython/numutils.py (exp_safe): new function, works around the
3319 underflow problems in Numeric.
3344 underflow problems in Numeric.
3320 (log2): New fn. Safe log in base 2: returns exact integer answer
3345 (log2): New fn. Safe log in base 2: returns exact integer answer
3321 for exact integer powers of 2.
3346 for exact integer powers of 2.
3322
3347
3323 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3348 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3324 properly.
3349 properly.
3325
3350
3326 2002-06-20 Fernando Perez <fperez@colorado.edu>
3351 2002-06-20 Fernando Perez <fperez@colorado.edu>
3327
3352
3328 * IPython/genutils.py (timing): new function like
3353 * IPython/genutils.py (timing): new function like
3329 Mathematica's. Similar to time_test, but returns more info.
3354 Mathematica's. Similar to time_test, but returns more info.
3330
3355
3331 2002-06-18 Fernando Perez <fperez@colorado.edu>
3356 2002-06-18 Fernando Perez <fperez@colorado.edu>
3332
3357
3333 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3358 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3334 according to Mike Heeter's suggestions.
3359 according to Mike Heeter's suggestions.
3335
3360
3336 2002-06-16 Fernando Perez <fperez@colorado.edu>
3361 2002-06-16 Fernando Perez <fperez@colorado.edu>
3337
3362
3338 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3363 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3339 system. GnuplotMagic is gone as a user-directory option. New files
3364 system. GnuplotMagic is gone as a user-directory option. New files
3340 make it easier to use all the gnuplot stuff both from external
3365 make it easier to use all the gnuplot stuff both from external
3341 programs as well as from IPython. Had to rewrite part of
3366 programs as well as from IPython. Had to rewrite part of
3342 hardcopy() b/c of a strange bug: often the ps files simply don't
3367 hardcopy() b/c of a strange bug: often the ps files simply don't
3343 get created, and require a repeat of the command (often several
3368 get created, and require a repeat of the command (often several
3344 times).
3369 times).
3345
3370
3346 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3371 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3347 resolve output channel at call time, so that if sys.stderr has
3372 resolve output channel at call time, so that if sys.stderr has
3348 been redirected by user this gets honored.
3373 been redirected by user this gets honored.
3349
3374
3350 2002-06-13 Fernando Perez <fperez@colorado.edu>
3375 2002-06-13 Fernando Perez <fperez@colorado.edu>
3351
3376
3352 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3377 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3353 IPShell. Kept a copy with the old names to avoid breaking people's
3378 IPShell. Kept a copy with the old names to avoid breaking people's
3354 embedded code.
3379 embedded code.
3355
3380
3356 * IPython/ipython: simplified it to the bare minimum after
3381 * IPython/ipython: simplified it to the bare minimum after
3357 Holger's suggestions. Added info about how to use it in
3382 Holger's suggestions. Added info about how to use it in
3358 PYTHONSTARTUP.
3383 PYTHONSTARTUP.
3359
3384
3360 * IPython/Shell.py (IPythonShell): changed the options passing
3385 * IPython/Shell.py (IPythonShell): changed the options passing
3361 from a string with funky %s replacements to a straight list. Maybe
3386 from a string with funky %s replacements to a straight list. Maybe
3362 a bit more typing, but it follows sys.argv conventions, so there's
3387 a bit more typing, but it follows sys.argv conventions, so there's
3363 less special-casing to remember.
3388 less special-casing to remember.
3364
3389
3365 2002-06-12 Fernando Perez <fperez@colorado.edu>
3390 2002-06-12 Fernando Perez <fperez@colorado.edu>
3366
3391
3367 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3392 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3368 command. Thanks to a suggestion by Mike Heeter.
3393 command. Thanks to a suggestion by Mike Heeter.
3369 (Magic.magic_pfile): added behavior to look at filenames if given
3394 (Magic.magic_pfile): added behavior to look at filenames if given
3370 arg is not a defined object.
3395 arg is not a defined object.
3371 (Magic.magic_save): New @save function to save code snippets. Also
3396 (Magic.magic_save): New @save function to save code snippets. Also
3372 a Mike Heeter idea.
3397 a Mike Heeter idea.
3373
3398
3374 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3399 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3375 plot() and replot(). Much more convenient now, especially for
3400 plot() and replot(). Much more convenient now, especially for
3376 interactive use.
3401 interactive use.
3377
3402
3378 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3403 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3379 filenames.
3404 filenames.
3380
3405
3381 2002-06-02 Fernando Perez <fperez@colorado.edu>
3406 2002-06-02 Fernando Perez <fperez@colorado.edu>
3382
3407
3383 * IPython/Struct.py (Struct.__init__): modified to admit
3408 * IPython/Struct.py (Struct.__init__): modified to admit
3384 initialization via another struct.
3409 initialization via another struct.
3385
3410
3386 * IPython/genutils.py (SystemExec.__init__): New stateful
3411 * IPython/genutils.py (SystemExec.__init__): New stateful
3387 interface to xsys and bq. Useful for writing system scripts.
3412 interface to xsys and bq. Useful for writing system scripts.
3388
3413
3389 2002-05-30 Fernando Perez <fperez@colorado.edu>
3414 2002-05-30 Fernando Perez <fperez@colorado.edu>
3390
3415
3391 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3416 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3392 documents. This will make the user download smaller (it's getting
3417 documents. This will make the user download smaller (it's getting
3393 too big).
3418 too big).
3394
3419
3395 2002-05-29 Fernando Perez <fperez@colorado.edu>
3420 2002-05-29 Fernando Perez <fperez@colorado.edu>
3396
3421
3397 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3422 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3398 fix problems with shelve and pickle. Seems to work, but I don't
3423 fix problems with shelve and pickle. Seems to work, but I don't
3399 know if corner cases break it. Thanks to Mike Heeter
3424 know if corner cases break it. Thanks to Mike Heeter
3400 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3425 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3401
3426
3402 2002-05-24 Fernando Perez <fperez@colorado.edu>
3427 2002-05-24 Fernando Perez <fperez@colorado.edu>
3403
3428
3404 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3429 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3405 macros having broken.
3430 macros having broken.
3406
3431
3407 2002-05-21 Fernando Perez <fperez@colorado.edu>
3432 2002-05-21 Fernando Perez <fperez@colorado.edu>
3408
3433
3409 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3434 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3410 introduced logging bug: all history before logging started was
3435 introduced logging bug: all history before logging started was
3411 being written one character per line! This came from the redesign
3436 being written one character per line! This came from the redesign
3412 of the input history as a special list which slices to strings,
3437 of the input history as a special list which slices to strings,
3413 not to lists.
3438 not to lists.
3414
3439
3415 2002-05-20 Fernando Perez <fperez@colorado.edu>
3440 2002-05-20 Fernando Perez <fperez@colorado.edu>
3416
3441
3417 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3442 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3418 be an attribute of all classes in this module. The design of these
3443 be an attribute of all classes in this module. The design of these
3419 classes needs some serious overhauling.
3444 classes needs some serious overhauling.
3420
3445
3421 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3446 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3422 which was ignoring '_' in option names.
3447 which was ignoring '_' in option names.
3423
3448
3424 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3449 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3425 'Verbose_novars' to 'Context' and made it the new default. It's a
3450 'Verbose_novars' to 'Context' and made it the new default. It's a
3426 bit more readable and also safer than verbose.
3451 bit more readable and also safer than verbose.
3427
3452
3428 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3453 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3429 triple-quoted strings.
3454 triple-quoted strings.
3430
3455
3431 * IPython/OInspect.py (__all__): new module exposing the object
3456 * IPython/OInspect.py (__all__): new module exposing the object
3432 introspection facilities. Now the corresponding magics are dummy
3457 introspection facilities. Now the corresponding magics are dummy
3433 wrappers around this. Having this module will make it much easier
3458 wrappers around this. Having this module will make it much easier
3434 to put these functions into our modified pdb.
3459 to put these functions into our modified pdb.
3435 This new object inspector system uses the new colorizing module,
3460 This new object inspector system uses the new colorizing module,
3436 so source code and other things are nicely syntax highlighted.
3461 so source code and other things are nicely syntax highlighted.
3437
3462
3438 2002-05-18 Fernando Perez <fperez@colorado.edu>
3463 2002-05-18 Fernando Perez <fperez@colorado.edu>
3439
3464
3440 * IPython/ColorANSI.py: Split the coloring tools into a separate
3465 * IPython/ColorANSI.py: Split the coloring tools into a separate
3441 module so I can use them in other code easier (they were part of
3466 module so I can use them in other code easier (they were part of
3442 ultraTB).
3467 ultraTB).
3443
3468
3444 2002-05-17 Fernando Perez <fperez@colorado.edu>
3469 2002-05-17 Fernando Perez <fperez@colorado.edu>
3445
3470
3446 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3471 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3447 fixed it to set the global 'g' also to the called instance, as
3472 fixed it to set the global 'g' also to the called instance, as
3448 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3473 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3449 user's 'g' variables).
3474 user's 'g' variables).
3450
3475
3451 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3476 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3452 global variables (aliases to _ih,_oh) so that users which expect
3477 global variables (aliases to _ih,_oh) so that users which expect
3453 In[5] or Out[7] to work aren't unpleasantly surprised.
3478 In[5] or Out[7] to work aren't unpleasantly surprised.
3454 (InputList.__getslice__): new class to allow executing slices of
3479 (InputList.__getslice__): new class to allow executing slices of
3455 input history directly. Very simple class, complements the use of
3480 input history directly. Very simple class, complements the use of
3456 macros.
3481 macros.
3457
3482
3458 2002-05-16 Fernando Perez <fperez@colorado.edu>
3483 2002-05-16 Fernando Perez <fperez@colorado.edu>
3459
3484
3460 * setup.py (docdirbase): make doc directory be just doc/IPython
3485 * setup.py (docdirbase): make doc directory be just doc/IPython
3461 without version numbers, it will reduce clutter for users.
3486 without version numbers, it will reduce clutter for users.
3462
3487
3463 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3488 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3464 execfile call to prevent possible memory leak. See for details:
3489 execfile call to prevent possible memory leak. See for details:
3465 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3490 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3466
3491
3467 2002-05-15 Fernando Perez <fperez@colorado.edu>
3492 2002-05-15 Fernando Perez <fperez@colorado.edu>
3468
3493
3469 * IPython/Magic.py (Magic.magic_psource): made the object
3494 * IPython/Magic.py (Magic.magic_psource): made the object
3470 introspection names be more standard: pdoc, pdef, pfile and
3495 introspection names be more standard: pdoc, pdef, pfile and
3471 psource. They all print/page their output, and it makes
3496 psource. They all print/page their output, and it makes
3472 remembering them easier. Kept old names for compatibility as
3497 remembering them easier. Kept old names for compatibility as
3473 aliases.
3498 aliases.
3474
3499
3475 2002-05-14 Fernando Perez <fperez@colorado.edu>
3500 2002-05-14 Fernando Perez <fperez@colorado.edu>
3476
3501
3477 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3502 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3478 what the mouse problem was. The trick is to use gnuplot with temp
3503 what the mouse problem was. The trick is to use gnuplot with temp
3479 files and NOT with pipes (for data communication), because having
3504 files and NOT with pipes (for data communication), because having
3480 both pipes and the mouse on is bad news.
3505 both pipes and the mouse on is bad news.
3481
3506
3482 2002-05-13 Fernando Perez <fperez@colorado.edu>
3507 2002-05-13 Fernando Perez <fperez@colorado.edu>
3483
3508
3484 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3509 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3485 bug. Information would be reported about builtins even when
3510 bug. Information would be reported about builtins even when
3486 user-defined functions overrode them.
3511 user-defined functions overrode them.
3487
3512
3488 2002-05-11 Fernando Perez <fperez@colorado.edu>
3513 2002-05-11 Fernando Perez <fperez@colorado.edu>
3489
3514
3490 * IPython/__init__.py (__all__): removed FlexCompleter from
3515 * IPython/__init__.py (__all__): removed FlexCompleter from
3491 __all__ so that things don't fail in platforms without readline.
3516 __all__ so that things don't fail in platforms without readline.
3492
3517
3493 2002-05-10 Fernando Perez <fperez@colorado.edu>
3518 2002-05-10 Fernando Perez <fperez@colorado.edu>
3494
3519
3495 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3520 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3496 it requires Numeric, effectively making Numeric a dependency for
3521 it requires Numeric, effectively making Numeric a dependency for
3497 IPython.
3522 IPython.
3498
3523
3499 * Released 0.2.13
3524 * Released 0.2.13
3500
3525
3501 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3526 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3502 profiler interface. Now all the major options from the profiler
3527 profiler interface. Now all the major options from the profiler
3503 module are directly supported in IPython, both for single
3528 module are directly supported in IPython, both for single
3504 expressions (@prun) and for full programs (@run -p).
3529 expressions (@prun) and for full programs (@run -p).
3505
3530
3506 2002-05-09 Fernando Perez <fperez@colorado.edu>
3531 2002-05-09 Fernando Perez <fperez@colorado.edu>
3507
3532
3508 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3533 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3509 magic properly formatted for screen.
3534 magic properly formatted for screen.
3510
3535
3511 * setup.py (make_shortcut): Changed things to put pdf version in
3536 * setup.py (make_shortcut): Changed things to put pdf version in
3512 doc/ instead of doc/manual (had to change lyxport a bit).
3537 doc/ instead of doc/manual (had to change lyxport a bit).
3513
3538
3514 * IPython/Magic.py (Profile.string_stats): made profile runs go
3539 * IPython/Magic.py (Profile.string_stats): made profile runs go
3515 through pager (they are long and a pager allows searching, saving,
3540 through pager (they are long and a pager allows searching, saving,
3516 etc.)
3541 etc.)
3517
3542
3518 2002-05-08 Fernando Perez <fperez@colorado.edu>
3543 2002-05-08 Fernando Perez <fperez@colorado.edu>
3519
3544
3520 * Released 0.2.12
3545 * Released 0.2.12
3521
3546
3522 2002-05-06 Fernando Perez <fperez@colorado.edu>
3547 2002-05-06 Fernando Perez <fperez@colorado.edu>
3523
3548
3524 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3549 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3525 introduced); 'hist n1 n2' was broken.
3550 introduced); 'hist n1 n2' was broken.
3526 (Magic.magic_pdb): added optional on/off arguments to @pdb
3551 (Magic.magic_pdb): added optional on/off arguments to @pdb
3527 (Magic.magic_run): added option -i to @run, which executes code in
3552 (Magic.magic_run): added option -i to @run, which executes code in
3528 the IPython namespace instead of a clean one. Also added @irun as
3553 the IPython namespace instead of a clean one. Also added @irun as
3529 an alias to @run -i.
3554 an alias to @run -i.
3530
3555
3531 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3556 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3532 fixed (it didn't really do anything, the namespaces were wrong).
3557 fixed (it didn't really do anything, the namespaces were wrong).
3533
3558
3534 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3559 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3535
3560
3536 * IPython/__init__.py (__all__): Fixed package namespace, now
3561 * IPython/__init__.py (__all__): Fixed package namespace, now
3537 'import IPython' does give access to IPython.<all> as
3562 'import IPython' does give access to IPython.<all> as
3538 expected. Also renamed __release__ to Release.
3563 expected. Also renamed __release__ to Release.
3539
3564
3540 * IPython/Debugger.py (__license__): created new Pdb class which
3565 * IPython/Debugger.py (__license__): created new Pdb class which
3541 functions like a drop-in for the normal pdb.Pdb but does NOT
3566 functions like a drop-in for the normal pdb.Pdb but does NOT
3542 import readline by default. This way it doesn't muck up IPython's
3567 import readline by default. This way it doesn't muck up IPython's
3543 readline handling, and now tab-completion finally works in the
3568 readline handling, and now tab-completion finally works in the
3544 debugger -- sort of. It completes things globally visible, but the
3569 debugger -- sort of. It completes things globally visible, but the
3545 completer doesn't track the stack as pdb walks it. That's a bit
3570 completer doesn't track the stack as pdb walks it. That's a bit
3546 tricky, and I'll have to implement it later.
3571 tricky, and I'll have to implement it later.
3547
3572
3548 2002-05-05 Fernando Perez <fperez@colorado.edu>
3573 2002-05-05 Fernando Perez <fperez@colorado.edu>
3549
3574
3550 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3575 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3551 magic docstrings when printed via ? (explicit \'s were being
3576 magic docstrings when printed via ? (explicit \'s were being
3552 printed).
3577 printed).
3553
3578
3554 * IPython/ipmaker.py (make_IPython): fixed namespace
3579 * IPython/ipmaker.py (make_IPython): fixed namespace
3555 identification bug. Now variables loaded via logs or command-line
3580 identification bug. Now variables loaded via logs or command-line
3556 files are recognized in the interactive namespace by @who.
3581 files are recognized in the interactive namespace by @who.
3557
3582
3558 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3583 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3559 log replay system stemming from the string form of Structs.
3584 log replay system stemming from the string form of Structs.
3560
3585
3561 * IPython/Magic.py (Macro.__init__): improved macros to properly
3586 * IPython/Magic.py (Macro.__init__): improved macros to properly
3562 handle magic commands in them.
3587 handle magic commands in them.
3563 (Magic.magic_logstart): usernames are now expanded so 'logstart
3588 (Magic.magic_logstart): usernames are now expanded so 'logstart
3564 ~/mylog' now works.
3589 ~/mylog' now works.
3565
3590
3566 * IPython/iplib.py (complete): fixed bug where paths starting with
3591 * IPython/iplib.py (complete): fixed bug where paths starting with
3567 '/' would be completed as magic names.
3592 '/' would be completed as magic names.
3568
3593
3569 2002-05-04 Fernando Perez <fperez@colorado.edu>
3594 2002-05-04 Fernando Perez <fperez@colorado.edu>
3570
3595
3571 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3596 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3572 allow running full programs under the profiler's control.
3597 allow running full programs under the profiler's control.
3573
3598
3574 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3599 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3575 mode to report exceptions verbosely but without formatting
3600 mode to report exceptions verbosely but without formatting
3576 variables. This addresses the issue of ipython 'freezing' (it's
3601 variables. This addresses the issue of ipython 'freezing' (it's
3577 not frozen, but caught in an expensive formatting loop) when huge
3602 not frozen, but caught in an expensive formatting loop) when huge
3578 variables are in the context of an exception.
3603 variables are in the context of an exception.
3579 (VerboseTB.text): Added '--->' markers at line where exception was
3604 (VerboseTB.text): Added '--->' markers at line where exception was
3580 triggered. Much clearer to read, especially in NoColor modes.
3605 triggered. Much clearer to read, especially in NoColor modes.
3581
3606
3582 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3607 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3583 implemented in reverse when changing to the new parse_options().
3608 implemented in reverse when changing to the new parse_options().
3584
3609
3585 2002-05-03 Fernando Perez <fperez@colorado.edu>
3610 2002-05-03 Fernando Perez <fperez@colorado.edu>
3586
3611
3587 * IPython/Magic.py (Magic.parse_options): new function so that
3612 * IPython/Magic.py (Magic.parse_options): new function so that
3588 magics can parse options easier.
3613 magics can parse options easier.
3589 (Magic.magic_prun): new function similar to profile.run(),
3614 (Magic.magic_prun): new function similar to profile.run(),
3590 suggested by Chris Hart.
3615 suggested by Chris Hart.
3591 (Magic.magic_cd): fixed behavior so that it only changes if
3616 (Magic.magic_cd): fixed behavior so that it only changes if
3592 directory actually is in history.
3617 directory actually is in history.
3593
3618
3594 * IPython/usage.py (__doc__): added information about potential
3619 * IPython/usage.py (__doc__): added information about potential
3595 slowness of Verbose exception mode when there are huge data
3620 slowness of Verbose exception mode when there are huge data
3596 structures to be formatted (thanks to Archie Paulson).
3621 structures to be formatted (thanks to Archie Paulson).
3597
3622
3598 * IPython/ipmaker.py (make_IPython): Changed default logging
3623 * IPython/ipmaker.py (make_IPython): Changed default logging
3599 (when simply called with -log) to use curr_dir/ipython.log in
3624 (when simply called with -log) to use curr_dir/ipython.log in
3600 rotate mode. Fixed crash which was occuring with -log before
3625 rotate mode. Fixed crash which was occuring with -log before
3601 (thanks to Jim Boyle).
3626 (thanks to Jim Boyle).
3602
3627
3603 2002-05-01 Fernando Perez <fperez@colorado.edu>
3628 2002-05-01 Fernando Perez <fperez@colorado.edu>
3604
3629
3605 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3630 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3606 was nasty -- though somewhat of a corner case).
3631 was nasty -- though somewhat of a corner case).
3607
3632
3608 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3633 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3609 text (was a bug).
3634 text (was a bug).
3610
3635
3611 2002-04-30 Fernando Perez <fperez@colorado.edu>
3636 2002-04-30 Fernando Perez <fperez@colorado.edu>
3612
3637
3613 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3638 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3614 a print after ^D or ^C from the user so that the In[] prompt
3639 a print after ^D or ^C from the user so that the In[] prompt
3615 doesn't over-run the gnuplot one.
3640 doesn't over-run the gnuplot one.
3616
3641
3617 2002-04-29 Fernando Perez <fperez@colorado.edu>
3642 2002-04-29 Fernando Perez <fperez@colorado.edu>
3618
3643
3619 * Released 0.2.10
3644 * Released 0.2.10
3620
3645
3621 * IPython/__release__.py (version): get date dynamically.
3646 * IPython/__release__.py (version): get date dynamically.
3622
3647
3623 * Misc. documentation updates thanks to Arnd's comments. Also ran
3648 * Misc. documentation updates thanks to Arnd's comments. Also ran
3624 a full spellcheck on the manual (hadn't been done in a while).
3649 a full spellcheck on the manual (hadn't been done in a while).
3625
3650
3626 2002-04-27 Fernando Perez <fperez@colorado.edu>
3651 2002-04-27 Fernando Perez <fperez@colorado.edu>
3627
3652
3628 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3653 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3629 starting a log in mid-session would reset the input history list.
3654 starting a log in mid-session would reset the input history list.
3630
3655
3631 2002-04-26 Fernando Perez <fperez@colorado.edu>
3656 2002-04-26 Fernando Perez <fperez@colorado.edu>
3632
3657
3633 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3658 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3634 all files were being included in an update. Now anything in
3659 all files were being included in an update. Now anything in
3635 UserConfig that matches [A-Za-z]*.py will go (this excludes
3660 UserConfig that matches [A-Za-z]*.py will go (this excludes
3636 __init__.py)
3661 __init__.py)
3637
3662
3638 2002-04-25 Fernando Perez <fperez@colorado.edu>
3663 2002-04-25 Fernando Perez <fperez@colorado.edu>
3639
3664
3640 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3665 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3641 to __builtins__ so that any form of embedded or imported code can
3666 to __builtins__ so that any form of embedded or imported code can
3642 test for being inside IPython.
3667 test for being inside IPython.
3643
3668
3644 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3669 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3645 changed to GnuplotMagic because it's now an importable module,
3670 changed to GnuplotMagic because it's now an importable module,
3646 this makes the name follow that of the standard Gnuplot module.
3671 this makes the name follow that of the standard Gnuplot module.
3647 GnuplotMagic can now be loaded at any time in mid-session.
3672 GnuplotMagic can now be loaded at any time in mid-session.
3648
3673
3649 2002-04-24 Fernando Perez <fperez@colorado.edu>
3674 2002-04-24 Fernando Perez <fperez@colorado.edu>
3650
3675
3651 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3676 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3652 the globals (IPython has its own namespace) and the
3677 the globals (IPython has its own namespace) and the
3653 PhysicalQuantity stuff is much better anyway.
3678 PhysicalQuantity stuff is much better anyway.
3654
3679
3655 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3680 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3656 embedding example to standard user directory for
3681 embedding example to standard user directory for
3657 distribution. Also put it in the manual.
3682 distribution. Also put it in the manual.
3658
3683
3659 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3684 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3660 instance as first argument (so it doesn't rely on some obscure
3685 instance as first argument (so it doesn't rely on some obscure
3661 hidden global).
3686 hidden global).
3662
3687
3663 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3688 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3664 delimiters. While it prevents ().TAB from working, it allows
3689 delimiters. While it prevents ().TAB from working, it allows
3665 completions in open (... expressions. This is by far a more common
3690 completions in open (... expressions. This is by far a more common
3666 case.
3691 case.
3667
3692
3668 2002-04-23 Fernando Perez <fperez@colorado.edu>
3693 2002-04-23 Fernando Perez <fperez@colorado.edu>
3669
3694
3670 * IPython/Extensions/InterpreterPasteInput.py: new
3695 * IPython/Extensions/InterpreterPasteInput.py: new
3671 syntax-processing module for pasting lines with >>> or ... at the
3696 syntax-processing module for pasting lines with >>> or ... at the
3672 start.
3697 start.
3673
3698
3674 * IPython/Extensions/PhysicalQ_Interactive.py
3699 * IPython/Extensions/PhysicalQ_Interactive.py
3675 (PhysicalQuantityInteractive.__int__): fixed to work with either
3700 (PhysicalQuantityInteractive.__int__): fixed to work with either
3676 Numeric or math.
3701 Numeric or math.
3677
3702
3678 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3703 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3679 provided profiles. Now we have:
3704 provided profiles. Now we have:
3680 -math -> math module as * and cmath with its own namespace.
3705 -math -> math module as * and cmath with its own namespace.
3681 -numeric -> Numeric as *, plus gnuplot & grace
3706 -numeric -> Numeric as *, plus gnuplot & grace
3682 -physics -> same as before
3707 -physics -> same as before
3683
3708
3684 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3709 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3685 user-defined magics wouldn't be found by @magic if they were
3710 user-defined magics wouldn't be found by @magic if they were
3686 defined as class methods. Also cleaned up the namespace search
3711 defined as class methods. Also cleaned up the namespace search
3687 logic and the string building (to use %s instead of many repeated
3712 logic and the string building (to use %s instead of many repeated
3688 string adds).
3713 string adds).
3689
3714
3690 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3715 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3691 of user-defined magics to operate with class methods (cleaner, in
3716 of user-defined magics to operate with class methods (cleaner, in
3692 line with the gnuplot code).
3717 line with the gnuplot code).
3693
3718
3694 2002-04-22 Fernando Perez <fperez@colorado.edu>
3719 2002-04-22 Fernando Perez <fperez@colorado.edu>
3695
3720
3696 * setup.py: updated dependency list so that manual is updated when
3721 * setup.py: updated dependency list so that manual is updated when
3697 all included files change.
3722 all included files change.
3698
3723
3699 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3724 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3700 the delimiter removal option (the fix is ugly right now).
3725 the delimiter removal option (the fix is ugly right now).
3701
3726
3702 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3727 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3703 all of the math profile (quicker loading, no conflict between
3728 all of the math profile (quicker loading, no conflict between
3704 g-9.8 and g-gnuplot).
3729 g-9.8 and g-gnuplot).
3705
3730
3706 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3731 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3707 name of post-mortem files to IPython_crash_report.txt.
3732 name of post-mortem files to IPython_crash_report.txt.
3708
3733
3709 * Cleanup/update of the docs. Added all the new readline info and
3734 * Cleanup/update of the docs. Added all the new readline info and
3710 formatted all lists as 'real lists'.
3735 formatted all lists as 'real lists'.
3711
3736
3712 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3737 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3713 tab-completion options, since the full readline parse_and_bind is
3738 tab-completion options, since the full readline parse_and_bind is
3714 now accessible.
3739 now accessible.
3715
3740
3716 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3741 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3717 handling of readline options. Now users can specify any string to
3742 handling of readline options. Now users can specify any string to
3718 be passed to parse_and_bind(), as well as the delimiters to be
3743 be passed to parse_and_bind(), as well as the delimiters to be
3719 removed.
3744 removed.
3720 (InteractiveShell.__init__): Added __name__ to the global
3745 (InteractiveShell.__init__): Added __name__ to the global
3721 namespace so that things like Itpl which rely on its existence
3746 namespace so that things like Itpl which rely on its existence
3722 don't crash.
3747 don't crash.
3723 (InteractiveShell._prefilter): Defined the default with a _ so
3748 (InteractiveShell._prefilter): Defined the default with a _ so
3724 that prefilter() is easier to override, while the default one
3749 that prefilter() is easier to override, while the default one
3725 remains available.
3750 remains available.
3726
3751
3727 2002-04-18 Fernando Perez <fperez@colorado.edu>
3752 2002-04-18 Fernando Perez <fperez@colorado.edu>
3728
3753
3729 * Added information about pdb in the docs.
3754 * Added information about pdb in the docs.
3730
3755
3731 2002-04-17 Fernando Perez <fperez@colorado.edu>
3756 2002-04-17 Fernando Perez <fperez@colorado.edu>
3732
3757
3733 * IPython/ipmaker.py (make_IPython): added rc_override option to
3758 * IPython/ipmaker.py (make_IPython): added rc_override option to
3734 allow passing config options at creation time which may override
3759 allow passing config options at creation time which may override
3735 anything set in the config files or command line. This is
3760 anything set in the config files or command line. This is
3736 particularly useful for configuring embedded instances.
3761 particularly useful for configuring embedded instances.
3737
3762
3738 2002-04-15 Fernando Perez <fperez@colorado.edu>
3763 2002-04-15 Fernando Perez <fperez@colorado.edu>
3739
3764
3740 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3765 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3741 crash embedded instances because of the input cache falling out of
3766 crash embedded instances because of the input cache falling out of
3742 sync with the output counter.
3767 sync with the output counter.
3743
3768
3744 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3769 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3745 mode which calls pdb after an uncaught exception in IPython itself.
3770 mode which calls pdb after an uncaught exception in IPython itself.
3746
3771
3747 2002-04-14 Fernando Perez <fperez@colorado.edu>
3772 2002-04-14 Fernando Perez <fperez@colorado.edu>
3748
3773
3749 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3774 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3750 readline, fix it back after each call.
3775 readline, fix it back after each call.
3751
3776
3752 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3777 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3753 method to force all access via __call__(), which guarantees that
3778 method to force all access via __call__(), which guarantees that
3754 traceback references are properly deleted.
3779 traceback references are properly deleted.
3755
3780
3756 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3781 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3757 improve printing when pprint is in use.
3782 improve printing when pprint is in use.
3758
3783
3759 2002-04-13 Fernando Perez <fperez@colorado.edu>
3784 2002-04-13 Fernando Perez <fperez@colorado.edu>
3760
3785
3761 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3786 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3762 exceptions aren't caught anymore. If the user triggers one, he
3787 exceptions aren't caught anymore. If the user triggers one, he
3763 should know why he's doing it and it should go all the way up,
3788 should know why he's doing it and it should go all the way up,
3764 just like any other exception. So now @abort will fully kill the
3789 just like any other exception. So now @abort will fully kill the
3765 embedded interpreter and the embedding code (unless that happens
3790 embedded interpreter and the embedding code (unless that happens
3766 to catch SystemExit).
3791 to catch SystemExit).
3767
3792
3768 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3793 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3769 and a debugger() method to invoke the interactive pdb debugger
3794 and a debugger() method to invoke the interactive pdb debugger
3770 after printing exception information. Also added the corresponding
3795 after printing exception information. Also added the corresponding
3771 -pdb option and @pdb magic to control this feature, and updated
3796 -pdb option and @pdb magic to control this feature, and updated
3772 the docs. After a suggestion from Christopher Hart
3797 the docs. After a suggestion from Christopher Hart
3773 (hart-AT-caltech.edu).
3798 (hart-AT-caltech.edu).
3774
3799
3775 2002-04-12 Fernando Perez <fperez@colorado.edu>
3800 2002-04-12 Fernando Perez <fperez@colorado.edu>
3776
3801
3777 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3802 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3778 the exception handlers defined by the user (not the CrashHandler)
3803 the exception handlers defined by the user (not the CrashHandler)
3779 so that user exceptions don't trigger an ipython bug report.
3804 so that user exceptions don't trigger an ipython bug report.
3780
3805
3781 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3806 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3782 configurable (it should have always been so).
3807 configurable (it should have always been so).
3783
3808
3784 2002-03-26 Fernando Perez <fperez@colorado.edu>
3809 2002-03-26 Fernando Perez <fperez@colorado.edu>
3785
3810
3786 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3811 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3787 and there to fix embedding namespace issues. This should all be
3812 and there to fix embedding namespace issues. This should all be
3788 done in a more elegant way.
3813 done in a more elegant way.
3789
3814
3790 2002-03-25 Fernando Perez <fperez@colorado.edu>
3815 2002-03-25 Fernando Perez <fperez@colorado.edu>
3791
3816
3792 * IPython/genutils.py (get_home_dir): Try to make it work under
3817 * IPython/genutils.py (get_home_dir): Try to make it work under
3793 win9x also.
3818 win9x also.
3794
3819
3795 2002-03-20 Fernando Perez <fperez@colorado.edu>
3820 2002-03-20 Fernando Perez <fperez@colorado.edu>
3796
3821
3797 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3822 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3798 sys.displayhook untouched upon __init__.
3823 sys.displayhook untouched upon __init__.
3799
3824
3800 2002-03-19 Fernando Perez <fperez@colorado.edu>
3825 2002-03-19 Fernando Perez <fperez@colorado.edu>
3801
3826
3802 * Released 0.2.9 (for embedding bug, basically).
3827 * Released 0.2.9 (for embedding bug, basically).
3803
3828
3804 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3829 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3805 exceptions so that enclosing shell's state can be restored.
3830 exceptions so that enclosing shell's state can be restored.
3806
3831
3807 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3832 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3808 naming conventions in the .ipython/ dir.
3833 naming conventions in the .ipython/ dir.
3809
3834
3810 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3835 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3811 from delimiters list so filenames with - in them get expanded.
3836 from delimiters list so filenames with - in them get expanded.
3812
3837
3813 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3838 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3814 sys.displayhook not being properly restored after an embedded call.
3839 sys.displayhook not being properly restored after an embedded call.
3815
3840
3816 2002-03-18 Fernando Perez <fperez@colorado.edu>
3841 2002-03-18 Fernando Perez <fperez@colorado.edu>
3817
3842
3818 * Released 0.2.8
3843 * Released 0.2.8
3819
3844
3820 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3845 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3821 some files weren't being included in a -upgrade.
3846 some files weren't being included in a -upgrade.
3822 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3847 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3823 on' so that the first tab completes.
3848 on' so that the first tab completes.
3824 (InteractiveShell.handle_magic): fixed bug with spaces around
3849 (InteractiveShell.handle_magic): fixed bug with spaces around
3825 quotes breaking many magic commands.
3850 quotes breaking many magic commands.
3826
3851
3827 * setup.py: added note about ignoring the syntax error messages at
3852 * setup.py: added note about ignoring the syntax error messages at
3828 installation.
3853 installation.
3829
3854
3830 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3855 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3831 streamlining the gnuplot interface, now there's only one magic @gp.
3856 streamlining the gnuplot interface, now there's only one magic @gp.
3832
3857
3833 2002-03-17 Fernando Perez <fperez@colorado.edu>
3858 2002-03-17 Fernando Perez <fperez@colorado.edu>
3834
3859
3835 * IPython/UserConfig/magic_gnuplot.py: new name for the
3860 * IPython/UserConfig/magic_gnuplot.py: new name for the
3836 example-magic_pm.py file. Much enhanced system, now with a shell
3861 example-magic_pm.py file. Much enhanced system, now with a shell
3837 for communicating directly with gnuplot, one command at a time.
3862 for communicating directly with gnuplot, one command at a time.
3838
3863
3839 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3864 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3840 setting __name__=='__main__'.
3865 setting __name__=='__main__'.
3841
3866
3842 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3867 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3843 mini-shell for accessing gnuplot from inside ipython. Should
3868 mini-shell for accessing gnuplot from inside ipython. Should
3844 extend it later for grace access too. Inspired by Arnd's
3869 extend it later for grace access too. Inspired by Arnd's
3845 suggestion.
3870 suggestion.
3846
3871
3847 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3872 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3848 calling magic functions with () in their arguments. Thanks to Arnd
3873 calling magic functions with () in their arguments. Thanks to Arnd
3849 Baecker for pointing this to me.
3874 Baecker for pointing this to me.
3850
3875
3851 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3876 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3852 infinitely for integer or complex arrays (only worked with floats).
3877 infinitely for integer or complex arrays (only worked with floats).
3853
3878
3854 2002-03-16 Fernando Perez <fperez@colorado.edu>
3879 2002-03-16 Fernando Perez <fperez@colorado.edu>
3855
3880
3856 * setup.py: Merged setup and setup_windows into a single script
3881 * setup.py: Merged setup and setup_windows into a single script
3857 which properly handles things for windows users.
3882 which properly handles things for windows users.
3858
3883
3859 2002-03-15 Fernando Perez <fperez@colorado.edu>
3884 2002-03-15 Fernando Perez <fperez@colorado.edu>
3860
3885
3861 * Big change to the manual: now the magics are all automatically
3886 * Big change to the manual: now the magics are all automatically
3862 documented. This information is generated from their docstrings
3887 documented. This information is generated from their docstrings
3863 and put in a latex file included by the manual lyx file. This way
3888 and put in a latex file included by the manual lyx file. This way
3864 we get always up to date information for the magics. The manual
3889 we get always up to date information for the magics. The manual
3865 now also has proper version information, also auto-synced.
3890 now also has proper version information, also auto-synced.
3866
3891
3867 For this to work, an undocumented --magic_docstrings option was added.
3892 For this to work, an undocumented --magic_docstrings option was added.
3868
3893
3869 2002-03-13 Fernando Perez <fperez@colorado.edu>
3894 2002-03-13 Fernando Perez <fperez@colorado.edu>
3870
3895
3871 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3896 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3872 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3897 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3873
3898
3874 2002-03-12 Fernando Perez <fperez@colorado.edu>
3899 2002-03-12 Fernando Perez <fperez@colorado.edu>
3875
3900
3876 * IPython/ultraTB.py (TermColors): changed color escapes again to
3901 * IPython/ultraTB.py (TermColors): changed color escapes again to
3877 fix the (old, reintroduced) line-wrapping bug. Basically, if
3902 fix the (old, reintroduced) line-wrapping bug. Basically, if
3878 \001..\002 aren't given in the color escapes, lines get wrapped
3903 \001..\002 aren't given in the color escapes, lines get wrapped
3879 weirdly. But giving those screws up old xterms and emacs terms. So
3904 weirdly. But giving those screws up old xterms and emacs terms. So
3880 I added some logic for emacs terms to be ok, but I can't identify old
3905 I added some logic for emacs terms to be ok, but I can't identify old
3881 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3906 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3882
3907
3883 2002-03-10 Fernando Perez <fperez@colorado.edu>
3908 2002-03-10 Fernando Perez <fperez@colorado.edu>
3884
3909
3885 * IPython/usage.py (__doc__): Various documentation cleanups and
3910 * IPython/usage.py (__doc__): Various documentation cleanups and
3886 updates, both in usage docstrings and in the manual.
3911 updates, both in usage docstrings and in the manual.
3887
3912
3888 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3913 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3889 handling of caching. Set minimum acceptabe value for having a
3914 handling of caching. Set minimum acceptabe value for having a
3890 cache at 20 values.
3915 cache at 20 values.
3891
3916
3892 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3917 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3893 install_first_time function to a method, renamed it and added an
3918 install_first_time function to a method, renamed it and added an
3894 'upgrade' mode. Now people can update their config directory with
3919 'upgrade' mode. Now people can update their config directory with
3895 a simple command line switch (-upgrade, also new).
3920 a simple command line switch (-upgrade, also new).
3896
3921
3897 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3922 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3898 @file (convenient for automagic users under Python >= 2.2).
3923 @file (convenient for automagic users under Python >= 2.2).
3899 Removed @files (it seemed more like a plural than an abbrev. of
3924 Removed @files (it seemed more like a plural than an abbrev. of
3900 'file show').
3925 'file show').
3901
3926
3902 * IPython/iplib.py (install_first_time): Fixed crash if there were
3927 * IPython/iplib.py (install_first_time): Fixed crash if there were
3903 backup files ('~') in .ipython/ install directory.
3928 backup files ('~') in .ipython/ install directory.
3904
3929
3905 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3930 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3906 system. Things look fine, but these changes are fairly
3931 system. Things look fine, but these changes are fairly
3907 intrusive. Test them for a few days.
3932 intrusive. Test them for a few days.
3908
3933
3909 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3934 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3910 the prompts system. Now all in/out prompt strings are user
3935 the prompts system. Now all in/out prompt strings are user
3911 controllable. This is particularly useful for embedding, as one
3936 controllable. This is particularly useful for embedding, as one
3912 can tag embedded instances with particular prompts.
3937 can tag embedded instances with particular prompts.
3913
3938
3914 Also removed global use of sys.ps1/2, which now allows nested
3939 Also removed global use of sys.ps1/2, which now allows nested
3915 embeddings without any problems. Added command-line options for
3940 embeddings without any problems. Added command-line options for
3916 the prompt strings.
3941 the prompt strings.
3917
3942
3918 2002-03-08 Fernando Perez <fperez@colorado.edu>
3943 2002-03-08 Fernando Perez <fperez@colorado.edu>
3919
3944
3920 * IPython/UserConfig/example-embed-short.py (ipshell): added
3945 * IPython/UserConfig/example-embed-short.py (ipshell): added
3921 example file with the bare minimum code for embedding.
3946 example file with the bare minimum code for embedding.
3922
3947
3923 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3948 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3924 functionality for the embeddable shell to be activated/deactivated
3949 functionality for the embeddable shell to be activated/deactivated
3925 either globally or at each call.
3950 either globally or at each call.
3926
3951
3927 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3952 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3928 rewriting the prompt with '--->' for auto-inputs with proper
3953 rewriting the prompt with '--->' for auto-inputs with proper
3929 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3954 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3930 this is handled by the prompts class itself, as it should.
3955 this is handled by the prompts class itself, as it should.
3931
3956
3932 2002-03-05 Fernando Perez <fperez@colorado.edu>
3957 2002-03-05 Fernando Perez <fperez@colorado.edu>
3933
3958
3934 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3959 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3935 @logstart to avoid name clashes with the math log function.
3960 @logstart to avoid name clashes with the math log function.
3936
3961
3937 * Big updates to X/Emacs section of the manual.
3962 * Big updates to X/Emacs section of the manual.
3938
3963
3939 * Removed ipython_emacs. Milan explained to me how to pass
3964 * Removed ipython_emacs. Milan explained to me how to pass
3940 arguments to ipython through Emacs. Some day I'm going to end up
3965 arguments to ipython through Emacs. Some day I'm going to end up
3941 learning some lisp...
3966 learning some lisp...
3942
3967
3943 2002-03-04 Fernando Perez <fperez@colorado.edu>
3968 2002-03-04 Fernando Perez <fperez@colorado.edu>
3944
3969
3945 * IPython/ipython_emacs: Created script to be used as the
3970 * IPython/ipython_emacs: Created script to be used as the
3946 py-python-command Emacs variable so we can pass IPython
3971 py-python-command Emacs variable so we can pass IPython
3947 parameters. I can't figure out how to tell Emacs directly to pass
3972 parameters. I can't figure out how to tell Emacs directly to pass
3948 parameters to IPython, so a dummy shell script will do it.
3973 parameters to IPython, so a dummy shell script will do it.
3949
3974
3950 Other enhancements made for things to work better under Emacs'
3975 Other enhancements made for things to work better under Emacs'
3951 various types of terminals. Many thanks to Milan Zamazal
3976 various types of terminals. Many thanks to Milan Zamazal
3952 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3977 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3953
3978
3954 2002-03-01 Fernando Perez <fperez@colorado.edu>
3979 2002-03-01 Fernando Perez <fperez@colorado.edu>
3955
3980
3956 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3981 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3957 that loading of readline is now optional. This gives better
3982 that loading of readline is now optional. This gives better
3958 control to emacs users.
3983 control to emacs users.
3959
3984
3960 * IPython/ultraTB.py (__date__): Modified color escape sequences
3985 * IPython/ultraTB.py (__date__): Modified color escape sequences
3961 and now things work fine under xterm and in Emacs' term buffers
3986 and now things work fine under xterm and in Emacs' term buffers
3962 (though not shell ones). Well, in emacs you get colors, but all
3987 (though not shell ones). Well, in emacs you get colors, but all
3963 seem to be 'light' colors (no difference between dark and light
3988 seem to be 'light' colors (no difference between dark and light
3964 ones). But the garbage chars are gone, and also in xterms. It
3989 ones). But the garbage chars are gone, and also in xterms. It
3965 seems that now I'm using 'cleaner' ansi sequences.
3990 seems that now I'm using 'cleaner' ansi sequences.
3966
3991
3967 2002-02-21 Fernando Perez <fperez@colorado.edu>
3992 2002-02-21 Fernando Perez <fperez@colorado.edu>
3968
3993
3969 * Released 0.2.7 (mainly to publish the scoping fix).
3994 * Released 0.2.7 (mainly to publish the scoping fix).
3970
3995
3971 * IPython/Logger.py (Logger.logstate): added. A corresponding
3996 * IPython/Logger.py (Logger.logstate): added. A corresponding
3972 @logstate magic was created.
3997 @logstate magic was created.
3973
3998
3974 * IPython/Magic.py: fixed nested scoping problem under Python
3999 * IPython/Magic.py: fixed nested scoping problem under Python
3975 2.1.x (automagic wasn't working).
4000 2.1.x (automagic wasn't working).
3976
4001
3977 2002-02-20 Fernando Perez <fperez@colorado.edu>
4002 2002-02-20 Fernando Perez <fperez@colorado.edu>
3978
4003
3979 * Released 0.2.6.
4004 * Released 0.2.6.
3980
4005
3981 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4006 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3982 option so that logs can come out without any headers at all.
4007 option so that logs can come out without any headers at all.
3983
4008
3984 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4009 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3985 SciPy.
4010 SciPy.
3986
4011
3987 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4012 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3988 that embedded IPython calls don't require vars() to be explicitly
4013 that embedded IPython calls don't require vars() to be explicitly
3989 passed. Now they are extracted from the caller's frame (code
4014 passed. Now they are extracted from the caller's frame (code
3990 snatched from Eric Jones' weave). Added better documentation to
4015 snatched from Eric Jones' weave). Added better documentation to
3991 the section on embedding and the example file.
4016 the section on embedding and the example file.
3992
4017
3993 * IPython/genutils.py (page): Changed so that under emacs, it just
4018 * IPython/genutils.py (page): Changed so that under emacs, it just
3994 prints the string. You can then page up and down in the emacs
4019 prints the string. You can then page up and down in the emacs
3995 buffer itself. This is how the builtin help() works.
4020 buffer itself. This is how the builtin help() works.
3996
4021
3997 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4022 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3998 macro scoping: macros need to be executed in the user's namespace
4023 macro scoping: macros need to be executed in the user's namespace
3999 to work as if they had been typed by the user.
4024 to work as if they had been typed by the user.
4000
4025
4001 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4026 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4002 execute automatically (no need to type 'exec...'). They then
4027 execute automatically (no need to type 'exec...'). They then
4003 behave like 'true macros'. The printing system was also modified
4028 behave like 'true macros'. The printing system was also modified
4004 for this to work.
4029 for this to work.
4005
4030
4006 2002-02-19 Fernando Perez <fperez@colorado.edu>
4031 2002-02-19 Fernando Perez <fperez@colorado.edu>
4007
4032
4008 * IPython/genutils.py (page_file): new function for paging files
4033 * IPython/genutils.py (page_file): new function for paging files
4009 in an OS-independent way. Also necessary for file viewing to work
4034 in an OS-independent way. Also necessary for file viewing to work
4010 well inside Emacs buffers.
4035 well inside Emacs buffers.
4011 (page): Added checks for being in an emacs buffer.
4036 (page): Added checks for being in an emacs buffer.
4012 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4037 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4013 same bug in iplib.
4038 same bug in iplib.
4014
4039
4015 2002-02-18 Fernando Perez <fperez@colorado.edu>
4040 2002-02-18 Fernando Perez <fperez@colorado.edu>
4016
4041
4017 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4042 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4018 of readline so that IPython can work inside an Emacs buffer.
4043 of readline so that IPython can work inside an Emacs buffer.
4019
4044
4020 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4045 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4021 method signatures (they weren't really bugs, but it looks cleaner
4046 method signatures (they weren't really bugs, but it looks cleaner
4022 and keeps PyChecker happy).
4047 and keeps PyChecker happy).
4023
4048
4024 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4049 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4025 for implementing various user-defined hooks. Currently only
4050 for implementing various user-defined hooks. Currently only
4026 display is done.
4051 display is done.
4027
4052
4028 * IPython/Prompts.py (CachedOutput._display): changed display
4053 * IPython/Prompts.py (CachedOutput._display): changed display
4029 functions so that they can be dynamically changed by users easily.
4054 functions so that they can be dynamically changed by users easily.
4030
4055
4031 * IPython/Extensions/numeric_formats.py (num_display): added an
4056 * IPython/Extensions/numeric_formats.py (num_display): added an
4032 extension for printing NumPy arrays in flexible manners. It
4057 extension for printing NumPy arrays in flexible manners. It
4033 doesn't do anything yet, but all the structure is in
4058 doesn't do anything yet, but all the structure is in
4034 place. Ultimately the plan is to implement output format control
4059 place. Ultimately the plan is to implement output format control
4035 like in Octave.
4060 like in Octave.
4036
4061
4037 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4062 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4038 methods are found at run-time by all the automatic machinery.
4063 methods are found at run-time by all the automatic machinery.
4039
4064
4040 2002-02-17 Fernando Perez <fperez@colorado.edu>
4065 2002-02-17 Fernando Perez <fperez@colorado.edu>
4041
4066
4042 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4067 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4043 whole file a little.
4068 whole file a little.
4044
4069
4045 * ToDo: closed this document. Now there's a new_design.lyx
4070 * ToDo: closed this document. Now there's a new_design.lyx
4046 document for all new ideas. Added making a pdf of it for the
4071 document for all new ideas. Added making a pdf of it for the
4047 end-user distro.
4072 end-user distro.
4048
4073
4049 * IPython/Logger.py (Logger.switch_log): Created this to replace
4074 * IPython/Logger.py (Logger.switch_log): Created this to replace
4050 logon() and logoff(). It also fixes a nasty crash reported by
4075 logon() and logoff(). It also fixes a nasty crash reported by
4051 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4076 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4052
4077
4053 * IPython/iplib.py (complete): got auto-completion to work with
4078 * IPython/iplib.py (complete): got auto-completion to work with
4054 automagic (I had wanted this for a long time).
4079 automagic (I had wanted this for a long time).
4055
4080
4056 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4081 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4057 to @file, since file() is now a builtin and clashes with automagic
4082 to @file, since file() is now a builtin and clashes with automagic
4058 for @file.
4083 for @file.
4059
4084
4060 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4085 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4061 of this was previously in iplib, which had grown to more than 2000
4086 of this was previously in iplib, which had grown to more than 2000
4062 lines, way too long. No new functionality, but it makes managing
4087 lines, way too long. No new functionality, but it makes managing
4063 the code a bit easier.
4088 the code a bit easier.
4064
4089
4065 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4090 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4066 information to crash reports.
4091 information to crash reports.
4067
4092
4068 2002-02-12 Fernando Perez <fperez@colorado.edu>
4093 2002-02-12 Fernando Perez <fperez@colorado.edu>
4069
4094
4070 * Released 0.2.5.
4095 * Released 0.2.5.
4071
4096
4072 2002-02-11 Fernando Perez <fperez@colorado.edu>
4097 2002-02-11 Fernando Perez <fperez@colorado.edu>
4073
4098
4074 * Wrote a relatively complete Windows installer. It puts
4099 * Wrote a relatively complete Windows installer. It puts
4075 everything in place, creates Start Menu entries and fixes the
4100 everything in place, creates Start Menu entries and fixes the
4076 color issues. Nothing fancy, but it works.
4101 color issues. Nothing fancy, but it works.
4077
4102
4078 2002-02-10 Fernando Perez <fperez@colorado.edu>
4103 2002-02-10 Fernando Perez <fperez@colorado.edu>
4079
4104
4080 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4105 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4081 os.path.expanduser() call so that we can type @run ~/myfile.py and
4106 os.path.expanduser() call so that we can type @run ~/myfile.py and
4082 have thigs work as expected.
4107 have thigs work as expected.
4083
4108
4084 * IPython/genutils.py (page): fixed exception handling so things
4109 * IPython/genutils.py (page): fixed exception handling so things
4085 work both in Unix and Windows correctly. Quitting a pager triggers
4110 work both in Unix and Windows correctly. Quitting a pager triggers
4086 an IOError/broken pipe in Unix, and in windows not finding a pager
4111 an IOError/broken pipe in Unix, and in windows not finding a pager
4087 is also an IOError, so I had to actually look at the return value
4112 is also an IOError, so I had to actually look at the return value
4088 of the exception, not just the exception itself. Should be ok now.
4113 of the exception, not just the exception itself. Should be ok now.
4089
4114
4090 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4115 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4091 modified to allow case-insensitive color scheme changes.
4116 modified to allow case-insensitive color scheme changes.
4092
4117
4093 2002-02-09 Fernando Perez <fperez@colorado.edu>
4118 2002-02-09 Fernando Perez <fperez@colorado.edu>
4094
4119
4095 * IPython/genutils.py (native_line_ends): new function to leave
4120 * IPython/genutils.py (native_line_ends): new function to leave
4096 user config files with os-native line-endings.
4121 user config files with os-native line-endings.
4097
4122
4098 * README and manual updates.
4123 * README and manual updates.
4099
4124
4100 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4125 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4101 instead of StringType to catch Unicode strings.
4126 instead of StringType to catch Unicode strings.
4102
4127
4103 * IPython/genutils.py (filefind): fixed bug for paths with
4128 * IPython/genutils.py (filefind): fixed bug for paths with
4104 embedded spaces (very common in Windows).
4129 embedded spaces (very common in Windows).
4105
4130
4106 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4131 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4107 files under Windows, so that they get automatically associated
4132 files under Windows, so that they get automatically associated
4108 with a text editor. Windows makes it a pain to handle
4133 with a text editor. Windows makes it a pain to handle
4109 extension-less files.
4134 extension-less files.
4110
4135
4111 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4136 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4112 warning about readline only occur for Posix. In Windows there's no
4137 warning about readline only occur for Posix. In Windows there's no
4113 way to get readline, so why bother with the warning.
4138 way to get readline, so why bother with the warning.
4114
4139
4115 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4140 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4116 for __str__ instead of dir(self), since dir() changed in 2.2.
4141 for __str__ instead of dir(self), since dir() changed in 2.2.
4117
4142
4118 * Ported to Windows! Tested on XP, I suspect it should work fine
4143 * Ported to Windows! Tested on XP, I suspect it should work fine
4119 on NT/2000, but I don't think it will work on 98 et al. That
4144 on NT/2000, but I don't think it will work on 98 et al. That
4120 series of Windows is such a piece of junk anyway that I won't try
4145 series of Windows is such a piece of junk anyway that I won't try
4121 porting it there. The XP port was straightforward, showed a few
4146 porting it there. The XP port was straightforward, showed a few
4122 bugs here and there (fixed all), in particular some string
4147 bugs here and there (fixed all), in particular some string
4123 handling stuff which required considering Unicode strings (which
4148 handling stuff which required considering Unicode strings (which
4124 Windows uses). This is good, but hasn't been too tested :) No
4149 Windows uses). This is good, but hasn't been too tested :) No
4125 fancy installer yet, I'll put a note in the manual so people at
4150 fancy installer yet, I'll put a note in the manual so people at
4126 least make manually a shortcut.
4151 least make manually a shortcut.
4127
4152
4128 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4153 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4129 into a single one, "colors". This now controls both prompt and
4154 into a single one, "colors". This now controls both prompt and
4130 exception color schemes, and can be changed both at startup
4155 exception color schemes, and can be changed both at startup
4131 (either via command-line switches or via ipythonrc files) and at
4156 (either via command-line switches or via ipythonrc files) and at
4132 runtime, with @colors.
4157 runtime, with @colors.
4133 (Magic.magic_run): renamed @prun to @run and removed the old
4158 (Magic.magic_run): renamed @prun to @run and removed the old
4134 @run. The two were too similar to warrant keeping both.
4159 @run. The two were too similar to warrant keeping both.
4135
4160
4136 2002-02-03 Fernando Perez <fperez@colorado.edu>
4161 2002-02-03 Fernando Perez <fperez@colorado.edu>
4137
4162
4138 * IPython/iplib.py (install_first_time): Added comment on how to
4163 * IPython/iplib.py (install_first_time): Added comment on how to
4139 configure the color options for first-time users. Put a <return>
4164 configure the color options for first-time users. Put a <return>
4140 request at the end so that small-terminal users get a chance to
4165 request at the end so that small-terminal users get a chance to
4141 read the startup info.
4166 read the startup info.
4142
4167
4143 2002-01-23 Fernando Perez <fperez@colorado.edu>
4168 2002-01-23 Fernando Perez <fperez@colorado.edu>
4144
4169
4145 * IPython/iplib.py (CachedOutput.update): Changed output memory
4170 * IPython/iplib.py (CachedOutput.update): Changed output memory
4146 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4171 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4147 input history we still use _i. Did this b/c these variable are
4172 input history we still use _i. Did this b/c these variable are
4148 very commonly used in interactive work, so the less we need to
4173 very commonly used in interactive work, so the less we need to
4149 type the better off we are.
4174 type the better off we are.
4150 (Magic.magic_prun): updated @prun to better handle the namespaces
4175 (Magic.magic_prun): updated @prun to better handle the namespaces
4151 the file will run in, including a fix for __name__ not being set
4176 the file will run in, including a fix for __name__ not being set
4152 before.
4177 before.
4153
4178
4154 2002-01-20 Fernando Perez <fperez@colorado.edu>
4179 2002-01-20 Fernando Perez <fperez@colorado.edu>
4155
4180
4156 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4181 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4157 extra garbage for Python 2.2. Need to look more carefully into
4182 extra garbage for Python 2.2. Need to look more carefully into
4158 this later.
4183 this later.
4159
4184
4160 2002-01-19 Fernando Perez <fperez@colorado.edu>
4185 2002-01-19 Fernando Perez <fperez@colorado.edu>
4161
4186
4162 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4187 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4163 display SyntaxError exceptions properly formatted when they occur
4188 display SyntaxError exceptions properly formatted when they occur
4164 (they can be triggered by imported code).
4189 (they can be triggered by imported code).
4165
4190
4166 2002-01-18 Fernando Perez <fperez@colorado.edu>
4191 2002-01-18 Fernando Perez <fperez@colorado.edu>
4167
4192
4168 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4193 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4169 SyntaxError exceptions are reported nicely formatted, instead of
4194 SyntaxError exceptions are reported nicely formatted, instead of
4170 spitting out only offset information as before.
4195 spitting out only offset information as before.
4171 (Magic.magic_prun): Added the @prun function for executing
4196 (Magic.magic_prun): Added the @prun function for executing
4172 programs with command line args inside IPython.
4197 programs with command line args inside IPython.
4173
4198
4174 2002-01-16 Fernando Perez <fperez@colorado.edu>
4199 2002-01-16 Fernando Perez <fperez@colorado.edu>
4175
4200
4176 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4201 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4177 to *not* include the last item given in a range. This brings their
4202 to *not* include the last item given in a range. This brings their
4178 behavior in line with Python's slicing:
4203 behavior in line with Python's slicing:
4179 a[n1:n2] -> a[n1]...a[n2-1]
4204 a[n1:n2] -> a[n1]...a[n2-1]
4180 It may be a bit less convenient, but I prefer to stick to Python's
4205 It may be a bit less convenient, but I prefer to stick to Python's
4181 conventions *everywhere*, so users never have to wonder.
4206 conventions *everywhere*, so users never have to wonder.
4182 (Magic.magic_macro): Added @macro function to ease the creation of
4207 (Magic.magic_macro): Added @macro function to ease the creation of
4183 macros.
4208 macros.
4184
4209
4185 2002-01-05 Fernando Perez <fperez@colorado.edu>
4210 2002-01-05 Fernando Perez <fperez@colorado.edu>
4186
4211
4187 * Released 0.2.4.
4212 * Released 0.2.4.
4188
4213
4189 * IPython/iplib.py (Magic.magic_pdef):
4214 * IPython/iplib.py (Magic.magic_pdef):
4190 (InteractiveShell.safe_execfile): report magic lines and error
4215 (InteractiveShell.safe_execfile): report magic lines and error
4191 lines without line numbers so one can easily copy/paste them for
4216 lines without line numbers so one can easily copy/paste them for
4192 re-execution.
4217 re-execution.
4193
4218
4194 * Updated manual with recent changes.
4219 * Updated manual with recent changes.
4195
4220
4196 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4221 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4197 docstring printing when class? is called. Very handy for knowing
4222 docstring printing when class? is called. Very handy for knowing
4198 how to create class instances (as long as __init__ is well
4223 how to create class instances (as long as __init__ is well
4199 documented, of course :)
4224 documented, of course :)
4200 (Magic.magic_doc): print both class and constructor docstrings.
4225 (Magic.magic_doc): print both class and constructor docstrings.
4201 (Magic.magic_pdef): give constructor info if passed a class and
4226 (Magic.magic_pdef): give constructor info if passed a class and
4202 __call__ info for callable object instances.
4227 __call__ info for callable object instances.
4203
4228
4204 2002-01-04 Fernando Perez <fperez@colorado.edu>
4229 2002-01-04 Fernando Perez <fperez@colorado.edu>
4205
4230
4206 * Made deep_reload() off by default. It doesn't always work
4231 * Made deep_reload() off by default. It doesn't always work
4207 exactly as intended, so it's probably safer to have it off. It's
4232 exactly as intended, so it's probably safer to have it off. It's
4208 still available as dreload() anyway, so nothing is lost.
4233 still available as dreload() anyway, so nothing is lost.
4209
4234
4210 2002-01-02 Fernando Perez <fperez@colorado.edu>
4235 2002-01-02 Fernando Perez <fperez@colorado.edu>
4211
4236
4212 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4237 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4213 so I wanted an updated release).
4238 so I wanted an updated release).
4214
4239
4215 2001-12-27 Fernando Perez <fperez@colorado.edu>
4240 2001-12-27 Fernando Perez <fperez@colorado.edu>
4216
4241
4217 * IPython/iplib.py (InteractiveShell.interact): Added the original
4242 * IPython/iplib.py (InteractiveShell.interact): Added the original
4218 code from 'code.py' for this module in order to change the
4243 code from 'code.py' for this module in order to change the
4219 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4244 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4220 the history cache would break when the user hit Ctrl-C, and
4245 the history cache would break when the user hit Ctrl-C, and
4221 interact() offers no way to add any hooks to it.
4246 interact() offers no way to add any hooks to it.
4222
4247
4223 2001-12-23 Fernando Perez <fperez@colorado.edu>
4248 2001-12-23 Fernando Perez <fperez@colorado.edu>
4224
4249
4225 * setup.py: added check for 'MANIFEST' before trying to remove
4250 * setup.py: added check for 'MANIFEST' before trying to remove
4226 it. Thanks to Sean Reifschneider.
4251 it. Thanks to Sean Reifschneider.
4227
4252
4228 2001-12-22 Fernando Perez <fperez@colorado.edu>
4253 2001-12-22 Fernando Perez <fperez@colorado.edu>
4229
4254
4230 * Released 0.2.2.
4255 * Released 0.2.2.
4231
4256
4232 * Finished (reasonably) writing the manual. Later will add the
4257 * Finished (reasonably) writing the manual. Later will add the
4233 python-standard navigation stylesheets, but for the time being
4258 python-standard navigation stylesheets, but for the time being
4234 it's fairly complete. Distribution will include html and pdf
4259 it's fairly complete. Distribution will include html and pdf
4235 versions.
4260 versions.
4236
4261
4237 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4262 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4238 (MayaVi author).
4263 (MayaVi author).
4239
4264
4240 2001-12-21 Fernando Perez <fperez@colorado.edu>
4265 2001-12-21 Fernando Perez <fperez@colorado.edu>
4241
4266
4242 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4267 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4243 good public release, I think (with the manual and the distutils
4268 good public release, I think (with the manual and the distutils
4244 installer). The manual can use some work, but that can go
4269 installer). The manual can use some work, but that can go
4245 slowly. Otherwise I think it's quite nice for end users. Next
4270 slowly. Otherwise I think it's quite nice for end users. Next
4246 summer, rewrite the guts of it...
4271 summer, rewrite the guts of it...
4247
4272
4248 * Changed format of ipythonrc files to use whitespace as the
4273 * Changed format of ipythonrc files to use whitespace as the
4249 separator instead of an explicit '='. Cleaner.
4274 separator instead of an explicit '='. Cleaner.
4250
4275
4251 2001-12-20 Fernando Perez <fperez@colorado.edu>
4276 2001-12-20 Fernando Perez <fperez@colorado.edu>
4252
4277
4253 * Started a manual in LyX. For now it's just a quick merge of the
4278 * Started a manual in LyX. For now it's just a quick merge of the
4254 various internal docstrings and READMEs. Later it may grow into a
4279 various internal docstrings and READMEs. Later it may grow into a
4255 nice, full-blown manual.
4280 nice, full-blown manual.
4256
4281
4257 * Set up a distutils based installer. Installation should now be
4282 * Set up a distutils based installer. Installation should now be
4258 trivially simple for end-users.
4283 trivially simple for end-users.
4259
4284
4260 2001-12-11 Fernando Perez <fperez@colorado.edu>
4285 2001-12-11 Fernando Perez <fperez@colorado.edu>
4261
4286
4262 * Released 0.2.0. First public release, announced it at
4287 * Released 0.2.0. First public release, announced it at
4263 comp.lang.python. From now on, just bugfixes...
4288 comp.lang.python. From now on, just bugfixes...
4264
4289
4265 * Went through all the files, set copyright/license notices and
4290 * Went through all the files, set copyright/license notices and
4266 cleaned up things. Ready for release.
4291 cleaned up things. Ready for release.
4267
4292
4268 2001-12-10 Fernando Perez <fperez@colorado.edu>
4293 2001-12-10 Fernando Perez <fperez@colorado.edu>
4269
4294
4270 * Changed the first-time installer not to use tarfiles. It's more
4295 * Changed the first-time installer not to use tarfiles. It's more
4271 robust now and less unix-dependent. Also makes it easier for
4296 robust now and less unix-dependent. Also makes it easier for
4272 people to later upgrade versions.
4297 people to later upgrade versions.
4273
4298
4274 * Changed @exit to @abort to reflect the fact that it's pretty
4299 * Changed @exit to @abort to reflect the fact that it's pretty
4275 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4300 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4276 becomes significant only when IPyhton is embedded: in that case,
4301 becomes significant only when IPyhton is embedded: in that case,
4277 C-D closes IPython only, but @abort kills the enclosing program
4302 C-D closes IPython only, but @abort kills the enclosing program
4278 too (unless it had called IPython inside a try catching
4303 too (unless it had called IPython inside a try catching
4279 SystemExit).
4304 SystemExit).
4280
4305
4281 * Created Shell module which exposes the actuall IPython Shell
4306 * Created Shell module which exposes the actuall IPython Shell
4282 classes, currently the normal and the embeddable one. This at
4307 classes, currently the normal and the embeddable one. This at
4283 least offers a stable interface we won't need to change when
4308 least offers a stable interface we won't need to change when
4284 (later) the internals are rewritten. That rewrite will be confined
4309 (later) the internals are rewritten. That rewrite will be confined
4285 to iplib and ipmaker, but the Shell interface should remain as is.
4310 to iplib and ipmaker, but the Shell interface should remain as is.
4286
4311
4287 * Added embed module which offers an embeddable IPShell object,
4312 * Added embed module which offers an embeddable IPShell object,
4288 useful to fire up IPython *inside* a running program. Great for
4313 useful to fire up IPython *inside* a running program. Great for
4289 debugging or dynamical data analysis.
4314 debugging or dynamical data analysis.
4290
4315
4291 2001-12-08 Fernando Perez <fperez@colorado.edu>
4316 2001-12-08 Fernando Perez <fperez@colorado.edu>
4292
4317
4293 * Fixed small bug preventing seeing info from methods of defined
4318 * Fixed small bug preventing seeing info from methods of defined
4294 objects (incorrect namespace in _ofind()).
4319 objects (incorrect namespace in _ofind()).
4295
4320
4296 * Documentation cleanup. Moved the main usage docstrings to a
4321 * Documentation cleanup. Moved the main usage docstrings to a
4297 separate file, usage.py (cleaner to maintain, and hopefully in the
4322 separate file, usage.py (cleaner to maintain, and hopefully in the
4298 future some perlpod-like way of producing interactive, man and
4323 future some perlpod-like way of producing interactive, man and
4299 html docs out of it will be found).
4324 html docs out of it will be found).
4300
4325
4301 * Added @profile to see your profile at any time.
4326 * Added @profile to see your profile at any time.
4302
4327
4303 * Added @p as an alias for 'print'. It's especially convenient if
4328 * Added @p as an alias for 'print'. It's especially convenient if
4304 using automagic ('p x' prints x).
4329 using automagic ('p x' prints x).
4305
4330
4306 * Small cleanups and fixes after a pychecker run.
4331 * Small cleanups and fixes after a pychecker run.
4307
4332
4308 * Changed the @cd command to handle @cd - and @cd -<n> for
4333 * Changed the @cd command to handle @cd - and @cd -<n> for
4309 visiting any directory in _dh.
4334 visiting any directory in _dh.
4310
4335
4311 * Introduced _dh, a history of visited directories. @dhist prints
4336 * Introduced _dh, a history of visited directories. @dhist prints
4312 it out with numbers.
4337 it out with numbers.
4313
4338
4314 2001-12-07 Fernando Perez <fperez@colorado.edu>
4339 2001-12-07 Fernando Perez <fperez@colorado.edu>
4315
4340
4316 * Released 0.1.22
4341 * Released 0.1.22
4317
4342
4318 * Made initialization a bit more robust against invalid color
4343 * Made initialization a bit more robust against invalid color
4319 options in user input (exit, not traceback-crash).
4344 options in user input (exit, not traceback-crash).
4320
4345
4321 * Changed the bug crash reporter to write the report only in the
4346 * Changed the bug crash reporter to write the report only in the
4322 user's .ipython directory. That way IPython won't litter people's
4347 user's .ipython directory. That way IPython won't litter people's
4323 hard disks with crash files all over the place. Also print on
4348 hard disks with crash files all over the place. Also print on
4324 screen the necessary mail command.
4349 screen the necessary mail command.
4325
4350
4326 * With the new ultraTB, implemented LightBG color scheme for light
4351 * With the new ultraTB, implemented LightBG color scheme for light
4327 background terminals. A lot of people like white backgrounds, so I
4352 background terminals. A lot of people like white backgrounds, so I
4328 guess we should at least give them something readable.
4353 guess we should at least give them something readable.
4329
4354
4330 2001-12-06 Fernando Perez <fperez@colorado.edu>
4355 2001-12-06 Fernando Perez <fperez@colorado.edu>
4331
4356
4332 * Modified the structure of ultraTB. Now there's a proper class
4357 * Modified the structure of ultraTB. Now there's a proper class
4333 for tables of color schemes which allow adding schemes easily and
4358 for tables of color schemes which allow adding schemes easily and
4334 switching the active scheme without creating a new instance every
4359 switching the active scheme without creating a new instance every
4335 time (which was ridiculous). The syntax for creating new schemes
4360 time (which was ridiculous). The syntax for creating new schemes
4336 is also cleaner. I think ultraTB is finally done, with a clean
4361 is also cleaner. I think ultraTB is finally done, with a clean
4337 class structure. Names are also much cleaner (now there's proper
4362 class structure. Names are also much cleaner (now there's proper
4338 color tables, no need for every variable to also have 'color' in
4363 color tables, no need for every variable to also have 'color' in
4339 its name).
4364 its name).
4340
4365
4341 * Broke down genutils into separate files. Now genutils only
4366 * Broke down genutils into separate files. Now genutils only
4342 contains utility functions, and classes have been moved to their
4367 contains utility functions, and classes have been moved to their
4343 own files (they had enough independent functionality to warrant
4368 own files (they had enough independent functionality to warrant
4344 it): ConfigLoader, OutputTrap, Struct.
4369 it): ConfigLoader, OutputTrap, Struct.
4345
4370
4346 2001-12-05 Fernando Perez <fperez@colorado.edu>
4371 2001-12-05 Fernando Perez <fperez@colorado.edu>
4347
4372
4348 * IPython turns 21! Released version 0.1.21, as a candidate for
4373 * IPython turns 21! Released version 0.1.21, as a candidate for
4349 public consumption. If all goes well, release in a few days.
4374 public consumption. If all goes well, release in a few days.
4350
4375
4351 * Fixed path bug (files in Extensions/ directory wouldn't be found
4376 * Fixed path bug (files in Extensions/ directory wouldn't be found
4352 unless IPython/ was explicitly in sys.path).
4377 unless IPython/ was explicitly in sys.path).
4353
4378
4354 * Extended the FlexCompleter class as MagicCompleter to allow
4379 * Extended the FlexCompleter class as MagicCompleter to allow
4355 completion of @-starting lines.
4380 completion of @-starting lines.
4356
4381
4357 * Created __release__.py file as a central repository for release
4382 * Created __release__.py file as a central repository for release
4358 info that other files can read from.
4383 info that other files can read from.
4359
4384
4360 * Fixed small bug in logging: when logging was turned on in
4385 * Fixed small bug in logging: when logging was turned on in
4361 mid-session, old lines with special meanings (!@?) were being
4386 mid-session, old lines with special meanings (!@?) were being
4362 logged without the prepended comment, which is necessary since
4387 logged without the prepended comment, which is necessary since
4363 they are not truly valid python syntax. This should make session
4388 they are not truly valid python syntax. This should make session
4364 restores produce less errors.
4389 restores produce less errors.
4365
4390
4366 * The namespace cleanup forced me to make a FlexCompleter class
4391 * The namespace cleanup forced me to make a FlexCompleter class
4367 which is nothing but a ripoff of rlcompleter, but with selectable
4392 which is nothing but a ripoff of rlcompleter, but with selectable
4368 namespace (rlcompleter only works in __main__.__dict__). I'll try
4393 namespace (rlcompleter only works in __main__.__dict__). I'll try
4369 to submit a note to the authors to see if this change can be
4394 to submit a note to the authors to see if this change can be
4370 incorporated in future rlcompleter releases (Dec.6: done)
4395 incorporated in future rlcompleter releases (Dec.6: done)
4371
4396
4372 * More fixes to namespace handling. It was a mess! Now all
4397 * More fixes to namespace handling. It was a mess! Now all
4373 explicit references to __main__.__dict__ are gone (except when
4398 explicit references to __main__.__dict__ are gone (except when
4374 really needed) and everything is handled through the namespace
4399 really needed) and everything is handled through the namespace
4375 dicts in the IPython instance. We seem to be getting somewhere
4400 dicts in the IPython instance. We seem to be getting somewhere
4376 with this, finally...
4401 with this, finally...
4377
4402
4378 * Small documentation updates.
4403 * Small documentation updates.
4379
4404
4380 * Created the Extensions directory under IPython (with an
4405 * Created the Extensions directory under IPython (with an
4381 __init__.py). Put the PhysicalQ stuff there. This directory should
4406 __init__.py). Put the PhysicalQ stuff there. This directory should
4382 be used for all special-purpose extensions.
4407 be used for all special-purpose extensions.
4383
4408
4384 * File renaming:
4409 * File renaming:
4385 ipythonlib --> ipmaker
4410 ipythonlib --> ipmaker
4386 ipplib --> iplib
4411 ipplib --> iplib
4387 This makes a bit more sense in terms of what these files actually do.
4412 This makes a bit more sense in terms of what these files actually do.
4388
4413
4389 * Moved all the classes and functions in ipythonlib to ipplib, so
4414 * Moved all the classes and functions in ipythonlib to ipplib, so
4390 now ipythonlib only has make_IPython(). This will ease up its
4415 now ipythonlib only has make_IPython(). This will ease up its
4391 splitting in smaller functional chunks later.
4416 splitting in smaller functional chunks later.
4392
4417
4393 * Cleaned up (done, I think) output of @whos. Better column
4418 * Cleaned up (done, I think) output of @whos. Better column
4394 formatting, and now shows str(var) for as much as it can, which is
4419 formatting, and now shows str(var) for as much as it can, which is
4395 typically what one gets with a 'print var'.
4420 typically what one gets with a 'print var'.
4396
4421
4397 2001-12-04 Fernando Perez <fperez@colorado.edu>
4422 2001-12-04 Fernando Perez <fperez@colorado.edu>
4398
4423
4399 * Fixed namespace problems. Now builtin/IPyhton/user names get
4424 * Fixed namespace problems. Now builtin/IPyhton/user names get
4400 properly reported in their namespace. Internal namespace handling
4425 properly reported in their namespace. Internal namespace handling
4401 is finally getting decent (not perfect yet, but much better than
4426 is finally getting decent (not perfect yet, but much better than
4402 the ad-hoc mess we had).
4427 the ad-hoc mess we had).
4403
4428
4404 * Removed -exit option. If people just want to run a python
4429 * Removed -exit option. If people just want to run a python
4405 script, that's what the normal interpreter is for. Less
4430 script, that's what the normal interpreter is for. Less
4406 unnecessary options, less chances for bugs.
4431 unnecessary options, less chances for bugs.
4407
4432
4408 * Added a crash handler which generates a complete post-mortem if
4433 * Added a crash handler which generates a complete post-mortem if
4409 IPython crashes. This will help a lot in tracking bugs down the
4434 IPython crashes. This will help a lot in tracking bugs down the
4410 road.
4435 road.
4411
4436
4412 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4437 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4413 which were boud to functions being reassigned would bypass the
4438 which were boud to functions being reassigned would bypass the
4414 logger, breaking the sync of _il with the prompt counter. This
4439 logger, breaking the sync of _il with the prompt counter. This
4415 would then crash IPython later when a new line was logged.
4440 would then crash IPython later when a new line was logged.
4416
4441
4417 2001-12-02 Fernando Perez <fperez@colorado.edu>
4442 2001-12-02 Fernando Perez <fperez@colorado.edu>
4418
4443
4419 * Made IPython a package. This means people don't have to clutter
4444 * Made IPython a package. This means people don't have to clutter
4420 their sys.path with yet another directory. Changed the INSTALL
4445 their sys.path with yet another directory. Changed the INSTALL
4421 file accordingly.
4446 file accordingly.
4422
4447
4423 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4448 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4424 sorts its output (so @who shows it sorted) and @whos formats the
4449 sorts its output (so @who shows it sorted) and @whos formats the
4425 table according to the width of the first column. Nicer, easier to
4450 table according to the width of the first column. Nicer, easier to
4426 read. Todo: write a generic table_format() which takes a list of
4451 read. Todo: write a generic table_format() which takes a list of
4427 lists and prints it nicely formatted, with optional row/column
4452 lists and prints it nicely formatted, with optional row/column
4428 separators and proper padding and justification.
4453 separators and proper padding and justification.
4429
4454
4430 * Released 0.1.20
4455 * Released 0.1.20
4431
4456
4432 * Fixed bug in @log which would reverse the inputcache list (a
4457 * Fixed bug in @log which would reverse the inputcache list (a
4433 copy operation was missing).
4458 copy operation was missing).
4434
4459
4435 * Code cleanup. @config was changed to use page(). Better, since
4460 * Code cleanup. @config was changed to use page(). Better, since
4436 its output is always quite long.
4461 its output is always quite long.
4437
4462
4438 * Itpl is back as a dependency. I was having too many problems
4463 * Itpl is back as a dependency. I was having too many problems
4439 getting the parametric aliases to work reliably, and it's just
4464 getting the parametric aliases to work reliably, and it's just
4440 easier to code weird string operations with it than playing %()s
4465 easier to code weird string operations with it than playing %()s
4441 games. It's only ~6k, so I don't think it's too big a deal.
4466 games. It's only ~6k, so I don't think it's too big a deal.
4442
4467
4443 * Found (and fixed) a very nasty bug with history. !lines weren't
4468 * Found (and fixed) a very nasty bug with history. !lines weren't
4444 getting cached, and the out of sync caches would crash
4469 getting cached, and the out of sync caches would crash
4445 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4470 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4446 division of labor a bit better. Bug fixed, cleaner structure.
4471 division of labor a bit better. Bug fixed, cleaner structure.
4447
4472
4448 2001-12-01 Fernando Perez <fperez@colorado.edu>
4473 2001-12-01 Fernando Perez <fperez@colorado.edu>
4449
4474
4450 * Released 0.1.19
4475 * Released 0.1.19
4451
4476
4452 * Added option -n to @hist to prevent line number printing. Much
4477 * Added option -n to @hist to prevent line number printing. Much
4453 easier to copy/paste code this way.
4478 easier to copy/paste code this way.
4454
4479
4455 * Created global _il to hold the input list. Allows easy
4480 * Created global _il to hold the input list. Allows easy
4456 re-execution of blocks of code by slicing it (inspired by Janko's
4481 re-execution of blocks of code by slicing it (inspired by Janko's
4457 comment on 'macros').
4482 comment on 'macros').
4458
4483
4459 * Small fixes and doc updates.
4484 * Small fixes and doc updates.
4460
4485
4461 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4486 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4462 much too fragile with automagic. Handles properly multi-line
4487 much too fragile with automagic. Handles properly multi-line
4463 statements and takes parameters.
4488 statements and takes parameters.
4464
4489
4465 2001-11-30 Fernando Perez <fperez@colorado.edu>
4490 2001-11-30 Fernando Perez <fperez@colorado.edu>
4466
4491
4467 * Version 0.1.18 released.
4492 * Version 0.1.18 released.
4468
4493
4469 * Fixed nasty namespace bug in initial module imports.
4494 * Fixed nasty namespace bug in initial module imports.
4470
4495
4471 * Added copyright/license notes to all code files (except
4496 * Added copyright/license notes to all code files (except
4472 DPyGetOpt). For the time being, LGPL. That could change.
4497 DPyGetOpt). For the time being, LGPL. That could change.
4473
4498
4474 * Rewrote a much nicer README, updated INSTALL, cleaned up
4499 * Rewrote a much nicer README, updated INSTALL, cleaned up
4475 ipythonrc-* samples.
4500 ipythonrc-* samples.
4476
4501
4477 * Overall code/documentation cleanup. Basically ready for
4502 * Overall code/documentation cleanup. Basically ready for
4478 release. Only remaining thing: licence decision (LGPL?).
4503 release. Only remaining thing: licence decision (LGPL?).
4479
4504
4480 * Converted load_config to a class, ConfigLoader. Now recursion
4505 * Converted load_config to a class, ConfigLoader. Now recursion
4481 control is better organized. Doesn't include the same file twice.
4506 control is better organized. Doesn't include the same file twice.
4482
4507
4483 2001-11-29 Fernando Perez <fperez@colorado.edu>
4508 2001-11-29 Fernando Perez <fperez@colorado.edu>
4484
4509
4485 * Got input history working. Changed output history variables from
4510 * Got input history working. Changed output history variables from
4486 _p to _o so that _i is for input and _o for output. Just cleaner
4511 _p to _o so that _i is for input and _o for output. Just cleaner
4487 convention.
4512 convention.
4488
4513
4489 * Implemented parametric aliases. This pretty much allows the
4514 * Implemented parametric aliases. This pretty much allows the
4490 alias system to offer full-blown shell convenience, I think.
4515 alias system to offer full-blown shell convenience, I think.
4491
4516
4492 * Version 0.1.17 released, 0.1.18 opened.
4517 * Version 0.1.17 released, 0.1.18 opened.
4493
4518
4494 * dot_ipython/ipythonrc (alias): added documentation.
4519 * dot_ipython/ipythonrc (alias): added documentation.
4495 (xcolor): Fixed small bug (xcolors -> xcolor)
4520 (xcolor): Fixed small bug (xcolors -> xcolor)
4496
4521
4497 * Changed the alias system. Now alias is a magic command to define
4522 * Changed the alias system. Now alias is a magic command to define
4498 aliases just like the shell. Rationale: the builtin magics should
4523 aliases just like the shell. Rationale: the builtin magics should
4499 be there for things deeply connected to IPython's
4524 be there for things deeply connected to IPython's
4500 architecture. And this is a much lighter system for what I think
4525 architecture. And this is a much lighter system for what I think
4501 is the really important feature: allowing users to define quickly
4526 is the really important feature: allowing users to define quickly
4502 magics that will do shell things for them, so they can customize
4527 magics that will do shell things for them, so they can customize
4503 IPython easily to match their work habits. If someone is really
4528 IPython easily to match their work habits. If someone is really
4504 desperate to have another name for a builtin alias, they can
4529 desperate to have another name for a builtin alias, they can
4505 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4530 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4506 works.
4531 works.
4507
4532
4508 2001-11-28 Fernando Perez <fperez@colorado.edu>
4533 2001-11-28 Fernando Perez <fperez@colorado.edu>
4509
4534
4510 * Changed @file so that it opens the source file at the proper
4535 * Changed @file so that it opens the source file at the proper
4511 line. Since it uses less, if your EDITOR environment is
4536 line. Since it uses less, if your EDITOR environment is
4512 configured, typing v will immediately open your editor of choice
4537 configured, typing v will immediately open your editor of choice
4513 right at the line where the object is defined. Not as quick as
4538 right at the line where the object is defined. Not as quick as
4514 having a direct @edit command, but for all intents and purposes it
4539 having a direct @edit command, but for all intents and purposes it
4515 works. And I don't have to worry about writing @edit to deal with
4540 works. And I don't have to worry about writing @edit to deal with
4516 all the editors, less does that.
4541 all the editors, less does that.
4517
4542
4518 * Version 0.1.16 released, 0.1.17 opened.
4543 * Version 0.1.16 released, 0.1.17 opened.
4519
4544
4520 * Fixed some nasty bugs in the page/page_dumb combo that could
4545 * Fixed some nasty bugs in the page/page_dumb combo that could
4521 crash IPython.
4546 crash IPython.
4522
4547
4523 2001-11-27 Fernando Perez <fperez@colorado.edu>
4548 2001-11-27 Fernando Perez <fperez@colorado.edu>
4524
4549
4525 * Version 0.1.15 released, 0.1.16 opened.
4550 * Version 0.1.15 released, 0.1.16 opened.
4526
4551
4527 * Finally got ? and ?? to work for undefined things: now it's
4552 * Finally got ? and ?? to work for undefined things: now it's
4528 possible to type {}.get? and get information about the get method
4553 possible to type {}.get? and get information about the get method
4529 of dicts, or os.path? even if only os is defined (so technically
4554 of dicts, or os.path? even if only os is defined (so technically
4530 os.path isn't). Works at any level. For example, after import os,
4555 os.path isn't). Works at any level. For example, after import os,
4531 os?, os.path?, os.path.abspath? all work. This is great, took some
4556 os?, os.path?, os.path.abspath? all work. This is great, took some
4532 work in _ofind.
4557 work in _ofind.
4533
4558
4534 * Fixed more bugs with logging. The sanest way to do it was to add
4559 * Fixed more bugs with logging. The sanest way to do it was to add
4535 to @log a 'mode' parameter. Killed two in one shot (this mode
4560 to @log a 'mode' parameter. Killed two in one shot (this mode
4536 option was a request of Janko's). I think it's finally clean
4561 option was a request of Janko's). I think it's finally clean
4537 (famous last words).
4562 (famous last words).
4538
4563
4539 * Added a page_dumb() pager which does a decent job of paging on
4564 * Added a page_dumb() pager which does a decent job of paging on
4540 screen, if better things (like less) aren't available. One less
4565 screen, if better things (like less) aren't available. One less
4541 unix dependency (someday maybe somebody will port this to
4566 unix dependency (someday maybe somebody will port this to
4542 windows).
4567 windows).
4543
4568
4544 * Fixed problem in magic_log: would lock of logging out if log
4569 * Fixed problem in magic_log: would lock of logging out if log
4545 creation failed (because it would still think it had succeeded).
4570 creation failed (because it would still think it had succeeded).
4546
4571
4547 * Improved the page() function using curses to auto-detect screen
4572 * Improved the page() function using curses to auto-detect screen
4548 size. Now it can make a much better decision on whether to print
4573 size. Now it can make a much better decision on whether to print
4549 or page a string. Option screen_length was modified: a value 0
4574 or page a string. Option screen_length was modified: a value 0
4550 means auto-detect, and that's the default now.
4575 means auto-detect, and that's the default now.
4551
4576
4552 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4577 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4553 go out. I'll test it for a few days, then talk to Janko about
4578 go out. I'll test it for a few days, then talk to Janko about
4554 licences and announce it.
4579 licences and announce it.
4555
4580
4556 * Fixed the length of the auto-generated ---> prompt which appears
4581 * Fixed the length of the auto-generated ---> prompt which appears
4557 for auto-parens and auto-quotes. Getting this right isn't trivial,
4582 for auto-parens and auto-quotes. Getting this right isn't trivial,
4558 with all the color escapes, different prompt types and optional
4583 with all the color escapes, different prompt types and optional
4559 separators. But it seems to be working in all the combinations.
4584 separators. But it seems to be working in all the combinations.
4560
4585
4561 2001-11-26 Fernando Perez <fperez@colorado.edu>
4586 2001-11-26 Fernando Perez <fperez@colorado.edu>
4562
4587
4563 * Wrote a regexp filter to get option types from the option names
4588 * Wrote a regexp filter to get option types from the option names
4564 string. This eliminates the need to manually keep two duplicate
4589 string. This eliminates the need to manually keep two duplicate
4565 lists.
4590 lists.
4566
4591
4567 * Removed the unneeded check_option_names. Now options are handled
4592 * Removed the unneeded check_option_names. Now options are handled
4568 in a much saner manner and it's easy to visually check that things
4593 in a much saner manner and it's easy to visually check that things
4569 are ok.
4594 are ok.
4570
4595
4571 * Updated version numbers on all files I modified to carry a
4596 * Updated version numbers on all files I modified to carry a
4572 notice so Janko and Nathan have clear version markers.
4597 notice so Janko and Nathan have clear version markers.
4573
4598
4574 * Updated docstring for ultraTB with my changes. I should send
4599 * Updated docstring for ultraTB with my changes. I should send
4575 this to Nathan.
4600 this to Nathan.
4576
4601
4577 * Lots of small fixes. Ran everything through pychecker again.
4602 * Lots of small fixes. Ran everything through pychecker again.
4578
4603
4579 * Made loading of deep_reload an cmd line option. If it's not too
4604 * Made loading of deep_reload an cmd line option. If it's not too
4580 kosher, now people can just disable it. With -nodeep_reload it's
4605 kosher, now people can just disable it. With -nodeep_reload it's
4581 still available as dreload(), it just won't overwrite reload().
4606 still available as dreload(), it just won't overwrite reload().
4582
4607
4583 * Moved many options to the no| form (-opt and -noopt
4608 * Moved many options to the no| form (-opt and -noopt
4584 accepted). Cleaner.
4609 accepted). Cleaner.
4585
4610
4586 * Changed magic_log so that if called with no parameters, it uses
4611 * Changed magic_log so that if called with no parameters, it uses
4587 'rotate' mode. That way auto-generated logs aren't automatically
4612 'rotate' mode. That way auto-generated logs aren't automatically
4588 over-written. For normal logs, now a backup is made if it exists
4613 over-written. For normal logs, now a backup is made if it exists
4589 (only 1 level of backups). A new 'backup' mode was added to the
4614 (only 1 level of backups). A new 'backup' mode was added to the
4590 Logger class to support this. This was a request by Janko.
4615 Logger class to support this. This was a request by Janko.
4591
4616
4592 * Added @logoff/@logon to stop/restart an active log.
4617 * Added @logoff/@logon to stop/restart an active log.
4593
4618
4594 * Fixed a lot of bugs in log saving/replay. It was pretty
4619 * Fixed a lot of bugs in log saving/replay. It was pretty
4595 broken. Now special lines (!@,/) appear properly in the command
4620 broken. Now special lines (!@,/) appear properly in the command
4596 history after a log replay.
4621 history after a log replay.
4597
4622
4598 * Tried and failed to implement full session saving via pickle. My
4623 * Tried and failed to implement full session saving via pickle. My
4599 idea was to pickle __main__.__dict__, but modules can't be
4624 idea was to pickle __main__.__dict__, but modules can't be
4600 pickled. This would be a better alternative to replaying logs, but
4625 pickled. This would be a better alternative to replaying logs, but
4601 seems quite tricky to get to work. Changed -session to be called
4626 seems quite tricky to get to work. Changed -session to be called
4602 -logplay, which more accurately reflects what it does. And if we
4627 -logplay, which more accurately reflects what it does. And if we
4603 ever get real session saving working, -session is now available.
4628 ever get real session saving working, -session is now available.
4604
4629
4605 * Implemented color schemes for prompts also. As for tracebacks,
4630 * Implemented color schemes for prompts also. As for tracebacks,
4606 currently only NoColor and Linux are supported. But now the
4631 currently only NoColor and Linux are supported. But now the
4607 infrastructure is in place, based on a generic ColorScheme
4632 infrastructure is in place, based on a generic ColorScheme
4608 class. So writing and activating new schemes both for the prompts
4633 class. So writing and activating new schemes both for the prompts
4609 and the tracebacks should be straightforward.
4634 and the tracebacks should be straightforward.
4610
4635
4611 * Version 0.1.13 released, 0.1.14 opened.
4636 * Version 0.1.13 released, 0.1.14 opened.
4612
4637
4613 * Changed handling of options for output cache. Now counter is
4638 * Changed handling of options for output cache. Now counter is
4614 hardwired starting at 1 and one specifies the maximum number of
4639 hardwired starting at 1 and one specifies the maximum number of
4615 entries *in the outcache* (not the max prompt counter). This is
4640 entries *in the outcache* (not the max prompt counter). This is
4616 much better, since many statements won't increase the cache
4641 much better, since many statements won't increase the cache
4617 count. It also eliminated some confusing options, now there's only
4642 count. It also eliminated some confusing options, now there's only
4618 one: cache_size.
4643 one: cache_size.
4619
4644
4620 * Added 'alias' magic function and magic_alias option in the
4645 * Added 'alias' magic function and magic_alias option in the
4621 ipythonrc file. Now the user can easily define whatever names he
4646 ipythonrc file. Now the user can easily define whatever names he
4622 wants for the magic functions without having to play weird
4647 wants for the magic functions without having to play weird
4623 namespace games. This gives IPython a real shell-like feel.
4648 namespace games. This gives IPython a real shell-like feel.
4624
4649
4625 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4650 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4626 @ or not).
4651 @ or not).
4627
4652
4628 This was one of the last remaining 'visible' bugs (that I know
4653 This was one of the last remaining 'visible' bugs (that I know
4629 of). I think if I can clean up the session loading so it works
4654 of). I think if I can clean up the session loading so it works
4630 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4655 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4631 about licensing).
4656 about licensing).
4632
4657
4633 2001-11-25 Fernando Perez <fperez@colorado.edu>
4658 2001-11-25 Fernando Perez <fperez@colorado.edu>
4634
4659
4635 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4660 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4636 there's a cleaner distinction between what ? and ?? show.
4661 there's a cleaner distinction between what ? and ?? show.
4637
4662
4638 * Added screen_length option. Now the user can define his own
4663 * Added screen_length option. Now the user can define his own
4639 screen size for page() operations.
4664 screen size for page() operations.
4640
4665
4641 * Implemented magic shell-like functions with automatic code
4666 * Implemented magic shell-like functions with automatic code
4642 generation. Now adding another function is just a matter of adding
4667 generation. Now adding another function is just a matter of adding
4643 an entry to a dict, and the function is dynamically generated at
4668 an entry to a dict, and the function is dynamically generated at
4644 run-time. Python has some really cool features!
4669 run-time. Python has some really cool features!
4645
4670
4646 * Renamed many options to cleanup conventions a little. Now all
4671 * Renamed many options to cleanup conventions a little. Now all
4647 are lowercase, and only underscores where needed. Also in the code
4672 are lowercase, and only underscores where needed. Also in the code
4648 option name tables are clearer.
4673 option name tables are clearer.
4649
4674
4650 * Changed prompts a little. Now input is 'In [n]:' instead of
4675 * Changed prompts a little. Now input is 'In [n]:' instead of
4651 'In[n]:='. This allows it the numbers to be aligned with the
4676 'In[n]:='. This allows it the numbers to be aligned with the
4652 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4677 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4653 Python (it was a Mathematica thing). The '...' continuation prompt
4678 Python (it was a Mathematica thing). The '...' continuation prompt
4654 was also changed a little to align better.
4679 was also changed a little to align better.
4655
4680
4656 * Fixed bug when flushing output cache. Not all _p<n> variables
4681 * Fixed bug when flushing output cache. Not all _p<n> variables
4657 exist, so their deletion needs to be wrapped in a try:
4682 exist, so their deletion needs to be wrapped in a try:
4658
4683
4659 * Figured out how to properly use inspect.formatargspec() (it
4684 * Figured out how to properly use inspect.formatargspec() (it
4660 requires the args preceded by *). So I removed all the code from
4685 requires the args preceded by *). So I removed all the code from
4661 _get_pdef in Magic, which was just replicating that.
4686 _get_pdef in Magic, which was just replicating that.
4662
4687
4663 * Added test to prefilter to allow redefining magic function names
4688 * Added test to prefilter to allow redefining magic function names
4664 as variables. This is ok, since the @ form is always available,
4689 as variables. This is ok, since the @ form is always available,
4665 but whe should allow the user to define a variable called 'ls' if
4690 but whe should allow the user to define a variable called 'ls' if
4666 he needs it.
4691 he needs it.
4667
4692
4668 * Moved the ToDo information from README into a separate ToDo.
4693 * Moved the ToDo information from README into a separate ToDo.
4669
4694
4670 * General code cleanup and small bugfixes. I think it's close to a
4695 * General code cleanup and small bugfixes. I think it's close to a
4671 state where it can be released, obviously with a big 'beta'
4696 state where it can be released, obviously with a big 'beta'
4672 warning on it.
4697 warning on it.
4673
4698
4674 * Got the magic function split to work. Now all magics are defined
4699 * Got the magic function split to work. Now all magics are defined
4675 in a separate class. It just organizes things a bit, and now
4700 in a separate class. It just organizes things a bit, and now
4676 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4701 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4677 was too long).
4702 was too long).
4678
4703
4679 * Changed @clear to @reset to avoid potential confusions with
4704 * Changed @clear to @reset to avoid potential confusions with
4680 the shell command clear. Also renamed @cl to @clear, which does
4705 the shell command clear. Also renamed @cl to @clear, which does
4681 exactly what people expect it to from their shell experience.
4706 exactly what people expect it to from their shell experience.
4682
4707
4683 Added a check to the @reset command (since it's so
4708 Added a check to the @reset command (since it's so
4684 destructive, it's probably a good idea to ask for confirmation).
4709 destructive, it's probably a good idea to ask for confirmation).
4685 But now reset only works for full namespace resetting. Since the
4710 But now reset only works for full namespace resetting. Since the
4686 del keyword is already there for deleting a few specific
4711 del keyword is already there for deleting a few specific
4687 variables, I don't see the point of having a redundant magic
4712 variables, I don't see the point of having a redundant magic
4688 function for the same task.
4713 function for the same task.
4689
4714
4690 2001-11-24 Fernando Perez <fperez@colorado.edu>
4715 2001-11-24 Fernando Perez <fperez@colorado.edu>
4691
4716
4692 * Updated the builtin docs (esp. the ? ones).
4717 * Updated the builtin docs (esp. the ? ones).
4693
4718
4694 * Ran all the code through pychecker. Not terribly impressed with
4719 * Ran all the code through pychecker. Not terribly impressed with
4695 it: lots of spurious warnings and didn't really find anything of
4720 it: lots of spurious warnings and didn't really find anything of
4696 substance (just a few modules being imported and not used).
4721 substance (just a few modules being imported and not used).
4697
4722
4698 * Implemented the new ultraTB functionality into IPython. New
4723 * Implemented the new ultraTB functionality into IPython. New
4699 option: xcolors. This chooses color scheme. xmode now only selects
4724 option: xcolors. This chooses color scheme. xmode now only selects
4700 between Plain and Verbose. Better orthogonality.
4725 between Plain and Verbose. Better orthogonality.
4701
4726
4702 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4727 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4703 mode and color scheme for the exception handlers. Now it's
4728 mode and color scheme for the exception handlers. Now it's
4704 possible to have the verbose traceback with no coloring.
4729 possible to have the verbose traceback with no coloring.
4705
4730
4706 2001-11-23 Fernando Perez <fperez@colorado.edu>
4731 2001-11-23 Fernando Perez <fperez@colorado.edu>
4707
4732
4708 * Version 0.1.12 released, 0.1.13 opened.
4733 * Version 0.1.12 released, 0.1.13 opened.
4709
4734
4710 * Removed option to set auto-quote and auto-paren escapes by
4735 * Removed option to set auto-quote and auto-paren escapes by
4711 user. The chances of breaking valid syntax are just too high. If
4736 user. The chances of breaking valid syntax are just too high. If
4712 someone *really* wants, they can always dig into the code.
4737 someone *really* wants, they can always dig into the code.
4713
4738
4714 * Made prompt separators configurable.
4739 * Made prompt separators configurable.
4715
4740
4716 2001-11-22 Fernando Perez <fperez@colorado.edu>
4741 2001-11-22 Fernando Perez <fperez@colorado.edu>
4717
4742
4718 * Small bugfixes in many places.
4743 * Small bugfixes in many places.
4719
4744
4720 * Removed the MyCompleter class from ipplib. It seemed redundant
4745 * Removed the MyCompleter class from ipplib. It seemed redundant
4721 with the C-p,C-n history search functionality. Less code to
4746 with the C-p,C-n history search functionality. Less code to
4722 maintain.
4747 maintain.
4723
4748
4724 * Moved all the original ipython.py code into ipythonlib.py. Right
4749 * Moved all the original ipython.py code into ipythonlib.py. Right
4725 now it's just one big dump into a function called make_IPython, so
4750 now it's just one big dump into a function called make_IPython, so
4726 no real modularity has been gained. But at least it makes the
4751 no real modularity has been gained. But at least it makes the
4727 wrapper script tiny, and since ipythonlib is a module, it gets
4752 wrapper script tiny, and since ipythonlib is a module, it gets
4728 compiled and startup is much faster.
4753 compiled and startup is much faster.
4729
4754
4730 This is a reasobably 'deep' change, so we should test it for a
4755 This is a reasobably 'deep' change, so we should test it for a
4731 while without messing too much more with the code.
4756 while without messing too much more with the code.
4732
4757
4733 2001-11-21 Fernando Perez <fperez@colorado.edu>
4758 2001-11-21 Fernando Perez <fperez@colorado.edu>
4734
4759
4735 * Version 0.1.11 released, 0.1.12 opened for further work.
4760 * Version 0.1.11 released, 0.1.12 opened for further work.
4736
4761
4737 * Removed dependency on Itpl. It was only needed in one place. It
4762 * Removed dependency on Itpl. It was only needed in one place. It
4738 would be nice if this became part of python, though. It makes life
4763 would be nice if this became part of python, though. It makes life
4739 *a lot* easier in some cases.
4764 *a lot* easier in some cases.
4740
4765
4741 * Simplified the prefilter code a bit. Now all handlers are
4766 * Simplified the prefilter code a bit. Now all handlers are
4742 expected to explicitly return a value (at least a blank string).
4767 expected to explicitly return a value (at least a blank string).
4743
4768
4744 * Heavy edits in ipplib. Removed the help system altogether. Now
4769 * Heavy edits in ipplib. Removed the help system altogether. Now
4745 obj?/?? is used for inspecting objects, a magic @doc prints
4770 obj?/?? is used for inspecting objects, a magic @doc prints
4746 docstrings, and full-blown Python help is accessed via the 'help'
4771 docstrings, and full-blown Python help is accessed via the 'help'
4747 keyword. This cleans up a lot of code (less to maintain) and does
4772 keyword. This cleans up a lot of code (less to maintain) and does
4748 the job. Since 'help' is now a standard Python component, might as
4773 the job. Since 'help' is now a standard Python component, might as
4749 well use it and remove duplicate functionality.
4774 well use it and remove duplicate functionality.
4750
4775
4751 Also removed the option to use ipplib as a standalone program. By
4776 Also removed the option to use ipplib as a standalone program. By
4752 now it's too dependent on other parts of IPython to function alone.
4777 now it's too dependent on other parts of IPython to function alone.
4753
4778
4754 * Fixed bug in genutils.pager. It would crash if the pager was
4779 * Fixed bug in genutils.pager. It would crash if the pager was
4755 exited immediately after opening (broken pipe).
4780 exited immediately after opening (broken pipe).
4756
4781
4757 * Trimmed down the VerboseTB reporting a little. The header is
4782 * Trimmed down the VerboseTB reporting a little. The header is
4758 much shorter now and the repeated exception arguments at the end
4783 much shorter now and the repeated exception arguments at the end
4759 have been removed. For interactive use the old header seemed a bit
4784 have been removed. For interactive use the old header seemed a bit
4760 excessive.
4785 excessive.
4761
4786
4762 * Fixed small bug in output of @whos for variables with multi-word
4787 * Fixed small bug in output of @whos for variables with multi-word
4763 types (only first word was displayed).
4788 types (only first word was displayed).
4764
4789
4765 2001-11-17 Fernando Perez <fperez@colorado.edu>
4790 2001-11-17 Fernando Perez <fperez@colorado.edu>
4766
4791
4767 * Version 0.1.10 released, 0.1.11 opened for further work.
4792 * Version 0.1.10 released, 0.1.11 opened for further work.
4768
4793
4769 * Modified dirs and friends. dirs now *returns* the stack (not
4794 * Modified dirs and friends. dirs now *returns* the stack (not
4770 prints), so one can manipulate it as a variable. Convenient to
4795 prints), so one can manipulate it as a variable. Convenient to
4771 travel along many directories.
4796 travel along many directories.
4772
4797
4773 * Fixed bug in magic_pdef: would only work with functions with
4798 * Fixed bug in magic_pdef: would only work with functions with
4774 arguments with default values.
4799 arguments with default values.
4775
4800
4776 2001-11-14 Fernando Perez <fperez@colorado.edu>
4801 2001-11-14 Fernando Perez <fperez@colorado.edu>
4777
4802
4778 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4803 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4779 example with IPython. Various other minor fixes and cleanups.
4804 example with IPython. Various other minor fixes and cleanups.
4780
4805
4781 * Version 0.1.9 released, 0.1.10 opened for further work.
4806 * Version 0.1.9 released, 0.1.10 opened for further work.
4782
4807
4783 * Added sys.path to the list of directories searched in the
4808 * Added sys.path to the list of directories searched in the
4784 execfile= option. It used to be the current directory and the
4809 execfile= option. It used to be the current directory and the
4785 user's IPYTHONDIR only.
4810 user's IPYTHONDIR only.
4786
4811
4787 2001-11-13 Fernando Perez <fperez@colorado.edu>
4812 2001-11-13 Fernando Perez <fperez@colorado.edu>
4788
4813
4789 * Reinstated the raw_input/prefilter separation that Janko had
4814 * Reinstated the raw_input/prefilter separation that Janko had
4790 initially. This gives a more convenient setup for extending the
4815 initially. This gives a more convenient setup for extending the
4791 pre-processor from the outside: raw_input always gets a string,
4816 pre-processor from the outside: raw_input always gets a string,
4792 and prefilter has to process it. We can then redefine prefilter
4817 and prefilter has to process it. We can then redefine prefilter
4793 from the outside and implement extensions for special
4818 from the outside and implement extensions for special
4794 purposes.
4819 purposes.
4795
4820
4796 Today I got one for inputting PhysicalQuantity objects
4821 Today I got one for inputting PhysicalQuantity objects
4797 (from Scientific) without needing any function calls at
4822 (from Scientific) without needing any function calls at
4798 all. Extremely convenient, and it's all done as a user-level
4823 all. Extremely convenient, and it's all done as a user-level
4799 extension (no IPython code was touched). Now instead of:
4824 extension (no IPython code was touched). Now instead of:
4800 a = PhysicalQuantity(4.2,'m/s**2')
4825 a = PhysicalQuantity(4.2,'m/s**2')
4801 one can simply say
4826 one can simply say
4802 a = 4.2 m/s**2
4827 a = 4.2 m/s**2
4803 or even
4828 or even
4804 a = 4.2 m/s^2
4829 a = 4.2 m/s^2
4805
4830
4806 I use this, but it's also a proof of concept: IPython really is
4831 I use this, but it's also a proof of concept: IPython really is
4807 fully user-extensible, even at the level of the parsing of the
4832 fully user-extensible, even at the level of the parsing of the
4808 command line. It's not trivial, but it's perfectly doable.
4833 command line. It's not trivial, but it's perfectly doable.
4809
4834
4810 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4835 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4811 the problem of modules being loaded in the inverse order in which
4836 the problem of modules being loaded in the inverse order in which
4812 they were defined in
4837 they were defined in
4813
4838
4814 * Version 0.1.8 released, 0.1.9 opened for further work.
4839 * Version 0.1.8 released, 0.1.9 opened for further work.
4815
4840
4816 * Added magics pdef, source and file. They respectively show the
4841 * Added magics pdef, source and file. They respectively show the
4817 definition line ('prototype' in C), source code and full python
4842 definition line ('prototype' in C), source code and full python
4818 file for any callable object. The object inspector oinfo uses
4843 file for any callable object. The object inspector oinfo uses
4819 these to show the same information.
4844 these to show the same information.
4820
4845
4821 * Version 0.1.7 released, 0.1.8 opened for further work.
4846 * Version 0.1.7 released, 0.1.8 opened for further work.
4822
4847
4823 * Separated all the magic functions into a class called Magic. The
4848 * Separated all the magic functions into a class called Magic. The
4824 InteractiveShell class was becoming too big for Xemacs to handle
4849 InteractiveShell class was becoming too big for Xemacs to handle
4825 (de-indenting a line would lock it up for 10 seconds while it
4850 (de-indenting a line would lock it up for 10 seconds while it
4826 backtracked on the whole class!)
4851 backtracked on the whole class!)
4827
4852
4828 FIXME: didn't work. It can be done, but right now namespaces are
4853 FIXME: didn't work. It can be done, but right now namespaces are
4829 all messed up. Do it later (reverted it for now, so at least
4854 all messed up. Do it later (reverted it for now, so at least
4830 everything works as before).
4855 everything works as before).
4831
4856
4832 * Got the object introspection system (magic_oinfo) working! I
4857 * Got the object introspection system (magic_oinfo) working! I
4833 think this is pretty much ready for release to Janko, so he can
4858 think this is pretty much ready for release to Janko, so he can
4834 test it for a while and then announce it. Pretty much 100% of what
4859 test it for a while and then announce it. Pretty much 100% of what
4835 I wanted for the 'phase 1' release is ready. Happy, tired.
4860 I wanted for the 'phase 1' release is ready. Happy, tired.
4836
4861
4837 2001-11-12 Fernando Perez <fperez@colorado.edu>
4862 2001-11-12 Fernando Perez <fperez@colorado.edu>
4838
4863
4839 * Version 0.1.6 released, 0.1.7 opened for further work.
4864 * Version 0.1.6 released, 0.1.7 opened for further work.
4840
4865
4841 * Fixed bug in printing: it used to test for truth before
4866 * Fixed bug in printing: it used to test for truth before
4842 printing, so 0 wouldn't print. Now checks for None.
4867 printing, so 0 wouldn't print. Now checks for None.
4843
4868
4844 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4869 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4845 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4870 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4846 reaches by hand into the outputcache. Think of a better way to do
4871 reaches by hand into the outputcache. Think of a better way to do
4847 this later.
4872 this later.
4848
4873
4849 * Various small fixes thanks to Nathan's comments.
4874 * Various small fixes thanks to Nathan's comments.
4850
4875
4851 * Changed magic_pprint to magic_Pprint. This way it doesn't
4876 * Changed magic_pprint to magic_Pprint. This way it doesn't
4852 collide with pprint() and the name is consistent with the command
4877 collide with pprint() and the name is consistent with the command
4853 line option.
4878 line option.
4854
4879
4855 * Changed prompt counter behavior to be fully like
4880 * Changed prompt counter behavior to be fully like
4856 Mathematica's. That is, even input that doesn't return a result
4881 Mathematica's. That is, even input that doesn't return a result
4857 raises the prompt counter. The old behavior was kind of confusing
4882 raises the prompt counter. The old behavior was kind of confusing
4858 (getting the same prompt number several times if the operation
4883 (getting the same prompt number several times if the operation
4859 didn't return a result).
4884 didn't return a result).
4860
4885
4861 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4886 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4862
4887
4863 * Fixed -Classic mode (wasn't working anymore).
4888 * Fixed -Classic mode (wasn't working anymore).
4864
4889
4865 * Added colored prompts using Nathan's new code. Colors are
4890 * Added colored prompts using Nathan's new code. Colors are
4866 currently hardwired, they can be user-configurable. For
4891 currently hardwired, they can be user-configurable. For
4867 developers, they can be chosen in file ipythonlib.py, at the
4892 developers, they can be chosen in file ipythonlib.py, at the
4868 beginning of the CachedOutput class def.
4893 beginning of the CachedOutput class def.
4869
4894
4870 2001-11-11 Fernando Perez <fperez@colorado.edu>
4895 2001-11-11 Fernando Perez <fperez@colorado.edu>
4871
4896
4872 * Version 0.1.5 released, 0.1.6 opened for further work.
4897 * Version 0.1.5 released, 0.1.6 opened for further work.
4873
4898
4874 * Changed magic_env to *return* the environment as a dict (not to
4899 * Changed magic_env to *return* the environment as a dict (not to
4875 print it). This way it prints, but it can also be processed.
4900 print it). This way it prints, but it can also be processed.
4876
4901
4877 * Added Verbose exception reporting to interactive
4902 * Added Verbose exception reporting to interactive
4878 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4903 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4879 traceback. Had to make some changes to the ultraTB file. This is
4904 traceback. Had to make some changes to the ultraTB file. This is
4880 probably the last 'big' thing in my mental todo list. This ties
4905 probably the last 'big' thing in my mental todo list. This ties
4881 in with the next entry:
4906 in with the next entry:
4882
4907
4883 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4908 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4884 has to specify is Plain, Color or Verbose for all exception
4909 has to specify is Plain, Color or Verbose for all exception
4885 handling.
4910 handling.
4886
4911
4887 * Removed ShellServices option. All this can really be done via
4912 * Removed ShellServices option. All this can really be done via
4888 the magic system. It's easier to extend, cleaner and has automatic
4913 the magic system. It's easier to extend, cleaner and has automatic
4889 namespace protection and documentation.
4914 namespace protection and documentation.
4890
4915
4891 2001-11-09 Fernando Perez <fperez@colorado.edu>
4916 2001-11-09 Fernando Perez <fperez@colorado.edu>
4892
4917
4893 * Fixed bug in output cache flushing (missing parameter to
4918 * Fixed bug in output cache flushing (missing parameter to
4894 __init__). Other small bugs fixed (found using pychecker).
4919 __init__). Other small bugs fixed (found using pychecker).
4895
4920
4896 * Version 0.1.4 opened for bugfixing.
4921 * Version 0.1.4 opened for bugfixing.
4897
4922
4898 2001-11-07 Fernando Perez <fperez@colorado.edu>
4923 2001-11-07 Fernando Perez <fperez@colorado.edu>
4899
4924
4900 * Version 0.1.3 released, mainly because of the raw_input bug.
4925 * Version 0.1.3 released, mainly because of the raw_input bug.
4901
4926
4902 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4927 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4903 and when testing for whether things were callable, a call could
4928 and when testing for whether things were callable, a call could
4904 actually be made to certain functions. They would get called again
4929 actually be made to certain functions. They would get called again
4905 once 'really' executed, with a resulting double call. A disaster
4930 once 'really' executed, with a resulting double call. A disaster
4906 in many cases (list.reverse() would never work!).
4931 in many cases (list.reverse() would never work!).
4907
4932
4908 * Removed prefilter() function, moved its code to raw_input (which
4933 * Removed prefilter() function, moved its code to raw_input (which
4909 after all was just a near-empty caller for prefilter). This saves
4934 after all was just a near-empty caller for prefilter). This saves
4910 a function call on every prompt, and simplifies the class a tiny bit.
4935 a function call on every prompt, and simplifies the class a tiny bit.
4911
4936
4912 * Fix _ip to __ip name in magic example file.
4937 * Fix _ip to __ip name in magic example file.
4913
4938
4914 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4939 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4915 work with non-gnu versions of tar.
4940 work with non-gnu versions of tar.
4916
4941
4917 2001-11-06 Fernando Perez <fperez@colorado.edu>
4942 2001-11-06 Fernando Perez <fperez@colorado.edu>
4918
4943
4919 * Version 0.1.2. Just to keep track of the recent changes.
4944 * Version 0.1.2. Just to keep track of the recent changes.
4920
4945
4921 * Fixed nasty bug in output prompt routine. It used to check 'if
4946 * Fixed nasty bug in output prompt routine. It used to check 'if
4922 arg != None...'. Problem is, this fails if arg implements a
4947 arg != None...'. Problem is, this fails if arg implements a
4923 special comparison (__cmp__) which disallows comparing to
4948 special comparison (__cmp__) which disallows comparing to
4924 None. Found it when trying to use the PhysicalQuantity module from
4949 None. Found it when trying to use the PhysicalQuantity module from
4925 ScientificPython.
4950 ScientificPython.
4926
4951
4927 2001-11-05 Fernando Perez <fperez@colorado.edu>
4952 2001-11-05 Fernando Perez <fperez@colorado.edu>
4928
4953
4929 * Also added dirs. Now the pushd/popd/dirs family functions
4954 * Also added dirs. Now the pushd/popd/dirs family functions
4930 basically like the shell, with the added convenience of going home
4955 basically like the shell, with the added convenience of going home
4931 when called with no args.
4956 when called with no args.
4932
4957
4933 * pushd/popd slightly modified to mimic shell behavior more
4958 * pushd/popd slightly modified to mimic shell behavior more
4934 closely.
4959 closely.
4935
4960
4936 * Added env,pushd,popd from ShellServices as magic functions. I
4961 * Added env,pushd,popd from ShellServices as magic functions. I
4937 think the cleanest will be to port all desired functions from
4962 think the cleanest will be to port all desired functions from
4938 ShellServices as magics and remove ShellServices altogether. This
4963 ShellServices as magics and remove ShellServices altogether. This
4939 will provide a single, clean way of adding functionality
4964 will provide a single, clean way of adding functionality
4940 (shell-type or otherwise) to IP.
4965 (shell-type or otherwise) to IP.
4941
4966
4942 2001-11-04 Fernando Perez <fperez@colorado.edu>
4967 2001-11-04 Fernando Perez <fperez@colorado.edu>
4943
4968
4944 * Added .ipython/ directory to sys.path. This way users can keep
4969 * Added .ipython/ directory to sys.path. This way users can keep
4945 customizations there and access them via import.
4970 customizations there and access them via import.
4946
4971
4947 2001-11-03 Fernando Perez <fperez@colorado.edu>
4972 2001-11-03 Fernando Perez <fperez@colorado.edu>
4948
4973
4949 * Opened version 0.1.1 for new changes.
4974 * Opened version 0.1.1 for new changes.
4950
4975
4951 * Changed version number to 0.1.0: first 'public' release, sent to
4976 * Changed version number to 0.1.0: first 'public' release, sent to
4952 Nathan and Janko.
4977 Nathan and Janko.
4953
4978
4954 * Lots of small fixes and tweaks.
4979 * Lots of small fixes and tweaks.
4955
4980
4956 * Minor changes to whos format. Now strings are shown, snipped if
4981 * Minor changes to whos format. Now strings are shown, snipped if
4957 too long.
4982 too long.
4958
4983
4959 * Changed ShellServices to work on __main__ so they show up in @who
4984 * Changed ShellServices to work on __main__ so they show up in @who
4960
4985
4961 * Help also works with ? at the end of a line:
4986 * Help also works with ? at the end of a line:
4962 ?sin and sin?
4987 ?sin and sin?
4963 both produce the same effect. This is nice, as often I use the
4988 both produce the same effect. This is nice, as often I use the
4964 tab-complete to find the name of a method, but I used to then have
4989 tab-complete to find the name of a method, but I used to then have
4965 to go to the beginning of the line to put a ? if I wanted more
4990 to go to the beginning of the line to put a ? if I wanted more
4966 info. Now I can just add the ? and hit return. Convenient.
4991 info. Now I can just add the ? and hit return. Convenient.
4967
4992
4968 2001-11-02 Fernando Perez <fperez@colorado.edu>
4993 2001-11-02 Fernando Perez <fperez@colorado.edu>
4969
4994
4970 * Python version check (>=2.1) added.
4995 * Python version check (>=2.1) added.
4971
4996
4972 * Added LazyPython documentation. At this point the docs are quite
4997 * Added LazyPython documentation. At this point the docs are quite
4973 a mess. A cleanup is in order.
4998 a mess. A cleanup is in order.
4974
4999
4975 * Auto-installer created. For some bizarre reason, the zipfiles
5000 * Auto-installer created. For some bizarre reason, the zipfiles
4976 module isn't working on my system. So I made a tar version
5001 module isn't working on my system. So I made a tar version
4977 (hopefully the command line options in various systems won't kill
5002 (hopefully the command line options in various systems won't kill
4978 me).
5003 me).
4979
5004
4980 * Fixes to Struct in genutils. Now all dictionary-like methods are
5005 * Fixes to Struct in genutils. Now all dictionary-like methods are
4981 protected (reasonably).
5006 protected (reasonably).
4982
5007
4983 * Added pager function to genutils and changed ? to print usage
5008 * Added pager function to genutils and changed ? to print usage
4984 note through it (it was too long).
5009 note through it (it was too long).
4985
5010
4986 * Added the LazyPython functionality. Works great! I changed the
5011 * Added the LazyPython functionality. Works great! I changed the
4987 auto-quote escape to ';', it's on home row and next to '. But
5012 auto-quote escape to ';', it's on home row and next to '. But
4988 both auto-quote and auto-paren (still /) escapes are command-line
5013 both auto-quote and auto-paren (still /) escapes are command-line
4989 parameters.
5014 parameters.
4990
5015
4991
5016
4992 2001-11-01 Fernando Perez <fperez@colorado.edu>
5017 2001-11-01 Fernando Perez <fperez@colorado.edu>
4993
5018
4994 * Version changed to 0.0.7. Fairly large change: configuration now
5019 * Version changed to 0.0.7. Fairly large change: configuration now
4995 is all stored in a directory, by default .ipython. There, all
5020 is all stored in a directory, by default .ipython. There, all
4996 config files have normal looking names (not .names)
5021 config files have normal looking names (not .names)
4997
5022
4998 * Version 0.0.6 Released first to Lucas and Archie as a test
5023 * Version 0.0.6 Released first to Lucas and Archie as a test
4999 run. Since it's the first 'semi-public' release, change version to
5024 run. Since it's the first 'semi-public' release, change version to
5000 > 0.0.6 for any changes now.
5025 > 0.0.6 for any changes now.
5001
5026
5002 * Stuff I had put in the ipplib.py changelog:
5027 * Stuff I had put in the ipplib.py changelog:
5003
5028
5004 Changes to InteractiveShell:
5029 Changes to InteractiveShell:
5005
5030
5006 - Made the usage message a parameter.
5031 - Made the usage message a parameter.
5007
5032
5008 - Require the name of the shell variable to be given. It's a bit
5033 - Require the name of the shell variable to be given. It's a bit
5009 of a hack, but allows the name 'shell' not to be hardwire in the
5034 of a hack, but allows the name 'shell' not to be hardwire in the
5010 magic (@) handler, which is problematic b/c it requires
5035 magic (@) handler, which is problematic b/c it requires
5011 polluting the global namespace with 'shell'. This in turn is
5036 polluting the global namespace with 'shell'. This in turn is
5012 fragile: if a user redefines a variable called shell, things
5037 fragile: if a user redefines a variable called shell, things
5013 break.
5038 break.
5014
5039
5015 - magic @: all functions available through @ need to be defined
5040 - magic @: all functions available through @ need to be defined
5016 as magic_<name>, even though they can be called simply as
5041 as magic_<name>, even though they can be called simply as
5017 @<name>. This allows the special command @magic to gather
5042 @<name>. This allows the special command @magic to gather
5018 information automatically about all existing magic functions,
5043 information automatically about all existing magic functions,
5019 even if they are run-time user extensions, by parsing the shell
5044 even if they are run-time user extensions, by parsing the shell
5020 instance __dict__ looking for special magic_ names.
5045 instance __dict__ looking for special magic_ names.
5021
5046
5022 - mainloop: added *two* local namespace parameters. This allows
5047 - mainloop: added *two* local namespace parameters. This allows
5023 the class to differentiate between parameters which were there
5048 the class to differentiate between parameters which were there
5024 before and after command line initialization was processed. This
5049 before and after command line initialization was processed. This
5025 way, later @who can show things loaded at startup by the
5050 way, later @who can show things loaded at startup by the
5026 user. This trick was necessary to make session saving/reloading
5051 user. This trick was necessary to make session saving/reloading
5027 really work: ideally after saving/exiting/reloading a session,
5052 really work: ideally after saving/exiting/reloading a session,
5028 *everythin* should look the same, including the output of @who. I
5053 *everythin* should look the same, including the output of @who. I
5029 was only able to make this work with this double namespace
5054 was only able to make this work with this double namespace
5030 trick.
5055 trick.
5031
5056
5032 - added a header to the logfile which allows (almost) full
5057 - added a header to the logfile which allows (almost) full
5033 session restoring.
5058 session restoring.
5034
5059
5035 - prepend lines beginning with @ or !, with a and log
5060 - prepend lines beginning with @ or !, with a and log
5036 them. Why? !lines: may be useful to know what you did @lines:
5061 them. Why? !lines: may be useful to know what you did @lines:
5037 they may affect session state. So when restoring a session, at
5062 they may affect session state. So when restoring a session, at
5038 least inform the user of their presence. I couldn't quite get
5063 least inform the user of their presence. I couldn't quite get
5039 them to properly re-execute, but at least the user is warned.
5064 them to properly re-execute, but at least the user is warned.
5040
5065
5041 * Started ChangeLog.
5066 * Started ChangeLog.
@@ -1,9491 +1,9505 b''
1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
2 \lyxformat 221
2 \lyxformat 221
3 \textclass article
3 \textclass article
4 \begin_preamble
4 \begin_preamble
5 %\usepackage{ae,aecompl}
5 %\usepackage{ae,aecompl}
6 \usepackage{color}
6 \usepackage{color}
7
7
8 % A few colors to replace the defaults for certain link types
8 % A few colors to replace the defaults for certain link types
9 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
9 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
10 \definecolor{darkorange}{rgb}{.71,0.21,0.01}
10 \definecolor{darkorange}{rgb}{.71,0.21,0.01}
11 \definecolor{darkred}{rgb}{.52,0.08,0.01}
11 \definecolor{darkred}{rgb}{.52,0.08,0.01}
12 \definecolor{darkgreen}{rgb}{.12,.54,.11}
12 \definecolor{darkgreen}{rgb}{.12,.54,.11}
13
13
14 % Use and configure listings package for nicely formatted code
14 % Use and configure listings package for nicely formatted code
15 \usepackage{listings}
15 \usepackage{listings}
16 \lstset{
16 \lstset{
17 language=Python,
17 language=Python,
18 basicstyle=\small\ttfamily,
18 basicstyle=\small\ttfamily,
19 commentstyle=\ttfamily\color{blue},
19 commentstyle=\ttfamily\color{blue},
20 stringstyle=\ttfamily\color{darkorange},
20 stringstyle=\ttfamily\color{darkorange},
21 showstringspaces=false,
21 showstringspaces=false,
22 breaklines=true,
22 breaklines=true,
23 postbreak = \space\dots
23 postbreak = \space\dots
24 }
24 }
25
25
26 \usepackage[%pdftex, % needed for pdflatex
26 \usepackage[%pdftex, % needed for pdflatex
27 breaklinks=true, % so long urls are correctly broken across lines
27 breaklinks=true, % so long urls are correctly broken across lines
28 colorlinks=true,
28 colorlinks=true,
29 urlcolor=blue,
29 urlcolor=blue,
30 linkcolor=darkred,
30 linkcolor=darkred,
31 citecolor=darkgreen,
31 citecolor=darkgreen,
32 ]{hyperref}
32 ]{hyperref}
33
33
34 \usepackage{html}
34 \usepackage{html}
35
35
36 % This helps prevent overly long lines that stretch beyond the margins
36 % This helps prevent overly long lines that stretch beyond the margins
37 \sloppy
37 \sloppy
38
38
39 % Define a \codelist command which either uses listings for latex, or
39 % Define a \codelist command which either uses listings for latex, or
40 % plain verbatim for html (since latex2html doesn't understand the
40 % plain verbatim for html (since latex2html doesn't understand the
41 % listings package).
41 % listings package).
42 \usepackage{verbatim}
42 \usepackage{verbatim}
43 \newcommand{\codelist}[1] {
43 \newcommand{\codelist}[1] {
44 \latex{\lstinputlisting{#1}}
44 \latex{\lstinputlisting{#1}}
45 \html{\verbatiminput{#1}}
45 \html{\verbatiminput{#1}}
46 }
46 }
47 \end_preamble
47 \end_preamble
48 \language english
48 \language english
49 \inputencoding latin1
49 \inputencoding latin1
50 \fontscheme palatino
50 \fontscheme palatino
51 \graphics default
51 \graphics default
52 \paperfontsize 11
52 \paperfontsize 11
53 \spacing single
53 \spacing single
54 \papersize Default
54 \papersize Default
55 \paperpackage a4
55 \paperpackage a4
56 \use_geometry 1
56 \use_geometry 1
57 \use_amsmath 0
57 \use_amsmath 0
58 \use_natbib 0
58 \use_natbib 0
59 \use_numerical_citations 0
59 \use_numerical_citations 0
60 \paperorientation portrait
60 \paperorientation portrait
61 \leftmargin 1in
61 \leftmargin 1in
62 \topmargin 1in
62 \topmargin 1in
63 \rightmargin 1in
63 \rightmargin 1in
64 \bottommargin 1in
64 \bottommargin 1in
65 \secnumdepth 3
65 \secnumdepth 3
66 \tocdepth 3
66 \tocdepth 3
67 \paragraph_separation skip
67 \paragraph_separation skip
68 \defskip medskip
68 \defskip medskip
69 \quotes_language english
69 \quotes_language english
70 \quotes_times 2
70 \quotes_times 2
71 \papercolumns 1
71 \papercolumns 1
72 \papersides 1
72 \papersides 2
73 \paperpagestyle fancy
73 \paperpagestyle fancy
74
74
75 \layout Title
75 \layout Title
76
76
77 IPython
77 IPython
78 \newline
78 \newline
79
79
80 \size larger
80 \size larger
81 An enhanced Interactive Python
81 An enhanced Interactive Python
82 \size large
82 \size large
83
83
84 \newline
84 \newline
85 User Manual, v.
85 User Manual, v.
86 __version__
86 __version__
87 \layout Author
87 \layout Author
88
88
89 Fernando P�rez
89 Fernando P�rez
90 \begin_inset Foot
91 collapsed true
92
93 \layout Standard
94
95
96 \size scriptsize
97 Department of Applied Mathematics, University of Colorado at Boulder.
98
99 \family typewriter
100 <Fernando.Perez@colorado.edu>
101 \end_inset
102
103
90 \layout Standard
104 \layout Standard
91
105
92
106
93 \begin_inset ERT
107 \begin_inset ERT
94 status Collapsed
108 status Collapsed
95
109
96 \layout Standard
110 \layout Standard
97
111
98 \backslash
112 \backslash
99 latex{
113 latex{
100 \end_inset
114 \end_inset
101
115
102
116
103 \begin_inset LatexCommand \tableofcontents{}
117 \begin_inset LatexCommand \tableofcontents{}
104
118
105 \end_inset
119 \end_inset
106
120
107
121
108 \begin_inset ERT
122 \begin_inset ERT
109 status Collapsed
123 status Collapsed
110
124
111 \layout Standard
125 \layout Standard
112 }
126 }
113 \end_inset
127 \end_inset
114
128
115
129
116 \layout Standard
130 \layout Standard
117
131
118
132
119 \begin_inset ERT
133 \begin_inset ERT
120 status Open
134 status Open
121
135
122 \layout Standard
136 \layout Standard
123
137
124 \backslash
138 \backslash
125 html{
139 html{
126 \backslash
140 \backslash
127 bodytext{bgcolor=#ffffff}}
141 bodytext{bgcolor=#ffffff}}
128 \end_inset
142 \end_inset
129
143
130
144
131 \layout Section
145 \layout Section
132 \pagebreak_top
146 \pagebreak_top
133 Overview
147 Overview
134 \layout Standard
148 \layout Standard
135
149
136 One of Python's most useful features is its interactive interpreter.
150 One of Python's most useful features is its interactive interpreter.
137 This system allows very fast testing of ideas without the overhead of creating
151 This system allows very fast testing of ideas without the overhead of creating
138 test files as is typical in most programming languages.
152 test files as is typical in most programming languages.
139 However, the interpreter supplied with the standard Python distribution
153 However, the interpreter supplied with the standard Python distribution
140 is somewhat limited for extended interactive use.
154 is somewhat limited for extended interactive use.
141 \layout Standard
155 \layout Standard
142
156
143 IPython is a free software project (released under the BSD license) which
157 IPython is a free software project (released under the BSD license) which
144 tries to:
158 tries to:
145 \layout Enumerate
159 \layout Enumerate
146
160
147 Provide an interactive shell superior to Python's default.
161 Provide an interactive shell superior to Python's default.
148 IPython has many features for object introspection, system shell access,
162 IPython has many features for object introspection, system shell access,
149 and its own special command system for adding functionality when working
163 and its own special command system for adding functionality when working
150 interactively.
164 interactively.
151 It tries to be a very efficient environment both for Python code development
165 It tries to be a very efficient environment both for Python code development
152 and for exploration of problems using Python objects (in situations like
166 and for exploration of problems using Python objects (in situations like
153 data analysis).
167 data analysis).
154 \layout Enumerate
168 \layout Enumerate
155
169
156 Serve as an embeddable, ready to use interpreter for your own programs.
170 Serve as an embeddable, ready to use interpreter for your own programs.
157 IPython can be started with a single call from inside another program,
171 IPython can be started with a single call from inside another program,
158 providing access to the current namespace.
172 providing access to the current namespace.
159 This can be very useful both for debugging purposes and for situations
173 This can be very useful both for debugging purposes and for situations
160 where a blend of batch-processing and interactive exploration are needed.
174 where a blend of batch-processing and interactive exploration are needed.
161 \layout Enumerate
175 \layout Enumerate
162
176
163 Offer a flexible framework which can be used as the base environment for
177 Offer a flexible framework which can be used as the base environment for
164 other systems with Python as the underlying language.
178 other systems with Python as the underlying language.
165 Specifically scientific environments like Mathematica, IDL and Matlab inspired
179 Specifically scientific environments like Mathematica, IDL and Matlab inspired
166 its design, but similar ideas can be useful in many fields.
180 its design, but similar ideas can be useful in many fields.
167 \layout Enumerate
181 \layout Enumerate
168
182
169 Allow interactive testing of threaded graphical toolkits.
183 Allow interactive testing of threaded graphical toolkits.
170 IPython has support for interactive, non-blocking control of GTK, Qt and
184 IPython has support for interactive, non-blocking control of GTK, Qt and
171 WX applications via special threading flags.
185 WX applications via special threading flags.
172 The normal Python shell can only do this for Tkinter applications.
186 The normal Python shell can only do this for Tkinter applications.
173 \layout Subsection
187 \layout Subsection
174
188
175 Main features
189 Main features
176 \layout Itemize
190 \layout Itemize
177
191
178 Dynamic object introspection.
192 Dynamic object introspection.
179 One can access docstrings, function definition prototypes, source code,
193 One can access docstrings, function definition prototypes, source code,
180 source files and other details of any object accessible to the interpreter
194 source files and other details of any object accessible to the interpreter
181 with a single keystroke (`
195 with a single keystroke (`
182 \family typewriter
196 \family typewriter
183 ?
197 ?
184 \family default
198 \family default
185 ', and using `
199 ', and using `
186 \family typewriter
200 \family typewriter
187 ??
201 ??
188 \family default
202 \family default
189 ' provides additional detail).
203 ' provides additional detail).
190 \layout Itemize
204 \layout Itemize
191
205
192 Searching through modules and namespaces with `
206 Searching through modules and namespaces with `
193 \family typewriter
207 \family typewriter
194 *
208 *
195 \family default
209 \family default
196 ' wildcards, both when using the `
210 ' wildcards, both when using the `
197 \family typewriter
211 \family typewriter
198 ?
212 ?
199 \family default
213 \family default
200 ' system and via the
214 ' system and via the
201 \family typewriter
215 \family typewriter
202 %psearch
216 %psearch
203 \family default
217 \family default
204 command.
218 command.
205 \layout Itemize
219 \layout Itemize
206
220
207 Completion in the local namespace, by typing TAB at the prompt.
221 Completion in the local namespace, by typing TAB at the prompt.
208 This works for keywords, methods, variables and files in the current directory.
222 This works for keywords, methods, variables and files in the current directory.
209 This is supported via the readline library, and full access to configuring
223 This is supported via the readline library, and full access to configuring
210 readline's behavior is provided.
224 readline's behavior is provided.
211 \layout Itemize
225 \layout Itemize
212
226
213 Numbered input/output prompts with command history (persistent across sessions
227 Numbered input/output prompts with command history (persistent across sessions
214 and tied to each profile), full searching in this history and caching of
228 and tied to each profile), full searching in this history and caching of
215 all input and output.
229 all input and output.
216 \layout Itemize
230 \layout Itemize
217
231
218 User-extensible `magic' commands.
232 User-extensible `magic' commands.
219 A set of commands prefixed with
233 A set of commands prefixed with
220 \family typewriter
234 \family typewriter
221 %
235 %
222 \family default
236 \family default
223 is available for controlling IPython itself and provides directory control,
237 is available for controlling IPython itself and provides directory control,
224 namespace information and many aliases to common system shell commands.
238 namespace information and many aliases to common system shell commands.
225 \layout Itemize
239 \layout Itemize
226
240
227 Alias facility for defining your own system aliases.
241 Alias facility for defining your own system aliases.
228 \layout Itemize
242 \layout Itemize
229
243
230 Complete system shell access.
244 Complete system shell access.
231 Lines starting with ! are passed directly to the system shell, and using
245 Lines starting with ! are passed directly to the system shell, and using
232 !! captures shell output into python variables for further use.
246 !! captures shell output into python variables for further use.
233 \layout Itemize
247 \layout Itemize
234
248
235 Background execution of Python commands in a separate thread.
249 Background execution of Python commands in a separate thread.
236 IPython has an internal job manager called
250 IPython has an internal job manager called
237 \family typewriter
251 \family typewriter
238 jobs
252 jobs
239 \family default
253 \family default
240 , and a conveninence backgrounding magic function called
254 , and a conveninence backgrounding magic function called
241 \family typewriter
255 \family typewriter
242 %bg
256 %bg
243 \family default
257 \family default
244 .
258 .
245 \layout Itemize
259 \layout Itemize
246
260
247 The ability to expand python variables when calling the system shell.
261 The ability to expand python variables when calling the system shell.
248 In a shell command, any python variable prefixed with
262 In a shell command, any python variable prefixed with
249 \family typewriter
263 \family typewriter
250 $
264 $
251 \family default
265 \family default
252 is expanded.
266 is expanded.
253 A double
267 A double
254 \family typewriter
268 \family typewriter
255 $$
269 $$
256 \family default
270 \family default
257 allows passing a literal
271 allows passing a literal
258 \family typewriter
272 \family typewriter
259 $
273 $
260 \family default
274 \family default
261 to the shell (for access to shell and environment variables like
275 to the shell (for access to shell and environment variables like
262 \family typewriter
276 \family typewriter
263 $PATH
277 $PATH
264 \family default
278 \family default
265 ).
279 ).
266 \layout Itemize
280 \layout Itemize
267
281
268 Filesystem navigation, via a magic
282 Filesystem navigation, via a magic
269 \family typewriter
283 \family typewriter
270 %cd
284 %cd
271 \family default
285 \family default
272 command, along with a persistent bookmark system (using
286 command, along with a persistent bookmark system (using
273 \family typewriter
287 \family typewriter
274 %bookmark
288 %bookmark
275 \family default
289 \family default
276 ) for fast access to frequently visited directories.
290 ) for fast access to frequently visited directories.
277 \layout Itemize
291 \layout Itemize
278
292
279 A lightweight persistence framework via the
293 A lightweight persistence framework via the
280 \family typewriter
294 \family typewriter
281 %store
295 %store
282 \family default
296 \family default
283 command, which allows you to save arbitrary Python variables.
297 command, which allows you to save arbitrary Python variables.
284 These get restored automatically when your session restarts.
298 These get restored automatically when your session restarts.
285 \layout Itemize
299 \layout Itemize
286
300
287 Automatic indentation (optional) of code as you type (through the readline
301 Automatic indentation (optional) of code as you type (through the readline
288 library).
302 library).
289 \layout Itemize
303 \layout Itemize
290
304
291 Macro system for quickly re-executing multiple lines of previous input with
305 Macro system for quickly re-executing multiple lines of previous input with
292 a single name.
306 a single name.
293 Macros can be stored persistently via
307 Macros can be stored persistently via
294 \family typewriter
308 \family typewriter
295 %store
309 %store
296 \family default
310 \family default
297 and edited via
311 and edited via
298 \family typewriter
312 \family typewriter
299 %edit
313 %edit
300 \family default
314 \family default
301 .
315 .
302
316
303 \layout Itemize
317 \layout Itemize
304
318
305 Session logging (you can then later use these logs as code in your programs).
319 Session logging (you can then later use these logs as code in your programs).
306 Logs can optionally timestamp all input, and also store session output
320 Logs can optionally timestamp all input, and also store session output
307 (marked as comments, so the log remains valid Python source code).
321 (marked as comments, so the log remains valid Python source code).
308 \layout Itemize
322 \layout Itemize
309
323
310 Session restoring: logs can be replayed to restore a previous session to
324 Session restoring: logs can be replayed to restore a previous session to
311 the state where you left it.
325 the state where you left it.
312 \layout Itemize
326 \layout Itemize
313
327
314 Verbose and colored exception traceback printouts.
328 Verbose and colored exception traceback printouts.
315 Easier to parse visually, and in verbose mode they produce a lot of useful
329 Easier to parse visually, and in verbose mode they produce a lot of useful
316 debugging information (basically a terminal version of the cgitb module).
330 debugging information (basically a terminal version of the cgitb module).
317 \layout Itemize
331 \layout Itemize
318
332
319 Auto-parentheses: callable objects can be executed without parentheses:
333 Auto-parentheses: callable objects can be executed without parentheses:
320
334
321 \family typewriter
335 \family typewriter
322 `sin 3'
336 `sin 3'
323 \family default
337 \family default
324 is automatically converted to
338 is automatically converted to
325 \family typewriter
339 \family typewriter
326 `sin(3)
340 `sin(3)
327 \family default
341 \family default
328 '.
342 '.
329 \layout Itemize
343 \layout Itemize
330
344
331 Auto-quoting: using `
345 Auto-quoting: using `
332 \family typewriter
346 \family typewriter
333 ,
347 ,
334 \family default
348 \family default
335 ' or `
349 ' or `
336 \family typewriter
350 \family typewriter
337 ;
351 ;
338 \family default
352 \family default
339 ' as the first character forces auto-quoting of the rest of the line:
353 ' as the first character forces auto-quoting of the rest of the line:
340 \family typewriter
354 \family typewriter
341 `,my_function a\SpecialChar ~
355 `,my_function a\SpecialChar ~
342 b'
356 b'
343 \family default
357 \family default
344 becomes automatically
358 becomes automatically
345 \family typewriter
359 \family typewriter
346 `my_function("a","b")'
360 `my_function("a","b")'
347 \family default
361 \family default
348 , while
362 , while
349 \family typewriter
363 \family typewriter
350 `;my_function a\SpecialChar ~
364 `;my_function a\SpecialChar ~
351 b'
365 b'
352 \family default
366 \family default
353 becomes
367 becomes
354 \family typewriter
368 \family typewriter
355 `my_function("a b")'
369 `my_function("a b")'
356 \family default
370 \family default
357 .
371 .
358 \layout Itemize
372 \layout Itemize
359
373
360 Extensible input syntax.
374 Extensible input syntax.
361 You can define filters that pre-process user input to simplify input in
375 You can define filters that pre-process user input to simplify input in
362 special situations.
376 special situations.
363 This allows for example pasting multi-line code fragments which start with
377 This allows for example pasting multi-line code fragments which start with
364
378
365 \family typewriter
379 \family typewriter
366 `>>>'
380 `>>>'
367 \family default
381 \family default
368 or
382 or
369 \family typewriter
383 \family typewriter
370 `...'
384 `...'
371 \family default
385 \family default
372 such as those from other python sessions or the standard Python documentation.
386 such as those from other python sessions or the standard Python documentation.
373 \layout Itemize
387 \layout Itemize
374
388
375 Flexible configuration system.
389 Flexible configuration system.
376 It uses a configuration file which allows permanent setting of all command-line
390 It uses a configuration file which allows permanent setting of all command-line
377 options, module loading, code and file execution.
391 options, module loading, code and file execution.
378 The system allows recursive file inclusion, so you can have a base file
392 The system allows recursive file inclusion, so you can have a base file
379 with defaults and layers which load other customizations for particular
393 with defaults and layers which load other customizations for particular
380 projects.
394 projects.
381 \layout Itemize
395 \layout Itemize
382
396
383 Embeddable.
397 Embeddable.
384 You can call IPython as a python shell inside your own python programs.
398 You can call IPython as a python shell inside your own python programs.
385 This can be used both for debugging code or for providing interactive abilities
399 This can be used both for debugging code or for providing interactive abilities
386 to your programs with knowledge about the local namespaces (very useful
400 to your programs with knowledge about the local namespaces (very useful
387 in debugging and data analysis situations).
401 in debugging and data analysis situations).
388 \layout Itemize
402 \layout Itemize
389
403
390 Easy debugger access.
404 Easy debugger access.
391 You can set IPython to call up an enhanced version of the Python debugger
405 You can set IPython to call up an enhanced version of the Python debugger
392 (
406 (
393 \family typewriter
407 \family typewriter
394 pdb
408 pdb
395 \family default
409 \family default
396 ) every time there is an uncaught exception.
410 ) every time there is an uncaught exception.
397 This drops you inside the code which triggered the exception with all the
411 This drops you inside the code which triggered the exception with all the
398 data live and it is possible to navigate the stack to rapidly isolate the
412 data live and it is possible to navigate the stack to rapidly isolate the
399 source of a bug.
413 source of a bug.
400 The
414 The
401 \family typewriter
415 \family typewriter
402 %run
416 %run
403 \family default
417 \family default
404 magic command --with the
418 magic command --with the
405 \family typewriter
419 \family typewriter
406 -d
420 -d
407 \family default
421 \family default
408 option-- can run any script under
422 option-- can run any script under
409 \family typewriter
423 \family typewriter
410 pdb
424 pdb
411 \family default
425 \family default
412 's control, automatically setting initial breakpoints for you.
426 's control, automatically setting initial breakpoints for you.
413 This version of
427 This version of
414 \family typewriter
428 \family typewriter
415 pdb
429 pdb
416 \family default
430 \family default
417 has IPython-specific improvements, including tab-completion and traceback
431 has IPython-specific improvements, including tab-completion and traceback
418 coloring support.
432 coloring support.
419 \layout Itemize
433 \layout Itemize
420
434
421 Profiler support.
435 Profiler support.
422 You can run single statements (similar to
436 You can run single statements (similar to
423 \family typewriter
437 \family typewriter
424 profile.run()
438 profile.run()
425 \family default
439 \family default
426 ) or complete programs under the profiler's control.
440 ) or complete programs under the profiler's control.
427 While this is possible with the standard
441 While this is possible with the standard
428 \family typewriter
442 \family typewriter
429 profile
443 profile
430 \family default
444 \family default
431 module, IPython wraps this functionality with magic commands (see
445 module, IPython wraps this functionality with magic commands (see
432 \family typewriter
446 \family typewriter
433 `%prun'
447 `%prun'
434 \family default
448 \family default
435 and
449 and
436 \family typewriter
450 \family typewriter
437 `%run -p
451 `%run -p
438 \family default
452 \family default
439 ') convenient for rapid interactive work.
453 ') convenient for rapid interactive work.
440 \layout Subsection
454 \layout Subsection
441
455
442 Portability and Python requirements
456 Portability and Python requirements
443 \layout Standard
457 \layout Standard
444
458
445
459
446 \series bold
460 \series bold
447 Python requirements:
461 Python requirements:
448 \series default
462 \series default
449 IPython requires with Python version 2.3 or newer.
463 IPython requires with Python version 2.3 or newer.
450 If you are still using Python 2.2 and can not upgrade, the last version
464 If you are still using Python 2.2 and can not upgrade, the last version
451 of IPython which worked with Python 2.2 was 0.6.15, so you will have to use
465 of IPython which worked with Python 2.2 was 0.6.15, so you will have to use
452 that.
466 that.
453 \layout Standard
467 \layout Standard
454
468
455 IPython is developed under
469 IPython is developed under
456 \series bold
470 \series bold
457 Linux
471 Linux
458 \series default
472 \series default
459 , but it should work in any reasonable Unix-type system (tested OK under
473 , but it should work in any reasonable Unix-type system (tested OK under
460 Solaris and the *BSD family, for which a port exists thanks to Dryice Liu).
474 Solaris and the *BSD family, for which a port exists thanks to Dryice Liu).
461 \layout Standard
475 \layout Standard
462
476
463
477
464 \series bold
478 \series bold
465 Mac OS X
479 Mac OS X
466 \series default
480 \series default
467 : it works, apparently without any problems (thanks to Jim Boyle at Lawrence
481 : it works, apparently without any problems (thanks to Jim Boyle at Lawrence
468 Livermore for the information).
482 Livermore for the information).
469 Thanks to Andrea Riciputi, Fink support is available.
483 Thanks to Andrea Riciputi, Fink support is available.
470 \layout Standard
484 \layout Standard
471
485
472
486
473 \series bold
487 \series bold
474 CygWin
488 CygWin
475 \series default
489 \series default
476 : it works mostly OK, though some users have reported problems with prompt
490 : it works mostly OK, though some users have reported problems with prompt
477 coloring.
491 coloring.
478 No satisfactory solution to this has been found so far, you may want to
492 No satisfactory solution to this has been found so far, you may want to
479 disable colors permanently in the
493 disable colors permanently in the
480 \family typewriter
494 \family typewriter
481 ipythonrc
495 ipythonrc
482 \family default
496 \family default
483 configuration file if you experience problems.
497 configuration file if you experience problems.
484 If you have proper color support under cygwin, please post to the IPython
498 If you have proper color support under cygwin, please post to the IPython
485 mailing list so this issue can be resolved for all users.
499 mailing list so this issue can be resolved for all users.
486 \layout Standard
500 \layout Standard
487
501
488
502
489 \series bold
503 \series bold
490 Windows
504 Windows
491 \series default
505 \series default
492 : it works well under Windows XP/2k, and I suspect NT should behave similarly.
506 : it works well under Windows XP/2k, and I suspect NT should behave similarly.
493 Section\SpecialChar ~
507 Section\SpecialChar ~
494
508
495 \begin_inset LatexCommand \ref{sub:Under-Windows}
509 \begin_inset LatexCommand \ref{sub:Under-Windows}
496
510
497 \end_inset
511 \end_inset
498
512
499 describes installation details for Windows, including some additional tools
513 describes installation details for Windows, including some additional tools
500 needed on this platform.
514 needed on this platform.
501 \layout Standard
515 \layout Standard
502
516
503 Windows 9x support is present, and has been reported to work fine (at least
517 Windows 9x support is present, and has been reported to work fine (at least
504 on WinME).
518 on WinME).
505 \layout Standard
519 \layout Standard
506
520
507 Note, that I have very little access to and experience with Windows development.
521 Note, that I have very little access to and experience with Windows development.
508 However, an excellent group of Win32 users (led by Ville Vainio), consistenly
522 However, an excellent group of Win32 users (led by Ville Vainio), consistenly
509 contribute bugfixes and platform-specific enhancements, so they more than
523 contribute bugfixes and platform-specific enhancements, so they more than
510 make up for my deficiencies on that front.
524 make up for my deficiencies on that front.
511 In fact, Win32 users report using IPython as a system shell (see Sec.\SpecialChar ~
525 In fact, Win32 users report using IPython as a system shell (see Sec.\SpecialChar ~
512
526
513 \begin_inset LatexCommand \ref{sec:IPython-as-shell}
527 \begin_inset LatexCommand \ref{sec:IPython-as-shell}
514
528
515 \end_inset
529 \end_inset
516
530
517 for details), as it offers a level of control and features which the default
531 for details), as it offers a level of control and features which the default
518
532
519 \family typewriter
533 \family typewriter
520 cmd.exe
534 cmd.exe
521 \family default
535 \family default
522 doesn't provide.
536 doesn't provide.
523 \layout Subsection
537 \layout Subsection
524
538
525 Location
539 Location
526 \layout Standard
540 \layout Standard
527
541
528 IPython is generously hosted at
542 IPython is generously hosted at
529 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
543 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
530
544
531 \end_inset
545 \end_inset
532
546
533 by the Enthought, Inc and the SciPy project.
547 by the Enthought, Inc and the SciPy project.
534 This site offers downloads, subversion access, mailing lists and a bug
548 This site offers downloads, subversion access, mailing lists and a bug
535 tracking system.
549 tracking system.
536 I am very grateful to Enthought (
550 I am very grateful to Enthought (
537 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
551 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
538
552
539 \end_inset
553 \end_inset
540
554
541 ) and all of the SciPy team for their contribution.
555 ) and all of the SciPy team for their contribution.
542 \layout Section
556 \layout Section
543
557
544
558
545 \begin_inset LatexCommand \label{sec:install}
559 \begin_inset LatexCommand \label{sec:install}
546
560
547 \end_inset
561 \end_inset
548
562
549 Installation
563 Installation
550 \layout Subsection
564 \layout Subsection
551
565
552 Instant instructions
566 Instant instructions
553 \layout Standard
567 \layout Standard
554
568
555 If you are of the impatient kind, under Linux/Unix simply untar/unzip the
569 If you are of the impatient kind, under Linux/Unix simply untar/unzip the
556 download, then install with
570 download, then install with
557 \family typewriter
571 \family typewriter
558 `python setup.py install'
572 `python setup.py install'
559 \family default
573 \family default
560 .
574 .
561 Under Windows, double-click on the provided
575 Under Windows, double-click on the provided
562 \family typewriter
576 \family typewriter
563 .exe
577 .exe
564 \family default
578 \family default
565 binary installer.
579 binary installer.
566 \layout Standard
580 \layout Standard
567
581
568 Then, take a look at Sections
582 Then, take a look at Sections
569 \begin_inset LatexCommand \ref{sec:good_config}
583 \begin_inset LatexCommand \ref{sec:good_config}
570
584
571 \end_inset
585 \end_inset
572
586
573 for configuring things optimally and
587 for configuring things optimally and
574 \begin_inset LatexCommand \ref{sec:quick_tips}
588 \begin_inset LatexCommand \ref{sec:quick_tips}
575
589
576 \end_inset
590 \end_inset
577
591
578 for quick tips on efficient use of IPython.
592 for quick tips on efficient use of IPython.
579 You can later refer to the rest of the manual for all the gory details.
593 You can later refer to the rest of the manual for all the gory details.
580 \layout Standard
594 \layout Standard
581
595
582 See the notes in sec.
596 See the notes in sec.
583
597
584 \begin_inset LatexCommand \ref{sec:upgrade}
598 \begin_inset LatexCommand \ref{sec:upgrade}
585
599
586 \end_inset
600 \end_inset
587
601
588 for upgrading IPython versions.
602 for upgrading IPython versions.
589 \layout Subsection
603 \layout Subsection
590
604
591 Detailed Unix instructions (Linux, Mac OS X, etc.)
605 Detailed Unix instructions (Linux, Mac OS X, etc.)
592 \layout Standard
606 \layout Standard
593
607
594 For RPM based systems, simply install the supplied package in the usual
608 For RPM based systems, simply install the supplied package in the usual
595 manner.
609 manner.
596 If you download the tar archive, the process is:
610 If you download the tar archive, the process is:
597 \layout Enumerate
611 \layout Enumerate
598
612
599 Unzip/untar the
613 Unzip/untar the
600 \family typewriter
614 \family typewriter
601 ipython-XXX.tar.gz
615 ipython-XXX.tar.gz
602 \family default
616 \family default
603 file wherever you want (
617 file wherever you want (
604 \family typewriter
618 \family typewriter
605 XXX
619 XXX
606 \family default
620 \family default
607 is the version number).
621 is the version number).
608 It will make a directory called
622 It will make a directory called
609 \family typewriter
623 \family typewriter
610 ipython-XXX.
624 ipython-XXX.
611
625
612 \family default
626 \family default
613 Change into that directory where you will find the files
627 Change into that directory where you will find the files
614 \family typewriter
628 \family typewriter
615 README
629 README
616 \family default
630 \family default
617 and
631 and
618 \family typewriter
632 \family typewriter
619 setup.py
633 setup.py
620 \family default
634 \family default
621 .
635 .
622
636
623 \family typewriter
637 \family typewriter
624 O
638 O
625 \family default
639 \family default
626 nce you've completed the installation, you can safely remove this directory.
640 nce you've completed the installation, you can safely remove this directory.
627
641
628 \layout Enumerate
642 \layout Enumerate
629
643
630 If you are installing over a previous installation of version 0.2.0 or earlier,
644 If you are installing over a previous installation of version 0.2.0 or earlier,
631 first remove your
645 first remove your
632 \family typewriter
646 \family typewriter
633 $HOME/.ipython
647 $HOME/.ipython
634 \family default
648 \family default
635 directory, since the configuration file format has changed somewhat (the
649 directory, since the configuration file format has changed somewhat (the
636 '=' were removed from all option specifications).
650 '=' were removed from all option specifications).
637 Or you can call ipython with the
651 Or you can call ipython with the
638 \family typewriter
652 \family typewriter
639 -upgrade
653 -upgrade
640 \family default
654 \family default
641 option and it will do this automatically for you.
655 option and it will do this automatically for you.
642 \layout Enumerate
656 \layout Enumerate
643
657
644 IPython uses distutils, so you can install it by simply typing at the system
658 IPython uses distutils, so you can install it by simply typing at the system
645 prompt (don't type the
659 prompt (don't type the
646 \family typewriter
660 \family typewriter
647 $
661 $
648 \family default
662 \family default
649 )
663 )
650 \newline
664 \newline
651
665
652 \family typewriter
666 \family typewriter
653 $ python setup.py install
667 $ python setup.py install
654 \family default
668 \family default
655
669
656 \newline
670 \newline
657 Note that this assumes you have root access to your machine.
671 Note that this assumes you have root access to your machine.
658 If you don't have root access or don't want IPython to go in the default
672 If you don't have root access or don't want IPython to go in the default
659 python directories, you'll need to use the
673 python directories, you'll need to use the
660 \begin_inset ERT
674 \begin_inset ERT
661 status Collapsed
675 status Collapsed
662
676
663 \layout Standard
677 \layout Standard
664
678
665 \backslash
679 \backslash
666 verb|--home|
680 verb|--home|
667 \end_inset
681 \end_inset
668
682
669 option (or
683 option (or
670 \begin_inset ERT
684 \begin_inset ERT
671 status Collapsed
685 status Collapsed
672
686
673 \layout Standard
687 \layout Standard
674
688
675 \backslash
689 \backslash
676 verb|--prefix|
690 verb|--prefix|
677 \end_inset
691 \end_inset
678
692
679 ).
693 ).
680 For example:
694 For example:
681 \newline
695 \newline
682
696
683 \begin_inset ERT
697 \begin_inset ERT
684 status Collapsed
698 status Collapsed
685
699
686 \layout Standard
700 \layout Standard
687
701
688 \backslash
702 \backslash
689 verb|$ python setup.py install --home $HOME/local|
703 verb|$ python setup.py install --home $HOME/local|
690 \end_inset
704 \end_inset
691
705
692
706
693 \newline
707 \newline
694 will install IPython into
708 will install IPython into
695 \family typewriter
709 \family typewriter
696 $HOME/local
710 $HOME/local
697 \family default
711 \family default
698 and its subdirectories (creating them if necessary).
712 and its subdirectories (creating them if necessary).
699 \newline
713 \newline
700 You can type
714 You can type
701 \newline
715 \newline
702
716
703 \begin_inset ERT
717 \begin_inset ERT
704 status Collapsed
718 status Collapsed
705
719
706 \layout Standard
720 \layout Standard
707
721
708 \backslash
722 \backslash
709 verb|$ python setup.py --help|
723 verb|$ python setup.py --help|
710 \end_inset
724 \end_inset
711
725
712
726
713 \newline
727 \newline
714 for more details.
728 for more details.
715 \newline
729 \newline
716 Note that if you change the default location for
730 Note that if you change the default location for
717 \begin_inset ERT
731 \begin_inset ERT
718 status Collapsed
732 status Collapsed
719
733
720 \layout Standard
734 \layout Standard
721
735
722 \backslash
736 \backslash
723 verb|--home|
737 verb|--home|
724 \end_inset
738 \end_inset
725
739
726 at installation, IPython may end up installed at a location which is not
740 at installation, IPython may end up installed at a location which is not
727 part of your
741 part of your
728 \family typewriter
742 \family typewriter
729 $PYTHONPATH
743 $PYTHONPATH
730 \family default
744 \family default
731 environment variable.
745 environment variable.
732 In this case, you'll need to configure this variable to include the actual
746 In this case, you'll need to configure this variable to include the actual
733 directory where the
747 directory where the
734 \family typewriter
748 \family typewriter
735 IPython/
749 IPython/
736 \family default
750 \family default
737 directory ended (typically the value you give to
751 directory ended (typically the value you give to
738 \begin_inset ERT
752 \begin_inset ERT
739 status Collapsed
753 status Collapsed
740
754
741 \layout Standard
755 \layout Standard
742
756
743 \backslash
757 \backslash
744 verb|--home|
758 verb|--home|
745 \end_inset
759 \end_inset
746
760
747 plus
761 plus
748 \family typewriter
762 \family typewriter
749 /lib/python
763 /lib/python
750 \family default
764 \family default
751 ).
765 ).
752 \layout Subsubsection
766 \layout Subsubsection
753
767
754 Mac OSX information
768 Mac OSX information
755 \layout Standard
769 \layout Standard
756
770
757 Under OSX, there is a choice you need to make.
771 Under OSX, there is a choice you need to make.
758 Apple ships its own build of Python, which lives in the core OSX filesystem
772 Apple ships its own build of Python, which lives in the core OSX filesystem
759 hierarchy.
773 hierarchy.
760 You can also manually install a separate Python, either purely by hand
774 You can also manually install a separate Python, either purely by hand
761 (typically in
775 (typically in
762 \family typewriter
776 \family typewriter
763 /usr/local
777 /usr/local
764 \family default
778 \family default
765 ) or by using Fink, which puts everything under
779 ) or by using Fink, which puts everything under
766 \family typewriter
780 \family typewriter
767 /sw
781 /sw
768 \family default
782 \family default
769 .
783 .
770 Which route to follow is a matter of personal preference, as I've seen
784 Which route to follow is a matter of personal preference, as I've seen
771 users who favor each of the approaches.
785 users who favor each of the approaches.
772 Here I will simply list the known installation issues under OSX, along
786 Here I will simply list the known installation issues under OSX, along
773 with their solutions.
787 with their solutions.
774 \layout Standard
788 \layout Standard
775
789
776 This page:
790 This page:
777 \begin_inset LatexCommand \htmlurl{http://geosci.uchicago.edu/~tobis/pylab.html}
791 \begin_inset LatexCommand \htmlurl{http://geosci.uchicago.edu/~tobis/pylab.html}
778
792
779 \end_inset
793 \end_inset
780
794
781 contains information on this topic, with additional details on how to make
795 contains information on this topic, with additional details on how to make
782 IPython and matplotlib play nicely under OSX.
796 IPython and matplotlib play nicely under OSX.
783 \layout Subsubsection*
797 \layout Subsubsection*
784
798
785 GUI problems
799 GUI problems
786 \layout Standard
800 \layout Standard
787
801
788 The following instructions apply to an install of IPython under OSX from
802 The following instructions apply to an install of IPython under OSX from
789 unpacking the
803 unpacking the
790 \family typewriter
804 \family typewriter
791 .tar.gz
805 .tar.gz
792 \family default
806 \family default
793 distribution and installing it for the default Python interpreter shipped
807 distribution and installing it for the default Python interpreter shipped
794 by Apple.
808 by Apple.
795 If you are using a fink install, fink will take care of these details for
809 If you are using a fink install, fink will take care of these details for
796 you, by installing IPython against fink's Python.
810 you, by installing IPython against fink's Python.
797 \layout Standard
811 \layout Standard
798
812
799 IPython offers various forms of support for interacting with graphical applicati
813 IPython offers various forms of support for interacting with graphical applicati
800 ons from the command line, from simple Tk apps (which are in principle always
814 ons from the command line, from simple Tk apps (which are in principle always
801 supported by Python) to interactive control of WX, Qt and GTK apps.
815 supported by Python) to interactive control of WX, Qt and GTK apps.
802 Under OSX, however, this requires that ipython is installed by calling
816 Under OSX, however, this requires that ipython is installed by calling
803 the special
817 the special
804 \family typewriter
818 \family typewriter
805 pythonw
819 pythonw
806 \family default
820 \family default
807 script at installation time, which takes care of coordinating things with
821 script at installation time, which takes care of coordinating things with
808 Apple's graphical environment.
822 Apple's graphical environment.
809 \layout Standard
823 \layout Standard
810
824
811 So when installing under OSX, it is best to use the following command:
825 So when installing under OSX, it is best to use the following command:
812 \family typewriter
826 \family typewriter
813
827
814 \newline
828 \newline
815
829
816 \family default
830 \family default
817
831
818 \begin_inset ERT
832 \begin_inset ERT
819 status Collapsed
833 status Collapsed
820
834
821 \layout Standard
835 \layout Standard
822
836
823 \backslash
837 \backslash
824 verb| $ sudo pythonw setup.py install --install-scripts=/usr/local/bin|
838 verb| $ sudo pythonw setup.py install --install-scripts=/usr/local/bin|
825 \end_inset
839 \end_inset
826
840
827
841
828 \newline
842 \newline
829 or
843 or
830 \newline
844 \newline
831
845
832 \begin_inset ERT
846 \begin_inset ERT
833 status Collapsed
847 status Collapsed
834
848
835 \layout Standard
849 \layout Standard
836
850
837 \backslash
851 \backslash
838 verb| $ sudo pythonw setup.py install --install-scripts=/usr/bin|
852 verb| $ sudo pythonw setup.py install --install-scripts=/usr/bin|
839 \end_inset
853 \end_inset
840
854
841
855
842 \newline
856 \newline
843 depending on where you like to keep hand-installed executables.
857 depending on where you like to keep hand-installed executables.
844 \layout Standard
858 \layout Standard
845
859
846 The resulting script will have an appropriate shebang line (the first line
860 The resulting script will have an appropriate shebang line (the first line
847 in the script whic begins with
861 in the script whic begins with
848 \family typewriter
862 \family typewriter
849 #!...
863 #!...
850 \family default
864 \family default
851 ) such that the ipython interpreter can interact with the OS X GUI.
865 ) such that the ipython interpreter can interact with the OS X GUI.
852 If the installed version does not work and has a shebang line that points
866 If the installed version does not work and has a shebang line that points
853 to, for example, just
867 to, for example, just
854 \family typewriter
868 \family typewriter
855 /usr/bin/python
869 /usr/bin/python
856 \family default
870 \family default
857 , then you might have a stale, cached version in your
871 , then you might have a stale, cached version in your
858 \family typewriter
872 \family typewriter
859 build/scripts-<python-version>
873 build/scripts-<python-version>
860 \family default
874 \family default
861 directory.
875 directory.
862 Delete that directory and rerun the
876 Delete that directory and rerun the
863 \family typewriter
877 \family typewriter
864 setup.py
878 setup.py
865 \family default
879 \family default
866 .
880 .
867
881
868 \layout Standard
882 \layout Standard
869
883
870 It is also a good idea to use the special flag
884 It is also a good idea to use the special flag
871 \begin_inset ERT
885 \begin_inset ERT
872 status Collapsed
886 status Collapsed
873
887
874 \layout Standard
888 \layout Standard
875
889
876 \backslash
890 \backslash
877 verb|--install-scripts|
891 verb|--install-scripts|
878 \end_inset
892 \end_inset
879
893
880 as indicated above, to ensure that the ipython scripts end up in a location
894 as indicated above, to ensure that the ipython scripts end up in a location
881 which is part of your
895 which is part of your
882 \family typewriter
896 \family typewriter
883 $PATH
897 $PATH
884 \family default
898 \family default
885 .
899 .
886 Otherwise Apple's Python will put the scripts in an internal directory
900 Otherwise Apple's Python will put the scripts in an internal directory
887 not available by default at the command line (if you use
901 not available by default at the command line (if you use
888 \family typewriter
902 \family typewriter
889 /usr/local/bin
903 /usr/local/bin
890 \family default
904 \family default
891 , you need to make sure this is in your
905 , you need to make sure this is in your
892 \family typewriter
906 \family typewriter
893 $PATH
907 $PATH
894 \family default
908 \family default
895 , which may not be true by default).
909 , which may not be true by default).
896 \layout Subsubsection*
910 \layout Subsubsection*
897
911
898 Readline problems
912 Readline problems
899 \layout Standard
913 \layout Standard
900
914
901 By default, the Python version shipped by Apple does
915 By default, the Python version shipped by Apple does
902 \emph on
916 \emph on
903 not
917 not
904 \emph default
918 \emph default
905 include the readline library, so central to IPython's behavior.
919 include the readline library, so central to IPython's behavior.
906 If you install IPython against Apple's Python, you will not have arrow
920 If you install IPython against Apple's Python, you will not have arrow
907 keys, tab completion, etc.
921 keys, tab completion, etc.
908 For Mac OSX 10.3 (Panther), you can find a prebuilt readline library here:
922 For Mac OSX 10.3 (Panther), you can find a prebuilt readline library here:
909 \newline
923 \newline
910
924
911 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip}
925 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip}
912
926
913 \end_inset
927 \end_inset
914
928
915
929
916 \layout Standard
930 \layout Standard
917
931
918 If you are using OSX 10.4 (Tiger), after installing this package you need
932 If you are using OSX 10.4 (Tiger), after installing this package you need
919 to either:
933 to either:
920 \layout Enumerate
934 \layout Enumerate
921
935
922 move
936 move
923 \family typewriter
937 \family typewriter
924 readline.so
938 readline.so
925 \family default
939 \family default
926 from
940 from
927 \family typewriter
941 \family typewriter
928 /Library/Python/2.3
942 /Library/Python/2.3
929 \family default
943 \family default
930 to
944 to
931 \family typewriter
945 \family typewriter
932 /Library/Python/2.3/site-packages
946 /Library/Python/2.3/site-packages
933 \family default
947 \family default
934 , or
948 , or
935 \layout Enumerate
949 \layout Enumerate
936
950
937 install
951 install
938 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/TigerPython23Compat.pkg.zip}
952 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/TigerPython23Compat.pkg.zip}
939
953
940 \end_inset
954 \end_inset
941
955
942
956
943 \layout Standard
957 \layout Standard
944
958
945 Users installing against Fink's Python or a properly hand-built one should
959 Users installing against Fink's Python or a properly hand-built one should
946 not have this problem.
960 not have this problem.
947 \layout Subsubsection*
961 \layout Subsubsection*
948
962
949 DarwinPorts
963 DarwinPorts
950 \layout Standard
964 \layout Standard
951
965
952 I report here a message from an OSX user, who suggests an alternative means
966 I report here a message from an OSX user, who suggests an alternative means
953 of using IPython under this operating system with good results.
967 of using IPython under this operating system with good results.
954 Please let me know of any updates that may be useful for this section.
968 Please let me know of any updates that may be useful for this section.
955 His message is reproduced verbatim below:
969 His message is reproduced verbatim below:
956 \layout Quote
970 \layout Quote
957
971
958 From: Markus Banfi
972 From: Markus Banfi
959 \family typewriter
973 \family typewriter
960 <markus.banfi-AT-mospheira.net>
974 <markus.banfi-AT-mospheira.net>
961 \layout Quote
975 \layout Quote
962
976
963 As a MacOS X (10.4.2) user I prefer to install software using DawinPorts instead
977 As a MacOS X (10.4.2) user I prefer to install software using DawinPorts instead
964 of Fink.
978 of Fink.
965 I had no problems installing ipython with DarwinPorts.
979 I had no problems installing ipython with DarwinPorts.
966 It's just:
980 It's just:
967 \layout Quote
981 \layout Quote
968
982
969
983
970 \family typewriter
984 \family typewriter
971 sudo port install py-ipython
985 sudo port install py-ipython
972 \layout Quote
986 \layout Quote
973
987
974 It automatically resolved all dependencies (python24, readline, py-readline).
988 It automatically resolved all dependencies (python24, readline, py-readline).
975 So far I did not encounter any problems with the DarwinPorts port of ipython.
989 So far I did not encounter any problems with the DarwinPorts port of ipython.
976
990
977 \layout Subsection
991 \layout Subsection
978
992
979
993
980 \begin_inset LatexCommand \label{sub:Under-Windows}
994 \begin_inset LatexCommand \label{sub:Under-Windows}
981
995
982 \end_inset
996 \end_inset
983
997
984 Windows instructions
998 Windows instructions
985 \layout Standard
999 \layout Standard
986
1000
987 Some of IPython's very useful features are:
1001 Some of IPython's very useful features are:
988 \layout Itemize
1002 \layout Itemize
989
1003
990 Integrated readline support (Tab-based file, object and attribute completion,
1004 Integrated readline support (Tab-based file, object and attribute completion,
991 input history across sessions, editable command line, etc.)
1005 input history across sessions, editable command line, etc.)
992 \layout Itemize
1006 \layout Itemize
993
1007
994 Coloring of prompts, code and tracebacks.
1008 Coloring of prompts, code and tracebacks.
995 \layout Standard
1009 \layout Standard
996
1010
997 These, by default, are only available under Unix-like operating systems.
1011 These, by default, are only available under Unix-like operating systems.
998 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
1012 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
999 from them.
1013 from them.
1000 His readline library implements both GNU readline functionality and color
1014 His readline library implements both GNU readline functionality and color
1001 support, so that IPython under Windows XP/2k can be as friendly and powerful
1015 support, so that IPython under Windows XP/2k can be as friendly and powerful
1002 as under Unix-like environments.
1016 as under Unix-like environments.
1003 \layout Standard
1017 \layout Standard
1004
1018
1005 The
1019 The
1006 \family typewriter
1020 \family typewriter
1007 readline
1021 readline
1008 \family default
1022 \family default
1009 extension needs two other libraries to work, so in all you need:
1023 extension needs two other libraries to work, so in all you need:
1010 \layout Enumerate
1024 \layout Enumerate
1011
1025
1012
1026
1013 \family typewriter
1027 \family typewriter
1014 PyWin32
1028 PyWin32
1015 \family default
1029 \family default
1016 from
1030 from
1017 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
1031 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
1018
1032
1019 \end_inset
1033 \end_inset
1020
1034
1021 .
1035 .
1022 \layout Enumerate
1036 \layout Enumerate
1023
1037
1024
1038
1025 \family typewriter
1039 \family typewriter
1026 CTypes
1040 CTypes
1027 \family default
1041 \family default
1028 from
1042 from
1029 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
1043 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
1030
1044
1031 \end_inset
1045 \end_inset
1032
1046
1033 (you
1047 (you
1034 \emph on
1048 \emph on
1035 must
1049 must
1036 \emph default
1050 \emph default
1037 use version 0.9.1 or newer).
1051 use version 0.9.1 or newer).
1038 \layout Enumerate
1052 \layout Enumerate
1039
1053
1040
1054
1041 \family typewriter
1055 \family typewriter
1042 Readline
1056 Readline
1043 \family default
1057 \family default
1044 for Windows from
1058 for Windows from
1045 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
1059 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
1046
1060
1047 \end_inset
1061 \end_inset
1048
1062
1049 .
1063 .
1050 \layout Standard
1064 \layout Standard
1051
1065
1052
1066
1053 \series bold
1067 \series bold
1054 Warning about a broken readline-like library:
1068 Warning about a broken readline-like library:
1055 \series default
1069 \series default
1056 several users have reported problems stemming from using the pseudo-readline
1070 several users have reported problems stemming from using the pseudo-readline
1057 library at
1071 library at
1058 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1072 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1059
1073
1060 \end_inset
1074 \end_inset
1061
1075
1062 .
1076 .
1063 This is a broken library which, while called readline, only implements
1077 This is a broken library which, while called readline, only implements
1064 an incomplete subset of the readline API.
1078 an incomplete subset of the readline API.
1065 Since it is still called readline, it fools IPython's detection mechanisms
1079 Since it is still called readline, it fools IPython's detection mechanisms
1066 and causes unpredictable crashes later.
1080 and causes unpredictable crashes later.
1067 If you wish to use IPython under Windows, you must NOT use this library,
1081 If you wish to use IPython under Windows, you must NOT use this library,
1068 which for all purposes is (at least as of version 1.6) terminally broken.
1082 which for all purposes is (at least as of version 1.6) terminally broken.
1069 \layout Subsubsection
1083 \layout Subsubsection
1070
1084
1071 Installation procedure
1085 Installation procedure
1072 \layout Standard
1086 \layout Standard
1073
1087
1074 Once you have the above installed, from the IPython download directory grab
1088 Once you have the above installed, from the IPython download directory grab
1075 the
1089 the
1076 \family typewriter
1090 \family typewriter
1077 ipython-XXX.win32.exe
1091 ipython-XXX.win32.exe
1078 \family default
1092 \family default
1079 file, where
1093 file, where
1080 \family typewriter
1094 \family typewriter
1081 XXX
1095 XXX
1082 \family default
1096 \family default
1083 represents the version number.
1097 represents the version number.
1084 This is a regular windows executable installer, which you can simply double-cli
1098 This is a regular windows executable installer, which you can simply double-cli
1085 ck to install.
1099 ck to install.
1086 It will add an entry for IPython to your Start Menu, as well as registering
1100 It will add an entry for IPython to your Start Menu, as well as registering
1087 IPython in the Windows list of applications, so you can later uninstall
1101 IPython in the Windows list of applications, so you can later uninstall
1088 it from the Control Panel.
1102 it from the Control Panel.
1089
1103
1090 \layout Standard
1104 \layout Standard
1091
1105
1092 IPython tries to install the configuration information in a directory named
1106 IPython tries to install the configuration information in a directory named
1093
1107
1094 \family typewriter
1108 \family typewriter
1095 .ipython
1109 .ipython
1096 \family default
1110 \family default
1097 (
1111 (
1098 \family typewriter
1112 \family typewriter
1099 _ipython
1113 _ipython
1100 \family default
1114 \family default
1101 under Windows) located in your `home' directory.
1115 under Windows) located in your `home' directory.
1102 IPython sets this directory by looking for a
1116 IPython sets this directory by looking for a
1103 \family typewriter
1117 \family typewriter
1104 HOME
1118 HOME
1105 \family default
1119 \family default
1106 environment variable; if such a variable does not exist, it uses
1120 environment variable; if such a variable does not exist, it uses
1107 \family typewriter
1121 \family typewriter
1108 HOMEDRIVE
1122 HOMEDRIVE
1109 \backslash
1123 \backslash
1110 HOMEPATH
1124 HOMEPATH
1111 \family default
1125 \family default
1112 (these are always defined by Windows).
1126 (these are always defined by Windows).
1113 This typically gives something like
1127 This typically gives something like
1114 \family typewriter
1128 \family typewriter
1115 C:
1129 C:
1116 \backslash
1130 \backslash
1117 Documents and Settings
1131 Documents and Settings
1118 \backslash
1132 \backslash
1119 YourUserName
1133 YourUserName
1120 \family default
1134 \family default
1121 , but your local details may vary.
1135 , but your local details may vary.
1122 In this directory you will find all the files that configure IPython's
1136 In this directory you will find all the files that configure IPython's
1123 defaults, and you can put there your profiles and extensions.
1137 defaults, and you can put there your profiles and extensions.
1124 This directory is automatically added by IPython to
1138 This directory is automatically added by IPython to
1125 \family typewriter
1139 \family typewriter
1126 sys.path
1140 sys.path
1127 \family default
1141 \family default
1128 , so anything you place there can be found by
1142 , so anything you place there can be found by
1129 \family typewriter
1143 \family typewriter
1130 import
1144 import
1131 \family default
1145 \family default
1132 statements.
1146 statements.
1133 \layout Paragraph
1147 \layout Paragraph
1134
1148
1135 Upgrading
1149 Upgrading
1136 \layout Standard
1150 \layout Standard
1137
1151
1138 For an IPython upgrade, you should first uninstall the previous version.
1152 For an IPython upgrade, you should first uninstall the previous version.
1139 This will ensure that all files and directories (such as the documentation)
1153 This will ensure that all files and directories (such as the documentation)
1140 which carry embedded version strings in their names are properly removed.
1154 which carry embedded version strings in their names are properly removed.
1141 \layout Paragraph
1155 \layout Paragraph
1142
1156
1143 Manual installation under Win32
1157 Manual installation under Win32
1144 \layout Standard
1158 \layout Standard
1145
1159
1146 In case the automatic installer does not work for some reason, you can download
1160 In case the automatic installer does not work for some reason, you can download
1147 the
1161 the
1148 \family typewriter
1162 \family typewriter
1149 ipython-XXX.tar.gz
1163 ipython-XXX.tar.gz
1150 \family default
1164 \family default
1151 file, which contains the full IPython source distribution (the popular
1165 file, which contains the full IPython source distribution (the popular
1152 WinZip can read
1166 WinZip can read
1153 \family typewriter
1167 \family typewriter
1154 .tar.gz
1168 .tar.gz
1155 \family default
1169 \family default
1156 files).
1170 files).
1157 After uncompressing the archive, you can install it at a command terminal
1171 After uncompressing the archive, you can install it at a command terminal
1158 just like any other Python module, by using
1172 just like any other Python module, by using
1159 \family typewriter
1173 \family typewriter
1160 `python setup.py install'
1174 `python setup.py install'
1161 \family default
1175 \family default
1162 .
1176 .
1163
1177
1164 \layout Standard
1178 \layout Standard
1165
1179
1166 After the installation, run the supplied
1180 After the installation, run the supplied
1167 \family typewriter
1181 \family typewriter
1168 win32_manual_post_install.py
1182 win32_manual_post_install.py
1169 \family default
1183 \family default
1170 script, which creates the necessary Start Menu shortcuts for you.
1184 script, which creates the necessary Start Menu shortcuts for you.
1171 \layout Subsection
1185 \layout Subsection
1172
1186
1173
1187
1174 \begin_inset LatexCommand \label{sec:upgrade}
1188 \begin_inset LatexCommand \label{sec:upgrade}
1175
1189
1176 \end_inset
1190 \end_inset
1177
1191
1178 Upgrading from a previous version
1192 Upgrading from a previous version
1179 \layout Standard
1193 \layout Standard
1180
1194
1181 If you are upgrading from a previous version of IPython, after doing the
1195 If you are upgrading from a previous version of IPython, after doing the
1182 routine installation described above, you should call IPython with the
1196 routine installation described above, you should call IPython with the
1183
1197
1184 \family typewriter
1198 \family typewriter
1185 -upgrade
1199 -upgrade
1186 \family default
1200 \family default
1187 option the first time you run your new copy.
1201 option the first time you run your new copy.
1188 This will automatically update your configuration directory while preserving
1202 This will automatically update your configuration directory while preserving
1189 copies of your old files.
1203 copies of your old files.
1190 You can then later merge back any personal customizations you may have
1204 You can then later merge back any personal customizations you may have
1191 made into the new files.
1205 made into the new files.
1192 It is a good idea to do this as there may be new options available in the
1206 It is a good idea to do this as there may be new options available in the
1193 new configuration files which you will not have.
1207 new configuration files which you will not have.
1194 \layout Standard
1208 \layout Standard
1195
1209
1196 Under Windows, if you don't know how to call python scripts with arguments
1210 Under Windows, if you don't know how to call python scripts with arguments
1197 from a command line, simply delete the old config directory and IPython
1211 from a command line, simply delete the old config directory and IPython
1198 will make a new one.
1212 will make a new one.
1199 Win2k and WinXP users will find it in
1213 Win2k and WinXP users will find it in
1200 \family typewriter
1214 \family typewriter
1201 C:
1215 C:
1202 \backslash
1216 \backslash
1203 Documents and Settings
1217 Documents and Settings
1204 \backslash
1218 \backslash
1205 YourUserName
1219 YourUserName
1206 \backslash
1220 \backslash
1207 _ipython
1221 _ipython
1208 \family default
1222 \family default
1209 , and Win 9x users under
1223 , and Win 9x users under
1210 \family typewriter
1224 \family typewriter
1211 C:
1225 C:
1212 \backslash
1226 \backslash
1213 Program Files
1227 Program Files
1214 \backslash
1228 \backslash
1215 IPython
1229 IPython
1216 \backslash
1230 \backslash
1217 _ipython.
1231 _ipython.
1218 \layout Section
1232 \layout Section
1219
1233
1220
1234
1221 \begin_inset LatexCommand \label{sec:good_config}
1235 \begin_inset LatexCommand \label{sec:good_config}
1222
1236
1223 \end_inset
1237 \end_inset
1224
1238
1225
1239
1226 \begin_inset OptArg
1240 \begin_inset OptArg
1227 collapsed true
1241 collapsed true
1228
1242
1229 \layout Standard
1243 \layout Standard
1230
1244
1231 Initial configuration
1245 Initial configuration
1232 \begin_inset ERT
1246 \begin_inset ERT
1233 status Collapsed
1247 status Collapsed
1234
1248
1235 \layout Standard
1249 \layout Standard
1236
1250
1237 \backslash
1251 \backslash
1238 ldots
1252 ldots
1239 \end_inset
1253 \end_inset
1240
1254
1241
1255
1242 \end_inset
1256 \end_inset
1243
1257
1244 Initial configuration of your environment
1258 Initial configuration of your environment
1245 \layout Standard
1259 \layout Standard
1246
1260
1247 This section will help you set various things in your environment for your
1261 This section will help you set various things in your environment for your
1248 IPython sessions to be as efficient as possible.
1262 IPython sessions to be as efficient as possible.
1249 All of IPython's configuration information, along with several example
1263 All of IPython's configuration information, along with several example
1250 files, is stored in a directory named by default
1264 files, is stored in a directory named by default
1251 \family typewriter
1265 \family typewriter
1252 $HOME/.ipython
1266 $HOME/.ipython
1253 \family default
1267 \family default
1254 .
1268 .
1255 You can change this by defining the environment variable
1269 You can change this by defining the environment variable
1256 \family typewriter
1270 \family typewriter
1257 IPYTHONDIR
1271 IPYTHONDIR
1258 \family default
1272 \family default
1259 , or at runtime with the command line option
1273 , or at runtime with the command line option
1260 \family typewriter
1274 \family typewriter
1261 -ipythondir
1275 -ipythondir
1262 \family default
1276 \family default
1263 .
1277 .
1264 \layout Standard
1278 \layout Standard
1265
1279
1266 If all goes well, the first time you run IPython it should automatically
1280 If all goes well, the first time you run IPython it should automatically
1267 create a user copy of the config directory for you, based on its builtin
1281 create a user copy of the config directory for you, based on its builtin
1268 defaults.
1282 defaults.
1269 You can look at the files it creates to learn more about configuring the
1283 You can look at the files it creates to learn more about configuring the
1270 system.
1284 system.
1271 The main file you will modify to configure IPython's behavior is called
1285 The main file you will modify to configure IPython's behavior is called
1272
1286
1273 \family typewriter
1287 \family typewriter
1274 ipythonrc
1288 ipythonrc
1275 \family default
1289 \family default
1276 (with a
1290 (with a
1277 \family typewriter
1291 \family typewriter
1278 .ini
1292 .ini
1279 \family default
1293 \family default
1280 extension under Windows), included for reference in Sec.
1294 extension under Windows), included for reference in Sec.
1281
1295
1282 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1296 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1283
1297
1284 \end_inset
1298 \end_inset
1285
1299
1286 .
1300 .
1287 This file is very commented and has many variables you can change to suit
1301 This file is very commented and has many variables you can change to suit
1288 your taste, you can find more details in Sec.
1302 your taste, you can find more details in Sec.
1289
1303
1290 \begin_inset LatexCommand \ref{sec:customization}
1304 \begin_inset LatexCommand \ref{sec:customization}
1291
1305
1292 \end_inset
1306 \end_inset
1293
1307
1294 .
1308 .
1295 Here we discuss the basic things you will want to make sure things are
1309 Here we discuss the basic things you will want to make sure things are
1296 working properly from the beginning.
1310 working properly from the beginning.
1297 \layout Subsection
1311 \layout Subsection
1298
1312
1299
1313
1300 \begin_inset LatexCommand \label{sec:help-access}
1314 \begin_inset LatexCommand \label{sec:help-access}
1301
1315
1302 \end_inset
1316 \end_inset
1303
1317
1304 Access to the Python help system
1318 Access to the Python help system
1305 \layout Standard
1319 \layout Standard
1306
1320
1307 This is true for Python in general (not just for IPython): you should have
1321 This is true for Python in general (not just for IPython): you should have
1308 an environment variable called
1322 an environment variable called
1309 \family typewriter
1323 \family typewriter
1310 PYTHONDOCS
1324 PYTHONDOCS
1311 \family default
1325 \family default
1312 pointing to the directory where your HTML Python documentation lives.
1326 pointing to the directory where your HTML Python documentation lives.
1313 In my system it's
1327 In my system it's
1314 \family typewriter
1328 \family typewriter
1315 /usr/share/doc/python-docs-2.3.4/html
1329 /usr/share/doc/python-docs-2.3.4/html
1316 \family default
1330 \family default
1317 , check your local details or ask your systems administrator.
1331 , check your local details or ask your systems administrator.
1318
1332
1319 \layout Standard
1333 \layout Standard
1320
1334
1321 This is the directory which holds the HTML version of the Python manuals.
1335 This is the directory which holds the HTML version of the Python manuals.
1322 Unfortunately it seems that different Linux distributions package these
1336 Unfortunately it seems that different Linux distributions package these
1323 files differently, so you may have to look around a bit.
1337 files differently, so you may have to look around a bit.
1324 Below I show the contents of this directory on my system for reference:
1338 Below I show the contents of this directory on my system for reference:
1325 \layout Standard
1339 \layout Standard
1326
1340
1327
1341
1328 \family typewriter
1342 \family typewriter
1329 [html]> ls
1343 [html]> ls
1330 \newline
1344 \newline
1331 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1345 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1332 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1346 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1333 \layout Standard
1347 \layout Standard
1334
1348
1335 You should really make sure this variable is correctly set so that Python's
1349 You should really make sure this variable is correctly set so that Python's
1336 pydoc-based help system works.
1350 pydoc-based help system works.
1337 It is a powerful and convenient system with full access to the Python manuals
1351 It is a powerful and convenient system with full access to the Python manuals
1338 and all modules accessible to you.
1352 and all modules accessible to you.
1339 \layout Standard
1353 \layout Standard
1340
1354
1341 Under Windows it seems that pydoc finds the documentation automatically,
1355 Under Windows it seems that pydoc finds the documentation automatically,
1342 so no extra setup appears necessary.
1356 so no extra setup appears necessary.
1343 \layout Subsection
1357 \layout Subsection
1344
1358
1345 Editor
1359 Editor
1346 \layout Standard
1360 \layout Standard
1347
1361
1348 The
1362 The
1349 \family typewriter
1363 \family typewriter
1350 %edit
1364 %edit
1351 \family default
1365 \family default
1352 command (and its alias
1366 command (and its alias
1353 \family typewriter
1367 \family typewriter
1354 %ed
1368 %ed
1355 \family default
1369 \family default
1356 ) will invoke the editor set in your environment as
1370 ) will invoke the editor set in your environment as
1357 \family typewriter
1371 \family typewriter
1358 EDITOR
1372 EDITOR
1359 \family default
1373 \family default
1360 .
1374 .
1361 If this variable is not set, it will default to
1375 If this variable is not set, it will default to
1362 \family typewriter
1376 \family typewriter
1363 vi
1377 vi
1364 \family default
1378 \family default
1365 under Linux/Unix and to
1379 under Linux/Unix and to
1366 \family typewriter
1380 \family typewriter
1367 notepad
1381 notepad
1368 \family default
1382 \family default
1369 under Windows.
1383 under Windows.
1370 You may want to set this variable properly and to a lightweight editor
1384 You may want to set this variable properly and to a lightweight editor
1371 which doesn't take too long to start (that is, something other than a new
1385 which doesn't take too long to start (that is, something other than a new
1372 instance of
1386 instance of
1373 \family typewriter
1387 \family typewriter
1374 Emacs
1388 Emacs
1375 \family default
1389 \family default
1376 ).
1390 ).
1377 This way you can edit multi-line code quickly and with the power of a real
1391 This way you can edit multi-line code quickly and with the power of a real
1378 editor right inside IPython.
1392 editor right inside IPython.
1379
1393
1380 \layout Standard
1394 \layout Standard
1381
1395
1382 If you are a dedicated
1396 If you are a dedicated
1383 \family typewriter
1397 \family typewriter
1384 Emacs
1398 Emacs
1385 \family default
1399 \family default
1386 user, you should set up the
1400 user, you should set up the
1387 \family typewriter
1401 \family typewriter
1388 Emacs
1402 Emacs
1389 \family default
1403 \family default
1390 server so that new requests are handled by the original process.
1404 server so that new requests are handled by the original process.
1391 This means that almost no time is spent in handling the request (assuming
1405 This means that almost no time is spent in handling the request (assuming
1392 an
1406 an
1393 \family typewriter
1407 \family typewriter
1394 Emacs
1408 Emacs
1395 \family default
1409 \family default
1396 process is already running).
1410 process is already running).
1397 For this to work, you need to set your
1411 For this to work, you need to set your
1398 \family typewriter
1412 \family typewriter
1399 EDITOR
1413 EDITOR
1400 \family default
1414 \family default
1401 environment variable to
1415 environment variable to
1402 \family typewriter
1416 \family typewriter
1403 'emacsclient'
1417 'emacsclient'
1404 \family default
1418 \family default
1405 .
1419 .
1406
1420
1407 \family typewriter
1421 \family typewriter
1408
1422
1409 \family default
1423 \family default
1410 The code below, supplied by Francois Pinard, can then be used in your
1424 The code below, supplied by Francois Pinard, can then be used in your
1411 \family typewriter
1425 \family typewriter
1412 .emacs
1426 .emacs
1413 \family default
1427 \family default
1414 file to enable the server:
1428 file to enable the server:
1415 \layout Standard
1429 \layout Standard
1416
1430
1417
1431
1418 \family typewriter
1432 \family typewriter
1419 (defvar server-buffer-clients)
1433 (defvar server-buffer-clients)
1420 \newline
1434 \newline
1421 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1435 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1422 \newline
1436 \newline
1423
1437
1424 \begin_inset ERT
1438 \begin_inset ERT
1425 status Collapsed
1439 status Collapsed
1426
1440
1427 \layout Standard
1441 \layout Standard
1428
1442
1429 \backslash
1443 \backslash
1430 hspace*{0mm}
1444 hspace*{0mm}
1431 \end_inset
1445 \end_inset
1432
1446
1433 \SpecialChar ~
1447 \SpecialChar ~
1434 \SpecialChar ~
1448 \SpecialChar ~
1435 (server-start)
1449 (server-start)
1436 \newline
1450 \newline
1437
1451
1438 \begin_inset ERT
1452 \begin_inset ERT
1439 status Collapsed
1453 status Collapsed
1440
1454
1441 \layout Standard
1455 \layout Standard
1442
1456
1443 \backslash
1457 \backslash
1444 hspace*{0mm}
1458 hspace*{0mm}
1445 \end_inset
1459 \end_inset
1446
1460
1447 \SpecialChar ~
1461 \SpecialChar ~
1448 \SpecialChar ~
1462 \SpecialChar ~
1449 (defun fp-kill-server-with-buffer-routine ()
1463 (defun fp-kill-server-with-buffer-routine ()
1450 \newline
1464 \newline
1451
1465
1452 \begin_inset ERT
1466 \begin_inset ERT
1453 status Collapsed
1467 status Collapsed
1454
1468
1455 \layout Standard
1469 \layout Standard
1456
1470
1457 \backslash
1471 \backslash
1458 hspace*{0mm}
1472 hspace*{0mm}
1459 \end_inset
1473 \end_inset
1460
1474
1461 \SpecialChar ~
1475 \SpecialChar ~
1462 \SpecialChar ~
1476 \SpecialChar ~
1463 \SpecialChar ~
1477 \SpecialChar ~
1464 \SpecialChar ~
1478 \SpecialChar ~
1465 (and server-buffer-clients (server-done)))
1479 (and server-buffer-clients (server-done)))
1466 \newline
1480 \newline
1467
1481
1468 \begin_inset ERT
1482 \begin_inset ERT
1469 status Collapsed
1483 status Collapsed
1470
1484
1471 \layout Standard
1485 \layout Standard
1472
1486
1473 \backslash
1487 \backslash
1474 hspace*{0mm}
1488 hspace*{0mm}
1475 \end_inset
1489 \end_inset
1476
1490
1477 \SpecialChar ~
1491 \SpecialChar ~
1478 \SpecialChar ~
1492 \SpecialChar ~
1479 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1493 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1480 \layout Standard
1494 \layout Standard
1481
1495
1482 You can also set the value of this editor via the commmand-line option '-
1496 You can also set the value of this editor via the commmand-line option '-
1483 \family typewriter
1497 \family typewriter
1484 editor'
1498 editor'
1485 \family default
1499 \family default
1486 or in your
1500 or in your
1487 \family typewriter
1501 \family typewriter
1488 ipythonrc
1502 ipythonrc
1489 \family default
1503 \family default
1490 file.
1504 file.
1491 This is useful if you wish to use specifically for IPython an editor different
1505 This is useful if you wish to use specifically for IPython an editor different
1492 from your typical default (and for Windows users who tend to use fewer
1506 from your typical default (and for Windows users who tend to use fewer
1493 environment variables).
1507 environment variables).
1494 \layout Subsection
1508 \layout Subsection
1495
1509
1496 Color
1510 Color
1497 \layout Standard
1511 \layout Standard
1498
1512
1499 The default IPython configuration has most bells and whistles turned on
1513 The default IPython configuration has most bells and whistles turned on
1500 (they're pretty safe).
1514 (they're pretty safe).
1501 But there's one that
1515 But there's one that
1502 \emph on
1516 \emph on
1503 may
1517 may
1504 \emph default
1518 \emph default
1505 cause problems on some systems: the use of color on screen for displaying
1519 cause problems on some systems: the use of color on screen for displaying
1506 information.
1520 information.
1507 This is very useful, since IPython can show prompts and exception tracebacks
1521 This is very useful, since IPython can show prompts and exception tracebacks
1508 with various colors, display syntax-highlighted source code, and in general
1522 with various colors, display syntax-highlighted source code, and in general
1509 make it easier to visually parse information.
1523 make it easier to visually parse information.
1510 \layout Standard
1524 \layout Standard
1511
1525
1512 The following terminals seem to handle the color sequences fine:
1526 The following terminals seem to handle the color sequences fine:
1513 \layout Itemize
1527 \layout Itemize
1514
1528
1515 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1529 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1516 \layout Itemize
1530 \layout Itemize
1517
1531
1518 CDE terminal (tested under Solaris).
1532 CDE terminal (tested under Solaris).
1519 This one boldfaces light colors.
1533 This one boldfaces light colors.
1520 \layout Itemize
1534 \layout Itemize
1521
1535
1522 (X)Emacs buffers.
1536 (X)Emacs buffers.
1523 See sec.
1537 See sec.
1524 \begin_inset LatexCommand \ref{sec:emacs}
1538 \begin_inset LatexCommand \ref{sec:emacs}
1525
1539
1526 \end_inset
1540 \end_inset
1527
1541
1528 for more details on using IPython with (X)Emacs.
1542 for more details on using IPython with (X)Emacs.
1529 \layout Itemize
1543 \layout Itemize
1530
1544
1531 A Windows (XP/2k) command prompt
1545 A Windows (XP/2k) command prompt
1532 \emph on
1546 \emph on
1533 with Gary Bishop's support extensions
1547 with Gary Bishop's support extensions
1534 \emph default
1548 \emph default
1535 .
1549 .
1536 Gary's extensions are discussed in Sec.\SpecialChar ~
1550 Gary's extensions are discussed in Sec.\SpecialChar ~
1537
1551
1538 \begin_inset LatexCommand \ref{sub:Under-Windows}
1552 \begin_inset LatexCommand \ref{sub:Under-Windows}
1539
1553
1540 \end_inset
1554 \end_inset
1541
1555
1542 .
1556 .
1543 \layout Itemize
1557 \layout Itemize
1544
1558
1545 A Windows (XP/2k) CygWin shell.
1559 A Windows (XP/2k) CygWin shell.
1546 Although some users have reported problems; it is not clear whether there
1560 Although some users have reported problems; it is not clear whether there
1547 is an issue for everyone or only under specific configurations.
1561 is an issue for everyone or only under specific configurations.
1548 If you have full color support under cygwin, please post to the IPython
1562 If you have full color support under cygwin, please post to the IPython
1549 mailing list so this issue can be resolved for all users.
1563 mailing list so this issue can be resolved for all users.
1550 \layout Standard
1564 \layout Standard
1551
1565
1552 These have shown problems:
1566 These have shown problems:
1553 \layout Itemize
1567 \layout Itemize
1554
1568
1555 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1569 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1556 or ssh.
1570 or ssh.
1557 \layout Itemize
1571 \layout Itemize
1558
1572
1559 Windows native command prompt in WinXP/2k,
1573 Windows native command prompt in WinXP/2k,
1560 \emph on
1574 \emph on
1561 without
1575 without
1562 \emph default
1576 \emph default
1563 Gary Bishop's extensions.
1577 Gary Bishop's extensions.
1564 Once Gary's readline library is installed, the normal WinXP/2k command
1578 Once Gary's readline library is installed, the normal WinXP/2k command
1565 prompt works perfectly.
1579 prompt works perfectly.
1566 \layout Standard
1580 \layout Standard
1567
1581
1568 Currently the following color schemes are available:
1582 Currently the following color schemes are available:
1569 \layout Itemize
1583 \layout Itemize
1570
1584
1571
1585
1572 \family typewriter
1586 \family typewriter
1573 NoColor
1587 NoColor
1574 \family default
1588 \family default
1575 : uses no color escapes at all (all escapes are empty
1589 : uses no color escapes at all (all escapes are empty
1576 \begin_inset Quotes eld
1590 \begin_inset Quotes eld
1577 \end_inset
1591 \end_inset
1578
1592
1579
1593
1580 \begin_inset Quotes eld
1594 \begin_inset Quotes eld
1581 \end_inset
1595 \end_inset
1582
1596
1583 strings).
1597 strings).
1584 This 'scheme' is thus fully safe to use in any terminal.
1598 This 'scheme' is thus fully safe to use in any terminal.
1585 \layout Itemize
1599 \layout Itemize
1586
1600
1587
1601
1588 \family typewriter
1602 \family typewriter
1589 Linux
1603 Linux
1590 \family default
1604 \family default
1591 : works well in Linux console type environments: dark background with light
1605 : works well in Linux console type environments: dark background with light
1592 fonts.
1606 fonts.
1593 It uses bright colors for information, so it is difficult to read if you
1607 It uses bright colors for information, so it is difficult to read if you
1594 have a light colored background.
1608 have a light colored background.
1595 \layout Itemize
1609 \layout Itemize
1596
1610
1597
1611
1598 \family typewriter
1612 \family typewriter
1599 LightBG
1613 LightBG
1600 \family default
1614 \family default
1601 : the basic colors are similar to those in the
1615 : the basic colors are similar to those in the
1602 \family typewriter
1616 \family typewriter
1603 Linux
1617 Linux
1604 \family default
1618 \family default
1605 scheme but darker.
1619 scheme but darker.
1606 It is easy to read in terminals with light backgrounds.
1620 It is easy to read in terminals with light backgrounds.
1607 \layout Standard
1621 \layout Standard
1608
1622
1609 IPython uses colors for two main groups of things: prompts and tracebacks
1623 IPython uses colors for two main groups of things: prompts and tracebacks
1610 which are directly printed to the terminal, and the object introspection
1624 which are directly printed to the terminal, and the object introspection
1611 system which passes large sets of data through a pager.
1625 system which passes large sets of data through a pager.
1612 \layout Subsubsection
1626 \layout Subsubsection
1613
1627
1614 Input/Output prompts and exception tracebacks
1628 Input/Output prompts and exception tracebacks
1615 \layout Standard
1629 \layout Standard
1616
1630
1617 You can test whether the colored prompts and tracebacks work on your system
1631 You can test whether the colored prompts and tracebacks work on your system
1618 interactively by typing
1632 interactively by typing
1619 \family typewriter
1633 \family typewriter
1620 '%colors Linux'
1634 '%colors Linux'
1621 \family default
1635 \family default
1622 at the prompt (use '
1636 at the prompt (use '
1623 \family typewriter
1637 \family typewriter
1624 %colors LightBG'
1638 %colors LightBG'
1625 \family default
1639 \family default
1626 if your terminal has a light background).
1640 if your terminal has a light background).
1627 If the input prompt shows garbage like:
1641 If the input prompt shows garbage like:
1628 \newline
1642 \newline
1629
1643
1630 \family typewriter
1644 \family typewriter
1631 [0;32mIn [[1;32m1[0;32m]: [0;00m
1645 [0;32mIn [[1;32m1[0;32m]: [0;00m
1632 \family default
1646 \family default
1633
1647
1634 \newline
1648 \newline
1635 instead of (in color) something like:
1649 instead of (in color) something like:
1636 \newline
1650 \newline
1637
1651
1638 \family typewriter
1652 \family typewriter
1639 In [1]:
1653 In [1]:
1640 \family default
1654 \family default
1641
1655
1642 \newline
1656 \newline
1643 this means that your terminal doesn't properly handle color escape sequences.
1657 this means that your terminal doesn't properly handle color escape sequences.
1644 You can go to a 'no color' mode by typing '
1658 You can go to a 'no color' mode by typing '
1645 \family typewriter
1659 \family typewriter
1646 %colors NoColor
1660 %colors NoColor
1647 \family default
1661 \family default
1648 '.
1662 '.
1649
1663
1650 \layout Standard
1664 \layout Standard
1651
1665
1652 You can try using a different terminal emulator program.
1666 You can try using a different terminal emulator program.
1653 To permanently set your color preferences, edit the file
1667 To permanently set your color preferences, edit the file
1654 \family typewriter
1668 \family typewriter
1655 $HOME/.ipython/ipythonrc
1669 $HOME/.ipython/ipythonrc
1656 \family default
1670 \family default
1657 and set the
1671 and set the
1658 \family typewriter
1672 \family typewriter
1659 colors
1673 colors
1660 \family default
1674 \family default
1661 option to the desired value.
1675 option to the desired value.
1662 \layout Subsubsection
1676 \layout Subsubsection
1663
1677
1664 Object details (types, docstrings, source code, etc.)
1678 Object details (types, docstrings, source code, etc.)
1665 \layout Standard
1679 \layout Standard
1666
1680
1667 IPython has a set of special functions for studying the objects you are
1681 IPython has a set of special functions for studying the objects you are
1668 working with, discussed in detail in Sec.
1682 working with, discussed in detail in Sec.
1669
1683
1670 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1684 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1671
1685
1672 \end_inset
1686 \end_inset
1673
1687
1674 .
1688 .
1675 But this system relies on passing information which is longer than your
1689 But this system relies on passing information which is longer than your
1676 screen through a data pager, such as the common Unix
1690 screen through a data pager, such as the common Unix
1677 \family typewriter
1691 \family typewriter
1678 less
1692 less
1679 \family default
1693 \family default
1680 and
1694 and
1681 \family typewriter
1695 \family typewriter
1682 more
1696 more
1683 \family default
1697 \family default
1684 programs.
1698 programs.
1685 In order to be able to see this information in color, your pager needs
1699 In order to be able to see this information in color, your pager needs
1686 to be properly configured.
1700 to be properly configured.
1687 I strongly recommend using
1701 I strongly recommend using
1688 \family typewriter
1702 \family typewriter
1689 less
1703 less
1690 \family default
1704 \family default
1691 instead of
1705 instead of
1692 \family typewriter
1706 \family typewriter
1693 more
1707 more
1694 \family default
1708 \family default
1695 , as it seems that
1709 , as it seems that
1696 \family typewriter
1710 \family typewriter
1697 more
1711 more
1698 \family default
1712 \family default
1699 simply can not understand colored text correctly.
1713 simply can not understand colored text correctly.
1700 \layout Standard
1714 \layout Standard
1701
1715
1702 In order to configure
1716 In order to configure
1703 \family typewriter
1717 \family typewriter
1704 less
1718 less
1705 \family default
1719 \family default
1706 as your default pager, do the following:
1720 as your default pager, do the following:
1707 \layout Enumerate
1721 \layout Enumerate
1708
1722
1709 Set the environment
1723 Set the environment
1710 \family typewriter
1724 \family typewriter
1711 PAGER
1725 PAGER
1712 \family default
1726 \family default
1713 variable to
1727 variable to
1714 \family typewriter
1728 \family typewriter
1715 less
1729 less
1716 \family default
1730 \family default
1717 .
1731 .
1718 \layout Enumerate
1732 \layout Enumerate
1719
1733
1720 Set the environment
1734 Set the environment
1721 \family typewriter
1735 \family typewriter
1722 LESS
1736 LESS
1723 \family default
1737 \family default
1724 variable to
1738 variable to
1725 \family typewriter
1739 \family typewriter
1726 -r
1740 -r
1727 \family default
1741 \family default
1728 (plus any other options you always want to pass to
1742 (plus any other options you always want to pass to
1729 \family typewriter
1743 \family typewriter
1730 less
1744 less
1731 \family default
1745 \family default
1732 by default).
1746 by default).
1733 This tells
1747 This tells
1734 \family typewriter
1748 \family typewriter
1735 less
1749 less
1736 \family default
1750 \family default
1737 to properly interpret control sequences, which is how color information
1751 to properly interpret control sequences, which is how color information
1738 is given to your terminal.
1752 is given to your terminal.
1739 \layout Standard
1753 \layout Standard
1740
1754
1741 For the
1755 For the
1742 \family typewriter
1756 \family typewriter
1743 csh
1757 csh
1744 \family default
1758 \family default
1745 or
1759 or
1746 \family typewriter
1760 \family typewriter
1747 tcsh
1761 tcsh
1748 \family default
1762 \family default
1749 shells, add to your
1763 shells, add to your
1750 \family typewriter
1764 \family typewriter
1751 ~/.cshrc
1765 ~/.cshrc
1752 \family default
1766 \family default
1753 file the lines:
1767 file the lines:
1754 \layout Standard
1768 \layout Standard
1755
1769
1756
1770
1757 \family typewriter
1771 \family typewriter
1758 setenv PAGER less
1772 setenv PAGER less
1759 \newline
1773 \newline
1760 setenv LESS -r
1774 setenv LESS -r
1761 \layout Standard
1775 \layout Standard
1762
1776
1763 There is similar syntax for other Unix shells, look at your system documentation
1777 There is similar syntax for other Unix shells, look at your system documentation
1764 for details.
1778 for details.
1765 \layout Standard
1779 \layout Standard
1766
1780
1767 If you are on a system which lacks proper data pagers (such as Windows),
1781 If you are on a system which lacks proper data pagers (such as Windows),
1768 IPython will use a very limited builtin pager.
1782 IPython will use a very limited builtin pager.
1769 \layout Subsection
1783 \layout Subsection
1770
1784
1771
1785
1772 \begin_inset LatexCommand \label{sec:emacs}
1786 \begin_inset LatexCommand \label{sec:emacs}
1773
1787
1774 \end_inset
1788 \end_inset
1775
1789
1776 (X)Emacs configuration
1790 (X)Emacs configuration
1777 \layout Standard
1791 \layout Standard
1778
1792
1779 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1793 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1780 (X)Emacs and IPython get along very well.
1794 (X)Emacs and IPython get along very well.
1781
1795
1782 \layout Standard
1796 \layout Standard
1783
1797
1784
1798
1785 \series bold
1799 \series bold
1786 Important note:
1800 Important note:
1787 \series default
1801 \series default
1788 You will need to use a recent enough version of
1802 You will need to use a recent enough version of
1789 \family typewriter
1803 \family typewriter
1790 python-mode.el
1804 python-mode.el
1791 \family default
1805 \family default
1792 , along with the file
1806 , along with the file
1793 \family typewriter
1807 \family typewriter
1794 ipython.el
1808 ipython.el
1795 \family default
1809 \family default
1796 .
1810 .
1797 You can check that the version you have of
1811 You can check that the version you have of
1798 \family typewriter
1812 \family typewriter
1799 python-mode.el
1813 python-mode.el
1800 \family default
1814 \family default
1801 is new enough by either looking at the revision number in the file itself,
1815 is new enough by either looking at the revision number in the file itself,
1802 or asking for it in (X)Emacs via
1816 or asking for it in (X)Emacs via
1803 \family typewriter
1817 \family typewriter
1804 M-x py-version
1818 M-x py-version
1805 \family default
1819 \family default
1806 .
1820 .
1807 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1821 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1808 \layout Standard
1822 \layout Standard
1809
1823
1810 The file
1824 The file
1811 \family typewriter
1825 \family typewriter
1812 ipython.el
1826 ipython.el
1813 \family default
1827 \family default
1814 is included with the IPython distribution, in the documentation directory
1828 is included with the IPython distribution, in the documentation directory
1815 (where this manual resides in PDF and HTML formats).
1829 (where this manual resides in PDF and HTML formats).
1816 \layout Standard
1830 \layout Standard
1817
1831
1818 Once you put these files in your Emacs path, all you need in your
1832 Once you put these files in your Emacs path, all you need in your
1819 \family typewriter
1833 \family typewriter
1820 .emacs
1834 .emacs
1821 \family default
1835 \family default
1822 file is:
1836 file is:
1823 \layout Standard
1837 \layout Standard
1824
1838
1825
1839
1826 \family typewriter
1840 \family typewriter
1827 (require 'ipython)
1841 (require 'ipython)
1828 \layout Standard
1842 \layout Standard
1829
1843
1830 This should give you full support for executing code snippets via IPython,
1844 This should give you full support for executing code snippets via IPython,
1831 opening IPython as your Python shell via
1845 opening IPython as your Python shell via
1832 \family typewriter
1846 \family typewriter
1833 C-c\SpecialChar ~
1847 C-c\SpecialChar ~
1834 !
1848 !
1835 \family default
1849 \family default
1836 , etc.
1850 , etc.
1837
1851
1838 \layout Subsubsection*
1852 \layout Subsubsection*
1839
1853
1840 Notes
1854 Notes
1841 \layout Itemize
1855 \layout Itemize
1842
1856
1843 There is one caveat you should be aware of: you must start the IPython shell
1857 There is one caveat you should be aware of: you must start the IPython shell
1844
1858
1845 \emph on
1859 \emph on
1846 before
1860 before
1847 \emph default
1861 \emph default
1848 attempting to execute any code regions via
1862 attempting to execute any code regions via
1849 \family typewriter
1863 \family typewriter
1850 C-c\SpecialChar ~
1864 C-c\SpecialChar ~
1851 |
1865 |
1852 \family default
1866 \family default
1853 .
1867 .
1854 Simply type
1868 Simply type
1855 \family typewriter
1869 \family typewriter
1856 C-c\SpecialChar ~
1870 C-c\SpecialChar ~
1857 !
1871 !
1858 \family default
1872 \family default
1859 to start IPython before passing any code regions to the interpreter, and
1873 to start IPython before passing any code regions to the interpreter, and
1860 you shouldn't experience any problems.
1874 you shouldn't experience any problems.
1861 \newline
1875 \newline
1862 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1876 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1863 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1877 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1864 \layout Itemize
1878 \layout Itemize
1865
1879
1866 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1880 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1867 ts should be directed to him through the IPython mailing lists.
1881 ts should be directed to him through the IPython mailing lists.
1868
1882
1869 \layout Itemize
1883 \layout Itemize
1870
1884
1871 This code is still somewhat experimental so it's a bit rough around the
1885 This code is still somewhat experimental so it's a bit rough around the
1872 edges (although in practice, it works quite well).
1886 edges (although in practice, it works quite well).
1873 \layout Itemize
1887 \layout Itemize
1874
1888
1875 Be aware that if you customize
1889 Be aware that if you customize
1876 \family typewriter
1890 \family typewriter
1877 py-python-command
1891 py-python-command
1878 \family default
1892 \family default
1879 previously, this value will override what
1893 previously, this value will override what
1880 \family typewriter
1894 \family typewriter
1881 ipython.el
1895 ipython.el
1882 \family default
1896 \family default
1883 does (because loading the customization variables comes later).
1897 does (because loading the customization variables comes later).
1884 \layout Section
1898 \layout Section
1885
1899
1886
1900
1887 \begin_inset LatexCommand \label{sec:quick_tips}
1901 \begin_inset LatexCommand \label{sec:quick_tips}
1888
1902
1889 \end_inset
1903 \end_inset
1890
1904
1891 Quick tips
1905 Quick tips
1892 \layout Standard
1906 \layout Standard
1893
1907
1894 IPython can be used as an improved replacement for the Python prompt, and
1908 IPython can be used as an improved replacement for the Python prompt, and
1895 for that you don't really need to read any more of this manual.
1909 for that you don't really need to read any more of this manual.
1896 But in this section we'll try to summarize a few tips on how to make the
1910 But in this section we'll try to summarize a few tips on how to make the
1897 most effective use of it for everyday Python development, highlighting
1911 most effective use of it for everyday Python development, highlighting
1898 things you might miss in the rest of the manual (which is getting long).
1912 things you might miss in the rest of the manual (which is getting long).
1899 We'll give references to parts in the manual which provide more detail
1913 We'll give references to parts in the manual which provide more detail
1900 when appropriate.
1914 when appropriate.
1901 \layout Standard
1915 \layout Standard
1902
1916
1903 The following article by Jeremy Jones provides an introductory tutorial
1917 The following article by Jeremy Jones provides an introductory tutorial
1904 about IPython:
1918 about IPython:
1905 \newline
1919 \newline
1906
1920
1907 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1921 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1908
1922
1909 \end_inset
1923 \end_inset
1910
1924
1911
1925
1912 \layout Itemize
1926 \layout Itemize
1913
1927
1914 The TAB key.
1928 The TAB key.
1915 TAB-completion, especially for attributes, is a convenient way to explore
1929 TAB-completion, especially for attributes, is a convenient way to explore
1916 the structure of any object you're dealing with.
1930 the structure of any object you're dealing with.
1917 Simply type
1931 Simply type
1918 \family typewriter
1932 \family typewriter
1919 object_name.<TAB>
1933 object_name.<TAB>
1920 \family default
1934 \family default
1921 and a list of the object's attributes will be printed (see sec.
1935 and a list of the object's attributes will be printed (see sec.
1922
1936
1923 \begin_inset LatexCommand \ref{sec:readline}
1937 \begin_inset LatexCommand \ref{sec:readline}
1924
1938
1925 \end_inset
1939 \end_inset
1926
1940
1927 for more).
1941 for more).
1928 Tab completion also works on file and directory names, which combined with
1942 Tab completion also works on file and directory names, which combined with
1929 IPython's alias system allows you to do from within IPython many of the
1943 IPython's alias system allows you to do from within IPython many of the
1930 things you normally would need the system shell for.
1944 things you normally would need the system shell for.
1931
1945
1932 \layout Itemize
1946 \layout Itemize
1933
1947
1934 Explore your objects.
1948 Explore your objects.
1935 Typing
1949 Typing
1936 \family typewriter
1950 \family typewriter
1937 object_name?
1951 object_name?
1938 \family default
1952 \family default
1939 will print all sorts of details about any object, including docstrings,
1953 will print all sorts of details about any object, including docstrings,
1940 function definition lines (for call arguments) and constructor details
1954 function definition lines (for call arguments) and constructor details
1941 for classes.
1955 for classes.
1942 The magic commands
1956 The magic commands
1943 \family typewriter
1957 \family typewriter
1944 %pdoc
1958 %pdoc
1945 \family default
1959 \family default
1946 ,
1960 ,
1947 \family typewriter
1961 \family typewriter
1948 %pdef
1962 %pdef
1949 \family default
1963 \family default
1950 ,
1964 ,
1951 \family typewriter
1965 \family typewriter
1952 %psource
1966 %psource
1953 \family default
1967 \family default
1954 and
1968 and
1955 \family typewriter
1969 \family typewriter
1956 %pfile
1970 %pfile
1957 \family default
1971 \family default
1958 will respectively print the docstring, function definition line, full source
1972 will respectively print the docstring, function definition line, full source
1959 code and the complete file for any object (when they can be found).
1973 code and the complete file for any object (when they can be found).
1960 If automagic is on (it is by default), you don't need to type the '
1974 If automagic is on (it is by default), you don't need to type the '
1961 \family typewriter
1975 \family typewriter
1962 %
1976 %
1963 \family default
1977 \family default
1964 ' explicitly.
1978 ' explicitly.
1965 See sec.
1979 See sec.
1966
1980
1967 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1981 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1968
1982
1969 \end_inset
1983 \end_inset
1970
1984
1971 for more.
1985 for more.
1972 \layout Itemize
1986 \layout Itemize
1973
1987
1974 The
1988 The
1975 \family typewriter
1989 \family typewriter
1976 %run
1990 %run
1977 \family default
1991 \family default
1978 magic command allows you to run any python script and load all of its data
1992 magic command allows you to run any python script and load all of its data
1979 directly into the interactive namespace.
1993 directly into the interactive namespace.
1980 Since the file is re-read from disk each time, changes you make to it are
1994 Since the file is re-read from disk each time, changes you make to it are
1981 reflected immediately (in contrast to the behavior of
1995 reflected immediately (in contrast to the behavior of
1982 \family typewriter
1996 \family typewriter
1983 import
1997 import
1984 \family default
1998 \family default
1985 ).
1999 ).
1986 I rarely use
2000 I rarely use
1987 \family typewriter
2001 \family typewriter
1988 import
2002 import
1989 \family default
2003 \family default
1990 for code I am testing, relying on
2004 for code I am testing, relying on
1991 \family typewriter
2005 \family typewriter
1992 %run
2006 %run
1993 \family default
2007 \family default
1994 instead.
2008 instead.
1995 See sec.
2009 See sec.
1996
2010
1997 \begin_inset LatexCommand \ref{sec:magic}
2011 \begin_inset LatexCommand \ref{sec:magic}
1998
2012
1999 \end_inset
2013 \end_inset
2000
2014
2001 for more on this and other magic commands, or type the name of any magic
2015 for more on this and other magic commands, or type the name of any magic
2002 command and ? to get details on it.
2016 command and ? to get details on it.
2003 See also sec.
2017 See also sec.
2004
2018
2005 \begin_inset LatexCommand \ref{sec:dreload}
2019 \begin_inset LatexCommand \ref{sec:dreload}
2006
2020
2007 \end_inset
2021 \end_inset
2008
2022
2009 for a recursive reload command.
2023 for a recursive reload command.
2010 \newline
2024 \newline
2011
2025
2012 \family typewriter
2026 \family typewriter
2013 %run
2027 %run
2014 \family default
2028 \family default
2015 also has special flags for timing the execution of your scripts (
2029 also has special flags for timing the execution of your scripts (
2016 \family typewriter
2030 \family typewriter
2017 -t
2031 -t
2018 \family default
2032 \family default
2019 ) and for executing them under the control of either Python's
2033 ) and for executing them under the control of either Python's
2020 \family typewriter
2034 \family typewriter
2021 pdb
2035 pdb
2022 \family default
2036 \family default
2023 debugger (
2037 debugger (
2024 \family typewriter
2038 \family typewriter
2025 -d
2039 -d
2026 \family default
2040 \family default
2027 ) or profiler (
2041 ) or profiler (
2028 \family typewriter
2042 \family typewriter
2029 -p
2043 -p
2030 \family default
2044 \family default
2031 ).
2045 ).
2032 With all of these,
2046 With all of these,
2033 \family typewriter
2047 \family typewriter
2034 %run
2048 %run
2035 \family default
2049 \family default
2036 can be used as the main tool for efficient interactive development of code
2050 can be used as the main tool for efficient interactive development of code
2037 which you write in your editor of choice.
2051 which you write in your editor of choice.
2038 \layout Itemize
2052 \layout Itemize
2039
2053
2040 Use the Python debugger,
2054 Use the Python debugger,
2041 \family typewriter
2055 \family typewriter
2042 pdb
2056 pdb
2043 \family default
2057 \family default
2044
2058
2045 \begin_inset Foot
2059 \begin_inset Foot
2046 collapsed true
2060 collapsed true
2047
2061
2048 \layout Standard
2062 \layout Standard
2049
2063
2050 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2064 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2051 to IPython's improved debugger and profiler support.
2065 to IPython's improved debugger and profiler support.
2052 \end_inset
2066 \end_inset
2053
2067
2054 .
2068 .
2055 The
2069 The
2056 \family typewriter
2070 \family typewriter
2057 %pdb
2071 %pdb
2058 \family default
2072 \family default
2059 command allows you to toggle on and off the automatic invocation of an
2073 command allows you to toggle on and off the automatic invocation of an
2060 IPython-enhanced
2074 IPython-enhanced
2061 \family typewriter
2075 \family typewriter
2062 pdb
2076 pdb
2063 \family default
2077 \family default
2064 debugger (with coloring, tab completion and more) at any uncaught exception.
2078 debugger (with coloring, tab completion and more) at any uncaught exception.
2065 The advantage of this is that
2079 The advantage of this is that
2066 \family typewriter
2080 \family typewriter
2067 pdb
2081 pdb
2068 \family default
2082 \family default
2069 starts
2083 starts
2070 \emph on
2084 \emph on
2071 inside
2085 inside
2072 \emph default
2086 \emph default
2073 the function where the exception occurred, with all data still available.
2087 the function where the exception occurred, with all data still available.
2074 You can print variables, see code, execute statements and even walk up
2088 You can print variables, see code, execute statements and even walk up
2075 and down the call stack to track down the true source of the problem (which
2089 and down the call stack to track down the true source of the problem (which
2076 often is many layers in the stack above where the exception gets triggered).
2090 often is many layers in the stack above where the exception gets triggered).
2077 \newline
2091 \newline
2078 Running programs with
2092 Running programs with
2079 \family typewriter
2093 \family typewriter
2080 %run
2094 %run
2081 \family default
2095 \family default
2082 and pdb active can be an efficient to develop and debug code, in many cases
2096 and pdb active can be an efficient to develop and debug code, in many cases
2083 eliminating the need for
2097 eliminating the need for
2084 \family typewriter
2098 \family typewriter
2085 print
2099 print
2086 \family default
2100 \family default
2087 statements or external debugging tools.
2101 statements or external debugging tools.
2088 I often simply put a
2102 I often simply put a
2089 \family typewriter
2103 \family typewriter
2090 1/0
2104 1/0
2091 \family default
2105 \family default
2092 in a place where I want to take a look so that pdb gets called, quickly
2106 in a place where I want to take a look so that pdb gets called, quickly
2093 view whatever variables I need to or test various pieces of code and then
2107 view whatever variables I need to or test various pieces of code and then
2094 remove the
2108 remove the
2095 \family typewriter
2109 \family typewriter
2096 1/0
2110 1/0
2097 \family default
2111 \family default
2098 .
2112 .
2099 \newline
2113 \newline
2100 Note also that `
2114 Note also that `
2101 \family typewriter
2115 \family typewriter
2102 %run -d
2116 %run -d
2103 \family default
2117 \family default
2104 ' activates
2118 ' activates
2105 \family typewriter
2119 \family typewriter
2106 pdb
2120 pdb
2107 \family default
2121 \family default
2108 and automatically sets initial breakpoints for you to step through your
2122 and automatically sets initial breakpoints for you to step through your
2109 code, watch variables, etc.
2123 code, watch variables, etc.
2110 See Sec.\SpecialChar ~
2124 See Sec.\SpecialChar ~
2111
2125
2112 \begin_inset LatexCommand \ref{sec:cache_output}
2126 \begin_inset LatexCommand \ref{sec:cache_output}
2113
2127
2114 \end_inset
2128 \end_inset
2115
2129
2116 for details.
2130 for details.
2117 \layout Itemize
2131 \layout Itemize
2118
2132
2119 Use the output cache.
2133 Use the output cache.
2120 All output results are automatically stored in a global dictionary named
2134 All output results are automatically stored in a global dictionary named
2121
2135
2122 \family typewriter
2136 \family typewriter
2123 Out
2137 Out
2124 \family default
2138 \family default
2125 and variables named
2139 and variables named
2126 \family typewriter
2140 \family typewriter
2127 _1
2141 _1
2128 \family default
2142 \family default
2129 ,
2143 ,
2130 \family typewriter
2144 \family typewriter
2131 _2
2145 _2
2132 \family default
2146 \family default
2133 , etc.
2147 , etc.
2134 alias them.
2148 alias them.
2135 For example, the result of input line 4 is available either as
2149 For example, the result of input line 4 is available either as
2136 \family typewriter
2150 \family typewriter
2137 Out[4]
2151 Out[4]
2138 \family default
2152 \family default
2139 or as
2153 or as
2140 \family typewriter
2154 \family typewriter
2141 _4
2155 _4
2142 \family default
2156 \family default
2143 .
2157 .
2144 Additionally, three variables named
2158 Additionally, three variables named
2145 \family typewriter
2159 \family typewriter
2146 _
2160 _
2147 \family default
2161 \family default
2148 ,
2162 ,
2149 \family typewriter
2163 \family typewriter
2150 __
2164 __
2151 \family default
2165 \family default
2152 and
2166 and
2153 \family typewriter
2167 \family typewriter
2154 ___
2168 ___
2155 \family default
2169 \family default
2156 are always kept updated with the for the last three results.
2170 are always kept updated with the for the last three results.
2157 This allows you to recall any previous result and further use it for new
2171 This allows you to recall any previous result and further use it for new
2158 calculations.
2172 calculations.
2159 See Sec.\SpecialChar ~
2173 See Sec.\SpecialChar ~
2160
2174
2161 \begin_inset LatexCommand \ref{sec:cache_output}
2175 \begin_inset LatexCommand \ref{sec:cache_output}
2162
2176
2163 \end_inset
2177 \end_inset
2164
2178
2165 for more.
2179 for more.
2166 \layout Itemize
2180 \layout Itemize
2167
2181
2168 Put a '
2182 Put a '
2169 \family typewriter
2183 \family typewriter
2170 ;
2184 ;
2171 \family default
2185 \family default
2172 ' at the end of a line to supress the printing of output.
2186 ' at the end of a line to supress the printing of output.
2173 This is useful when doing calculations which generate long output you are
2187 This is useful when doing calculations which generate long output you are
2174 not interested in seeing.
2188 not interested in seeing.
2175 The
2189 The
2176 \family typewriter
2190 \family typewriter
2177 _*
2191 _*
2178 \family default
2192 \family default
2179 variables and the
2193 variables and the
2180 \family typewriter
2194 \family typewriter
2181 Out[]
2195 Out[]
2182 \family default
2196 \family default
2183 list do get updated with the contents of the output, even if it is not
2197 list do get updated with the contents of the output, even if it is not
2184 printed.
2198 printed.
2185 You can thus still access the generated results this way for further processing.
2199 You can thus still access the generated results this way for further processing.
2186 \layout Itemize
2200 \layout Itemize
2187
2201
2188 A similar system exists for caching input.
2202 A similar system exists for caching input.
2189 All input is stored in a global list called
2203 All input is stored in a global list called
2190 \family typewriter
2204 \family typewriter
2191 In
2205 In
2192 \family default
2206 \family default
2193 , so you can re-execute lines 22 through 28 plus line 34 by typing
2207 , so you can re-execute lines 22 through 28 plus line 34 by typing
2194 \family typewriter
2208 \family typewriter
2195 'exec In[22:29]+In[34]'
2209 'exec In[22:29]+In[34]'
2196 \family default
2210 \family default
2197 (using Python slicing notation).
2211 (using Python slicing notation).
2198 If you need to execute the same set of lines often, you can assign them
2212 If you need to execute the same set of lines often, you can assign them
2199 to a macro with the
2213 to a macro with the
2200 \family typewriter
2214 \family typewriter
2201 %macro
2215 %macro
2202 \family default
2216 \family default
2203
2217
2204 \family typewriter
2218 \family typewriter
2205 function.
2219 function.
2206
2220
2207 \family default
2221 \family default
2208 See sec.
2222 See sec.
2209
2223
2210 \begin_inset LatexCommand \ref{sec:cache_input}
2224 \begin_inset LatexCommand \ref{sec:cache_input}
2211
2225
2212 \end_inset
2226 \end_inset
2213
2227
2214 for more.
2228 for more.
2215 \layout Itemize
2229 \layout Itemize
2216
2230
2217 Use your input history.
2231 Use your input history.
2218 The
2232 The
2219 \family typewriter
2233 \family typewriter
2220 %hist
2234 %hist
2221 \family default
2235 \family default
2222 command can show you all previous input, without line numbers if desired
2236 command can show you all previous input, without line numbers if desired
2223 (option
2237 (option
2224 \family typewriter
2238 \family typewriter
2225 -n
2239 -n
2226 \family default
2240 \family default
2227 ) so you can directly copy and paste code either back in IPython or in a
2241 ) so you can directly copy and paste code either back in IPython or in a
2228 text editor.
2242 text editor.
2229 You can also save all your history by turning on logging via
2243 You can also save all your history by turning on logging via
2230 \family typewriter
2244 \family typewriter
2231 %logstart
2245 %logstart
2232 \family default
2246 \family default
2233 ; these logs can later be either reloaded as IPython sessions or used as
2247 ; these logs can later be either reloaded as IPython sessions or used as
2234 code for your programs.
2248 code for your programs.
2235 \layout Itemize
2249 \layout Itemize
2236
2250
2237 Define your own system aliases.
2251 Define your own system aliases.
2238 Even though IPython gives you access to your system shell via the
2252 Even though IPython gives you access to your system shell via the
2239 \family typewriter
2253 \family typewriter
2240 !
2254 !
2241 \family default
2255 \family default
2242 prefix, it is convenient to have aliases to the system commands you use
2256 prefix, it is convenient to have aliases to the system commands you use
2243 most often.
2257 most often.
2244 This allows you to work seamlessly from inside IPython with the same commands
2258 This allows you to work seamlessly from inside IPython with the same commands
2245 you are used to in your system shell.
2259 you are used to in your system shell.
2246 \newline
2260 \newline
2247 IPython comes with some pre-defined aliases and a complete system for changing
2261 IPython comes with some pre-defined aliases and a complete system for changing
2248 directories, both via a stack (see
2262 directories, both via a stack (see
2249 \family typewriter
2263 \family typewriter
2250 %pushd
2264 %pushd
2251 \family default
2265 \family default
2252 ,
2266 ,
2253 \family typewriter
2267 \family typewriter
2254 %popd
2268 %popd
2255 \family default
2269 \family default
2256 and
2270 and
2257 \family typewriter
2271 \family typewriter
2258 %ds
2272 %ds
2259 \family default
2273 \family default
2260 ) and via direct
2274 ) and via direct
2261 \family typewriter
2275 \family typewriter
2262 %cd
2276 %cd
2263 \family default
2277 \family default
2264 .
2278 .
2265 The latter keeps a history of visited directories and allows you to go
2279 The latter keeps a history of visited directories and allows you to go
2266 to any previously visited one.
2280 to any previously visited one.
2267 \layout Itemize
2281 \layout Itemize
2268
2282
2269 Use Python to manipulate the results of system commands.
2283 Use Python to manipulate the results of system commands.
2270 The `
2284 The `
2271 \family typewriter
2285 \family typewriter
2272 !!
2286 !!
2273 \family default
2287 \family default
2274 ' special syntax, and the
2288 ' special syntax, and the
2275 \family typewriter
2289 \family typewriter
2276 %sc
2290 %sc
2277 \family default
2291 \family default
2278 and
2292 and
2279 \family typewriter
2293 \family typewriter
2280 %sx
2294 %sx
2281 \family default
2295 \family default
2282 magic commands allow you to capture system output into Python variables.
2296 magic commands allow you to capture system output into Python variables.
2283 \layout Itemize
2297 \layout Itemize
2284
2298
2285 Expand python variables when calling the shell (either via
2299 Expand python variables when calling the shell (either via
2286 \family typewriter
2300 \family typewriter
2287 `!'
2301 `!'
2288 \family default
2302 \family default
2289 and
2303 and
2290 \family typewriter
2304 \family typewriter
2291 `!!'
2305 `!!'
2292 \family default
2306 \family default
2293 or via aliases) by prepending a
2307 or via aliases) by prepending a
2294 \family typewriter
2308 \family typewriter
2295 $
2309 $
2296 \family default
2310 \family default
2297 in front of them.
2311 in front of them.
2298 You can also expand complete python expressions.
2312 You can also expand complete python expressions.
2299 See sec.\SpecialChar ~
2313 See sec.\SpecialChar ~
2300
2314
2301 \begin_inset LatexCommand \ref{sub:System-shell-access}
2315 \begin_inset LatexCommand \ref{sub:System-shell-access}
2302
2316
2303 \end_inset
2317 \end_inset
2304
2318
2305 for more.
2319 for more.
2306 \layout Itemize
2320 \layout Itemize
2307
2321
2308 Use profiles to maintain different configurations (modules to load, function
2322 Use profiles to maintain different configurations (modules to load, function
2309 definitions, option settings) for particular tasks.
2323 definitions, option settings) for particular tasks.
2310 You can then have customized versions of IPython for specific purposes.
2324 You can then have customized versions of IPython for specific purposes.
2311 See sec.\SpecialChar ~
2325 See sec.\SpecialChar ~
2312
2326
2313 \begin_inset LatexCommand \ref{sec:profiles}
2327 \begin_inset LatexCommand \ref{sec:profiles}
2314
2328
2315 \end_inset
2329 \end_inset
2316
2330
2317 for more.
2331 for more.
2318 \layout Itemize
2332 \layout Itemize
2319
2333
2320 Embed IPython in your programs.
2334 Embed IPython in your programs.
2321 A few lines of code are enough to load a complete IPython inside your own
2335 A few lines of code are enough to load a complete IPython inside your own
2322 programs, giving you the ability to work with your data interactively after
2336 programs, giving you the ability to work with your data interactively after
2323 automatic processing has been completed.
2337 automatic processing has been completed.
2324 See sec.\SpecialChar ~
2338 See sec.\SpecialChar ~
2325
2339
2326 \begin_inset LatexCommand \ref{sec:embed}
2340 \begin_inset LatexCommand \ref{sec:embed}
2327
2341
2328 \end_inset
2342 \end_inset
2329
2343
2330 for more.
2344 for more.
2331 \layout Itemize
2345 \layout Itemize
2332
2346
2333 Use the Python profiler.
2347 Use the Python profiler.
2334 When dealing with performance issues, the
2348 When dealing with performance issues, the
2335 \family typewriter
2349 \family typewriter
2336 %run
2350 %run
2337 \family default
2351 \family default
2338 command with a
2352 command with a
2339 \family typewriter
2353 \family typewriter
2340 -p
2354 -p
2341 \family default
2355 \family default
2342 option allows you to run complete programs under the control of the Python
2356 option allows you to run complete programs under the control of the Python
2343 profiler.
2357 profiler.
2344 The
2358 The
2345 \family typewriter
2359 \family typewriter
2346 %prun
2360 %prun
2347 \family default
2361 \family default
2348 command does a similar job for single Python expressions (like function
2362 command does a similar job for single Python expressions (like function
2349 calls).
2363 calls).
2350 \layout Itemize
2364 \layout Itemize
2351
2365
2352 Use the IPython.demo.Demo class to load any Python script as an interactive
2366 Use the IPython.demo.Demo class to load any Python script as an interactive
2353 demo.
2367 demo.
2354 With a minimal amount of simple markup, you can control the execution of
2368 With a minimal amount of simple markup, you can control the execution of
2355 the script, stopping as needed.
2369 the script, stopping as needed.
2356 See sec.\SpecialChar ~
2370 See sec.\SpecialChar ~
2357
2371
2358 \begin_inset LatexCommand \ref{sec:interactive-demos}
2372 \begin_inset LatexCommand \ref{sec:interactive-demos}
2359
2373
2360 \end_inset
2374 \end_inset
2361
2375
2362 for more.
2376 for more.
2363 \layout Subsection
2377 \layout Subsection
2364
2378
2365 Source code handling tips
2379 Source code handling tips
2366 \layout Standard
2380 \layout Standard
2367
2381
2368 IPython is a line-oriented program, without full control of the terminal.
2382 IPython is a line-oriented program, without full control of the terminal.
2369 Therefore, it doesn't support true multiline editing.
2383 Therefore, it doesn't support true multiline editing.
2370 However, it has a number of useful tools to help you in dealing effectively
2384 However, it has a number of useful tools to help you in dealing effectively
2371 with more complex editing.
2385 with more complex editing.
2372 \layout Standard
2386 \layout Standard
2373
2387
2374 The
2388 The
2375 \family typewriter
2389 \family typewriter
2376 %edit
2390 %edit
2377 \family default
2391 \family default
2378 command gives a reasonable approximation of multiline editing, by invoking
2392 command gives a reasonable approximation of multiline editing, by invoking
2379 your favorite editor on the spot.
2393 your favorite editor on the spot.
2380 IPython will execute the code you type in there as if it were typed interactive
2394 IPython will execute the code you type in there as if it were typed interactive
2381 ly.
2395 ly.
2382 Type
2396 Type
2383 \family typewriter
2397 \family typewriter
2384 %edit?
2398 %edit?
2385 \family default
2399 \family default
2386 for the full details on the edit command.
2400 for the full details on the edit command.
2387 \layout Standard
2401 \layout Standard
2388
2402
2389 If you have typed various commands during a session, which you'd like to
2403 If you have typed various commands during a session, which you'd like to
2390 reuse, IPython provides you with a number of tools.
2404 reuse, IPython provides you with a number of tools.
2391 Start by using
2405 Start by using
2392 \family typewriter
2406 \family typewriter
2393 %hist
2407 %hist
2394 \family default
2408 \family default
2395 to see your input history, so you can see the line numbers of all input.
2409 to see your input history, so you can see the line numbers of all input.
2396 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
2410 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
2397 and 28.
2411 and 28.
2398 All the commands below can operate on these with the syntax
2412 All the commands below can operate on these with the syntax
2399 \layout LyX-Code
2413 \layout LyX-Code
2400
2414
2401 %command 10-20 24 28
2415 %command 10-20 24 28
2402 \layout Standard
2416 \layout Standard
2403
2417
2404 where the command given can be:
2418 where the command given can be:
2405 \layout Itemize
2419 \layout Itemize
2406
2420
2407
2421
2408 \family typewriter
2422 \family typewriter
2409 %macro <macroname>
2423 %macro <macroname>
2410 \family default
2424 \family default
2411 : this stores the lines into a variable which, when called at the prompt,
2425 : this stores the lines into a variable which, when called at the prompt,
2412 re-executes the input.
2426 re-executes the input.
2413 Macros can be edited later using
2427 Macros can be edited later using
2414 \family typewriter
2428 \family typewriter
2415 `%edit macroname
2429 `%edit macroname
2416 \family default
2430 \family default
2417 ', and they can be stored persistently across sessions with `
2431 ', and they can be stored persistently across sessions with `
2418 \family typewriter
2432 \family typewriter
2419 %store macroname
2433 %store macroname
2420 \family default
2434 \family default
2421 ' (the storage system is per-profile).
2435 ' (the storage system is per-profile).
2422 The combination of quick macros, persistent storage and editing, allows
2436 The combination of quick macros, persistent storage and editing, allows
2423 you to easily refine quick-and-dirty interactive input into permanent utilities
2437 you to easily refine quick-and-dirty interactive input into permanent utilities
2424 , always available both in IPython and as files for general reuse.
2438 , always available both in IPython and as files for general reuse.
2425 \layout Itemize
2439 \layout Itemize
2426
2440
2427
2441
2428 \family typewriter
2442 \family typewriter
2429 %edit
2443 %edit
2430 \family default
2444 \family default
2431 : this will open a text editor with those lines pre-loaded for further modificat
2445 : this will open a text editor with those lines pre-loaded for further modificat
2432 ion.
2446 ion.
2433 It will then execute the resulting file's contents as if you had typed
2447 It will then execute the resulting file's contents as if you had typed
2434 it at the prompt.
2448 it at the prompt.
2435 \layout Itemize
2449 \layout Itemize
2436
2450
2437
2451
2438 \family typewriter
2452 \family typewriter
2439 %save <filename>
2453 %save <filename>
2440 \family default
2454 \family default
2441 : this saves the lines directly to a named file on disk.
2455 : this saves the lines directly to a named file on disk.
2442 \layout Standard
2456 \layout Standard
2443
2457
2444 While
2458 While
2445 \family typewriter
2459 \family typewriter
2446 %macro
2460 %macro
2447 \family default
2461 \family default
2448 saves input lines into memory for interactive re-execution, sometimes you'd
2462 saves input lines into memory for interactive re-execution, sometimes you'd
2449 like to save your input directly to a file.
2463 like to save your input directly to a file.
2450 The
2464 The
2451 \family typewriter
2465 \family typewriter
2452 %save
2466 %save
2453 \family default
2467 \family default
2454 magic does this: its input sytnax is the same as
2468 magic does this: its input sytnax is the same as
2455 \family typewriter
2469 \family typewriter
2456 %macro
2470 %macro
2457 \family default
2471 \family default
2458 , but it saves your input directly to a Python file.
2472 , but it saves your input directly to a Python file.
2459 Note that the
2473 Note that the
2460 \family typewriter
2474 \family typewriter
2461 %logstart
2475 %logstart
2462 \family default
2476 \family default
2463 command also saves input, but it logs
2477 command also saves input, but it logs
2464 \emph on
2478 \emph on
2465 all
2479 all
2466 \emph default
2480 \emph default
2467 input to disk (though you can temporarily suspend it and reactivate it
2481 input to disk (though you can temporarily suspend it and reactivate it
2468 with
2482 with
2469 \family typewriter
2483 \family typewriter
2470 %logoff/%logon
2484 %logoff/%logon
2471 \family default
2485 \family default
2472 );
2486 );
2473 \family typewriter
2487 \family typewriter
2474 %save
2488 %save
2475 \family default
2489 \family default
2476 allows you to select which lines of input you need to save.
2490 allows you to select which lines of input you need to save.
2477 \layout Subsubsection*
2491 \layout Subsubsection*
2478
2492
2479 Lightweight 'version control'
2493 Lightweight 'version control'
2480 \layout Standard
2494 \layout Standard
2481
2495
2482 When you call
2496 When you call
2483 \family typewriter
2497 \family typewriter
2484 %edit
2498 %edit
2485 \family default
2499 \family default
2486 with no arguments, IPython opens an empty editor with a temporary file,
2500 with no arguments, IPython opens an empty editor with a temporary file,
2487 and it returns the contents of your editing session as a string variable.
2501 and it returns the contents of your editing session as a string variable.
2488 Thanks to IPython's output caching mechanism, this is automatically stored:
2502 Thanks to IPython's output caching mechanism, this is automatically stored:
2489 \layout LyX-Code
2503 \layout LyX-Code
2490
2504
2491 In [1]: %edit
2505 In [1]: %edit
2492 \layout LyX-Code
2506 \layout LyX-Code
2493
2507
2494 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
2508 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
2495 \layout LyX-Code
2509 \layout LyX-Code
2496
2510
2497 Editing...
2511 Editing...
2498 done.
2512 done.
2499 Executing edited code...
2513 Executing edited code...
2500 \layout LyX-Code
2514 \layout LyX-Code
2501
2515
2502 hello - this is a temporary file
2516 hello - this is a temporary file
2503 \layout LyX-Code
2517 \layout LyX-Code
2504
2518
2505 Out[1]: "print 'hello - this is a temporary file'
2519 Out[1]: "print 'hello - this is a temporary file'
2506 \backslash
2520 \backslash
2507 n"
2521 n"
2508 \layout Standard
2522 \layout Standard
2509
2523
2510 Now, if you call
2524 Now, if you call
2511 \family typewriter
2525 \family typewriter
2512 `%edit -p'
2526 `%edit -p'
2513 \family default
2527 \family default
2514 , IPython tries to open an editor with the same data as the last time you
2528 , IPython tries to open an editor with the same data as the last time you
2515 used
2529 used
2516 \family typewriter
2530 \family typewriter
2517 %edit
2531 %edit
2518 \family default
2532 \family default
2519 .
2533 .
2520 So if you haven't used
2534 So if you haven't used
2521 \family typewriter
2535 \family typewriter
2522 %edit
2536 %edit
2523 \family default
2537 \family default
2524 in the meantime, this same contents will reopen; however, it will be done
2538 in the meantime, this same contents will reopen; however, it will be done
2525 in a
2539 in a
2526 \emph on
2540 \emph on
2527 new file
2541 new file
2528 \emph default
2542 \emph default
2529 .
2543 .
2530 This means that if you make changes and you later want to find an old version,
2544 This means that if you make changes and you later want to find an old version,
2531 you can always retrieve it by using its output number, via
2545 you can always retrieve it by using its output number, via
2532 \family typewriter
2546 \family typewriter
2533 `%edit _NN'
2547 `%edit _NN'
2534 \family default
2548 \family default
2535 , where
2549 , where
2536 \family typewriter
2550 \family typewriter
2537 NN
2551 NN
2538 \family default
2552 \family default
2539 is the number of the output prompt.
2553 is the number of the output prompt.
2540 \layout Standard
2554 \layout Standard
2541
2555
2542 Continuing with the example above, this should illustrate this idea:
2556 Continuing with the example above, this should illustrate this idea:
2543 \layout LyX-Code
2557 \layout LyX-Code
2544
2558
2545 In [2]: edit -p
2559 In [2]: edit -p
2546 \layout LyX-Code
2560 \layout LyX-Code
2547
2561
2548 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
2562 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
2549 \layout LyX-Code
2563 \layout LyX-Code
2550
2564
2551 Editing...
2565 Editing...
2552 done.
2566 done.
2553 Executing edited code...
2567 Executing edited code...
2554 \layout LyX-Code
2568 \layout LyX-Code
2555
2569
2556 hello - now I made some changes
2570 hello - now I made some changes
2557 \layout LyX-Code
2571 \layout LyX-Code
2558
2572
2559 Out[2]: "print 'hello - now I made some changes'
2573 Out[2]: "print 'hello - now I made some changes'
2560 \backslash
2574 \backslash
2561 n"
2575 n"
2562 \layout LyX-Code
2576 \layout LyX-Code
2563
2577
2564 In [3]: edit _1
2578 In [3]: edit _1
2565 \layout LyX-Code
2579 \layout LyX-Code
2566
2580
2567 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
2581 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
2568 \layout LyX-Code
2582 \layout LyX-Code
2569
2583
2570 Editing...
2584 Editing...
2571 done.
2585 done.
2572 Executing edited code...
2586 Executing edited code...
2573 \layout LyX-Code
2587 \layout LyX-Code
2574
2588
2575 hello - this is a temporary file
2589 hello - this is a temporary file
2576 \layout LyX-Code
2590 \layout LyX-Code
2577
2591
2578 IPython version control at work :)
2592 IPython version control at work :)
2579 \layout LyX-Code
2593 \layout LyX-Code
2580
2594
2581 Out[3]: "print 'hello - this is a temporary file'
2595 Out[3]: "print 'hello - this is a temporary file'
2582 \backslash
2596 \backslash
2583 nprint 'IPython version control at work :)'
2597 nprint 'IPython version control at work :)'
2584 \backslash
2598 \backslash
2585 n"
2599 n"
2586 \layout Standard
2600 \layout Standard
2587
2601
2588 This section was written after a contribution by Alexander Belchenko on
2602 This section was written after a contribution by Alexander Belchenko on
2589 the IPython user list.
2603 the IPython user list.
2590 \layout LyX-Code
2604 \layout LyX-Code
2591
2605
2592 \layout Subsection
2606 \layout Subsection
2593
2607
2594 Effective logging
2608 Effective logging
2595 \layout Standard
2609 \layout Standard
2596
2610
2597 A very useful suggestion sent in by Robert Kern follows:
2611 A very useful suggestion sent in by Robert Kern follows:
2598 \layout Standard
2612 \layout Standard
2599
2613
2600 I recently happened on a nifty way to keep tidy per-project log files.
2614 I recently happened on a nifty way to keep tidy per-project log files.
2601 I made a profile for my project (which is called "parkfield").
2615 I made a profile for my project (which is called "parkfield").
2602 \layout LyX-Code
2616 \layout LyX-Code
2603
2617
2604 include ipythonrc
2618 include ipythonrc
2605 \layout LyX-Code
2619 \layout LyX-Code
2606
2620
2607 # cancel earlier logfile invocation:
2621 # cancel earlier logfile invocation:
2608 \layout LyX-Code
2622 \layout LyX-Code
2609
2623
2610 logfile ''
2624 logfile ''
2611 \layout LyX-Code
2625 \layout LyX-Code
2612
2626
2613 execute import time
2627 execute import time
2614 \layout LyX-Code
2628 \layout LyX-Code
2615
2629
2616 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
2630 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
2617 \layout LyX-Code
2631 \layout LyX-Code
2618
2632
2619 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
2633 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
2620 \layout Standard
2634 \layout Standard
2621
2635
2622 I also added a shell alias for convenience:
2636 I also added a shell alias for convenience:
2623 \layout LyX-Code
2637 \layout LyX-Code
2624
2638
2625 alias parkfield="ipython -pylab -profile parkfield"
2639 alias parkfield="ipython -pylab -profile parkfield"
2626 \layout Standard
2640 \layout Standard
2627
2641
2628 Now I have a nice little directory with everything I ever type in, organized
2642 Now I have a nice little directory with everything I ever type in, organized
2629 by project and date.
2643 by project and date.
2630 \layout Standard
2644 \layout Standard
2631
2645
2632
2646
2633 \series bold
2647 \series bold
2634 Contribute your own:
2648 Contribute your own:
2635 \series default
2649 \series default
2636 If you have your own favorite tip on using IPython efficiently for a certain
2650 If you have your own favorite tip on using IPython efficiently for a certain
2637 task (especially things which can't be done in the normal Python interpreter),
2651 task (especially things which can't be done in the normal Python interpreter),
2638 don't hesitate to send it!
2652 don't hesitate to send it!
2639 \layout Section
2653 \layout Section
2640
2654
2641 Command-line use
2655 Command-line use
2642 \layout Standard
2656 \layout Standard
2643
2657
2644 You start IPython with the command:
2658 You start IPython with the command:
2645 \layout Standard
2659 \layout Standard
2646
2660
2647
2661
2648 \family typewriter
2662 \family typewriter
2649 $ ipython [options] files
2663 $ ipython [options] files
2650 \layout Standard
2664 \layout Standard
2651
2665
2652 If invoked with no options, it executes all the files listed in sequence
2666 If invoked with no options, it executes all the files listed in sequence
2653 and drops you into the interpreter while still acknowledging any options
2667 and drops you into the interpreter while still acknowledging any options
2654 you may have set in your ipythonrc file.
2668 you may have set in your ipythonrc file.
2655 This behavior is different from standard Python, which when called as
2669 This behavior is different from standard Python, which when called as
2656 \family typewriter
2670 \family typewriter
2657 python -i
2671 python -i
2658 \family default
2672 \family default
2659 will only execute one file and ignore your configuration setup.
2673 will only execute one file and ignore your configuration setup.
2660 \layout Standard
2674 \layout Standard
2661
2675
2662 Please note that some of the configuration options are not available at
2676 Please note that some of the configuration options are not available at
2663 the command line, simply because they are not practical here.
2677 the command line, simply because they are not practical here.
2664 Look into your ipythonrc configuration file for details on those.
2678 Look into your ipythonrc configuration file for details on those.
2665 This file typically installed in the
2679 This file typically installed in the
2666 \family typewriter
2680 \family typewriter
2667 $HOME/.ipython
2681 $HOME/.ipython
2668 \family default
2682 \family default
2669 directory.
2683 directory.
2670 For Windows users,
2684 For Windows users,
2671 \family typewriter
2685 \family typewriter
2672 $HOME
2686 $HOME
2673 \family default
2687 \family default
2674 resolves to
2688 resolves to
2675 \family typewriter
2689 \family typewriter
2676 C:
2690 C:
2677 \backslash
2691 \backslash
2678
2692
2679 \backslash
2693 \backslash
2680 Documents and Settings
2694 Documents and Settings
2681 \backslash
2695 \backslash
2682
2696
2683 \backslash
2697 \backslash
2684 YourUserName
2698 YourUserName
2685 \family default
2699 \family default
2686 in most instances.
2700 in most instances.
2687 In the rest of this text, we will refer to this directory as
2701 In the rest of this text, we will refer to this directory as
2688 \family typewriter
2702 \family typewriter
2689 IPYTHONDIR
2703 IPYTHONDIR
2690 \family default
2704 \family default
2691 .
2705 .
2692 \layout Subsection
2706 \layout Subsection
2693
2707
2694
2708
2695 \begin_inset LatexCommand \label{sec:threading-opts}
2709 \begin_inset LatexCommand \label{sec:threading-opts}
2696
2710
2697 \end_inset
2711 \end_inset
2698
2712
2699 Special Threading Options
2713 Special Threading Options
2700 \layout Standard
2714 \layout Standard
2701
2715
2702 The following special options are ONLY valid at the beginning of the command
2716 The following special options are ONLY valid at the beginning of the command
2703 line, and not later.
2717 line, and not later.
2704 This is because they control the initial- ization of ipython itself, before
2718 This is because they control the initial- ization of ipython itself, before
2705 the normal option-handling mechanism is active.
2719 the normal option-handling mechanism is active.
2706 \layout List
2720 \layout List
2707 \labelwidthstring 00.00.0000
2721 \labelwidthstring 00.00.0000
2708
2722
2709
2723
2710 \family typewriter
2724 \family typewriter
2711 \series bold
2725 \series bold
2712 -gthread,\SpecialChar ~
2726 -gthread,\SpecialChar ~
2713 -qthread,\SpecialChar ~
2727 -qthread,\SpecialChar ~
2714 -wthread,\SpecialChar ~
2728 -wthread,\SpecialChar ~
2715 -pylab:
2729 -pylab:
2716 \family default
2730 \family default
2717 \series default
2731 \series default
2718 Only
2732 Only
2719 \emph on
2733 \emph on
2720 one
2734 one
2721 \emph default
2735 \emph default
2722 of these can be given, and it can only be given as the first option passed
2736 of these can be given, and it can only be given as the first option passed
2723 to IPython (it will have no effect in any other position).
2737 to IPython (it will have no effect in any other position).
2724 They provide threading support for the GTK Qt and WXPython toolkits, and
2738 They provide threading support for the GTK Qt and WXPython toolkits, and
2725 for the matplotlib library.
2739 for the matplotlib library.
2726 \layout List
2740 \layout List
2727 \labelwidthstring 00.00.0000
2741 \labelwidthstring 00.00.0000
2728
2742
2729 \SpecialChar ~
2743 \SpecialChar ~
2730 With any of the first three options, IPython starts running a separate
2744 With any of the first three options, IPython starts running a separate
2731 thread for the graphical toolkit's operation, so that you can open and
2745 thread for the graphical toolkit's operation, so that you can open and
2732 control graphical elements from within an IPython command line, without
2746 control graphical elements from within an IPython command line, without
2733 blocking.
2747 blocking.
2734 All three provide essentially the same functionality, respectively for
2748 All three provide essentially the same functionality, respectively for
2735 GTK, QT and WXWidgets (via their Python interfaces).
2749 GTK, QT and WXWidgets (via their Python interfaces).
2736 \layout List
2750 \layout List
2737 \labelwidthstring 00.00.0000
2751 \labelwidthstring 00.00.0000
2738
2752
2739 \SpecialChar ~
2753 \SpecialChar ~
2740 Note that with
2754 Note that with
2741 \family typewriter
2755 \family typewriter
2742 -wthread
2756 -wthread
2743 \family default
2757 \family default
2744 , you can additionally use the -wxversion option to request a specific version
2758 , you can additionally use the -wxversion option to request a specific version
2745 of wx to be used.
2759 of wx to be used.
2746 This requires that you have the
2760 This requires that you have the
2747 \family typewriter
2761 \family typewriter
2748 wxversion
2762 wxversion
2749 \family default
2763 \family default
2750 Python module installed, which is part of recent wxPython distributions.
2764 Python module installed, which is part of recent wxPython distributions.
2751 \layout List
2765 \layout List
2752 \labelwidthstring 00.00.0000
2766 \labelwidthstring 00.00.0000
2753
2767
2754 \SpecialChar ~
2768 \SpecialChar ~
2755 If
2769 If
2756 \family typewriter
2770 \family typewriter
2757 -pylab
2771 -pylab
2758 \family default
2772 \family default
2759 is given, IPython loads special support for the mat plotlib library (
2773 is given, IPython loads special support for the mat plotlib library (
2760 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2774 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2761
2775
2762 \end_inset
2776 \end_inset
2763
2777
2764 ), allowing interactive usage of any of its backends as defined in the user's
2778 ), allowing interactive usage of any of its backends as defined in the user's
2765
2779
2766 \family typewriter
2780 \family typewriter
2767 ~/.matplotlib/matplotlibrc
2781 ~/.matplotlib/matplotlibrc
2768 \family default
2782 \family default
2769 file.
2783 file.
2770 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2784 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2771 of matplotlib backend requires it.
2785 of matplotlib backend requires it.
2772 It also modifies the
2786 It also modifies the
2773 \family typewriter
2787 \family typewriter
2774 %run
2788 %run
2775 \family default
2789 \family default
2776 command to correctly execute (without blocking) any matplotlib-based script
2790 command to correctly execute (without blocking) any matplotlib-based script
2777 which calls
2791 which calls
2778 \family typewriter
2792 \family typewriter
2779 show()
2793 show()
2780 \family default
2794 \family default
2781 at the end.
2795 at the end.
2782
2796
2783 \layout List
2797 \layout List
2784 \labelwidthstring 00.00.0000
2798 \labelwidthstring 00.00.0000
2785
2799
2786
2800
2787 \family typewriter
2801 \family typewriter
2788 \series bold
2802 \series bold
2789 -tk
2803 -tk
2790 \family default
2804 \family default
2791 \series default
2805 \series default
2792 The
2806 The
2793 \family typewriter
2807 \family typewriter
2794 -g/q/wthread
2808 -g/q/wthread
2795 \family default
2809 \family default
2796 options, and
2810 options, and
2797 \family typewriter
2811 \family typewriter
2798 -pylab
2812 -pylab
2799 \family default
2813 \family default
2800 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2814 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2801 Tk graphical interfaces.
2815 Tk graphical interfaces.
2802 This means that when either GTK, Qt or WX threading is active, any attempt
2816 This means that when either GTK, Qt or WX threading is active, any attempt
2803 to open a Tk GUI will result in a dead window, and possibly cause the Python
2817 to open a Tk GUI will result in a dead window, and possibly cause the Python
2804 interpreter to crash.
2818 interpreter to crash.
2805 An extra option,
2819 An extra option,
2806 \family typewriter
2820 \family typewriter
2807 -tk
2821 -tk
2808 \family default
2822 \family default
2809 , is available to address this issue.
2823 , is available to address this issue.
2810 It can
2824 It can
2811 \emph on
2825 \emph on
2812 only
2826 only
2813 \emph default
2827 \emph default
2814 be given as a
2828 be given as a
2815 \emph on
2829 \emph on
2816 second
2830 second
2817 \emph default
2831 \emph default
2818 option after any of the above (
2832 option after any of the above (
2819 \family typewriter
2833 \family typewriter
2820 -gthread
2834 -gthread
2821 \family default
2835 \family default
2822 ,
2836 ,
2823 \family typewriter
2837 \family typewriter
2824 -wthread
2838 -wthread
2825 \family default
2839 \family default
2826 or
2840 or
2827 \family typewriter
2841 \family typewriter
2828 -pylab
2842 -pylab
2829 \family default
2843 \family default
2830 ).
2844 ).
2831 \layout List
2845 \layout List
2832 \labelwidthstring 00.00.0000
2846 \labelwidthstring 00.00.0000
2833
2847
2834 \SpecialChar ~
2848 \SpecialChar ~
2835 If
2849 If
2836 \family typewriter
2850 \family typewriter
2837 -tk
2851 -tk
2838 \family default
2852 \family default
2839 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2853 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2840 This is however potentially unreliable, and you will have to test on your
2854 This is however potentially unreliable, and you will have to test on your
2841 platform and Python configuration to determine whether it works for you.
2855 platform and Python configuration to determine whether it works for you.
2842 Debian users have reported success, apparently due to the fact that Debian
2856 Debian users have reported success, apparently due to the fact that Debian
2843 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2857 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2844 Under other Linux environments (such as Fedora Core 2/3), this option has
2858 Under other Linux environments (such as Fedora Core 2/3), this option has
2845 caused random crashes and lockups of the Python interpreter.
2859 caused random crashes and lockups of the Python interpreter.
2846 Under other operating systems (Mac OSX and Windows), you'll need to try
2860 Under other operating systems (Mac OSX and Windows), you'll need to try
2847 it to find out, since currently no user reports are available.
2861 it to find out, since currently no user reports are available.
2848 \layout List
2862 \layout List
2849 \labelwidthstring 00.00.0000
2863 \labelwidthstring 00.00.0000
2850
2864
2851 \SpecialChar ~
2865 \SpecialChar ~
2852 There is unfortunately no way for IPython to determine at run time whether
2866 There is unfortunately no way for IPython to determine at run time whether
2853
2867
2854 \family typewriter
2868 \family typewriter
2855 -tk
2869 -tk
2856 \family default
2870 \family default
2857 will work reliably or not, so you will need to do some experiments before
2871 will work reliably or not, so you will need to do some experiments before
2858 relying on it for regular work.
2872 relying on it for regular work.
2859
2873
2860 \layout Subsection
2874 \layout Subsection
2861
2875
2862
2876
2863 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2877 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2864
2878
2865 \end_inset
2879 \end_inset
2866
2880
2867 Regular Options
2881 Regular Options
2868 \layout Standard
2882 \layout Standard
2869
2883
2870 After the above threading options have been given, regular options can follow
2884 After the above threading options have been given, regular options can follow
2871 in any order.
2885 in any order.
2872 All options can be abbreviated to their shortest non-ambiguous form and
2886 All options can be abbreviated to their shortest non-ambiguous form and
2873 are case-sensitive.
2887 are case-sensitive.
2874 One or two dashes can be used.
2888 One or two dashes can be used.
2875 Some options have an alternate short form, indicated after a
2889 Some options have an alternate short form, indicated after a
2876 \family typewriter
2890 \family typewriter
2877 |
2891 |
2878 \family default
2892 \family default
2879 .
2893 .
2880 \layout Standard
2894 \layout Standard
2881
2895
2882 Most options can also be set from your ipythonrc configuration file.
2896 Most options can also be set from your ipythonrc configuration file.
2883 See the provided example for more details on what the options do.
2897 See the provided example for more details on what the options do.
2884 Options given at the command line override the values set in the ipythonrc
2898 Options given at the command line override the values set in the ipythonrc
2885 file.
2899 file.
2886 \layout Standard
2900 \layout Standard
2887
2901
2888 All options with a
2902 All options with a
2889 \family typewriter
2903 \family typewriter
2890 [no]
2904 [no]
2891 \family default
2905 \family default
2892 prepended can be specified in negated form (
2906 prepended can be specified in negated form (
2893 \family typewriter
2907 \family typewriter
2894 -nooption
2908 -nooption
2895 \family default
2909 \family default
2896 instead of
2910 instead of
2897 \family typewriter
2911 \family typewriter
2898 -option
2912 -option
2899 \family default
2913 \family default
2900 ) to turn the feature off.
2914 ) to turn the feature off.
2901 \layout List
2915 \layout List
2902 \labelwidthstring 00.00.0000
2916 \labelwidthstring 00.00.0000
2903
2917
2904
2918
2905 \family typewriter
2919 \family typewriter
2906 \series bold
2920 \series bold
2907 -help
2921 -help
2908 \family default
2922 \family default
2909 \series default
2923 \series default
2910 : print a help message and exit.
2924 : print a help message and exit.
2911 \layout List
2925 \layout List
2912 \labelwidthstring 00.00.0000
2926 \labelwidthstring 00.00.0000
2913
2927
2914
2928
2915 \family typewriter
2929 \family typewriter
2916 \series bold
2930 \series bold
2917 -pylab:
2931 -pylab:
2918 \family default
2932 \family default
2919 \series default
2933 \series default
2920 this can
2934 this can
2921 \emph on
2935 \emph on
2922 only
2936 only
2923 \emph default
2937 \emph default
2924 be given as the
2938 be given as the
2925 \emph on
2939 \emph on
2926 first
2940 first
2927 \emph default
2941 \emph default
2928 option passed to IPython (it will have no effect in any other position).
2942 option passed to IPython (it will have no effect in any other position).
2929 It adds special support for the matplotlib library (
2943 It adds special support for the matplotlib library (
2930 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2944 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2931
2945
2932 \end_inset
2946 \end_inset
2933
2947
2934 ), allowing interactive usage of any of its backends as defined in the user's
2948 ), allowing interactive usage of any of its backends as defined in the user's
2935
2949
2936 \family typewriter
2950 \family typewriter
2937 .matplotlibrc
2951 .matplotlibrc
2938 \family default
2952 \family default
2939 file.
2953 file.
2940 It automatically activates GTK or WX threading for IPyhton if the choice
2954 It automatically activates GTK or WX threading for IPyhton if the choice
2941 of matplotlib backend requires it.
2955 of matplotlib backend requires it.
2942 It also modifies the
2956 It also modifies the
2943 \family typewriter
2957 \family typewriter
2944 %run
2958 %run
2945 \family default
2959 \family default
2946 command to correctly execute (without blocking) any matplotlib-based script
2960 command to correctly execute (without blocking) any matplotlib-based script
2947 which calls
2961 which calls
2948 \family typewriter
2962 \family typewriter
2949 show()
2963 show()
2950 \family default
2964 \family default
2951 at the end.
2965 at the end.
2952 See Sec.\SpecialChar ~
2966 See Sec.\SpecialChar ~
2953
2967
2954 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2968 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2955
2969
2956 \end_inset
2970 \end_inset
2957
2971
2958 for more details.
2972 for more details.
2959 \layout List
2973 \layout List
2960 \labelwidthstring 00.00.0000
2974 \labelwidthstring 00.00.0000
2961
2975
2962
2976
2963 \family typewriter
2977 \family typewriter
2964 \series bold
2978 \series bold
2965 -autocall <val>:
2979 -autocall <val>:
2966 \family default
2980 \family default
2967 \series default
2981 \series default
2968 Make IPython automatically call any callable object even if you didn't
2982 Make IPython automatically call any callable object even if you didn't
2969 type explicit parentheses.
2983 type explicit parentheses.
2970 For example, `str 43' becomes `str(43)' automatically.
2984 For example, `str 43' becomes `str(43)' automatically.
2971 The value can be `0' to disable the feature, `1' for
2985 The value can be `0' to disable the feature, `1' for
2972 \emph on
2986 \emph on
2973 smart
2987 smart
2974 \emph default
2988 \emph default
2975 autocall, where it is not applied if there are no more arguments on the
2989 autocall, where it is not applied if there are no more arguments on the
2976 line, and `2' for
2990 line, and `2' for
2977 \emph on
2991 \emph on
2978 full
2992 full
2979 \emph default
2993 \emph default
2980 autocall, where all callable objects are automatically called (even if
2994 autocall, where all callable objects are automatically called (even if
2981 no arguments are present).
2995 no arguments are present).
2982 The default is `1'.
2996 The default is `1'.
2983 \layout List
2997 \layout List
2984 \labelwidthstring 00.00.0000
2998 \labelwidthstring 00.00.0000
2985
2999
2986
3000
2987 \family typewriter
3001 \family typewriter
2988 \series bold
3002 \series bold
2989 -[no]autoindent:
3003 -[no]autoindent:
2990 \family default
3004 \family default
2991 \series default
3005 \series default
2992 Turn automatic indentation on/off.
3006 Turn automatic indentation on/off.
2993 \layout List
3007 \layout List
2994 \labelwidthstring 00.00.0000
3008 \labelwidthstring 00.00.0000
2995
3009
2996
3010
2997 \family typewriter
3011 \family typewriter
2998 \series bold
3012 \series bold
2999 -[no]automagic
3013 -[no]automagic
3000 \series default
3014 \series default
3001 :
3015 :
3002 \family default
3016 \family default
3003 make magic commands automatic (without needing their first character to
3017 make magic commands automatic (without needing their first character to
3004 be
3018 be
3005 \family typewriter
3019 \family typewriter
3006 %
3020 %
3007 \family default
3021 \family default
3008 ).
3022 ).
3009 Type
3023 Type
3010 \family typewriter
3024 \family typewriter
3011 %magic
3025 %magic
3012 \family default
3026 \family default
3013 at the IPython prompt for more information.
3027 at the IPython prompt for more information.
3014 \layout List
3028 \layout List
3015 \labelwidthstring 00.00.0000
3029 \labelwidthstring 00.00.0000
3016
3030
3017
3031
3018 \family typewriter
3032 \family typewriter
3019 \series bold
3033 \series bold
3020 -[no]autoedit_syntax:
3034 -[no]autoedit_syntax:
3021 \family default
3035 \family default
3022 \series default
3036 \series default
3023 When a syntax error occurs after editing a file, automatically open the
3037 When a syntax error occurs after editing a file, automatically open the
3024 file to the trouble causing line for convenient fixing.
3038 file to the trouble causing line for convenient fixing.
3025
3039
3026 \layout List
3040 \layout List
3027 \labelwidthstring 00.00.0000
3041 \labelwidthstring 00.00.0000
3028
3042
3029
3043
3030 \family typewriter
3044 \family typewriter
3031 \series bold
3045 \series bold
3032 -[no]banner
3046 -[no]banner
3033 \series default
3047 \series default
3034 :
3048 :
3035 \family default
3049 \family default
3036 Print the initial information banner (default on).
3050 Print the initial information banner (default on).
3037 \layout List
3051 \layout List
3038 \labelwidthstring 00.00.0000
3052 \labelwidthstring 00.00.0000
3039
3053
3040
3054
3041 \family typewriter
3055 \family typewriter
3042 \series bold
3056 \series bold
3043 -c\SpecialChar ~
3057 -c\SpecialChar ~
3044 <command>:
3058 <command>:
3045 \family default
3059 \family default
3046 \series default
3060 \series default
3047 execute the given command string, and set sys.argv to
3061 execute the given command string, and set sys.argv to
3048 \family typewriter
3062 \family typewriter
3049 ['c']
3063 ['c']
3050 \family default
3064 \family default
3051 .
3065 .
3052 This is similar to the
3066 This is similar to the
3053 \family typewriter
3067 \family typewriter
3054 -c
3068 -c
3055 \family default
3069 \family default
3056 option in the normal Python interpreter.
3070 option in the normal Python interpreter.
3057
3071
3058 \layout List
3072 \layout List
3059 \labelwidthstring 00.00.0000
3073 \labelwidthstring 00.00.0000
3060
3074
3061
3075
3062 \family typewriter
3076 \family typewriter
3063 \series bold
3077 \series bold
3064 -cache_size|cs\SpecialChar ~
3078 -cache_size|cs\SpecialChar ~
3065 <n>
3079 <n>
3066 \series default
3080 \series default
3067 :
3081 :
3068 \family default
3082 \family default
3069 size of the output cache (maximum number of entries to hold in memory).
3083 size of the output cache (maximum number of entries to hold in memory).
3070 The default is 1000, you can change it permanently in your config file.
3084 The default is 1000, you can change it permanently in your config file.
3071 Setting it to 0 completely disables the caching system, and the minimum
3085 Setting it to 0 completely disables the caching system, and the minimum
3072 value accepted is 20 (if you provide a value less than 20, it is reset
3086 value accepted is 20 (if you provide a value less than 20, it is reset
3073 to 0 and a warning is issued) This limit is defined because otherwise you'll
3087 to 0 and a warning is issued) This limit is defined because otherwise you'll
3074 spend more time re-flushing a too small cache than working.
3088 spend more time re-flushing a too small cache than working.
3075 \layout List
3089 \layout List
3076 \labelwidthstring 00.00.0000
3090 \labelwidthstring 00.00.0000
3077
3091
3078
3092
3079 \family typewriter
3093 \family typewriter
3080 \series bold
3094 \series bold
3081 -classic|cl
3095 -classic|cl
3082 \series default
3096 \series default
3083 :
3097 :
3084 \family default
3098 \family default
3085 Gives IPython a similar feel to the classic Python prompt.
3099 Gives IPython a similar feel to the classic Python prompt.
3086 \layout List
3100 \layout List
3087 \labelwidthstring 00.00.0000
3101 \labelwidthstring 00.00.0000
3088
3102
3089
3103
3090 \family typewriter
3104 \family typewriter
3091 \series bold
3105 \series bold
3092 -colors\SpecialChar ~
3106 -colors\SpecialChar ~
3093 <scheme>:
3107 <scheme>:
3094 \family default
3108 \family default
3095 \series default
3109 \series default
3096 Color scheme for prompts and exception reporting.
3110 Color scheme for prompts and exception reporting.
3097 Currently implemented: NoColor, Linux and LightBG.
3111 Currently implemented: NoColor, Linux and LightBG.
3098 \layout List
3112 \layout List
3099 \labelwidthstring 00.00.0000
3113 \labelwidthstring 00.00.0000
3100
3114
3101
3115
3102 \family typewriter
3116 \family typewriter
3103 \series bold
3117 \series bold
3104 -[no]color_info:
3118 -[no]color_info:
3105 \family default
3119 \family default
3106 \series default
3120 \series default
3107 IPython can display information about objects via a set of functions, and
3121 IPython can display information about objects via a set of functions, and
3108 optionally can use colors for this, syntax highlighting source code and
3122 optionally can use colors for this, syntax highlighting source code and
3109 various other elements.
3123 various other elements.
3110 However, because this information is passed through a pager (like 'less')
3124 However, because this information is passed through a pager (like 'less')
3111 and many pagers get confused with color codes, this option is off by default.
3125 and many pagers get confused with color codes, this option is off by default.
3112 You can test it and turn it on permanently in your ipythonrc file if it
3126 You can test it and turn it on permanently in your ipythonrc file if it
3113 works for you.
3127 works for you.
3114 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
3128 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
3115 that in RedHat 7.2 doesn't.
3129 that in RedHat 7.2 doesn't.
3116 \layout List
3130 \layout List
3117 \labelwidthstring 00.00.0000
3131 \labelwidthstring 00.00.0000
3118
3132
3119 \SpecialChar ~
3133 \SpecialChar ~
3120 Test it and turn it on permanently if it works with your system.
3134 Test it and turn it on permanently if it works with your system.
3121 The magic function
3135 The magic function
3122 \family typewriter
3136 \family typewriter
3123 %color_info
3137 %color_info
3124 \family default
3138 \family default
3125 allows you to toggle this interactively for testing.
3139 allows you to toggle this interactively for testing.
3126 \layout List
3140 \layout List
3127 \labelwidthstring 00.00.0000
3141 \labelwidthstring 00.00.0000
3128
3142
3129
3143
3130 \family typewriter
3144 \family typewriter
3131 \series bold
3145 \series bold
3132 -[no]debug
3146 -[no]debug
3133 \family default
3147 \family default
3134 \series default
3148 \series default
3135 : Show information about the loading process.
3149 : Show information about the loading process.
3136 Very useful to pin down problems with your configuration files or to get
3150 Very useful to pin down problems with your configuration files or to get
3137 details about session restores.
3151 details about session restores.
3138 \layout List
3152 \layout List
3139 \labelwidthstring 00.00.0000
3153 \labelwidthstring 00.00.0000
3140
3154
3141
3155
3142 \family typewriter
3156 \family typewriter
3143 \series bold
3157 \series bold
3144 -[no]deep_reload
3158 -[no]deep_reload
3145 \series default
3159 \series default
3146 :
3160 :
3147 \family default
3161 \family default
3148 IPython can use the
3162 IPython can use the
3149 \family typewriter
3163 \family typewriter
3150 deep_reload
3164 deep_reload
3151 \family default
3165 \family default
3152 module which reloads changes in modules recursively (it replaces the
3166 module which reloads changes in modules recursively (it replaces the
3153 \family typewriter
3167 \family typewriter
3154 reload()
3168 reload()
3155 \family default
3169 \family default
3156 function, so you don't need to change anything to use it).
3170 function, so you don't need to change anything to use it).
3157
3171
3158 \family typewriter
3172 \family typewriter
3159 deep_reload()
3173 deep_reload()
3160 \family default
3174 \family default
3161 forces a full reload of modules whose code may have changed, which the
3175 forces a full reload of modules whose code may have changed, which the
3162 default
3176 default
3163 \family typewriter
3177 \family typewriter
3164 reload()
3178 reload()
3165 \family default
3179 \family default
3166 function does not.
3180 function does not.
3167 \layout List
3181 \layout List
3168 \labelwidthstring 00.00.0000
3182 \labelwidthstring 00.00.0000
3169
3183
3170 \SpecialChar ~
3184 \SpecialChar ~
3171 When deep_reload is off, IPython will use the normal
3185 When deep_reload is off, IPython will use the normal
3172 \family typewriter
3186 \family typewriter
3173 reload()
3187 reload()
3174 \family default
3188 \family default
3175 , but deep_reload will still be available as
3189 , but deep_reload will still be available as
3176 \family typewriter
3190 \family typewriter
3177 dreload()
3191 dreload()
3178 \family default
3192 \family default
3179 .
3193 .
3180 This feature is off by default [which means that you have both normal
3194 This feature is off by default [which means that you have both normal
3181 \family typewriter
3195 \family typewriter
3182 reload()
3196 reload()
3183 \family default
3197 \family default
3184 and
3198 and
3185 \family typewriter
3199 \family typewriter
3186 dreload()
3200 dreload()
3187 \family default
3201 \family default
3188 ].
3202 ].
3189 \layout List
3203 \layout List
3190 \labelwidthstring 00.00.0000
3204 \labelwidthstring 00.00.0000
3191
3205
3192
3206
3193 \family typewriter
3207 \family typewriter
3194 \series bold
3208 \series bold
3195 -editor\SpecialChar ~
3209 -editor\SpecialChar ~
3196 <name>
3210 <name>
3197 \family default
3211 \family default
3198 \series default
3212 \series default
3199 : Which editor to use with the
3213 : Which editor to use with the
3200 \family typewriter
3214 \family typewriter
3201 %edit
3215 %edit
3202 \family default
3216 \family default
3203 command.
3217 command.
3204 By default, IPython will honor your
3218 By default, IPython will honor your
3205 \family typewriter
3219 \family typewriter
3206 EDITOR
3220 EDITOR
3207 \family default
3221 \family default
3208 environment variable (if not set, vi is the Unix default and notepad the
3222 environment variable (if not set, vi is the Unix default and notepad the
3209 Windows one).
3223 Windows one).
3210 Since this editor is invoked on the fly by IPython and is meant for editing
3224 Since this editor is invoked on the fly by IPython and is meant for editing
3211 small code snippets, you may want to use a small, lightweight editor here
3225 small code snippets, you may want to use a small, lightweight editor here
3212 (in case your default
3226 (in case your default
3213 \family typewriter
3227 \family typewriter
3214 EDITOR
3228 EDITOR
3215 \family default
3229 \family default
3216 is something like Emacs).
3230 is something like Emacs).
3217 \layout List
3231 \layout List
3218 \labelwidthstring 00.00.0000
3232 \labelwidthstring 00.00.0000
3219
3233
3220
3234
3221 \family typewriter
3235 \family typewriter
3222 \series bold
3236 \series bold
3223 -ipythondir\SpecialChar ~
3237 -ipythondir\SpecialChar ~
3224 <name>
3238 <name>
3225 \series default
3239 \series default
3226 :
3240 :
3227 \family default
3241 \family default
3228 name of your IPython configuration directory
3242 name of your IPython configuration directory
3229 \family typewriter
3243 \family typewriter
3230 IPYTHONDIR
3244 IPYTHONDIR
3231 \family default
3245 \family default
3232 .
3246 .
3233 This can also be specified through the environment variable
3247 This can also be specified through the environment variable
3234 \family typewriter
3248 \family typewriter
3235 IPYTHONDIR
3249 IPYTHONDIR
3236 \family default
3250 \family default
3237 .
3251 .
3238 \layout List
3252 \layout List
3239 \labelwidthstring 00.00.0000
3253 \labelwidthstring 00.00.0000
3240
3254
3241
3255
3242 \family typewriter
3256 \family typewriter
3243 \series bold
3257 \series bold
3244 -log|l
3258 -log|l
3245 \family default
3259 \family default
3246 \series default
3260 \series default
3247 : generate a log file of all input.
3261 : generate a log file of all input.
3248 The file is named
3262 The file is named
3249 \family typewriter
3263 \family typewriter
3250 ipython_log.py
3264 ipython_log.py
3251 \family default
3265 \family default
3252 in your current directory (which prevents logs from multiple IPython sessions
3266 in your current directory (which prevents logs from multiple IPython sessions
3253 from trampling each other).
3267 from trampling each other).
3254 You can use this to later restore a session by loading your logfile as
3268 You can use this to later restore a session by loading your logfile as
3255 a file to be executed with option
3269 a file to be executed with option
3256 \family typewriter
3270 \family typewriter
3257 -logplay
3271 -logplay
3258 \family default
3272 \family default
3259 (see below).
3273 (see below).
3260 \layout List
3274 \layout List
3261 \labelwidthstring 00.00.0000
3275 \labelwidthstring 00.00.0000
3262
3276
3263
3277
3264 \family typewriter
3278 \family typewriter
3265 \series bold
3279 \series bold
3266 -logfile|lf\SpecialChar ~
3280 -logfile|lf\SpecialChar ~
3267 <name>
3281 <name>
3268 \series default
3282 \series default
3269 :
3283 :
3270 \family default
3284 \family default
3271 specify the name of your logfile.
3285 specify the name of your logfile.
3272 \layout List
3286 \layout List
3273 \labelwidthstring 00.00.0000
3287 \labelwidthstring 00.00.0000
3274
3288
3275
3289
3276 \family typewriter
3290 \family typewriter
3277 \series bold
3291 \series bold
3278 -logplay|lp\SpecialChar ~
3292 -logplay|lp\SpecialChar ~
3279 <name>
3293 <name>
3280 \series default
3294 \series default
3281 :
3295 :
3282 \family default
3296 \family default
3283 you can replay a previous log.
3297 you can replay a previous log.
3284 For restoring a session as close as possible to the state you left it in,
3298 For restoring a session as close as possible to the state you left it in,
3285 use this option (don't just run the logfile).
3299 use this option (don't just run the logfile).
3286 With
3300 With
3287 \family typewriter
3301 \family typewriter
3288 -logplay
3302 -logplay
3289 \family default
3303 \family default
3290 , IPython will try to reconstruct the previous working environment in full,
3304 , IPython will try to reconstruct the previous working environment in full,
3291 not just execute the commands in the logfile.
3305 not just execute the commands in the logfile.
3292 \layout List
3306 \layout List
3293 \labelwidthstring 00.00.0000
3307 \labelwidthstring 00.00.0000
3294
3308
3295 \SpecialChar ~
3309 \SpecialChar ~
3296 When a session is restored, logging is automatically turned on again with
3310 When a session is restored, logging is automatically turned on again with
3297 the name of the logfile it was invoked with (it is read from the log header).
3311 the name of the logfile it was invoked with (it is read from the log header).
3298 So once you've turned logging on for a session, you can quit IPython and
3312 So once you've turned logging on for a session, you can quit IPython and
3299 reload it as many times as you want and it will continue to log its history
3313 reload it as many times as you want and it will continue to log its history
3300 and restore from the beginning every time.
3314 and restore from the beginning every time.
3301 \layout List
3315 \layout List
3302 \labelwidthstring 00.00.0000
3316 \labelwidthstring 00.00.0000
3303
3317
3304 \SpecialChar ~
3318 \SpecialChar ~
3305 Caveats: there are limitations in this option.
3319 Caveats: there are limitations in this option.
3306 The history variables
3320 The history variables
3307 \family typewriter
3321 \family typewriter
3308 _i*
3322 _i*
3309 \family default
3323 \family default
3310 ,
3324 ,
3311 \family typewriter
3325 \family typewriter
3312 _*
3326 _*
3313 \family default
3327 \family default
3314 and
3328 and
3315 \family typewriter
3329 \family typewriter
3316 _dh
3330 _dh
3317 \family default
3331 \family default
3318 don't get restored properly.
3332 don't get restored properly.
3319 In the future we will try to implement full session saving by writing and
3333 In the future we will try to implement full session saving by writing and
3320 retrieving a 'snapshot' of the memory state of IPython.
3334 retrieving a 'snapshot' of the memory state of IPython.
3321 But our first attempts failed because of inherent limitations of Python's
3335 But our first attempts failed because of inherent limitations of Python's
3322 Pickle module, so this may have to wait.
3336 Pickle module, so this may have to wait.
3323 \layout List
3337 \layout List
3324 \labelwidthstring 00.00.0000
3338 \labelwidthstring 00.00.0000
3325
3339
3326
3340
3327 \family typewriter
3341 \family typewriter
3328 \series bold
3342 \series bold
3329 -[no]messages
3343 -[no]messages
3330 \series default
3344 \series default
3331 :
3345 :
3332 \family default
3346 \family default
3333 Print messages which IPython collects about its startup process (default
3347 Print messages which IPython collects about its startup process (default
3334 on).
3348 on).
3335 \layout List
3349 \layout List
3336 \labelwidthstring 00.00.0000
3350 \labelwidthstring 00.00.0000
3337
3351
3338
3352
3339 \family typewriter
3353 \family typewriter
3340 \series bold
3354 \series bold
3341 -[no]pdb
3355 -[no]pdb
3342 \family default
3356 \family default
3343 \series default
3357 \series default
3344 : Automatically call the pdb debugger after every uncaught exception.
3358 : Automatically call the pdb debugger after every uncaught exception.
3345 If you are used to debugging using pdb, this puts you automatically inside
3359 If you are used to debugging using pdb, this puts you automatically inside
3346 of it after any call (either in IPython or in code called by it) which
3360 of it after any call (either in IPython or in code called by it) which
3347 triggers an exception which goes uncaught.
3361 triggers an exception which goes uncaught.
3348 \layout List
3362 \layout List
3349 \labelwidthstring 00.00.0000
3363 \labelwidthstring 00.00.0000
3350
3364
3351
3365
3352 \family typewriter
3366 \family typewriter
3353 \series bold
3367 \series bold
3354 -[no]pprint
3368 -[no]pprint
3355 \series default
3369 \series default
3356 :
3370 :
3357 \family default
3371 \family default
3358 ipython can optionally use the pprint (pretty printer) module for displaying
3372 ipython can optionally use the pprint (pretty printer) module for displaying
3359 results.
3373 results.
3360 pprint tends to give a nicer display of nested data structures.
3374 pprint tends to give a nicer display of nested data structures.
3361 If you like it, you can turn it on permanently in your config file (default
3375 If you like it, you can turn it on permanently in your config file (default
3362 off).
3376 off).
3363 \layout List
3377 \layout List
3364 \labelwidthstring 00.00.0000
3378 \labelwidthstring 00.00.0000
3365
3379
3366
3380
3367 \family typewriter
3381 \family typewriter
3368 \series bold
3382 \series bold
3369 -profile|p <name>
3383 -profile|p <name>
3370 \series default
3384 \series default
3371 :
3385 :
3372 \family default
3386 \family default
3373 assume that your config file is
3387 assume that your config file is
3374 \family typewriter
3388 \family typewriter
3375 ipythonrc-<name>
3389 ipythonrc-<name>
3376 \family default
3390 \family default
3377 (looks in current dir first, then in
3391 (looks in current dir first, then in
3378 \family typewriter
3392 \family typewriter
3379 IPYTHONDIR
3393 IPYTHONDIR
3380 \family default
3394 \family default
3381 ).
3395 ).
3382 This is a quick way to keep and load multiple config files for different
3396 This is a quick way to keep and load multiple config files for different
3383 tasks, especially if you use the include option of config files.
3397 tasks, especially if you use the include option of config files.
3384 You can keep a basic
3398 You can keep a basic
3385 \family typewriter
3399 \family typewriter
3386 IPYTHONDIR/ipythonrc
3400 IPYTHONDIR/ipythonrc
3387 \family default
3401 \family default
3388 file and then have other 'profiles' which include this one and load extra
3402 file and then have other 'profiles' which include this one and load extra
3389 things for particular tasks.
3403 things for particular tasks.
3390 For example:
3404 For example:
3391 \layout List
3405 \layout List
3392 \labelwidthstring 00.00.0000
3406 \labelwidthstring 00.00.0000
3393
3407
3394
3408
3395 \family typewriter
3409 \family typewriter
3396 \SpecialChar ~
3410 \SpecialChar ~
3397
3411
3398 \family default
3412 \family default
3399 1.
3413 1.
3400
3414
3401 \family typewriter
3415 \family typewriter
3402 $HOME/.ipython/ipythonrc
3416 $HOME/.ipython/ipythonrc
3403 \family default
3417 \family default
3404 : load basic things you always want.
3418 : load basic things you always want.
3405 \layout List
3419 \layout List
3406 \labelwidthstring 00.00.0000
3420 \labelwidthstring 00.00.0000
3407
3421
3408
3422
3409 \family typewriter
3423 \family typewriter
3410 \SpecialChar ~
3424 \SpecialChar ~
3411
3425
3412 \family default
3426 \family default
3413 2.
3427 2.
3414
3428
3415 \family typewriter
3429 \family typewriter
3416 $HOME/.ipython/ipythonrc-math
3430 $HOME/.ipython/ipythonrc-math
3417 \family default
3431 \family default
3418 : load (1) and basic math-related modules.
3432 : load (1) and basic math-related modules.
3419
3433
3420 \layout List
3434 \layout List
3421 \labelwidthstring 00.00.0000
3435 \labelwidthstring 00.00.0000
3422
3436
3423
3437
3424 \family typewriter
3438 \family typewriter
3425 \SpecialChar ~
3439 \SpecialChar ~
3426
3440
3427 \family default
3441 \family default
3428 3.
3442 3.
3429
3443
3430 \family typewriter
3444 \family typewriter
3431 $HOME/.ipython/ipythonrc-numeric
3445 $HOME/.ipython/ipythonrc-numeric
3432 \family default
3446 \family default
3433 : load (1) and Numeric and plotting modules.
3447 : load (1) and Numeric and plotting modules.
3434 \layout List
3448 \layout List
3435 \labelwidthstring 00.00.0000
3449 \labelwidthstring 00.00.0000
3436
3450
3437 \SpecialChar ~
3451 \SpecialChar ~
3438 Since it is possible to create an endless loop by having circular file
3452 Since it is possible to create an endless loop by having circular file
3439 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3453 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3440 \layout List
3454 \layout List
3441 \labelwidthstring 00.00.0000
3455 \labelwidthstring 00.00.0000
3442
3456
3443
3457
3444 \family typewriter
3458 \family typewriter
3445 \series bold
3459 \series bold
3446 -prompt_in1|pi1\SpecialChar ~
3460 -prompt_in1|pi1\SpecialChar ~
3447 <string>:
3461 <string>:
3448 \family default
3462 \family default
3449 \series default
3463 \series default
3450 Specify the string used for input prompts.
3464 Specify the string used for input prompts.
3451 Note that if you are using numbered prompts, the number is represented
3465 Note that if you are using numbered prompts, the number is represented
3452 with a '
3466 with a '
3453 \backslash
3467 \backslash
3454 #' in the string.
3468 #' in the string.
3455 Don't forget to quote strings with spaces embedded in them.
3469 Don't forget to quote strings with spaces embedded in them.
3456 Default: '
3470 Default: '
3457 \family typewriter
3471 \family typewriter
3458 In\SpecialChar ~
3472 In\SpecialChar ~
3459 [
3473 [
3460 \backslash
3474 \backslash
3461 #]:
3475 #]:
3462 \family default
3476 \family default
3463 '.
3477 '.
3464 Sec.\SpecialChar ~
3478 Sec.\SpecialChar ~
3465
3479
3466 \begin_inset LatexCommand \ref{sec:prompts}
3480 \begin_inset LatexCommand \ref{sec:prompts}
3467
3481
3468 \end_inset
3482 \end_inset
3469
3483
3470 discusses in detail all the available escapes to customize your prompts.
3484 discusses in detail all the available escapes to customize your prompts.
3471 \layout List
3485 \layout List
3472 \labelwidthstring 00.00.0000
3486 \labelwidthstring 00.00.0000
3473
3487
3474
3488
3475 \family typewriter
3489 \family typewriter
3476 \series bold
3490 \series bold
3477 -prompt_in2|pi2\SpecialChar ~
3491 -prompt_in2|pi2\SpecialChar ~
3478 <string>:
3492 <string>:
3479 \family default
3493 \family default
3480 \series default
3494 \series default
3481 Similar to the previous option, but used for the continuation prompts.
3495 Similar to the previous option, but used for the continuation prompts.
3482 The special sequence '
3496 The special sequence '
3483 \family typewriter
3497 \family typewriter
3484
3498
3485 \backslash
3499 \backslash
3486 D
3500 D
3487 \family default
3501 \family default
3488 ' is similar to '
3502 ' is similar to '
3489 \family typewriter
3503 \family typewriter
3490
3504
3491 \backslash
3505 \backslash
3492 #
3506 #
3493 \family default
3507 \family default
3494 ', but with all digits replaced dots (so you can have your continuation
3508 ', but with all digits replaced dots (so you can have your continuation
3495 prompt aligned with your input prompt).
3509 prompt aligned with your input prompt).
3496 Default: '
3510 Default: '
3497 \family typewriter
3511 \family typewriter
3498 \SpecialChar ~
3512 \SpecialChar ~
3499 \SpecialChar ~
3513 \SpecialChar ~
3500 \SpecialChar ~
3514 \SpecialChar ~
3501 .
3515 .
3502 \backslash
3516 \backslash
3503 D.:
3517 D.:
3504 \family default
3518 \family default
3505 ' (note three spaces at the start for alignment with '
3519 ' (note three spaces at the start for alignment with '
3506 \family typewriter
3520 \family typewriter
3507 In\SpecialChar ~
3521 In\SpecialChar ~
3508 [
3522 [
3509 \backslash
3523 \backslash
3510 #]
3524 #]
3511 \family default
3525 \family default
3512 ').
3526 ').
3513 \layout List
3527 \layout List
3514 \labelwidthstring 00.00.0000
3528 \labelwidthstring 00.00.0000
3515
3529
3516
3530
3517 \family typewriter
3531 \family typewriter
3518 \series bold
3532 \series bold
3519 -prompt_out|po\SpecialChar ~
3533 -prompt_out|po\SpecialChar ~
3520 <string>:
3534 <string>:
3521 \family default
3535 \family default
3522 \series default
3536 \series default
3523 String used for output prompts, also uses numbers like
3537 String used for output prompts, also uses numbers like
3524 \family typewriter
3538 \family typewriter
3525 prompt_in1
3539 prompt_in1
3526 \family default
3540 \family default
3527 .
3541 .
3528 Default: '
3542 Default: '
3529 \family typewriter
3543 \family typewriter
3530 Out[
3544 Out[
3531 \backslash
3545 \backslash
3532 #]:
3546 #]:
3533 \family default
3547 \family default
3534 '
3548 '
3535 \layout List
3549 \layout List
3536 \labelwidthstring 00.00.0000
3550 \labelwidthstring 00.00.0000
3537
3551
3538
3552
3539 \family typewriter
3553 \family typewriter
3540 \series bold
3554 \series bold
3541 -quick
3555 -quick
3542 \family default
3556 \family default
3543 \series default
3557 \series default
3544 : start in bare bones mode (no config file loaded).
3558 : start in bare bones mode (no config file loaded).
3545 \layout List
3559 \layout List
3546 \labelwidthstring 00.00.0000
3560 \labelwidthstring 00.00.0000
3547
3561
3548
3562
3549 \family typewriter
3563 \family typewriter
3550 \series bold
3564 \series bold
3551 -rcfile\SpecialChar ~
3565 -rcfile\SpecialChar ~
3552 <name>
3566 <name>
3553 \series default
3567 \series default
3554 :
3568 :
3555 \family default
3569 \family default
3556 name of your IPython resource configuration file.
3570 name of your IPython resource configuration file.
3557 Normally IPython loads ipythonrc (from current directory) or
3571 Normally IPython loads ipythonrc (from current directory) or
3558 \family typewriter
3572 \family typewriter
3559 IPYTHONDIR/ipythonrc
3573 IPYTHONDIR/ipythonrc
3560 \family default
3574 \family default
3561 .
3575 .
3562 \layout List
3576 \layout List
3563 \labelwidthstring 00.00.0000
3577 \labelwidthstring 00.00.0000
3564
3578
3565 \SpecialChar ~
3579 \SpecialChar ~
3566 If the loading of your config file fails, IPython starts with a bare bones
3580 If the loading of your config file fails, IPython starts with a bare bones
3567 configuration (no modules loaded at all).
3581 configuration (no modules loaded at all).
3568 \layout List
3582 \layout List
3569 \labelwidthstring 00.00.0000
3583 \labelwidthstring 00.00.0000
3570
3584
3571
3585
3572 \family typewriter
3586 \family typewriter
3573 \series bold
3587 \series bold
3574 -[no]readline
3588 -[no]readline
3575 \family default
3589 \family default
3576 \series default
3590 \series default
3577 : use the readline library, which is needed to support name completion and
3591 : use the readline library, which is needed to support name completion and
3578 command history, among other things.
3592 command history, among other things.
3579 It is enabled by default, but may cause problems for users of X/Emacs in
3593 It is enabled by default, but may cause problems for users of X/Emacs in
3580 Python comint or shell buffers.
3594 Python comint or shell buffers.
3581 \layout List
3595 \layout List
3582 \labelwidthstring 00.00.0000
3596 \labelwidthstring 00.00.0000
3583
3597
3584 \SpecialChar ~
3598 \SpecialChar ~
3585 Note that X/Emacs 'eterm' buffers (opened with
3599 Note that X/Emacs 'eterm' buffers (opened with
3586 \family typewriter
3600 \family typewriter
3587 M-x\SpecialChar ~
3601 M-x\SpecialChar ~
3588 term
3602 term
3589 \family default
3603 \family default
3590 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3604 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3591 \family typewriter
3605 \family typewriter
3592 M-x\SpecialChar ~
3606 M-x\SpecialChar ~
3593 shell
3607 shell
3594 \family default
3608 \family default
3595 and
3609 and
3596 \family typewriter
3610 \family typewriter
3597 C-c\SpecialChar ~
3611 C-c\SpecialChar ~
3598 !
3612 !
3599 \family default
3613 \family default
3600 ) buffers do not.
3614 ) buffers do not.
3601 \layout List
3615 \layout List
3602 \labelwidthstring 00.00.0000
3616 \labelwidthstring 00.00.0000
3603
3617
3604
3618
3605 \family typewriter
3619 \family typewriter
3606 \series bold
3620 \series bold
3607 -screen_length|sl\SpecialChar ~
3621 -screen_length|sl\SpecialChar ~
3608 <n>
3622 <n>
3609 \series default
3623 \series default
3610 :
3624 :
3611 \family default
3625 \family default
3612 number of lines of your screen.
3626 number of lines of your screen.
3613 This is used to control printing of very long strings.
3627 This is used to control printing of very long strings.
3614 Strings longer than this number of lines will be sent through a pager instead
3628 Strings longer than this number of lines will be sent through a pager instead
3615 of directly printed.
3629 of directly printed.
3616 \layout List
3630 \layout List
3617 \labelwidthstring 00.00.0000
3631 \labelwidthstring 00.00.0000
3618
3632
3619 \SpecialChar ~
3633 \SpecialChar ~
3620 The default value for this is 0, which means IPython will auto-detect your
3634 The default value for this is 0, which means IPython will auto-detect your
3621 screen size every time it needs to print certain potentially long strings
3635 screen size every time it needs to print certain potentially long strings
3622 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3636 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3623 internally).
3637 internally).
3624 If for some reason this isn't working well (it needs curses support), specify
3638 If for some reason this isn't working well (it needs curses support), specify
3625 it yourself.
3639 it yourself.
3626 Otherwise don't change the default.
3640 Otherwise don't change the default.
3627 \layout List
3641 \layout List
3628 \labelwidthstring 00.00.0000
3642 \labelwidthstring 00.00.0000
3629
3643
3630
3644
3631 \family typewriter
3645 \family typewriter
3632 \series bold
3646 \series bold
3633 -separate_in|si\SpecialChar ~
3647 -separate_in|si\SpecialChar ~
3634 <string>
3648 <string>
3635 \series default
3649 \series default
3636 :
3650 :
3637 \family default
3651 \family default
3638 separator before input prompts.
3652 separator before input prompts.
3639 Default: '
3653 Default: '
3640 \family typewriter
3654 \family typewriter
3641
3655
3642 \backslash
3656 \backslash
3643 n
3657 n
3644 \family default
3658 \family default
3645 '
3659 '
3646 \layout List
3660 \layout List
3647 \labelwidthstring 00.00.0000
3661 \labelwidthstring 00.00.0000
3648
3662
3649
3663
3650 \family typewriter
3664 \family typewriter
3651 \series bold
3665 \series bold
3652 -separate_out|so\SpecialChar ~
3666 -separate_out|so\SpecialChar ~
3653 <string>
3667 <string>
3654 \family default
3668 \family default
3655 \series default
3669 \series default
3656 : separator before output prompts.
3670 : separator before output prompts.
3657 Default: nothing.
3671 Default: nothing.
3658 \layout List
3672 \layout List
3659 \labelwidthstring 00.00.0000
3673 \labelwidthstring 00.00.0000
3660
3674
3661
3675
3662 \family typewriter
3676 \family typewriter
3663 \series bold
3677 \series bold
3664 -separate_out2|so2\SpecialChar ~
3678 -separate_out2|so2\SpecialChar ~
3665 <string>
3679 <string>
3666 \series default
3680 \series default
3667 :
3681 :
3668 \family default
3682 \family default
3669 separator after output prompts.
3683 separator after output prompts.
3670 Default: nothing.
3684 Default: nothing.
3671 \layout List
3685 \layout List
3672 \labelwidthstring 00.00.0000
3686 \labelwidthstring 00.00.0000
3673
3687
3674 \SpecialChar ~
3688 \SpecialChar ~
3675 For these three options, use the value 0 to specify no separator.
3689 For these three options, use the value 0 to specify no separator.
3676 \layout List
3690 \layout List
3677 \labelwidthstring 00.00.0000
3691 \labelwidthstring 00.00.0000
3678
3692
3679
3693
3680 \family typewriter
3694 \family typewriter
3681 \series bold
3695 \series bold
3682 -nosep
3696 -nosep
3683 \series default
3697 \series default
3684 :
3698 :
3685 \family default
3699 \family default
3686 shorthand for
3700 shorthand for
3687 \family typewriter
3701 \family typewriter
3688 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3702 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3689 \family default
3703 \family default
3690 .
3704 .
3691 Simply removes all input/output separators.
3705 Simply removes all input/output separators.
3692 \layout List
3706 \layout List
3693 \labelwidthstring 00.00.0000
3707 \labelwidthstring 00.00.0000
3694
3708
3695
3709
3696 \family typewriter
3710 \family typewriter
3697 \series bold
3711 \series bold
3698 -upgrade
3712 -upgrade
3699 \family default
3713 \family default
3700 \series default
3714 \series default
3701 : allows you to upgrade your
3715 : allows you to upgrade your
3702 \family typewriter
3716 \family typewriter
3703 IPYTHONDIR
3717 IPYTHONDIR
3704 \family default
3718 \family default
3705 configuration when you install a new version of IPython.
3719 configuration when you install a new version of IPython.
3706 Since new versions may include new command line options or example files,
3720 Since new versions may include new command line options or example files,
3707 this copies updated ipythonrc-type files.
3721 this copies updated ipythonrc-type files.
3708 However, it backs up (with a
3722 However, it backs up (with a
3709 \family typewriter
3723 \family typewriter
3710 .old
3724 .old
3711 \family default
3725 \family default
3712 extension) all files which it overwrites so that you can merge back any
3726 extension) all files which it overwrites so that you can merge back any
3713 customizations you might have in your personal files.
3727 customizations you might have in your personal files.
3714 \layout List
3728 \layout List
3715 \labelwidthstring 00.00.0000
3729 \labelwidthstring 00.00.0000
3716
3730
3717
3731
3718 \family typewriter
3732 \family typewriter
3719 \series bold
3733 \series bold
3720 -Version
3734 -Version
3721 \series default
3735 \series default
3722 :
3736 :
3723 \family default
3737 \family default
3724 print version information and exit.
3738 print version information and exit.
3725 \layout List
3739 \layout List
3726 \labelwidthstring 00.00.0000
3740 \labelwidthstring 00.00.0000
3727
3741
3728
3742
3729 \family typewriter
3743 \family typewriter
3730 \series bold
3744 \series bold
3731 -wxversion\SpecialChar ~
3745 -wxversion\SpecialChar ~
3732 <string>:
3746 <string>:
3733 \family default
3747 \family default
3734 \series default
3748 \series default
3735 Select a specific version of wxPython (used in conjunction with
3749 Select a specific version of wxPython (used in conjunction with
3736 \family typewriter
3750 \family typewriter
3737 -wthread
3751 -wthread
3738 \family default
3752 \family default
3739 ).
3753 ).
3740 Requires the wxversion module, part of recent wxPython distributions
3754 Requires the wxversion module, part of recent wxPython distributions
3741 \layout List
3755 \layout List
3742 \labelwidthstring 00.00.0000
3756 \labelwidthstring 00.00.0000
3743
3757
3744
3758
3745 \family typewriter
3759 \family typewriter
3746 \series bold
3760 \series bold
3747 -xmode\SpecialChar ~
3761 -xmode\SpecialChar ~
3748 <modename>
3762 <modename>
3749 \series default
3763 \series default
3750 :
3764 :
3751 \family default
3765 \family default
3752 Mode for exception reporting.
3766 Mode for exception reporting.
3753 \layout List
3767 \layout List
3754 \labelwidthstring 00.00.0000
3768 \labelwidthstring 00.00.0000
3755
3769
3756 \SpecialChar ~
3770 \SpecialChar ~
3757 Valid modes: Plain, Context and Verbose.
3771 Valid modes: Plain, Context and Verbose.
3758 \layout List
3772 \layout List
3759 \labelwidthstring 00.00.0000
3773 \labelwidthstring 00.00.0000
3760
3774
3761 \SpecialChar ~
3775 \SpecialChar ~
3762 Plain: similar to python's normal traceback printing.
3776 Plain: similar to python's normal traceback printing.
3763 \layout List
3777 \layout List
3764 \labelwidthstring 00.00.0000
3778 \labelwidthstring 00.00.0000
3765
3779
3766 \SpecialChar ~
3780 \SpecialChar ~
3767 Context: prints 5 lines of context source code around each line in the
3781 Context: prints 5 lines of context source code around each line in the
3768 traceback.
3782 traceback.
3769 \layout List
3783 \layout List
3770 \labelwidthstring 00.00.0000
3784 \labelwidthstring 00.00.0000
3771
3785
3772 \SpecialChar ~
3786 \SpecialChar ~
3773 Verbose: similar to Context, but additionally prints the variables currently
3787 Verbose: similar to Context, but additionally prints the variables currently
3774 visible where the exception happened (shortening their strings if too long).
3788 visible where the exception happened (shortening their strings if too long).
3775 This can potentially be very slow, if you happen to have a huge data structure
3789 This can potentially be very slow, if you happen to have a huge data structure
3776 whose string representation is complex to compute.
3790 whose string representation is complex to compute.
3777 Your computer may appear to freeze for a while with cpu usage at 100%.
3791 Your computer may appear to freeze for a while with cpu usage at 100%.
3778 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3792 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3779 it more than once).
3793 it more than once).
3780 \layout Section
3794 \layout Section
3781
3795
3782 Interactive use
3796 Interactive use
3783 \layout Standard
3797 \layout Standard
3784
3798
3785
3799
3786 \series bold
3800 \series bold
3787 Warning
3801 Warning
3788 \series default
3802 \series default
3789 : IPython relies on the existence of a global variable called
3803 : IPython relies on the existence of a global variable called
3790 \family typewriter
3804 \family typewriter
3791 __IP
3805 __IP
3792 \family default
3806 \family default
3793 which controls the shell itself.
3807 which controls the shell itself.
3794 If you redefine
3808 If you redefine
3795 \family typewriter
3809 \family typewriter
3796 __IP
3810 __IP
3797 \family default
3811 \family default
3798 to anything, bizarre behavior will quickly occur.
3812 to anything, bizarre behavior will quickly occur.
3799 \layout Standard
3813 \layout Standard
3800
3814
3801 Other than the above warning, IPython is meant to work as a drop-in replacement
3815 Other than the above warning, IPython is meant to work as a drop-in replacement
3802 for the standard interactive interpreter.
3816 for the standard interactive interpreter.
3803 As such, any code which is valid python should execute normally under IPython
3817 As such, any code which is valid python should execute normally under IPython
3804 (cases where this is not true should be reported as bugs).
3818 (cases where this is not true should be reported as bugs).
3805 It does, however, offer many features which are not available at a standard
3819 It does, however, offer many features which are not available at a standard
3806 python prompt.
3820 python prompt.
3807 What follows is a list of these.
3821 What follows is a list of these.
3808 \layout Subsection
3822 \layout Subsection
3809
3823
3810 Caution for Windows users
3824 Caution for Windows users
3811 \layout Standard
3825 \layout Standard
3812
3826
3813 Windows, unfortunately, uses the `
3827 Windows, unfortunately, uses the `
3814 \family typewriter
3828 \family typewriter
3815
3829
3816 \backslash
3830 \backslash
3817
3831
3818 \family default
3832 \family default
3819 ' character as a path separator.
3833 ' character as a path separator.
3820 This is a terrible choice, because `
3834 This is a terrible choice, because `
3821 \family typewriter
3835 \family typewriter
3822
3836
3823 \backslash
3837 \backslash
3824
3838
3825 \family default
3839 \family default
3826 ' also represents the escape character in most modern programming languages,
3840 ' also represents the escape character in most modern programming languages,
3827 including Python.
3841 including Python.
3828 For this reason, issuing many of the commands discussed below (especially
3842 For this reason, issuing many of the commands discussed below (especially
3829 magics which affect the filesystem) with `
3843 magics which affect the filesystem) with `
3830 \family typewriter
3844 \family typewriter
3831
3845
3832 \backslash
3846 \backslash
3833
3847
3834 \family default
3848 \family default
3835 ' in them will cause strange errors.
3849 ' in them will cause strange errors.
3836 \layout Standard
3850 \layout Standard
3837
3851
3838 A partial solution is to use instead the `
3852 A partial solution is to use instead the `
3839 \family typewriter
3853 \family typewriter
3840 /
3854 /
3841 \family default
3855 \family default
3842 ' character as a path separator, which Windows recognizes in
3856 ' character as a path separator, which Windows recognizes in
3843 \emph on
3857 \emph on
3844 most
3858 most
3845 \emph default
3859 \emph default
3846 situations.
3860 situations.
3847 However, in Windows commands `
3861 However, in Windows commands `
3848 \family typewriter
3862 \family typewriter
3849 /
3863 /
3850 \family default
3864 \family default
3851 ' flags options, so you can not use it for the root directory.
3865 ' flags options, so you can not use it for the root directory.
3852 This means that paths beginning at the root must be typed in a contrived
3866 This means that paths beginning at the root must be typed in a contrived
3853 manner like:
3867 manner like:
3854 \newline
3868 \newline
3855
3869
3856 \family typewriter
3870 \family typewriter
3857 %copy
3871 %copy
3858 \backslash
3872 \backslash
3859 opt/foo/bar.txt
3873 opt/foo/bar.txt
3860 \backslash
3874 \backslash
3861 tmp
3875 tmp
3862 \layout Standard
3876 \layout Standard
3863
3877
3864 There is no sensible thing IPython can do to truly work around this flaw
3878 There is no sensible thing IPython can do to truly work around this flaw
3865 in Windows
3879 in Windows
3866 \begin_inset Foot
3880 \begin_inset Foot
3867 collapsed true
3881 collapsed true
3868
3882
3869 \layout Standard
3883 \layout Standard
3870
3884
3871 If anyone comes up with a
3885 If anyone comes up with a
3872 \emph on
3886 \emph on
3873 clean
3887 clean
3874 \emph default
3888 \emph default
3875 solution which works consistently and does not negatively impact other
3889 solution which works consistently and does not negatively impact other
3876 platforms at all, I'll gladly accept a patch.
3890 platforms at all, I'll gladly accept a patch.
3877 \end_inset
3891 \end_inset
3878
3892
3879 .
3893 .
3880 \layout Subsection
3894 \layout Subsection
3881
3895
3882
3896
3883 \begin_inset LatexCommand \label{sec:magic}
3897 \begin_inset LatexCommand \label{sec:magic}
3884
3898
3885 \end_inset
3899 \end_inset
3886
3900
3887 Magic command system
3901 Magic command system
3888 \layout Standard
3902 \layout Standard
3889
3903
3890 IPython will treat any line whose first character is a
3904 IPython will treat any line whose first character is a
3891 \family typewriter
3905 \family typewriter
3892 %
3906 %
3893 \family default
3907 \family default
3894 as a special call to a 'magic' function.
3908 as a special call to a 'magic' function.
3895 These allow you to control the behavior of IPython itself, plus a lot of
3909 These allow you to control the behavior of IPython itself, plus a lot of
3896 system-type features.
3910 system-type features.
3897 They are all prefixed with a
3911 They are all prefixed with a
3898 \family typewriter
3912 \family typewriter
3899 %
3913 %
3900 \family default
3914 \family default
3901 character, but parameters are given without parentheses or quotes.
3915 character, but parameters are given without parentheses or quotes.
3902 \layout Standard
3916 \layout Standard
3903
3917
3904 Example: typing
3918 Example: typing
3905 \family typewriter
3919 \family typewriter
3906 '%cd mydir'
3920 '%cd mydir'
3907 \family default
3921 \family default
3908 (without the quotes) changes you working directory to
3922 (without the quotes) changes you working directory to
3909 \family typewriter
3923 \family typewriter
3910 'mydir'
3924 'mydir'
3911 \family default
3925 \family default
3912 , if it exists.
3926 , if it exists.
3913 \layout Standard
3927 \layout Standard
3914
3928
3915 If you have 'automagic' enabled (in your
3929 If you have 'automagic' enabled (in your
3916 \family typewriter
3930 \family typewriter
3917 ipythonrc
3931 ipythonrc
3918 \family default
3932 \family default
3919 file, via the command line option
3933 file, via the command line option
3920 \family typewriter
3934 \family typewriter
3921 -automagic
3935 -automagic
3922 \family default
3936 \family default
3923 or with the
3937 or with the
3924 \family typewriter
3938 \family typewriter
3925 %automagic
3939 %automagic
3926 \family default
3940 \family default
3927 function), you don't need to type in the
3941 function), you don't need to type in the
3928 \family typewriter
3942 \family typewriter
3929 %
3943 %
3930 \family default
3944 \family default
3931 explicitly.
3945 explicitly.
3932 IPython will scan its internal list of magic functions and call one if
3946 IPython will scan its internal list of magic functions and call one if
3933 it exists.
3947 it exists.
3934 With automagic on you can then just type '
3948 With automagic on you can then just type '
3935 \family typewriter
3949 \family typewriter
3936 cd mydir
3950 cd mydir
3937 \family default
3951 \family default
3938 ' to go to directory '
3952 ' to go to directory '
3939 \family typewriter
3953 \family typewriter
3940 mydir
3954 mydir
3941 \family default
3955 \family default
3942 '.
3956 '.
3943 The automagic system has the lowest possible precedence in name searches,
3957 The automagic system has the lowest possible precedence in name searches,
3944 so defining an identifier with the same name as an existing magic function
3958 so defining an identifier with the same name as an existing magic function
3945 will shadow it for automagic use.
3959 will shadow it for automagic use.
3946 You can still access the shadowed magic function by explicitly using the
3960 You can still access the shadowed magic function by explicitly using the
3947
3961
3948 \family typewriter
3962 \family typewriter
3949 %
3963 %
3950 \family default
3964 \family default
3951 character at the beginning of the line.
3965 character at the beginning of the line.
3952 \layout Standard
3966 \layout Standard
3953
3967
3954 An example (with automagic on) should clarify all this:
3968 An example (with automagic on) should clarify all this:
3955 \layout LyX-Code
3969 \layout LyX-Code
3956
3970
3957 In [1]: cd ipython # %cd is called by automagic
3971 In [1]: cd ipython # %cd is called by automagic
3958 \layout LyX-Code
3972 \layout LyX-Code
3959
3973
3960 /home/fperez/ipython
3974 /home/fperez/ipython
3961 \layout LyX-Code
3975 \layout LyX-Code
3962
3976
3963 In [2]: cd=1 # now cd is just a variable
3977 In [2]: cd=1 # now cd is just a variable
3964 \layout LyX-Code
3978 \layout LyX-Code
3965
3979
3966 In [3]: cd ..
3980 In [3]: cd ..
3967 # and doesn't work as a function anymore
3981 # and doesn't work as a function anymore
3968 \layout LyX-Code
3982 \layout LyX-Code
3969
3983
3970 ------------------------------------------------------------
3984 ------------------------------------------------------------
3971 \layout LyX-Code
3985 \layout LyX-Code
3972
3986
3973 File "<console>", line 1
3987 File "<console>", line 1
3974 \layout LyX-Code
3988 \layout LyX-Code
3975
3989
3976 cd ..
3990 cd ..
3977 \layout LyX-Code
3991 \layout LyX-Code
3978
3992
3979 ^
3993 ^
3980 \layout LyX-Code
3994 \layout LyX-Code
3981
3995
3982 SyntaxError: invalid syntax
3996 SyntaxError: invalid syntax
3983 \layout LyX-Code
3997 \layout LyX-Code
3984
3998
3985 \layout LyX-Code
3999 \layout LyX-Code
3986
4000
3987 In [4]: %cd ..
4001 In [4]: %cd ..
3988 # but %cd always works
4002 # but %cd always works
3989 \layout LyX-Code
4003 \layout LyX-Code
3990
4004
3991 /home/fperez
4005 /home/fperez
3992 \layout LyX-Code
4006 \layout LyX-Code
3993
4007
3994 In [5]: del cd # if you remove the cd variable
4008 In [5]: del cd # if you remove the cd variable
3995 \layout LyX-Code
4009 \layout LyX-Code
3996
4010
3997 In [6]: cd ipython # automagic can work again
4011 In [6]: cd ipython # automagic can work again
3998 \layout LyX-Code
4012 \layout LyX-Code
3999
4013
4000 /home/fperez/ipython
4014 /home/fperez/ipython
4001 \layout Standard
4015 \layout Standard
4002
4016
4003 You can define your own magic functions to extend the system.
4017 You can define your own magic functions to extend the system.
4004 The following is a snippet of code which shows how to do it.
4018 The following is a snippet of code which shows how to do it.
4005 It is provided as file
4019 It is provided as file
4006 \family typewriter
4020 \family typewriter
4007 example-magic.py
4021 example-magic.py
4008 \family default
4022 \family default
4009 in the examples directory:
4023 in the examples directory:
4010 \layout Standard
4024 \layout Standard
4011
4025
4012
4026
4013 \begin_inset ERT
4027 \begin_inset ERT
4014 status Open
4028 status Open
4015
4029
4016 \layout Standard
4030 \layout Standard
4017
4031
4018 \backslash
4032 \backslash
4019 codelist{examples/example-magic.py}
4033 codelist{examples/example-magic.py}
4020 \end_inset
4034 \end_inset
4021
4035
4022
4036
4023 \layout Standard
4037 \layout Standard
4024
4038
4025 You can also define your own aliased names for magic functions.
4039 You can also define your own aliased names for magic functions.
4026 In your
4040 In your
4027 \family typewriter
4041 \family typewriter
4028 ipythonrc
4042 ipythonrc
4029 \family default
4043 \family default
4030 file, placing a line like:
4044 file, placing a line like:
4031 \layout Standard
4045 \layout Standard
4032
4046
4033
4047
4034 \family typewriter
4048 \family typewriter
4035 execute __IP.magic_cl = __IP.magic_clear
4049 execute __IP.magic_cl = __IP.magic_clear
4036 \layout Standard
4050 \layout Standard
4037
4051
4038 will define
4052 will define
4039 \family typewriter
4053 \family typewriter
4040 %cl
4054 %cl
4041 \family default
4055 \family default
4042 as a new name for
4056 as a new name for
4043 \family typewriter
4057 \family typewriter
4044 %clear
4058 %clear
4045 \family default
4059 \family default
4046 .
4060 .
4047 \layout Standard
4061 \layout Standard
4048
4062
4049 Type
4063 Type
4050 \family typewriter
4064 \family typewriter
4051 %magic
4065 %magic
4052 \family default
4066 \family default
4053 for more information, including a list of all available magic functions
4067 for more information, including a list of all available magic functions
4054 at any time and their docstrings.
4068 at any time and their docstrings.
4055 You can also type
4069 You can also type
4056 \family typewriter
4070 \family typewriter
4057 %magic_function_name?
4071 %magic_function_name?
4058 \family default
4072 \family default
4059 (see sec.
4073 (see sec.
4060
4074
4061 \begin_inset LatexCommand \ref{sec:dyn-object-info}
4075 \begin_inset LatexCommand \ref{sec:dyn-object-info}
4062
4076
4063 \end_inset
4077 \end_inset
4064
4078
4065 for information on the
4079 for information on the
4066 \family typewriter
4080 \family typewriter
4067 '?'
4081 '?'
4068 \family default
4082 \family default
4069 system) to get information about any particular magic function you are
4083 system) to get information about any particular magic function you are
4070 interested in.
4084 interested in.
4071 \layout Subsubsection
4085 \layout Subsubsection
4072
4086
4073 Magic commands
4087 Magic commands
4074 \layout Standard
4088 \layout Standard
4075
4089
4076 The rest of this section is automatically generated for each release from
4090 The rest of this section is automatically generated for each release from
4077 the docstrings in the IPython code.
4091 the docstrings in the IPython code.
4078 Therefore the formatting is somewhat minimal, but this method has the advantage
4092 Therefore the formatting is somewhat minimal, but this method has the advantage
4079 of having information always in sync with the code.
4093 of having information always in sync with the code.
4080 \layout Standard
4094 \layout Standard
4081
4095
4082 A list of all the magic commands available in IPython's
4096 A list of all the magic commands available in IPython's
4083 \emph on
4097 \emph on
4084 default
4098 default
4085 \emph default
4099 \emph default
4086 installation follows.
4100 installation follows.
4087 This is similar to what you'll see by simply typing
4101 This is similar to what you'll see by simply typing
4088 \family typewriter
4102 \family typewriter
4089 %magic
4103 %magic
4090 \family default
4104 \family default
4091 at the prompt, but that will also give you information about magic commands
4105 at the prompt, but that will also give you information about magic commands
4092 you may have added as part of your personal customizations.
4106 you may have added as part of your personal customizations.
4093 \layout Standard
4107 \layout Standard
4094
4108
4095
4109
4096 \begin_inset Include \input{magic.tex}
4110 \begin_inset Include \input{magic.tex}
4097 preview false
4111 preview false
4098
4112
4099 \end_inset
4113 \end_inset
4100
4114
4101
4115
4102 \layout Subsection
4116 \layout Subsection
4103
4117
4104 Access to the standard Python help
4118 Access to the standard Python help
4105 \layout Standard
4119 \layout Standard
4106
4120
4107 As of Python 2.1, a help system is available with access to object docstrings
4121 As of Python 2.1, a help system is available with access to object docstrings
4108 and the Python manuals.
4122 and the Python manuals.
4109 Simply type
4123 Simply type
4110 \family typewriter
4124 \family typewriter
4111 'help'
4125 'help'
4112 \family default
4126 \family default
4113 (no quotes) to access it.
4127 (no quotes) to access it.
4114 You can also type
4128 You can also type
4115 \family typewriter
4129 \family typewriter
4116 help(object)
4130 help(object)
4117 \family default
4131 \family default
4118 to obtain information about a given object, and
4132 to obtain information about a given object, and
4119 \family typewriter
4133 \family typewriter
4120 help('keyword')
4134 help('keyword')
4121 \family default
4135 \family default
4122 for information on a keyword.
4136 for information on a keyword.
4123 As noted in sec.
4137 As noted in sec.
4124
4138
4125 \begin_inset LatexCommand \ref{sec:help-access}
4139 \begin_inset LatexCommand \ref{sec:help-access}
4126
4140
4127 \end_inset
4141 \end_inset
4128
4142
4129 , you need to properly configure your environment variable
4143 , you need to properly configure your environment variable
4130 \family typewriter
4144 \family typewriter
4131 PYTHONDOCS
4145 PYTHONDOCS
4132 \family default
4146 \family default
4133 for this feature to work correctly.
4147 for this feature to work correctly.
4134 \layout Subsection
4148 \layout Subsection
4135
4149
4136
4150
4137 \begin_inset LatexCommand \label{sec:dyn-object-info}
4151 \begin_inset LatexCommand \label{sec:dyn-object-info}
4138
4152
4139 \end_inset
4153 \end_inset
4140
4154
4141 Dynamic object information
4155 Dynamic object information
4142 \layout Standard
4156 \layout Standard
4143
4157
4144 Typing
4158 Typing
4145 \family typewriter
4159 \family typewriter
4146 ?word
4160 ?word
4147 \family default
4161 \family default
4148 or
4162 or
4149 \family typewriter
4163 \family typewriter
4150 word?
4164 word?
4151 \family default
4165 \family default
4152 prints detailed information about an object.
4166 prints detailed information about an object.
4153 If certain strings in the object are too long (docstrings, code, etc.) they
4167 If certain strings in the object are too long (docstrings, code, etc.) they
4154 get snipped in the center for brevity.
4168 get snipped in the center for brevity.
4155 This system gives access variable types and values, full source code for
4169 This system gives access variable types and values, full source code for
4156 any object (if available), function prototypes and other useful information.
4170 any object (if available), function prototypes and other useful information.
4157 \layout Standard
4171 \layout Standard
4158
4172
4159 Typing
4173 Typing
4160 \family typewriter
4174 \family typewriter
4161 ??word
4175 ??word
4162 \family default
4176 \family default
4163 or
4177 or
4164 \family typewriter
4178 \family typewriter
4165 word??
4179 word??
4166 \family default
4180 \family default
4167 gives access to the full information without snipping long strings.
4181 gives access to the full information without snipping long strings.
4168 Long strings are sent to the screen through the
4182 Long strings are sent to the screen through the
4169 \family typewriter
4183 \family typewriter
4170 less
4184 less
4171 \family default
4185 \family default
4172 pager if longer than the screen and printed otherwise.
4186 pager if longer than the screen and printed otherwise.
4173 On systems lacking the
4187 On systems lacking the
4174 \family typewriter
4188 \family typewriter
4175 less
4189 less
4176 \family default
4190 \family default
4177 command, IPython uses a very basic internal pager.
4191 command, IPython uses a very basic internal pager.
4178 \layout Standard
4192 \layout Standard
4179
4193
4180 The following magic functions are particularly useful for gathering information
4194 The following magic functions are particularly useful for gathering information
4181 about your working environment.
4195 about your working environment.
4182 You can get more details by typing
4196 You can get more details by typing
4183 \family typewriter
4197 \family typewriter
4184 %magic
4198 %magic
4185 \family default
4199 \family default
4186 or querying them individually (use
4200 or querying them individually (use
4187 \family typewriter
4201 \family typewriter
4188 %function_name?
4202 %function_name?
4189 \family default
4203 \family default
4190 with or without the
4204 with or without the
4191 \family typewriter
4205 \family typewriter
4192 %
4206 %
4193 \family default
4207 \family default
4194 ), this is just a summary:
4208 ), this is just a summary:
4195 \layout List
4209 \layout List
4196 \labelwidthstring 00.00.0000
4210 \labelwidthstring 00.00.0000
4197
4211
4198
4212
4199 \family typewriter
4213 \family typewriter
4200 \series bold
4214 \series bold
4201 %pdoc\SpecialChar ~
4215 %pdoc\SpecialChar ~
4202 <object>
4216 <object>
4203 \family default
4217 \family default
4204 \series default
4218 \series default
4205 : Print (or run through a pager if too long) the docstring for an object.
4219 : Print (or run through a pager if too long) the docstring for an object.
4206 If the given object is a class, it will print both the class and the constructo
4220 If the given object is a class, it will print both the class and the constructo
4207 r docstrings.
4221 r docstrings.
4208 \layout List
4222 \layout List
4209 \labelwidthstring 00.00.0000
4223 \labelwidthstring 00.00.0000
4210
4224
4211
4225
4212 \family typewriter
4226 \family typewriter
4213 \series bold
4227 \series bold
4214 %pdef\SpecialChar ~
4228 %pdef\SpecialChar ~
4215 <object>
4229 <object>
4216 \family default
4230 \family default
4217 \series default
4231 \series default
4218 : Print the definition header for any callable object.
4232 : Print the definition header for any callable object.
4219 If the object is a class, print the constructor information.
4233 If the object is a class, print the constructor information.
4220 \layout List
4234 \layout List
4221 \labelwidthstring 00.00.0000
4235 \labelwidthstring 00.00.0000
4222
4236
4223
4237
4224 \family typewriter
4238 \family typewriter
4225 \series bold
4239 \series bold
4226 %psource\SpecialChar ~
4240 %psource\SpecialChar ~
4227 <object>
4241 <object>
4228 \family default
4242 \family default
4229 \series default
4243 \series default
4230 : Print (or run through a pager if too long) the source code for an object.
4244 : Print (or run through a pager if too long) the source code for an object.
4231 \layout List
4245 \layout List
4232 \labelwidthstring 00.00.0000
4246 \labelwidthstring 00.00.0000
4233
4247
4234
4248
4235 \family typewriter
4249 \family typewriter
4236 \series bold
4250 \series bold
4237 %pfile\SpecialChar ~
4251 %pfile\SpecialChar ~
4238 <object>
4252 <object>
4239 \family default
4253 \family default
4240 \series default
4254 \series default
4241 : Show the entire source file where an object was defined via a pager, opening
4255 : Show the entire source file where an object was defined via a pager, opening
4242 it at the line where the object definition begins.
4256 it at the line where the object definition begins.
4243 \layout List
4257 \layout List
4244 \labelwidthstring 00.00.0000
4258 \labelwidthstring 00.00.0000
4245
4259
4246
4260
4247 \family typewriter
4261 \family typewriter
4248 \series bold
4262 \series bold
4249 %who/%whos
4263 %who/%whos
4250 \family default
4264 \family default
4251 \series default
4265 \series default
4252 : These functions give information about identifiers you have defined interactiv
4266 : These functions give information about identifiers you have defined interactiv
4253 ely (not things you loaded or defined in your configuration files).
4267 ely (not things you loaded or defined in your configuration files).
4254
4268
4255 \family typewriter
4269 \family typewriter
4256 %who
4270 %who
4257 \family default
4271 \family default
4258 just prints a list of identifiers and
4272 just prints a list of identifiers and
4259 \family typewriter
4273 \family typewriter
4260 %whos
4274 %whos
4261 \family default
4275 \family default
4262 prints a table with some basic details about each identifier.
4276 prints a table with some basic details about each identifier.
4263 \layout Standard
4277 \layout Standard
4264
4278
4265 Note that the dynamic object information functions (
4279 Note that the dynamic object information functions (
4266 \family typewriter
4280 \family typewriter
4267 ?/??, %pdoc, %pfile, %pdef, %psource
4281 ?/??, %pdoc, %pfile, %pdef, %psource
4268 \family default
4282 \family default
4269 ) give you access to documentation even on things which are not really defined
4283 ) give you access to documentation even on things which are not really defined
4270 as separate identifiers.
4284 as separate identifiers.
4271 Try for example typing
4285 Try for example typing
4272 \family typewriter
4286 \family typewriter
4273 {}.get?
4287 {}.get?
4274 \family default
4288 \family default
4275 or after doing
4289 or after doing
4276 \family typewriter
4290 \family typewriter
4277 import os
4291 import os
4278 \family default
4292 \family default
4279 , type
4293 , type
4280 \family typewriter
4294 \family typewriter
4281 os.path.abspath??
4295 os.path.abspath??
4282 \family default
4296 \family default
4283 .
4297 .
4284 \layout Subsection
4298 \layout Subsection
4285
4299
4286
4300
4287 \begin_inset LatexCommand \label{sec:readline}
4301 \begin_inset LatexCommand \label{sec:readline}
4288
4302
4289 \end_inset
4303 \end_inset
4290
4304
4291 Readline-based features
4305 Readline-based features
4292 \layout Standard
4306 \layout Standard
4293
4307
4294 These features require the GNU readline library, so they won't work if your
4308 These features require the GNU readline library, so they won't work if your
4295 Python installation lacks readline support.
4309 Python installation lacks readline support.
4296 We will first describe the default behavior IPython uses, and then how
4310 We will first describe the default behavior IPython uses, and then how
4297 to change it to suit your preferences.
4311 to change it to suit your preferences.
4298 \layout Subsubsection
4312 \layout Subsubsection
4299
4313
4300 Command line completion
4314 Command line completion
4301 \layout Standard
4315 \layout Standard
4302
4316
4303 At any time, hitting TAB will complete any available python commands or
4317 At any time, hitting TAB will complete any available python commands or
4304 variable names, and show you a list of the possible completions if there's
4318 variable names, and show you a list of the possible completions if there's
4305 no unambiguous one.
4319 no unambiguous one.
4306 It will also complete filenames in the current directory if no python names
4320 It will also complete filenames in the current directory if no python names
4307 match what you've typed so far.
4321 match what you've typed so far.
4308 \layout Subsubsection
4322 \layout Subsubsection
4309
4323
4310 Search command history
4324 Search command history
4311 \layout Standard
4325 \layout Standard
4312
4326
4313 IPython provides two ways for searching through previous input and thus
4327 IPython provides two ways for searching through previous input and thus
4314 reduce the need for repetitive typing:
4328 reduce the need for repetitive typing:
4315 \layout Enumerate
4329 \layout Enumerate
4316
4330
4317 Start typing, and then use
4331 Start typing, and then use
4318 \family typewriter
4332 \family typewriter
4319 Ctrl-p
4333 Ctrl-p
4320 \family default
4334 \family default
4321 (previous,up) and
4335 (previous,up) and
4322 \family typewriter
4336 \family typewriter
4323 Ctrl-n
4337 Ctrl-n
4324 \family default
4338 \family default
4325 (next,down) to search through only the history items that match what you've
4339 (next,down) to search through only the history items that match what you've
4326 typed so far.
4340 typed so far.
4327 If you use
4341 If you use
4328 \family typewriter
4342 \family typewriter
4329 Ctrl-p/Ctrl-n
4343 Ctrl-p/Ctrl-n
4330 \family default
4344 \family default
4331 at a blank prompt, they just behave like normal arrow keys.
4345 at a blank prompt, they just behave like normal arrow keys.
4332 \layout Enumerate
4346 \layout Enumerate
4333
4347
4334 Hit
4348 Hit
4335 \family typewriter
4349 \family typewriter
4336 Ctrl-r
4350 Ctrl-r
4337 \family default
4351 \family default
4338 : opens a search prompt.
4352 : opens a search prompt.
4339 Begin typing and the system searches your history for lines that contain
4353 Begin typing and the system searches your history for lines that contain
4340 what you've typed so far, completing as much as it can.
4354 what you've typed so far, completing as much as it can.
4341 \layout Subsubsection
4355 \layout Subsubsection
4342
4356
4343 Persistent command history across sessions
4357 Persistent command history across sessions
4344 \layout Standard
4358 \layout Standard
4345
4359
4346 IPython will save your input history when it leaves and reload it next time
4360 IPython will save your input history when it leaves and reload it next time
4347 you restart it.
4361 you restart it.
4348 By default, the history file is named
4362 By default, the history file is named
4349 \family typewriter
4363 \family typewriter
4350 $IPYTHONDIR/history
4364 $IPYTHONDIR/history
4351 \family default
4365 \family default
4352 , but if you've loaded a named profile, '
4366 , but if you've loaded a named profile, '
4353 \family typewriter
4367 \family typewriter
4354 -PROFILE_NAME
4368 -PROFILE_NAME
4355 \family default
4369 \family default
4356 ' is appended to the name.
4370 ' is appended to the name.
4357 This allows you to keep separate histories related to various tasks: commands
4371 This allows you to keep separate histories related to various tasks: commands
4358 related to numerical work will not be clobbered by a system shell history,
4372 related to numerical work will not be clobbered by a system shell history,
4359 for example.
4373 for example.
4360 \layout Subsubsection
4374 \layout Subsubsection
4361
4375
4362 Autoindent
4376 Autoindent
4363 \layout Standard
4377 \layout Standard
4364
4378
4365 IPython can recognize lines ending in ':' and indent the next line, while
4379 IPython can recognize lines ending in ':' and indent the next line, while
4366 also un-indenting automatically after 'raise' or 'return'.
4380 also un-indenting automatically after 'raise' or 'return'.
4367
4381
4368 \layout Standard
4382 \layout Standard
4369
4383
4370 This feature uses the readline library, so it will honor your
4384 This feature uses the readline library, so it will honor your
4371 \family typewriter
4385 \family typewriter
4372 ~/.inputrc
4386 ~/.inputrc
4373 \family default
4387 \family default
4374 configuration (or whatever file your
4388 configuration (or whatever file your
4375 \family typewriter
4389 \family typewriter
4376 INPUTRC
4390 INPUTRC
4377 \family default
4391 \family default
4378 variable points to).
4392 variable points to).
4379 Adding the following lines to your
4393 Adding the following lines to your
4380 \family typewriter
4394 \family typewriter
4381 .inputrc
4395 .inputrc
4382 \family default
4396 \family default
4383 file can make indenting/unindenting more convenient (
4397 file can make indenting/unindenting more convenient (
4384 \family typewriter
4398 \family typewriter
4385 M-i
4399 M-i
4386 \family default
4400 \family default
4387 indents,
4401 indents,
4388 \family typewriter
4402 \family typewriter
4389 M-u
4403 M-u
4390 \family default
4404 \family default
4391 unindents):
4405 unindents):
4392 \layout Standard
4406 \layout Standard
4393
4407
4394
4408
4395 \family typewriter
4409 \family typewriter
4396 $if Python
4410 $if Python
4397 \newline
4411 \newline
4398 "
4412 "
4399 \backslash
4413 \backslash
4400 M-i": "\SpecialChar ~
4414 M-i": "\SpecialChar ~
4401 \SpecialChar ~
4415 \SpecialChar ~
4402 \SpecialChar ~
4416 \SpecialChar ~
4403 \SpecialChar ~
4417 \SpecialChar ~
4404 "
4418 "
4405 \newline
4419 \newline
4406 "
4420 "
4407 \backslash
4421 \backslash
4408 M-u": "
4422 M-u": "
4409 \backslash
4423 \backslash
4410 d
4424 d
4411 \backslash
4425 \backslash
4412 d
4426 d
4413 \backslash
4427 \backslash
4414 d
4428 d
4415 \backslash
4429 \backslash
4416 d"
4430 d"
4417 \newline
4431 \newline
4418 $endif
4432 $endif
4419 \layout Standard
4433 \layout Standard
4420
4434
4421 Note that there are 4 spaces between the quote marks after
4435 Note that there are 4 spaces between the quote marks after
4422 \family typewriter
4436 \family typewriter
4423 "M-i"
4437 "M-i"
4424 \family default
4438 \family default
4425 above.
4439 above.
4426 \layout Standard
4440 \layout Standard
4427
4441
4428
4442
4429 \series bold
4443 \series bold
4430 Warning:
4444 Warning:
4431 \series default
4445 \series default
4432 this feature is ON by default, but it can cause problems with the pasting
4446 this feature is ON by default, but it can cause problems with the pasting
4433 of multi-line indented code (the pasted code gets re-indented on each line).
4447 of multi-line indented code (the pasted code gets re-indented on each line).
4434 A magic function
4448 A magic function
4435 \family typewriter
4449 \family typewriter
4436 %autoindent
4450 %autoindent
4437 \family default
4451 \family default
4438 allows you to toggle it on/off at runtime.
4452 allows you to toggle it on/off at runtime.
4439 You can also disable it permanently on in your
4453 You can also disable it permanently on in your
4440 \family typewriter
4454 \family typewriter
4441 ipythonrc
4455 ipythonrc
4442 \family default
4456 \family default
4443 file (set
4457 file (set
4444 \family typewriter
4458 \family typewriter
4445 autoindent 0
4459 autoindent 0
4446 \family default
4460 \family default
4447 ).
4461 ).
4448 \layout Subsubsection
4462 \layout Subsubsection
4449
4463
4450 Customizing readline behavior
4464 Customizing readline behavior
4451 \layout Standard
4465 \layout Standard
4452
4466
4453 All these features are based on the GNU readline library, which has an extremely
4467 All these features are based on the GNU readline library, which has an extremely
4454 customizable interface.
4468 customizable interface.
4455 Normally, readline is configured via a file which defines the behavior
4469 Normally, readline is configured via a file which defines the behavior
4456 of the library; the details of the syntax for this can be found in the
4470 of the library; the details of the syntax for this can be found in the
4457 readline documentation available with your system or on the Internet.
4471 readline documentation available with your system or on the Internet.
4458 IPython doesn't read this file (if it exists) directly, but it does support
4472 IPython doesn't read this file (if it exists) directly, but it does support
4459 passing to readline valid options via a simple interface.
4473 passing to readline valid options via a simple interface.
4460 In brief, you can customize readline by setting the following options in
4474 In brief, you can customize readline by setting the following options in
4461 your
4475 your
4462 \family typewriter
4476 \family typewriter
4463 ipythonrc
4477 ipythonrc
4464 \family default
4478 \family default
4465 configuration file (note that these options can
4479 configuration file (note that these options can
4466 \emph on
4480 \emph on
4467 not
4481 not
4468 \emph default
4482 \emph default
4469 be specified at the command line):
4483 be specified at the command line):
4470 \layout List
4484 \layout List
4471 \labelwidthstring 00.00.0000
4485 \labelwidthstring 00.00.0000
4472
4486
4473
4487
4474 \family typewriter
4488 \family typewriter
4475 \series bold
4489 \series bold
4476 readline_parse_and_bind:
4490 readline_parse_and_bind:
4477 \family default
4491 \family default
4478 \series default
4492 \series default
4479 this option can appear as many times as you want, each time defining a
4493 this option can appear as many times as you want, each time defining a
4480 string to be executed via a
4494 string to be executed via a
4481 \family typewriter
4495 \family typewriter
4482 readline.parse_and_bind()
4496 readline.parse_and_bind()
4483 \family default
4497 \family default
4484 command.
4498 command.
4485 The syntax for valid commands of this kind can be found by reading the
4499 The syntax for valid commands of this kind can be found by reading the
4486 documentation for the GNU readline library, as these commands are of the
4500 documentation for the GNU readline library, as these commands are of the
4487 kind which readline accepts in its configuration file.
4501 kind which readline accepts in its configuration file.
4488 \layout List
4502 \layout List
4489 \labelwidthstring 00.00.0000
4503 \labelwidthstring 00.00.0000
4490
4504
4491
4505
4492 \family typewriter
4506 \family typewriter
4493 \series bold
4507 \series bold
4494 readline_remove_delims:
4508 readline_remove_delims:
4495 \family default
4509 \family default
4496 \series default
4510 \series default
4497 a string of characters to be removed from the default word-delimiters list
4511 a string of characters to be removed from the default word-delimiters list
4498 used by readline, so that completions may be performed on strings which
4512 used by readline, so that completions may be performed on strings which
4499 contain them.
4513 contain them.
4500 Do not change the default value unless you know what you're doing.
4514 Do not change the default value unless you know what you're doing.
4501 \layout List
4515 \layout List
4502 \labelwidthstring 00.00.0000
4516 \labelwidthstring 00.00.0000
4503
4517
4504
4518
4505 \family typewriter
4519 \family typewriter
4506 \series bold
4520 \series bold
4507 readline_omit__names
4521 readline_omit__names
4508 \family default
4522 \family default
4509 \series default
4523 \series default
4510 : when tab-completion is enabled, hitting
4524 : when tab-completion is enabled, hitting
4511 \family typewriter
4525 \family typewriter
4512 <tab>
4526 <tab>
4513 \family default
4527 \family default
4514 after a '
4528 after a '
4515 \family typewriter
4529 \family typewriter
4516 .
4530 .
4517 \family default
4531 \family default
4518 ' in a name will complete all attributes of an object, including all the
4532 ' in a name will complete all attributes of an object, including all the
4519 special methods whose names include double underscores (like
4533 special methods whose names include double underscores (like
4520 \family typewriter
4534 \family typewriter
4521 __getitem__
4535 __getitem__
4522 \family default
4536 \family default
4523 or
4537 or
4524 \family typewriter
4538 \family typewriter
4525 __class__
4539 __class__
4526 \family default
4540 \family default
4527 ).
4541 ).
4528 If you'd rather not see these names by default, you can set this option
4542 If you'd rather not see these names by default, you can set this option
4529 to 1.
4543 to 1.
4530 Note that even when this option is set, you can still see those names by
4544 Note that even when this option is set, you can still see those names by
4531 explicitly typing a
4545 explicitly typing a
4532 \family typewriter
4546 \family typewriter
4533 _
4547 _
4534 \family default
4548 \family default
4535 after the period and hitting
4549 after the period and hitting
4536 \family typewriter
4550 \family typewriter
4537 <tab>
4551 <tab>
4538 \family default
4552 \family default
4539 : '
4553 : '
4540 \family typewriter
4554 \family typewriter
4541 name._<tab>
4555 name._<tab>
4542 \family default
4556 \family default
4543 ' will always complete attribute names starting with '
4557 ' will always complete attribute names starting with '
4544 \family typewriter
4558 \family typewriter
4545 _
4559 _
4546 \family default
4560 \family default
4547 '.
4561 '.
4548 \layout List
4562 \layout List
4549 \labelwidthstring 00.00.0000
4563 \labelwidthstring 00.00.0000
4550
4564
4551 \SpecialChar ~
4565 \SpecialChar ~
4552 This option is off by default so that new users see all attributes of any
4566 This option is off by default so that new users see all attributes of any
4553 objects they are dealing with.
4567 objects they are dealing with.
4554 \layout Standard
4568 \layout Standard
4555
4569
4556 You will find the default values along with a corresponding detailed explanation
4570 You will find the default values along with a corresponding detailed explanation
4557 in your
4571 in your
4558 \family typewriter
4572 \family typewriter
4559 ipythonrc
4573 ipythonrc
4560 \family default
4574 \family default
4561 file.
4575 file.
4562 \layout Subsection
4576 \layout Subsection
4563
4577
4564 Session logging and restoring
4578 Session logging and restoring
4565 \layout Standard
4579 \layout Standard
4566
4580
4567 You can log all input from a session either by starting IPython with the
4581 You can log all input from a session either by starting IPython with the
4568 command line switches
4582 command line switches
4569 \family typewriter
4583 \family typewriter
4570 -log
4584 -log
4571 \family default
4585 \family default
4572 or
4586 or
4573 \family typewriter
4587 \family typewriter
4574 -logfile
4588 -logfile
4575 \family default
4589 \family default
4576 (see sec.
4590 (see sec.
4577
4591
4578 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4592 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4579
4593
4580 \end_inset
4594 \end_inset
4581
4595
4582 )or by activating the logging at any moment with the magic function
4596 )or by activating the logging at any moment with the magic function
4583 \family typewriter
4597 \family typewriter
4584 %logstart
4598 %logstart
4585 \family default
4599 \family default
4586 .
4600 .
4587
4601
4588 \layout Standard
4602 \layout Standard
4589
4603
4590 Log files can later be reloaded with the
4604 Log files can later be reloaded with the
4591 \family typewriter
4605 \family typewriter
4592 -logplay
4606 -logplay
4593 \family default
4607 \family default
4594 option and IPython will attempt to 'replay' the log by executing all the
4608 option and IPython will attempt to 'replay' the log by executing all the
4595 lines in it, thus restoring the state of a previous session.
4609 lines in it, thus restoring the state of a previous session.
4596 This feature is not quite perfect, but can still be useful in many cases.
4610 This feature is not quite perfect, but can still be useful in many cases.
4597 \layout Standard
4611 \layout Standard
4598
4612
4599 The log files can also be used as a way to have a permanent record of any
4613 The log files can also be used as a way to have a permanent record of any
4600 code you wrote while experimenting.
4614 code you wrote while experimenting.
4601 Log files are regular text files which you can later open in your favorite
4615 Log files are regular text files which you can later open in your favorite
4602 text editor to extract code or to 'clean them up' before using them to
4616 text editor to extract code or to 'clean them up' before using them to
4603 replay a session.
4617 replay a session.
4604 \layout Standard
4618 \layout Standard
4605
4619
4606 The
4620 The
4607 \family typewriter
4621 \family typewriter
4608 %logstart
4622 %logstart
4609 \family default
4623 \family default
4610 function for activating logging in mid-session is used as follows:
4624 function for activating logging in mid-session is used as follows:
4611 \layout Standard
4625 \layout Standard
4612
4626
4613
4627
4614 \family typewriter
4628 \family typewriter
4615 %logstart [log_name [log_mode]]
4629 %logstart [log_name [log_mode]]
4616 \layout Standard
4630 \layout Standard
4617
4631
4618 If no name is given, it defaults to a file named
4632 If no name is given, it defaults to a file named
4619 \family typewriter
4633 \family typewriter
4620 'log'
4634 'log'
4621 \family default
4635 \family default
4622 in your IPYTHONDIR directory, in
4636 in your IPYTHONDIR directory, in
4623 \family typewriter
4637 \family typewriter
4624 'rotate'
4638 'rotate'
4625 \family default
4639 \family default
4626 mode (see below).
4640 mode (see below).
4627 \layout Standard
4641 \layout Standard
4628
4642
4629 '
4643 '
4630 \family typewriter
4644 \family typewriter
4631 %logstart name
4645 %logstart name
4632 \family default
4646 \family default
4633 ' saves to file
4647 ' saves to file
4634 \family typewriter
4648 \family typewriter
4635 'name'
4649 'name'
4636 \family default
4650 \family default
4637 in
4651 in
4638 \family typewriter
4652 \family typewriter
4639 'backup'
4653 'backup'
4640 \family default
4654 \family default
4641 mode.
4655 mode.
4642 It saves your history up to that point and then continues logging.
4656 It saves your history up to that point and then continues logging.
4643 \layout Standard
4657 \layout Standard
4644
4658
4645
4659
4646 \family typewriter
4660 \family typewriter
4647 %logstart
4661 %logstart
4648 \family default
4662 \family default
4649 takes a second optional parameter: logging mode.
4663 takes a second optional parameter: logging mode.
4650 This can be one of (note that the modes are given unquoted):
4664 This can be one of (note that the modes are given unquoted):
4651 \layout List
4665 \layout List
4652 \labelwidthstring 00.00.0000
4666 \labelwidthstring 00.00.0000
4653
4667
4654
4668
4655 \family typewriter
4669 \family typewriter
4656 over
4670 over
4657 \family default
4671 \family default
4658 : overwrite existing
4672 : overwrite existing
4659 \family typewriter
4673 \family typewriter
4660 log_name
4674 log_name
4661 \family default
4675 \family default
4662 .
4676 .
4663 \layout List
4677 \layout List
4664 \labelwidthstring 00.00.0000
4678 \labelwidthstring 00.00.0000
4665
4679
4666
4680
4667 \family typewriter
4681 \family typewriter
4668 backup
4682 backup
4669 \family default
4683 \family default
4670 : rename (if exists) to
4684 : rename (if exists) to
4671 \family typewriter
4685 \family typewriter
4672 log_name~
4686 log_name~
4673 \family default
4687 \family default
4674 and start
4688 and start
4675 \family typewriter
4689 \family typewriter
4676 log_name
4690 log_name
4677 \family default
4691 \family default
4678 .
4692 .
4679 \layout List
4693 \layout List
4680 \labelwidthstring 00.00.0000
4694 \labelwidthstring 00.00.0000
4681
4695
4682
4696
4683 \family typewriter
4697 \family typewriter
4684 append
4698 append
4685 \family default
4699 \family default
4686 : well, that says it.
4700 : well, that says it.
4687 \layout List
4701 \layout List
4688 \labelwidthstring 00.00.0000
4702 \labelwidthstring 00.00.0000
4689
4703
4690
4704
4691 \family typewriter
4705 \family typewriter
4692 rotate
4706 rotate
4693 \family default
4707 \family default
4694 : create rotating logs
4708 : create rotating logs
4695 \family typewriter
4709 \family typewriter
4696 log_name
4710 log_name
4697 \family default
4711 \family default
4698 .
4712 .
4699 \family typewriter
4713 \family typewriter
4700 1~
4714 1~
4701 \family default
4715 \family default
4702 ,
4716 ,
4703 \family typewriter
4717 \family typewriter
4704 log_name.2~
4718 log_name.2~
4705 \family default
4719 \family default
4706 , etc.
4720 , etc.
4707 \layout Standard
4721 \layout Standard
4708
4722
4709 The
4723 The
4710 \family typewriter
4724 \family typewriter
4711 %logoff
4725 %logoff
4712 \family default
4726 \family default
4713 and
4727 and
4714 \family typewriter
4728 \family typewriter
4715 %logon
4729 %logon
4716 \family default
4730 \family default
4717 functions allow you to temporarily stop and resume logging to a file which
4731 functions allow you to temporarily stop and resume logging to a file which
4718 had previously been started with
4732 had previously been started with
4719 \family typewriter
4733 \family typewriter
4720 %logstart
4734 %logstart
4721 \family default
4735 \family default
4722 .
4736 .
4723 They will fail (with an explanation) if you try to use them before logging
4737 They will fail (with an explanation) if you try to use them before logging
4724 has been started.
4738 has been started.
4725 \layout Subsection
4739 \layout Subsection
4726
4740
4727
4741
4728 \begin_inset LatexCommand \label{sub:System-shell-access}
4742 \begin_inset LatexCommand \label{sub:System-shell-access}
4729
4743
4730 \end_inset
4744 \end_inset
4731
4745
4732 System shell access
4746 System shell access
4733 \layout Standard
4747 \layout Standard
4734
4748
4735 Any input line beginning with a
4749 Any input line beginning with a
4736 \family typewriter
4750 \family typewriter
4737 !
4751 !
4738 \family default
4752 \family default
4739 character is passed verbatim (minus the
4753 character is passed verbatim (minus the
4740 \family typewriter
4754 \family typewriter
4741 !
4755 !
4742 \family default
4756 \family default
4743 , of course) to the underlying operating system.
4757 , of course) to the underlying operating system.
4744 For example, typing
4758 For example, typing
4745 \family typewriter
4759 \family typewriter
4746 !ls
4760 !ls
4747 \family default
4761 \family default
4748 will run
4762 will run
4749 \family typewriter
4763 \family typewriter
4750 'ls'
4764 'ls'
4751 \family default
4765 \family default
4752 in the current directory.
4766 in the current directory.
4753 \layout Subsubsection
4767 \layout Subsubsection
4754
4768
4755 Manual capture of command output
4769 Manual capture of command output
4756 \layout Standard
4770 \layout Standard
4757
4771
4758 If the input line begins with
4772 If the input line begins with
4759 \emph on
4773 \emph on
4760 two
4774 two
4761 \emph default
4775 \emph default
4762 exclamation marks,
4776 exclamation marks,
4763 \family typewriter
4777 \family typewriter
4764 !!
4778 !!
4765 \family default
4779 \family default
4766 , the command is executed but its output is captured and returned as a python
4780 , the command is executed but its output is captured and returned as a python
4767 list, split on newlines.
4781 list, split on newlines.
4768 Any output sent by the subprocess to standard error is printed separately,
4782 Any output sent by the subprocess to standard error is printed separately,
4769 so that the resulting list only captures standard output.
4783 so that the resulting list only captures standard output.
4770 The
4784 The
4771 \family typewriter
4785 \family typewriter
4772 !!
4786 !!
4773 \family default
4787 \family default
4774 syntax is a shorthand for the
4788 syntax is a shorthand for the
4775 \family typewriter
4789 \family typewriter
4776 %sx
4790 %sx
4777 \family default
4791 \family default
4778 magic command.
4792 magic command.
4779 \layout Standard
4793 \layout Standard
4780
4794
4781 Finally, the
4795 Finally, the
4782 \family typewriter
4796 \family typewriter
4783 %sc
4797 %sc
4784 \family default
4798 \family default
4785 magic (short for `shell capture') is similar to
4799 magic (short for `shell capture') is similar to
4786 \family typewriter
4800 \family typewriter
4787 %sx
4801 %sx
4788 \family default
4802 \family default
4789 , but allowing more fine-grained control of the capture details, and storing
4803 , but allowing more fine-grained control of the capture details, and storing
4790 the result directly into a named variable.
4804 the result directly into a named variable.
4791 \layout Standard
4805 \layout Standard
4792
4806
4793 See Sec.\SpecialChar ~
4807 See Sec.\SpecialChar ~
4794
4808
4795 \begin_inset LatexCommand \ref{sec:magic}
4809 \begin_inset LatexCommand \ref{sec:magic}
4796
4810
4797 \end_inset
4811 \end_inset
4798
4812
4799 for details on the magics
4813 for details on the magics
4800 \family typewriter
4814 \family typewriter
4801 %sc
4815 %sc
4802 \family default
4816 \family default
4803 and
4817 and
4804 \family typewriter
4818 \family typewriter
4805 %sx
4819 %sx
4806 \family default
4820 \family default
4807 , or use IPython's own help (
4821 , or use IPython's own help (
4808 \family typewriter
4822 \family typewriter
4809 sc?
4823 sc?
4810 \family default
4824 \family default
4811 and
4825 and
4812 \family typewriter
4826 \family typewriter
4813 sx?
4827 sx?
4814 \family default
4828 \family default
4815 ) for further details.
4829 ) for further details.
4816 \layout Standard
4830 \layout Standard
4817
4831
4818 IPython also allows you to expand the value of python variables when making
4832 IPython also allows you to expand the value of python variables when making
4819 system calls.
4833 system calls.
4820 Any python variable or expression which you prepend with
4834 Any python variable or expression which you prepend with
4821 \family typewriter
4835 \family typewriter
4822 $
4836 $
4823 \family default
4837 \family default
4824 will get expanded before the system call is made.
4838 will get expanded before the system call is made.
4825
4839
4826 \layout Standard
4840 \layout Standard
4827
4841
4828
4842
4829 \family typewriter
4843 \family typewriter
4830 In [1]: pyvar='Hello world'
4844 In [1]: pyvar='Hello world'
4831 \newline
4845 \newline
4832 In [2]: !echo "A python variable: $pyvar"
4846 In [2]: !echo "A python variable: $pyvar"
4833 \newline
4847 \newline
4834 A python variable: Hello world
4848 A python variable: Hello world
4835 \layout Standard
4849 \layout Standard
4836
4850
4837 If you want the shell to actually see a literal
4851 If you want the shell to actually see a literal
4838 \family typewriter
4852 \family typewriter
4839 $
4853 $
4840 \family default
4854 \family default
4841 , you need to type it twice:
4855 , you need to type it twice:
4842 \layout Standard
4856 \layout Standard
4843
4857
4844
4858
4845 \family typewriter
4859 \family typewriter
4846 In [3]: !echo "A system variable: $$HOME"
4860 In [3]: !echo "A system variable: $$HOME"
4847 \newline
4861 \newline
4848 A system variable: /home/fperez
4862 A system variable: /home/fperez
4849 \layout Standard
4863 \layout Standard
4850
4864
4851 You can pass arbitrary expressions, though you'll need to delimit them with
4865 You can pass arbitrary expressions, though you'll need to delimit them with
4852
4866
4853 \family typewriter
4867 \family typewriter
4854 {}
4868 {}
4855 \family default
4869 \family default
4856 if there is ambiguity as to the extent of the expression:
4870 if there is ambiguity as to the extent of the expression:
4857 \layout Standard
4871 \layout Standard
4858
4872
4859
4873
4860 \family typewriter
4874 \family typewriter
4861 In [5]: x=10
4875 In [5]: x=10
4862 \newline
4876 \newline
4863 In [6]: y=20
4877 In [6]: y=20
4864 \newline
4878 \newline
4865 In [13]: !echo $x+y
4879 In [13]: !echo $x+y
4866 \newline
4880 \newline
4867 10+y
4881 10+y
4868 \newline
4882 \newline
4869 In [7]: !echo ${x+y}
4883 In [7]: !echo ${x+y}
4870 \newline
4884 \newline
4871 30
4885 30
4872 \layout Standard
4886 \layout Standard
4873
4887
4874 Even object attributes can be expanded:
4888 Even object attributes can be expanded:
4875 \layout Standard
4889 \layout Standard
4876
4890
4877
4891
4878 \family typewriter
4892 \family typewriter
4879 In [12]: !echo $sys.argv
4893 In [12]: !echo $sys.argv
4880 \newline
4894 \newline
4881 [/home/fperez/usr/bin/ipython]
4895 [/home/fperez/usr/bin/ipython]
4882 \layout Subsection
4896 \layout Subsection
4883
4897
4884 System command aliases
4898 System command aliases
4885 \layout Standard
4899 \layout Standard
4886
4900
4887 The
4901 The
4888 \family typewriter
4902 \family typewriter
4889 %alias
4903 %alias
4890 \family default
4904 \family default
4891 magic function and the
4905 magic function and the
4892 \family typewriter
4906 \family typewriter
4893 alias
4907 alias
4894 \family default
4908 \family default
4895 option in the
4909 option in the
4896 \family typewriter
4910 \family typewriter
4897 ipythonrc
4911 ipythonrc
4898 \family default
4912 \family default
4899 configuration file allow you to define magic functions which are in fact
4913 configuration file allow you to define magic functions which are in fact
4900 system shell commands.
4914 system shell commands.
4901 These aliases can have parameters.
4915 These aliases can have parameters.
4902
4916
4903 \layout Standard
4917 \layout Standard
4904
4918
4905 '
4919 '
4906 \family typewriter
4920 \family typewriter
4907 %alias alias_name cmd
4921 %alias alias_name cmd
4908 \family default
4922 \family default
4909 ' defines '
4923 ' defines '
4910 \family typewriter
4924 \family typewriter
4911 alias_name
4925 alias_name
4912 \family default
4926 \family default
4913 ' as an alias for '
4927 ' as an alias for '
4914 \family typewriter
4928 \family typewriter
4915 cmd
4929 cmd
4916 \family default
4930 \family default
4917 '
4931 '
4918 \layout Standard
4932 \layout Standard
4919
4933
4920 Then, typing '
4934 Then, typing '
4921 \family typewriter
4935 \family typewriter
4922 %alias_name params
4936 %alias_name params
4923 \family default
4937 \family default
4924 ' will execute the system command '
4938 ' will execute the system command '
4925 \family typewriter
4939 \family typewriter
4926 cmd params
4940 cmd params
4927 \family default
4941 \family default
4928 ' (from your underlying operating system).
4942 ' (from your underlying operating system).
4929
4943
4930 \layout Standard
4944 \layout Standard
4931
4945
4932 You can also define aliases with parameters using
4946 You can also define aliases with parameters using
4933 \family typewriter
4947 \family typewriter
4934 %s
4948 %s
4935 \family default
4949 \family default
4936 specifiers (one per parameter).
4950 specifiers (one per parameter).
4937 The following example defines the
4951 The following example defines the
4938 \family typewriter
4952 \family typewriter
4939 %parts
4953 %parts
4940 \family default
4954 \family default
4941 function as an alias to the command '
4955 function as an alias to the command '
4942 \family typewriter
4956 \family typewriter
4943 echo first %s second %s
4957 echo first %s second %s
4944 \family default
4958 \family default
4945 ' where each
4959 ' where each
4946 \family typewriter
4960 \family typewriter
4947 %s
4961 %s
4948 \family default
4962 \family default
4949 will be replaced by a positional parameter to the call to
4963 will be replaced by a positional parameter to the call to
4950 \family typewriter
4964 \family typewriter
4951 %parts:
4965 %parts:
4952 \layout Standard
4966 \layout Standard
4953
4967
4954
4968
4955 \family typewriter
4969 \family typewriter
4956 In [1]: alias parts echo first %s second %s
4970 In [1]: alias parts echo first %s second %s
4957 \newline
4971 \newline
4958 In [2]: %parts A B
4972 In [2]: %parts A B
4959 \newline
4973 \newline
4960 first A second B
4974 first A second B
4961 \newline
4975 \newline
4962 In [3]: %parts A
4976 In [3]: %parts A
4963 \newline
4977 \newline
4964 Incorrect number of arguments: 2 expected.
4978 Incorrect number of arguments: 2 expected.
4965
4979
4966 \newline
4980 \newline
4967 parts is an alias to: 'echo first %s second %s'
4981 parts is an alias to: 'echo first %s second %s'
4968 \layout Standard
4982 \layout Standard
4969
4983
4970 If called with no parameters,
4984 If called with no parameters,
4971 \family typewriter
4985 \family typewriter
4972 %alias
4986 %alias
4973 \family default
4987 \family default
4974 prints the table of currently defined aliases.
4988 prints the table of currently defined aliases.
4975 \layout Standard
4989 \layout Standard
4976
4990
4977 The
4991 The
4978 \family typewriter
4992 \family typewriter
4979 %rehash/rehashx
4993 %rehash/rehashx
4980 \family default
4994 \family default
4981 magics allow you to load your entire
4995 magics allow you to load your entire
4982 \family typewriter
4996 \family typewriter
4983 $PATH
4997 $PATH
4984 \family default
4998 \family default
4985 as ipython aliases.
4999 as ipython aliases.
4986 See their respective docstrings (or sec.\SpecialChar ~
5000 See their respective docstrings (or sec.\SpecialChar ~
4987
5001
4988 \begin_inset LatexCommand \ref{sec:magic}
5002 \begin_inset LatexCommand \ref{sec:magic}
4989
5003
4990 \end_inset
5004 \end_inset
4991
5005
4992 for further details).
5006 for further details).
4993 \layout Subsection
5007 \layout Subsection
4994
5008
4995
5009
4996 \begin_inset LatexCommand \label{sec:dreload}
5010 \begin_inset LatexCommand \label{sec:dreload}
4997
5011
4998 \end_inset
5012 \end_inset
4999
5013
5000 Recursive reload
5014 Recursive reload
5001 \layout Standard
5015 \layout Standard
5002
5016
5003 The
5017 The
5004 \family typewriter
5018 \family typewriter
5005 %dreload
5019 %dreload
5006 \family default
5020 \family default
5007 command does a recursive reload of a module: changes made to the module
5021 command does a recursive reload of a module: changes made to the module
5008 since you imported will actually be available without having to exit.
5022 since you imported will actually be available without having to exit.
5009 \layout Subsection
5023 \layout Subsection
5010
5024
5011 Verbose and colored exception traceback printouts
5025 Verbose and colored exception traceback printouts
5012 \layout Standard
5026 \layout Standard
5013
5027
5014 IPython provides the option to see very detailed exception tracebacks, which
5028 IPython provides the option to see very detailed exception tracebacks, which
5015 can be especially useful when debugging large programs.
5029 can be especially useful when debugging large programs.
5016 You can run any Python file with the
5030 You can run any Python file with the
5017 \family typewriter
5031 \family typewriter
5018 %run
5032 %run
5019 \family default
5033 \family default
5020 function to benefit from these detailed tracebacks.
5034 function to benefit from these detailed tracebacks.
5021 Furthermore, both normal and verbose tracebacks can be colored (if your
5035 Furthermore, both normal and verbose tracebacks can be colored (if your
5022 terminal supports it) which makes them much easier to parse visually.
5036 terminal supports it) which makes them much easier to parse visually.
5023 \layout Standard
5037 \layout Standard
5024
5038
5025 See the magic
5039 See the magic
5026 \family typewriter
5040 \family typewriter
5027 xmode
5041 xmode
5028 \family default
5042 \family default
5029 and
5043 and
5030 \family typewriter
5044 \family typewriter
5031 colors
5045 colors
5032 \family default
5046 \family default
5033 functions for details (just type
5047 functions for details (just type
5034 \family typewriter
5048 \family typewriter
5035 %magic
5049 %magic
5036 \family default
5050 \family default
5037 ).
5051 ).
5038 \layout Standard
5052 \layout Standard
5039
5053
5040 These features are basically a terminal version of Ka-Ping Yee's
5054 These features are basically a terminal version of Ka-Ping Yee's
5041 \family typewriter
5055 \family typewriter
5042 cgitb
5056 cgitb
5043 \family default
5057 \family default
5044 module, now part of the standard Python library.
5058 module, now part of the standard Python library.
5045 \layout Subsection
5059 \layout Subsection
5046
5060
5047
5061
5048 \begin_inset LatexCommand \label{sec:cache_input}
5062 \begin_inset LatexCommand \label{sec:cache_input}
5049
5063
5050 \end_inset
5064 \end_inset
5051
5065
5052 Input caching system
5066 Input caching system
5053 \layout Standard
5067 \layout Standard
5054
5068
5055 IPython offers numbered prompts (In/Out) with input and output caching.
5069 IPython offers numbered prompts (In/Out) with input and output caching.
5056 All input is saved and can be retrieved as variables (besides the usual
5070 All input is saved and can be retrieved as variables (besides the usual
5057 arrow key recall).
5071 arrow key recall).
5058 \layout Standard
5072 \layout Standard
5059
5073
5060 The following GLOBAL variables always exist (so don't overwrite them!):
5074 The following GLOBAL variables always exist (so don't overwrite them!):
5061
5075
5062 \family typewriter
5076 \family typewriter
5063 _i
5077 _i
5064 \family default
5078 \family default
5065 : stores previous input.
5079 : stores previous input.
5066
5080
5067 \family typewriter
5081 \family typewriter
5068 _ii
5082 _ii
5069 \family default
5083 \family default
5070 : next previous.
5084 : next previous.
5071
5085
5072 \family typewriter
5086 \family typewriter
5073 _iii
5087 _iii
5074 \family default
5088 \family default
5075 : next-next previous.
5089 : next-next previous.
5076
5090
5077 \family typewriter
5091 \family typewriter
5078 _ih
5092 _ih
5079 \family default
5093 \family default
5080 : a list of all input
5094 : a list of all input
5081 \family typewriter
5095 \family typewriter
5082 _ih[n]
5096 _ih[n]
5083 \family default
5097 \family default
5084 is the input from line
5098 is the input from line
5085 \family typewriter
5099 \family typewriter
5086 n
5100 n
5087 \family default
5101 \family default
5088 and this list is aliased to the global variable
5102 and this list is aliased to the global variable
5089 \family typewriter
5103 \family typewriter
5090 In
5104 In
5091 \family default
5105 \family default
5092 .
5106 .
5093 If you overwrite
5107 If you overwrite
5094 \family typewriter
5108 \family typewriter
5095 In
5109 In
5096 \family default
5110 \family default
5097 with a variable of your own, you can remake the assignment to the internal
5111 with a variable of your own, you can remake the assignment to the internal
5098 list with a simple
5112 list with a simple
5099 \family typewriter
5113 \family typewriter
5100 'In=_ih'
5114 'In=_ih'
5101 \family default
5115 \family default
5102 .
5116 .
5103 \layout Standard
5117 \layout Standard
5104
5118
5105 Additionally, global variables named
5119 Additionally, global variables named
5106 \family typewriter
5120 \family typewriter
5107 _i<n>
5121 _i<n>
5108 \family default
5122 \family default
5109 are dynamically created (
5123 are dynamically created (
5110 \family typewriter
5124 \family typewriter
5111 <n>
5125 <n>
5112 \family default
5126 \family default
5113 being the prompt counter), such that
5127 being the prompt counter), such that
5114 \newline
5128 \newline
5115
5129
5116 \family typewriter
5130 \family typewriter
5117 _i<n> == _ih[<n>] == In[<n>].
5131 _i<n> == _ih[<n>] == In[<n>].
5118 \layout Standard
5132 \layout Standard
5119
5133
5120 For example, what you typed at prompt 14 is available as
5134 For example, what you typed at prompt 14 is available as
5121 \family typewriter
5135 \family typewriter
5122 _i14,
5136 _i14,
5123 \family default
5137 \family default
5124
5138
5125 \family typewriter
5139 \family typewriter
5126 _ih[14]
5140 _ih[14]
5127 \family default
5141 \family default
5128 and
5142 and
5129 \family typewriter
5143 \family typewriter
5130 In[14]
5144 In[14]
5131 \family default
5145 \family default
5132 .
5146 .
5133 \layout Standard
5147 \layout Standard
5134
5148
5135 This allows you to easily cut and paste multi line interactive prompts by
5149 This allows you to easily cut and paste multi line interactive prompts by
5136 printing them out: they print like a clean string, without prompt characters.
5150 printing them out: they print like a clean string, without prompt characters.
5137 You can also manipulate them like regular variables (they are strings),
5151 You can also manipulate them like regular variables (they are strings),
5138 modify or exec them (typing
5152 modify or exec them (typing
5139 \family typewriter
5153 \family typewriter
5140 'exec _i9'
5154 'exec _i9'
5141 \family default
5155 \family default
5142 will re-execute the contents of input prompt 9, '
5156 will re-execute the contents of input prompt 9, '
5143 \family typewriter
5157 \family typewriter
5144 exec In[9:14]+In[18]
5158 exec In[9:14]+In[18]
5145 \family default
5159 \family default
5146 ' will re-execute lines 9 through 13 and line 18).
5160 ' will re-execute lines 9 through 13 and line 18).
5147 \layout Standard
5161 \layout Standard
5148
5162
5149 You can also re-execute multiple lines of input easily by using the magic
5163 You can also re-execute multiple lines of input easily by using the magic
5150
5164
5151 \family typewriter
5165 \family typewriter
5152 %macro
5166 %macro
5153 \family default
5167 \family default
5154 function (which automates the process and allows re-execution without having
5168 function (which automates the process and allows re-execution without having
5155 to type '
5169 to type '
5156 \family typewriter
5170 \family typewriter
5157 exec
5171 exec
5158 \family default
5172 \family default
5159 ' every time).
5173 ' every time).
5160 The macro system also allows you to re-execute previous lines which include
5174 The macro system also allows you to re-execute previous lines which include
5161 magic function calls (which require special processing).
5175 magic function calls (which require special processing).
5162 Type
5176 Type
5163 \family typewriter
5177 \family typewriter
5164 %macro?
5178 %macro?
5165 \family default
5179 \family default
5166 or see sec.
5180 or see sec.
5167
5181
5168 \begin_inset LatexCommand \ref{sec:magic}
5182 \begin_inset LatexCommand \ref{sec:magic}
5169
5183
5170 \end_inset
5184 \end_inset
5171
5185
5172 for more details on the macro system.
5186 for more details on the macro system.
5173 \layout Standard
5187 \layout Standard
5174
5188
5175 A history function
5189 A history function
5176 \family typewriter
5190 \family typewriter
5177 %hist
5191 %hist
5178 \family default
5192 \family default
5179 allows you to see any part of your input history by printing a range of
5193 allows you to see any part of your input history by printing a range of
5180 the
5194 the
5181 \family typewriter
5195 \family typewriter
5182 _i
5196 _i
5183 \family default
5197 \family default
5184 variables.
5198 variables.
5185 \layout Subsection
5199 \layout Subsection
5186
5200
5187
5201
5188 \begin_inset LatexCommand \label{sec:cache_output}
5202 \begin_inset LatexCommand \label{sec:cache_output}
5189
5203
5190 \end_inset
5204 \end_inset
5191
5205
5192 Output caching system
5206 Output caching system
5193 \layout Standard
5207 \layout Standard
5194
5208
5195 For output that is returned from actions, a system similar to the input
5209 For output that is returned from actions, a system similar to the input
5196 cache exists but using
5210 cache exists but using
5197 \family typewriter
5211 \family typewriter
5198 _
5212 _
5199 \family default
5213 \family default
5200 instead of
5214 instead of
5201 \family typewriter
5215 \family typewriter
5202 _i
5216 _i
5203 \family default
5217 \family default
5204 .
5218 .
5205 Only actions that produce a result (NOT assignments, for example) are cached.
5219 Only actions that produce a result (NOT assignments, for example) are cached.
5206 If you are familiar with Mathematica, IPython's
5220 If you are familiar with Mathematica, IPython's
5207 \family typewriter
5221 \family typewriter
5208 _
5222 _
5209 \family default
5223 \family default
5210 variables behave exactly like Mathematica's
5224 variables behave exactly like Mathematica's
5211 \family typewriter
5225 \family typewriter
5212 %
5226 %
5213 \family default
5227 \family default
5214 variables.
5228 variables.
5215 \layout Standard
5229 \layout Standard
5216
5230
5217 The following GLOBAL variables always exist (so don't overwrite them!):
5231 The following GLOBAL variables always exist (so don't overwrite them!):
5218
5232
5219 \layout List
5233 \layout List
5220 \labelwidthstring 00.00.0000
5234 \labelwidthstring 00.00.0000
5221
5235
5222
5236
5223 \family typewriter
5237 \family typewriter
5224 \series bold
5238 \series bold
5225 _
5239 _
5226 \family default
5240 \family default
5227 \series default
5241 \series default
5228 (a
5242 (a
5229 \emph on
5243 \emph on
5230 single
5244 single
5231 \emph default
5245 \emph default
5232 underscore) : stores previous output, like Python's default interpreter.
5246 underscore) : stores previous output, like Python's default interpreter.
5233 \layout List
5247 \layout List
5234 \labelwidthstring 00.00.0000
5248 \labelwidthstring 00.00.0000
5235
5249
5236
5250
5237 \family typewriter
5251 \family typewriter
5238 \series bold
5252 \series bold
5239 __
5253 __
5240 \family default
5254 \family default
5241 \series default
5255 \series default
5242 (two underscores): next previous.
5256 (two underscores): next previous.
5243 \layout List
5257 \layout List
5244 \labelwidthstring 00.00.0000
5258 \labelwidthstring 00.00.0000
5245
5259
5246
5260
5247 \family typewriter
5261 \family typewriter
5248 \series bold
5262 \series bold
5249 ___
5263 ___
5250 \family default
5264 \family default
5251 \series default
5265 \series default
5252 (three underscores): next-next previous.
5266 (three underscores): next-next previous.
5253 \layout Standard
5267 \layout Standard
5254
5268
5255 Additionally, global variables named
5269 Additionally, global variables named
5256 \family typewriter
5270 \family typewriter
5257 _<n>
5271 _<n>
5258 \family default
5272 \family default
5259 are dynamically created (
5273 are dynamically created (
5260 \family typewriter
5274 \family typewriter
5261 <n>
5275 <n>
5262 \family default
5276 \family default
5263 being the prompt counter), such that the result of output
5277 being the prompt counter), such that the result of output
5264 \family typewriter
5278 \family typewriter
5265 <n>
5279 <n>
5266 \family default
5280 \family default
5267 is always available as
5281 is always available as
5268 \family typewriter
5282 \family typewriter
5269 _<n>
5283 _<n>
5270 \family default
5284 \family default
5271 (don't use the angle brackets, just the number, e.g.
5285 (don't use the angle brackets, just the number, e.g.
5272
5286
5273 \family typewriter
5287 \family typewriter
5274 _21
5288 _21
5275 \family default
5289 \family default
5276 ).
5290 ).
5277 \layout Standard
5291 \layout Standard
5278
5292
5279 These global variables are all stored in a global dictionary (not a list,
5293 These global variables are all stored in a global dictionary (not a list,
5280 since it only has entries for lines which returned a result) available
5294 since it only has entries for lines which returned a result) available
5281 under the names
5295 under the names
5282 \family typewriter
5296 \family typewriter
5283 _oh
5297 _oh
5284 \family default
5298 \family default
5285 and
5299 and
5286 \family typewriter
5300 \family typewriter
5287 Out
5301 Out
5288 \family default
5302 \family default
5289 (similar to
5303 (similar to
5290 \family typewriter
5304 \family typewriter
5291 _ih
5305 _ih
5292 \family default
5306 \family default
5293 and
5307 and
5294 \family typewriter
5308 \family typewriter
5295 In
5309 In
5296 \family default
5310 \family default
5297 ).
5311 ).
5298 So the output from line 12 can be obtained as
5312 So the output from line 12 can be obtained as
5299 \family typewriter
5313 \family typewriter
5300 _12
5314 _12
5301 \family default
5315 \family default
5302 ,
5316 ,
5303 \family typewriter
5317 \family typewriter
5304 Out[12]
5318 Out[12]
5305 \family default
5319 \family default
5306 or
5320 or
5307 \family typewriter
5321 \family typewriter
5308 _oh[12]
5322 _oh[12]
5309 \family default
5323 \family default
5310 .
5324 .
5311 If you accidentally overwrite the
5325 If you accidentally overwrite the
5312 \family typewriter
5326 \family typewriter
5313 Out
5327 Out
5314 \family default
5328 \family default
5315 variable you can recover it by typing
5329 variable you can recover it by typing
5316 \family typewriter
5330 \family typewriter
5317 'Out=_oh
5331 'Out=_oh
5318 \family default
5332 \family default
5319 ' at the prompt.
5333 ' at the prompt.
5320 \layout Standard
5334 \layout Standard
5321
5335
5322 This system obviously can potentially put heavy memory demands on your system,
5336 This system obviously can potentially put heavy memory demands on your system,
5323 since it prevents Python's garbage collector from removing any previously
5337 since it prevents Python's garbage collector from removing any previously
5324 computed results.
5338 computed results.
5325 You can control how many results are kept in memory with the option (at
5339 You can control how many results are kept in memory with the option (at
5326 the command line or in your
5340 the command line or in your
5327 \family typewriter
5341 \family typewriter
5328 ipythonrc
5342 ipythonrc
5329 \family default
5343 \family default
5330 file)
5344 file)
5331 \family typewriter
5345 \family typewriter
5332 cache_size
5346 cache_size
5333 \family default
5347 \family default
5334 .
5348 .
5335 If you set it to 0, the whole system is completely disabled and the prompts
5349 If you set it to 0, the whole system is completely disabled and the prompts
5336 revert to the classic
5350 revert to the classic
5337 \family typewriter
5351 \family typewriter
5338 '>>>'
5352 '>>>'
5339 \family default
5353 \family default
5340 of normal Python.
5354 of normal Python.
5341 \layout Subsection
5355 \layout Subsection
5342
5356
5343 Directory history
5357 Directory history
5344 \layout Standard
5358 \layout Standard
5345
5359
5346 Your history of visited directories is kept in the global list
5360 Your history of visited directories is kept in the global list
5347 \family typewriter
5361 \family typewriter
5348 _dh
5362 _dh
5349 \family default
5363 \family default
5350 , and the magic
5364 , and the magic
5351 \family typewriter
5365 \family typewriter
5352 %cd
5366 %cd
5353 \family default
5367 \family default
5354 command can be used to go to any entry in that list.
5368 command can be used to go to any entry in that list.
5355 The
5369 The
5356 \family typewriter
5370 \family typewriter
5357 %dhist
5371 %dhist
5358 \family default
5372 \family default
5359 command allows you to view this history.
5373 command allows you to view this history.
5360 \layout Subsection
5374 \layout Subsection
5361
5375
5362 Automatic parentheses and quotes
5376 Automatic parentheses and quotes
5363 \layout Standard
5377 \layout Standard
5364
5378
5365 These features were adapted from Nathan Gray's LazyPython.
5379 These features were adapted from Nathan Gray's LazyPython.
5366 They are meant to allow less typing for common situations.
5380 They are meant to allow less typing for common situations.
5367 \layout Subsubsection
5381 \layout Subsubsection
5368
5382
5369 Automatic parentheses
5383 Automatic parentheses
5370 \layout Standard
5384 \layout Standard
5371
5385
5372 Callable objects (i.e.
5386 Callable objects (i.e.
5373 functions, methods, etc) can be invoked like this (notice the commas between
5387 functions, methods, etc) can be invoked like this (notice the commas between
5374 the arguments):
5388 the arguments):
5375 \layout Standard
5389 \layout Standard
5376
5390
5377
5391
5378 \family typewriter
5392 \family typewriter
5379 >>> callable_ob arg1, arg2, arg3
5393 >>> callable_ob arg1, arg2, arg3
5380 \layout Standard
5394 \layout Standard
5381
5395
5382 and the input will be translated to this:
5396 and the input will be translated to this:
5383 \layout Standard
5397 \layout Standard
5384
5398
5385
5399
5386 \family typewriter
5400 \family typewriter
5387 --> callable_ob(arg1, arg2, arg3)
5401 --> callable_ob(arg1, arg2, arg3)
5388 \layout Standard
5402 \layout Standard
5389
5403
5390 You can force automatic parentheses by using '/' as the first character
5404 You can force automatic parentheses by using '/' as the first character
5391 of a line.
5405 of a line.
5392 For example:
5406 For example:
5393 \layout Standard
5407 \layout Standard
5394
5408
5395
5409
5396 \family typewriter
5410 \family typewriter
5397 >>> /globals # becomes 'globals()'
5411 >>> /globals # becomes 'globals()'
5398 \layout Standard
5412 \layout Standard
5399
5413
5400 Note that the '/' MUST be the first character on the line! This won't work:
5414 Note that the '/' MUST be the first character on the line! This won't work:
5401
5415
5402 \layout Standard
5416 \layout Standard
5403
5417
5404
5418
5405 \family typewriter
5419 \family typewriter
5406 >>> print /globals # syntax error
5420 >>> print /globals # syntax error
5407 \layout Standard
5421 \layout Standard
5408
5422
5409 In most cases the automatic algorithm should work, so you should rarely
5423 In most cases the automatic algorithm should work, so you should rarely
5410 need to explicitly invoke /.
5424 need to explicitly invoke /.
5411 One notable exception is if you are trying to call a function with a list
5425 One notable exception is if you are trying to call a function with a list
5412 of tuples as arguments (the parenthesis will confuse IPython):
5426 of tuples as arguments (the parenthesis will confuse IPython):
5413 \layout Standard
5427 \layout Standard
5414
5428
5415
5429
5416 \family typewriter
5430 \family typewriter
5417 In [1]: zip (1,2,3),(4,5,6) # won't work
5431 In [1]: zip (1,2,3),(4,5,6) # won't work
5418 \layout Standard
5432 \layout Standard
5419
5433
5420 but this will work:
5434 but this will work:
5421 \layout Standard
5435 \layout Standard
5422
5436
5423
5437
5424 \family typewriter
5438 \family typewriter
5425 In [2]: /zip (1,2,3),(4,5,6)
5439 In [2]: /zip (1,2,3),(4,5,6)
5426 \newline
5440 \newline
5427 ------> zip ((1,2,3),(4,5,6))
5441 ------> zip ((1,2,3),(4,5,6))
5428 \newline
5442 \newline
5429 Out[2]= [(1, 4), (2, 5), (3, 6)]
5443 Out[2]= [(1, 4), (2, 5), (3, 6)]
5430 \layout Standard
5444 \layout Standard
5431
5445
5432 IPython tells you that it has altered your command line by displaying the
5446 IPython tells you that it has altered your command line by displaying the
5433 new command line preceded by
5447 new command line preceded by
5434 \family typewriter
5448 \family typewriter
5435 -->
5449 -->
5436 \family default
5450 \family default
5437 .
5451 .
5438 e.g.:
5452 e.g.:
5439 \layout Standard
5453 \layout Standard
5440
5454
5441
5455
5442 \family typewriter
5456 \family typewriter
5443 In [18]: callable list
5457 In [18]: callable list
5444 \newline
5458 \newline
5445 -------> callable (list)
5459 -------> callable (list)
5446 \layout Subsubsection
5460 \layout Subsubsection
5447
5461
5448 Automatic quoting
5462 Automatic quoting
5449 \layout Standard
5463 \layout Standard
5450
5464
5451 You can force automatic quoting of a function's arguments by using
5465 You can force automatic quoting of a function's arguments by using
5452 \family typewriter
5466 \family typewriter
5453 `,'
5467 `,'
5454 \family default
5468 \family default
5455 or
5469 or
5456 \family typewriter
5470 \family typewriter
5457 `;'
5471 `;'
5458 \family default
5472 \family default
5459 as the first character of a line.
5473 as the first character of a line.
5460 For example:
5474 For example:
5461 \layout Standard
5475 \layout Standard
5462
5476
5463
5477
5464 \family typewriter
5478 \family typewriter
5465 >>> ,my_function /home/me # becomes my_function("/home/me")
5479 >>> ,my_function /home/me # becomes my_function("/home/me")
5466 \layout Standard
5480 \layout Standard
5467
5481
5468 If you use
5482 If you use
5469 \family typewriter
5483 \family typewriter
5470 `;'
5484 `;'
5471 \family default
5485 \family default
5472 instead, the whole argument is quoted as a single string (while
5486 instead, the whole argument is quoted as a single string (while
5473 \family typewriter
5487 \family typewriter
5474 `,'
5488 `,'
5475 \family default
5489 \family default
5476 splits on whitespace):
5490 splits on whitespace):
5477 \layout Standard
5491 \layout Standard
5478
5492
5479
5493
5480 \family typewriter
5494 \family typewriter
5481 >>> ,my_function a b c # becomes my_function("a","b","c")
5495 >>> ,my_function a b c # becomes my_function("a","b","c")
5482 \layout Standard
5496 \layout Standard
5483
5497
5484
5498
5485 \family typewriter
5499 \family typewriter
5486 >>> ;my_function a b c # becomes my_function("a b c")
5500 >>> ;my_function a b c # becomes my_function("a b c")
5487 \layout Standard
5501 \layout Standard
5488
5502
5489 Note that the `
5503 Note that the `
5490 \family typewriter
5504 \family typewriter
5491 ,
5505 ,
5492 \family default
5506 \family default
5493 ' or `
5507 ' or `
5494 \family typewriter
5508 \family typewriter
5495 ;
5509 ;
5496 \family default
5510 \family default
5497 ' MUST be the first character on the line! This won't work:
5511 ' MUST be the first character on the line! This won't work:
5498 \layout Standard
5512 \layout Standard
5499
5513
5500
5514
5501 \family typewriter
5515 \family typewriter
5502 >>> x = ,my_function /home/me # syntax error
5516 >>> x = ,my_function /home/me # syntax error
5503 \layout Section
5517 \layout Section
5504
5518
5505
5519
5506 \begin_inset LatexCommand \label{sec:customization}
5520 \begin_inset LatexCommand \label{sec:customization}
5507
5521
5508 \end_inset
5522 \end_inset
5509
5523
5510 Customization
5524 Customization
5511 \layout Standard
5525 \layout Standard
5512
5526
5513 As we've already mentioned, IPython reads a configuration file which can
5527 As we've already mentioned, IPython reads a configuration file which can
5514 be specified at the command line (
5528 be specified at the command line (
5515 \family typewriter
5529 \family typewriter
5516 -rcfile
5530 -rcfile
5517 \family default
5531 \family default
5518 ) or which by default is assumed to be called
5532 ) or which by default is assumed to be called
5519 \family typewriter
5533 \family typewriter
5520 ipythonrc
5534 ipythonrc
5521 \family default
5535 \family default
5522 .
5536 .
5523 Such a file is looked for in the current directory where IPython is started
5537 Such a file is looked for in the current directory where IPython is started
5524 and then in your
5538 and then in your
5525 \family typewriter
5539 \family typewriter
5526 IPYTHONDIR
5540 IPYTHONDIR
5527 \family default
5541 \family default
5528 , which allows you to have local configuration files for specific projects.
5542 , which allows you to have local configuration files for specific projects.
5529 In this section we will call these types of configuration files simply
5543 In this section we will call these types of configuration files simply
5530 rcfiles (short for resource configuration file).
5544 rcfiles (short for resource configuration file).
5531 \layout Standard
5545 \layout Standard
5532
5546
5533 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5547 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5534 one per line.
5548 one per line.
5535 Lines beginning with a
5549 Lines beginning with a
5536 \family typewriter
5550 \family typewriter
5537 #
5551 #
5538 \family default
5552 \family default
5539 are ignored as comments, but comments can
5553 are ignored as comments, but comments can
5540 \series bold
5554 \series bold
5541 not
5555 not
5542 \series default
5556 \series default
5543 be put on lines with data (the parser is fairly primitive).
5557 be put on lines with data (the parser is fairly primitive).
5544 Note that these are not python files, and this is deliberate, because it
5558 Note that these are not python files, and this is deliberate, because it
5545 allows us to do some things which would be quite tricky to implement if
5559 allows us to do some things which would be quite tricky to implement if
5546 they were normal python files.
5560 they were normal python files.
5547 \layout Standard
5561 \layout Standard
5548
5562
5549 First, an rcfile can contain permanent default values for almost all command
5563 First, an rcfile can contain permanent default values for almost all command
5550 line options (except things like
5564 line options (except things like
5551 \family typewriter
5565 \family typewriter
5552 -help
5566 -help
5553 \family default
5567 \family default
5554 or
5568 or
5555 \family typewriter
5569 \family typewriter
5556 -Version
5570 -Version
5557 \family default
5571 \family default
5558 ).
5572 ).
5559 Sec\SpecialChar ~
5573 Sec\SpecialChar ~
5560
5574
5561 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5575 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5562
5576
5563 \end_inset
5577 \end_inset
5564
5578
5565 contains a description of all command-line options.
5579 contains a description of all command-line options.
5566 However, values you explicitly specify at the command line override the
5580 However, values you explicitly specify at the command line override the
5567 values defined in the rcfile.
5581 values defined in the rcfile.
5568 \layout Standard
5582 \layout Standard
5569
5583
5570 Besides command line option values, the rcfile can specify values for certain
5584 Besides command line option values, the rcfile can specify values for certain
5571 extra special options which are not available at the command line.
5585 extra special options which are not available at the command line.
5572 These options are briefly described below.
5586 These options are briefly described below.
5573
5587
5574 \layout Standard
5588 \layout Standard
5575
5589
5576 Each of these options may appear as many times as you need it in the file.
5590 Each of these options may appear as many times as you need it in the file.
5577 \layout List
5591 \layout List
5578 \labelwidthstring 00.00.0000
5592 \labelwidthstring 00.00.0000
5579
5593
5580
5594
5581 \family typewriter
5595 \family typewriter
5582 \series bold
5596 \series bold
5583 include\SpecialChar ~
5597 include\SpecialChar ~
5584 <file1>\SpecialChar ~
5598 <file1>\SpecialChar ~
5585 <file2>\SpecialChar ~
5599 <file2>\SpecialChar ~
5586 ...
5600 ...
5587 \family default
5601 \family default
5588 \series default
5602 \series default
5589 : you can name
5603 : you can name
5590 \emph on
5604 \emph on
5591 other
5605 other
5592 \emph default
5606 \emph default
5593 rcfiles you want to recursively load up to 15 levels (don't use the
5607 rcfiles you want to recursively load up to 15 levels (don't use the
5594 \family typewriter
5608 \family typewriter
5595 <>
5609 <>
5596 \family default
5610 \family default
5597 brackets in your names!).
5611 brackets in your names!).
5598 This feature allows you to define a 'base' rcfile with general options
5612 This feature allows you to define a 'base' rcfile with general options
5599 and special-purpose files which can be loaded only when needed with particular
5613 and special-purpose files which can be loaded only when needed with particular
5600 configuration options.
5614 configuration options.
5601 To make this more convenient, IPython accepts the
5615 To make this more convenient, IPython accepts the
5602 \family typewriter
5616 \family typewriter
5603 -profile <name>
5617 -profile <name>
5604 \family default
5618 \family default
5605 option (abbreviates to
5619 option (abbreviates to
5606 \family typewriter
5620 \family typewriter
5607 -p <name
5621 -p <name
5608 \family default
5622 \family default
5609 >)
5623 >)
5610 \family typewriter
5624 \family typewriter
5611 which
5625 which
5612 \family default
5626 \family default
5613 tells it to look for an rcfile named
5627 tells it to look for an rcfile named
5614 \family typewriter
5628 \family typewriter
5615 ipythonrc-<name>
5629 ipythonrc-<name>
5616 \family default
5630 \family default
5617 .
5631 .
5618
5632
5619 \layout List
5633 \layout List
5620 \labelwidthstring 00.00.0000
5634 \labelwidthstring 00.00.0000
5621
5635
5622
5636
5623 \family typewriter
5637 \family typewriter
5624 \series bold
5638 \series bold
5625 import_mod\SpecialChar ~
5639 import_mod\SpecialChar ~
5626 <mod1>\SpecialChar ~
5640 <mod1>\SpecialChar ~
5627 <mod2>\SpecialChar ~
5641 <mod2>\SpecialChar ~
5628 ...
5642 ...
5629 \family default
5643 \family default
5630 \series default
5644 \series default
5631 : import modules with '
5645 : import modules with '
5632 \family typewriter
5646 \family typewriter
5633 import
5647 import
5634 \family default
5648 \family default
5635
5649
5636 \family typewriter
5650 \family typewriter
5637 <mod1>,<mod2>,...
5651 <mod1>,<mod2>,...
5638 \family default
5652 \family default
5639 '
5653 '
5640 \layout List
5654 \layout List
5641 \labelwidthstring 00.00.0000
5655 \labelwidthstring 00.00.0000
5642
5656
5643
5657
5644 \family typewriter
5658 \family typewriter
5645 \series bold
5659 \series bold
5646 import_some\SpecialChar ~
5660 import_some\SpecialChar ~
5647 <mod>\SpecialChar ~
5661 <mod>\SpecialChar ~
5648 <f1>\SpecialChar ~
5662 <f1>\SpecialChar ~
5649 <f2>\SpecialChar ~
5663 <f2>\SpecialChar ~
5650 ...
5664 ...
5651 \family default
5665 \family default
5652 \series default
5666 \series default
5653 : import functions with '
5667 : import functions with '
5654 \family typewriter
5668 \family typewriter
5655 from <mod> import
5669 from <mod> import
5656 \family default
5670 \family default
5657
5671
5658 \family typewriter
5672 \family typewriter
5659 <f1>,<f2>,...
5673 <f1>,<f2>,...
5660 \family default
5674 \family default
5661 '
5675 '
5662 \layout List
5676 \layout List
5663 \labelwidthstring 00.00.0000
5677 \labelwidthstring 00.00.0000
5664
5678
5665
5679
5666 \family typewriter
5680 \family typewriter
5667 \series bold
5681 \series bold
5668 import_all\SpecialChar ~
5682 import_all\SpecialChar ~
5669 <mod1>\SpecialChar ~
5683 <mod1>\SpecialChar ~
5670 <mod2>\SpecialChar ~
5684 <mod2>\SpecialChar ~
5671 ...
5685 ...
5672 \family default
5686 \family default
5673 \series default
5687 \series default
5674 : for each module listed import functions with '
5688 : for each module listed import functions with '
5675 \family typewriter
5689 \family typewriter
5676 from <mod> import *
5690 from <mod> import *
5677 \family default
5691 \family default
5678 '
5692 '
5679 \layout List
5693 \layout List
5680 \labelwidthstring 00.00.0000
5694 \labelwidthstring 00.00.0000
5681
5695
5682
5696
5683 \family typewriter
5697 \family typewriter
5684 \series bold
5698 \series bold
5685 execute\SpecialChar ~
5699 execute\SpecialChar ~
5686 <python\SpecialChar ~
5700 <python\SpecialChar ~
5687 code>
5701 code>
5688 \family default
5702 \family default
5689 \series default
5703 \series default
5690 : give any single-line python code to be executed.
5704 : give any single-line python code to be executed.
5691 \layout List
5705 \layout List
5692 \labelwidthstring 00.00.0000
5706 \labelwidthstring 00.00.0000
5693
5707
5694
5708
5695 \family typewriter
5709 \family typewriter
5696 \series bold
5710 \series bold
5697 execfile\SpecialChar ~
5711 execfile\SpecialChar ~
5698 <filename>
5712 <filename>
5699 \family default
5713 \family default
5700 \series default
5714 \series default
5701 : execute the python file given with an '
5715 : execute the python file given with an '
5702 \family typewriter
5716 \family typewriter
5703 execfile(filename)
5717 execfile(filename)
5704 \family default
5718 \family default
5705 ' command.
5719 ' command.
5706 Username expansion is performed on the given names.
5720 Username expansion is performed on the given names.
5707 So if you need any amount of extra fancy customization that won't fit in
5721 So if you need any amount of extra fancy customization that won't fit in
5708 any of the above 'canned' options, you can just put it in a separate python
5722 any of the above 'canned' options, you can just put it in a separate python
5709 file and execute it.
5723 file and execute it.
5710 \layout List
5724 \layout List
5711 \labelwidthstring 00.00.0000
5725 \labelwidthstring 00.00.0000
5712
5726
5713
5727
5714 \family typewriter
5728 \family typewriter
5715 \series bold
5729 \series bold
5716 alias\SpecialChar ~
5730 alias\SpecialChar ~
5717 <alias_def>
5731 <alias_def>
5718 \family default
5732 \family default
5719 \series default
5733 \series default
5720 : this is equivalent to calling '
5734 : this is equivalent to calling '
5721 \family typewriter
5735 \family typewriter
5722 %alias\SpecialChar ~
5736 %alias\SpecialChar ~
5723 <alias_def>
5737 <alias_def>
5724 \family default
5738 \family default
5725 ' at the IPython command line.
5739 ' at the IPython command line.
5726 This way, from within IPython you can do common system tasks without having
5740 This way, from within IPython you can do common system tasks without having
5727 to exit it or use the
5741 to exit it or use the
5728 \family typewriter
5742 \family typewriter
5729 !
5743 !
5730 \family default
5744 \family default
5731 escape.
5745 escape.
5732 IPython isn't meant to be a shell replacement, but it is often very useful
5746 IPython isn't meant to be a shell replacement, but it is often very useful
5733 to be able to do things with files while testing code.
5747 to be able to do things with files while testing code.
5734 This gives you the flexibility to have within IPython any aliases you may
5748 This gives you the flexibility to have within IPython any aliases you may
5735 be used to under your normal system shell.
5749 be used to under your normal system shell.
5736 \layout Subsection
5750 \layout Subsection
5737
5751
5738
5752
5739 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5753 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5740
5754
5741 \end_inset
5755 \end_inset
5742
5756
5743 Sample
5757 Sample
5744 \family typewriter
5758 \family typewriter
5745 ipythonrc
5759 ipythonrc
5746 \family default
5760 \family default
5747 file
5761 file
5748 \layout Standard
5762 \layout Standard
5749
5763
5750 The default rcfile, called
5764 The default rcfile, called
5751 \family typewriter
5765 \family typewriter
5752 ipythonrc
5766 ipythonrc
5753 \family default
5767 \family default
5754 and supplied in your
5768 and supplied in your
5755 \family typewriter
5769 \family typewriter
5756 IPYTHONDIR
5770 IPYTHONDIR
5757 \family default
5771 \family default
5758 directory contains lots of comments on all of these options.
5772 directory contains lots of comments on all of these options.
5759 We reproduce it here for reference:
5773 We reproduce it here for reference:
5760 \layout Standard
5774 \layout Standard
5761
5775
5762
5776
5763 \begin_inset ERT
5777 \begin_inset ERT
5764 status Open
5778 status Open
5765
5779
5766 \layout Standard
5780 \layout Standard
5767
5781
5768 \backslash
5782 \backslash
5769 codelist{../IPython/UserConfig/ipythonrc}
5783 codelist{../IPython/UserConfig/ipythonrc}
5770 \end_inset
5784 \end_inset
5771
5785
5772
5786
5773 \layout Subsection
5787 \layout Subsection
5774
5788
5775
5789
5776 \begin_inset LatexCommand \label{sec:prompts}
5790 \begin_inset LatexCommand \label{sec:prompts}
5777
5791
5778 \end_inset
5792 \end_inset
5779
5793
5780 Fine-tuning your prompt
5794 Fine-tuning your prompt
5781 \layout Standard
5795 \layout Standard
5782
5796
5783 IPython's prompts can be customized using a syntax similar to that of the
5797 IPython's prompts can be customized using a syntax similar to that of the
5784
5798
5785 \family typewriter
5799 \family typewriter
5786 bash
5800 bash
5787 \family default
5801 \family default
5788 shell.
5802 shell.
5789 Many of
5803 Many of
5790 \family typewriter
5804 \family typewriter
5791 bash
5805 bash
5792 \family default
5806 \family default
5793 's escapes are supported, as well as a few additional ones.
5807 's escapes are supported, as well as a few additional ones.
5794 We list them below:
5808 We list them below:
5795 \layout Description
5809 \layout Description
5796
5810
5797
5811
5798 \backslash
5812 \backslash
5799 # the prompt/history count number
5813 # the prompt/history count number
5800 \layout Description
5814 \layout Description
5801
5815
5802
5816
5803 \backslash
5817 \backslash
5804 D the prompt/history count, with the actual digits replaced by dots.
5818 D the prompt/history count, with the actual digits replaced by dots.
5805 Used mainly in continuation prompts (prompt_in2)
5819 Used mainly in continuation prompts (prompt_in2)
5806 \layout Description
5820 \layout Description
5807
5821
5808
5822
5809 \backslash
5823 \backslash
5810 w the current working directory
5824 w the current working directory
5811 \layout Description
5825 \layout Description
5812
5826
5813
5827
5814 \backslash
5828 \backslash
5815 W the basename of current working directory
5829 W the basename of current working directory
5816 \layout Description
5830 \layout Description
5817
5831
5818
5832
5819 \backslash
5833 \backslash
5820 X
5834 X
5821 \emph on
5835 \emph on
5822 n
5836 n
5823 \emph default
5837 \emph default
5824 where
5838 where
5825 \begin_inset Formula $n=0\ldots5.$
5839 \begin_inset Formula $n=0\ldots5.$
5826 \end_inset
5840 \end_inset
5827
5841
5828 The current working directory, with
5842 The current working directory, with
5829 \family typewriter
5843 \family typewriter
5830 $HOME
5844 $HOME
5831 \family default
5845 \family default
5832 replaced by
5846 replaced by
5833 \family typewriter
5847 \family typewriter
5834 ~
5848 ~
5835 \family default
5849 \family default
5836 , and filtered out to contain only
5850 , and filtered out to contain only
5837 \begin_inset Formula $n$
5851 \begin_inset Formula $n$
5838 \end_inset
5852 \end_inset
5839
5853
5840 path elements
5854 path elements
5841 \layout Description
5855 \layout Description
5842
5856
5843
5857
5844 \backslash
5858 \backslash
5845 Y
5859 Y
5846 \emph on
5860 \emph on
5847 n
5861 n
5848 \emph default
5862 \emph default
5849 Similar to
5863 Similar to
5850 \backslash
5864 \backslash
5851 X
5865 X
5852 \emph on
5866 \emph on
5853 n
5867 n
5854 \emph default
5868 \emph default
5855 , but with the
5869 , but with the
5856 \begin_inset Formula $n+1$
5870 \begin_inset Formula $n+1$
5857 \end_inset
5871 \end_inset
5858
5872
5859 element included if it is
5873 element included if it is
5860 \family typewriter
5874 \family typewriter
5861 ~
5875 ~
5862 \family default
5876 \family default
5863 (this is similar to the behavior of the %c
5877 (this is similar to the behavior of the %c
5864 \emph on
5878 \emph on
5865 n
5879 n
5866 \emph default
5880 \emph default
5867 escapes in
5881 escapes in
5868 \family typewriter
5882 \family typewriter
5869 tcsh
5883 tcsh
5870 \family default
5884 \family default
5871 )
5885 )
5872 \layout Description
5886 \layout Description
5873
5887
5874
5888
5875 \backslash
5889 \backslash
5876 u the username of the current user
5890 u the username of the current user
5877 \layout Description
5891 \layout Description
5878
5892
5879
5893
5880 \backslash
5894 \backslash
5881 $ if the effective UID is 0, a #, otherwise a $
5895 $ if the effective UID is 0, a #, otherwise a $
5882 \layout Description
5896 \layout Description
5883
5897
5884
5898
5885 \backslash
5899 \backslash
5886 h the hostname up to the first `.'
5900 h the hostname up to the first `.'
5887 \layout Description
5901 \layout Description
5888
5902
5889
5903
5890 \backslash
5904 \backslash
5891 H the hostname
5905 H the hostname
5892 \layout Description
5906 \layout Description
5893
5907
5894
5908
5895 \backslash
5909 \backslash
5896 n a newline
5910 n a newline
5897 \layout Description
5911 \layout Description
5898
5912
5899
5913
5900 \backslash
5914 \backslash
5901 r a carriage return
5915 r a carriage return
5902 \layout Description
5916 \layout Description
5903
5917
5904
5918
5905 \backslash
5919 \backslash
5906 v IPython version string
5920 v IPython version string
5907 \layout Standard
5921 \layout Standard
5908
5922
5909 In addition to these, ANSI color escapes can be insterted into the prompts,
5923 In addition to these, ANSI color escapes can be insterted into the prompts,
5910 as
5924 as
5911 \family typewriter
5925 \family typewriter
5912
5926
5913 \backslash
5927 \backslash
5914 C_
5928 C_
5915 \emph on
5929 \emph on
5916 ColorName
5930 ColorName
5917 \family default
5931 \family default
5918 \emph default
5932 \emph default
5919 .
5933 .
5920 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5934 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5921 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5935 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5922 Normal, Purple, Red, White, Yellow.
5936 Normal, Purple, Red, White, Yellow.
5923 \layout Standard
5937 \layout Standard
5924
5938
5925 Finally, IPython supports the evaluation of arbitrary expressions in your
5939 Finally, IPython supports the evaluation of arbitrary expressions in your
5926 prompt string.
5940 prompt string.
5927 The prompt strings are evaluated through the syntax of PEP 215, but basically
5941 The prompt strings are evaluated through the syntax of PEP 215, but basically
5928 you can use
5942 you can use
5929 \family typewriter
5943 \family typewriter
5930 $x.y
5944 $x.y
5931 \family default
5945 \family default
5932 to expand the value of
5946 to expand the value of
5933 \family typewriter
5947 \family typewriter
5934 x.y
5948 x.y
5935 \family default
5949 \family default
5936 , and for more complicated expressions you can use braces:
5950 , and for more complicated expressions you can use braces:
5937 \family typewriter
5951 \family typewriter
5938 ${foo()+x}
5952 ${foo()+x}
5939 \family default
5953 \family default
5940 will call function
5954 will call function
5941 \family typewriter
5955 \family typewriter
5942 foo
5956 foo
5943 \family default
5957 \family default
5944 and add to it the value of
5958 and add to it the value of
5945 \family typewriter
5959 \family typewriter
5946 x
5960 x
5947 \family default
5961 \family default
5948 , before putting the result into your prompt.
5962 , before putting the result into your prompt.
5949 For example, using
5963 For example, using
5950 \newline
5964 \newline
5951
5965
5952 \family typewriter
5966 \family typewriter
5953 prompt_in1 '${commands.getoutput("uptime")}
5967 prompt_in1 '${commands.getoutput("uptime")}
5954 \backslash
5968 \backslash
5955 nIn [
5969 nIn [
5956 \backslash
5970 \backslash
5957 #]: '
5971 #]: '
5958 \newline
5972 \newline
5959
5973
5960 \family default
5974 \family default
5961 will print the result of the uptime command on each prompt (assuming the
5975 will print the result of the uptime command on each prompt (assuming the
5962
5976
5963 \family typewriter
5977 \family typewriter
5964 commands
5978 commands
5965 \family default
5979 \family default
5966 module has been imported in your
5980 module has been imported in your
5967 \family typewriter
5981 \family typewriter
5968 ipythonrc
5982 ipythonrc
5969 \family default
5983 \family default
5970 file).
5984 file).
5971 \layout Subsubsection
5985 \layout Subsubsection
5972
5986
5973 Prompt examples
5987 Prompt examples
5974 \layout Standard
5988 \layout Standard
5975
5989
5976 The following options in an ipythonrc file will give you IPython's default
5990 The following options in an ipythonrc file will give you IPython's default
5977 prompts:
5991 prompts:
5978 \layout Standard
5992 \layout Standard
5979
5993
5980
5994
5981 \family typewriter
5995 \family typewriter
5982 prompt_in1 'In [
5996 prompt_in1 'In [
5983 \backslash
5997 \backslash
5984 #]:'
5998 #]:'
5985 \newline
5999 \newline
5986 prompt_in2 '\SpecialChar ~
6000 prompt_in2 '\SpecialChar ~
5987 \SpecialChar ~
6001 \SpecialChar ~
5988 \SpecialChar ~
6002 \SpecialChar ~
5989 .
6003 .
5990 \backslash
6004 \backslash
5991 D.:'
6005 D.:'
5992 \newline
6006 \newline
5993 prompt_out 'Out[
6007 prompt_out 'Out[
5994 \backslash
6008 \backslash
5995 #]:'
6009 #]:'
5996 \layout Standard
6010 \layout Standard
5997
6011
5998 which look like this:
6012 which look like this:
5999 \layout Standard
6013 \layout Standard
6000
6014
6001
6015
6002 \family typewriter
6016 \family typewriter
6003 In [1]: 1+2
6017 In [1]: 1+2
6004 \newline
6018 \newline
6005 Out[1]: 3
6019 Out[1]: 3
6006 \layout Standard
6020 \layout Standard
6007
6021
6008
6022
6009 \family typewriter
6023 \family typewriter
6010 In [2]: for i in (1,2,3):
6024 In [2]: for i in (1,2,3):
6011 \newline
6025 \newline
6012
6026
6013 \begin_inset ERT
6027 \begin_inset ERT
6014 status Collapsed
6028 status Collapsed
6015
6029
6016 \layout Standard
6030 \layout Standard
6017
6031
6018 \backslash
6032 \backslash
6019 hspace*{0mm}
6033 hspace*{0mm}
6020 \end_inset
6034 \end_inset
6021
6035
6022 \SpecialChar ~
6036 \SpecialChar ~
6023 \SpecialChar ~
6037 \SpecialChar ~
6024 \SpecialChar ~
6038 \SpecialChar ~
6025 ...: \SpecialChar ~
6039 ...: \SpecialChar ~
6026 \SpecialChar ~
6040 \SpecialChar ~
6027 \SpecialChar ~
6041 \SpecialChar ~
6028 \SpecialChar ~
6042 \SpecialChar ~
6029 print i,
6043 print i,
6030 \newline
6044 \newline
6031
6045
6032 \begin_inset ERT
6046 \begin_inset ERT
6033 status Collapsed
6047 status Collapsed
6034
6048
6035 \layout Standard
6049 \layout Standard
6036
6050
6037 \backslash
6051 \backslash
6038 hspace*{0mm}
6052 hspace*{0mm}
6039 \end_inset
6053 \end_inset
6040
6054
6041 \SpecialChar ~
6055 \SpecialChar ~
6042 \SpecialChar ~
6056 \SpecialChar ~
6043 \SpecialChar ~
6057 \SpecialChar ~
6044 ...:
6058 ...:
6045 \newline
6059 \newline
6046 1 2 3
6060 1 2 3
6047 \layout Standard
6061 \layout Standard
6048
6062
6049 These will give you a very colorful prompt with path information:
6063 These will give you a very colorful prompt with path information:
6050 \layout Standard
6064 \layout Standard
6051
6065
6052
6066
6053 \family typewriter
6067 \family typewriter
6054 #prompt_in1 '
6068 #prompt_in1 '
6055 \backslash
6069 \backslash
6056 C_Red
6070 C_Red
6057 \backslash
6071 \backslash
6058 u
6072 u
6059 \backslash
6073 \backslash
6060 C_Blue[
6074 C_Blue[
6061 \backslash
6075 \backslash
6062 C_Cyan
6076 C_Cyan
6063 \backslash
6077 \backslash
6064 Y1
6078 Y1
6065 \backslash
6079 \backslash
6066 C_Blue]
6080 C_Blue]
6067 \backslash
6081 \backslash
6068 C_LightGreen
6082 C_LightGreen
6069 \backslash
6083 \backslash
6070 #>'
6084 #>'
6071 \newline
6085 \newline
6072 prompt_in2 ' ..
6086 prompt_in2 ' ..
6073 \backslash
6087 \backslash
6074 D>'
6088 D>'
6075 \newline
6089 \newline
6076 prompt_out '<
6090 prompt_out '<
6077 \backslash
6091 \backslash
6078 #>'
6092 #>'
6079 \layout Standard
6093 \layout Standard
6080
6094
6081 which look like this:
6095 which look like this:
6082 \layout Standard
6096 \layout Standard
6083
6097
6084
6098
6085 \family typewriter
6099 \family typewriter
6086 \color red
6100 \color red
6087 fperez
6101 fperez
6088 \color blue
6102 \color blue
6089 [
6103 [
6090 \color cyan
6104 \color cyan
6091 ~/ipython
6105 ~/ipython
6092 \color blue
6106 \color blue
6093 ]
6107 ]
6094 \color green
6108 \color green
6095 1>
6109 1>
6096 \color default
6110 \color default
6097 1+2
6111 1+2
6098 \newline
6112 \newline
6099
6113
6100 \begin_inset ERT
6114 \begin_inset ERT
6101 status Collapsed
6115 status Collapsed
6102
6116
6103 \layout Standard
6117 \layout Standard
6104
6118
6105 \backslash
6119 \backslash
6106 hspace*{0mm}
6120 hspace*{0mm}
6107 \end_inset
6121 \end_inset
6108
6122
6109 \SpecialChar ~
6123 \SpecialChar ~
6110 \SpecialChar ~
6124 \SpecialChar ~
6111 \SpecialChar ~
6125 \SpecialChar ~
6112 \SpecialChar ~
6126 \SpecialChar ~
6113 \SpecialChar ~
6127 \SpecialChar ~
6114 \SpecialChar ~
6128 \SpecialChar ~
6115 \SpecialChar ~
6129 \SpecialChar ~
6116 \SpecialChar ~
6130 \SpecialChar ~
6117 \SpecialChar ~
6131 \SpecialChar ~
6118 \SpecialChar ~
6132 \SpecialChar ~
6119 \SpecialChar ~
6133 \SpecialChar ~
6120 \SpecialChar ~
6134 \SpecialChar ~
6121 \SpecialChar ~
6135 \SpecialChar ~
6122 \SpecialChar ~
6136 \SpecialChar ~
6123 \SpecialChar ~
6137 \SpecialChar ~
6124 \SpecialChar ~
6138 \SpecialChar ~
6125
6139
6126 \color red
6140 \color red
6127 <1>
6141 <1>
6128 \color default
6142 \color default
6129 3
6143 3
6130 \newline
6144 \newline
6131
6145
6132 \color red
6146 \color red
6133 fperez
6147 fperez
6134 \color blue
6148 \color blue
6135 [
6149 [
6136 \color cyan
6150 \color cyan
6137 ~/ipython
6151 ~/ipython
6138 \color blue
6152 \color blue
6139 ]
6153 ]
6140 \color green
6154 \color green
6141 2>
6155 2>
6142 \color default
6156 \color default
6143 for i in (1,2,3):
6157 for i in (1,2,3):
6144 \newline
6158 \newline
6145
6159
6146 \begin_inset ERT
6160 \begin_inset ERT
6147 status Collapsed
6161 status Collapsed
6148
6162
6149 \layout Standard
6163 \layout Standard
6150
6164
6151 \backslash
6165 \backslash
6152 hspace*{0mm}
6166 hspace*{0mm}
6153 \end_inset
6167 \end_inset
6154
6168
6155 \SpecialChar ~
6169 \SpecialChar ~
6156 \SpecialChar ~
6170 \SpecialChar ~
6157 \SpecialChar ~
6171 \SpecialChar ~
6158 \SpecialChar ~
6172 \SpecialChar ~
6159 \SpecialChar ~
6173 \SpecialChar ~
6160 \SpecialChar ~
6174 \SpecialChar ~
6161 \SpecialChar ~
6175 \SpecialChar ~
6162 \SpecialChar ~
6176 \SpecialChar ~
6163 \SpecialChar ~
6177 \SpecialChar ~
6164 \SpecialChar ~
6178 \SpecialChar ~
6165 \SpecialChar ~
6179 \SpecialChar ~
6166 \SpecialChar ~
6180 \SpecialChar ~
6167 \SpecialChar ~
6181 \SpecialChar ~
6168 \SpecialChar ~
6182 \SpecialChar ~
6169 \SpecialChar ~
6183 \SpecialChar ~
6170
6184
6171 \color green
6185 \color green
6172 ...>
6186 ...>
6173 \color default
6187 \color default
6174 \SpecialChar ~
6188 \SpecialChar ~
6175 \SpecialChar ~
6189 \SpecialChar ~
6176 \SpecialChar ~
6190 \SpecialChar ~
6177 \SpecialChar ~
6191 \SpecialChar ~
6178 print i,
6192 print i,
6179 \newline
6193 \newline
6180
6194
6181 \begin_inset ERT
6195 \begin_inset ERT
6182 status Collapsed
6196 status Collapsed
6183
6197
6184 \layout Standard
6198 \layout Standard
6185
6199
6186 \backslash
6200 \backslash
6187 hspace*{0mm}
6201 hspace*{0mm}
6188 \end_inset
6202 \end_inset
6189
6203
6190 \SpecialChar ~
6204 \SpecialChar ~
6191 \SpecialChar ~
6205 \SpecialChar ~
6192 \SpecialChar ~
6206 \SpecialChar ~
6193 \SpecialChar ~
6207 \SpecialChar ~
6194 \SpecialChar ~
6208 \SpecialChar ~
6195 \SpecialChar ~
6209 \SpecialChar ~
6196 \SpecialChar ~
6210 \SpecialChar ~
6197 \SpecialChar ~
6211 \SpecialChar ~
6198 \SpecialChar ~
6212 \SpecialChar ~
6199 \SpecialChar ~
6213 \SpecialChar ~
6200 \SpecialChar ~
6214 \SpecialChar ~
6201 \SpecialChar ~
6215 \SpecialChar ~
6202 \SpecialChar ~
6216 \SpecialChar ~
6203 \SpecialChar ~
6217 \SpecialChar ~
6204 \SpecialChar ~
6218 \SpecialChar ~
6205
6219
6206 \color green
6220 \color green
6207 ...>
6221 ...>
6208 \color default
6222 \color default
6209
6223
6210 \newline
6224 \newline
6211 1 2 3
6225 1 2 3
6212 \layout Standard
6226 \layout Standard
6213
6227
6214 The following shows the usage of dynamic expression evaluation:
6228 The following shows the usage of dynamic expression evaluation:
6215 \layout Subsection
6229 \layout Subsection
6216
6230
6217
6231
6218 \begin_inset LatexCommand \label{sec:profiles}
6232 \begin_inset LatexCommand \label{sec:profiles}
6219
6233
6220 \end_inset
6234 \end_inset
6221
6235
6222 IPython profiles
6236 IPython profiles
6223 \layout Standard
6237 \layout Standard
6224
6238
6225 As we already mentioned, IPython supports the
6239 As we already mentioned, IPython supports the
6226 \family typewriter
6240 \family typewriter
6227 -profile
6241 -profile
6228 \family default
6242 \family default
6229 command-line option (see sec.
6243 command-line option (see sec.
6230
6244
6231 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
6245 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
6232
6246
6233 \end_inset
6247 \end_inset
6234
6248
6235 ).
6249 ).
6236 A profile is nothing more than a particular configuration file like your
6250 A profile is nothing more than a particular configuration file like your
6237 basic
6251 basic
6238 \family typewriter
6252 \family typewriter
6239 ipythonrc
6253 ipythonrc
6240 \family default
6254 \family default
6241 one, but with particular customizations for a specific purpose.
6255 one, but with particular customizations for a specific purpose.
6242 When you start IPython with '
6256 When you start IPython with '
6243 \family typewriter
6257 \family typewriter
6244 ipython -profile <name>
6258 ipython -profile <name>
6245 \family default
6259 \family default
6246 ', it assumes that in your
6260 ', it assumes that in your
6247 \family typewriter
6261 \family typewriter
6248 IPYTHONDIR
6262 IPYTHONDIR
6249 \family default
6263 \family default
6250 there is a file called
6264 there is a file called
6251 \family typewriter
6265 \family typewriter
6252 ipythonrc-<name>
6266 ipythonrc-<name>
6253 \family default
6267 \family default
6254 , and loads it instead of the normal
6268 , and loads it instead of the normal
6255 \family typewriter
6269 \family typewriter
6256 ipythonrc
6270 ipythonrc
6257 \family default
6271 \family default
6258 .
6272 .
6259 \layout Standard
6273 \layout Standard
6260
6274
6261 This system allows you to maintain multiple configurations which load modules,
6275 This system allows you to maintain multiple configurations which load modules,
6262 set options, define functions, etc.
6276 set options, define functions, etc.
6263 suitable for different tasks and activate them in a very simple manner.
6277 suitable for different tasks and activate them in a very simple manner.
6264 In order to avoid having to repeat all of your basic options (common things
6278 In order to avoid having to repeat all of your basic options (common things
6265 that don't change such as your color preferences, for example), any profile
6279 that don't change such as your color preferences, for example), any profile
6266 can include another configuration file.
6280 can include another configuration file.
6267 The most common way to use profiles is then to have each one include your
6281 The most common way to use profiles is then to have each one include your
6268 basic
6282 basic
6269 \family typewriter
6283 \family typewriter
6270 ipythonrc
6284 ipythonrc
6271 \family default
6285 \family default
6272 file as a starting point, and then add further customizations.
6286 file as a starting point, and then add further customizations.
6273 \layout Standard
6287 \layout Standard
6274
6288
6275 In sections
6289 In sections
6276 \begin_inset LatexCommand \ref{sec:syntax-extensions}
6290 \begin_inset LatexCommand \ref{sec:syntax-extensions}
6277
6291
6278 \end_inset
6292 \end_inset
6279
6293
6280 and
6294 and
6281 \begin_inset LatexCommand \ref{sec:Gnuplot}
6295 \begin_inset LatexCommand \ref{sec:Gnuplot}
6282
6296
6283 \end_inset
6297 \end_inset
6284
6298
6285 we discuss some particular profiles which come as part of the standard
6299 we discuss some particular profiles which come as part of the standard
6286 IPython distribution.
6300 IPython distribution.
6287 You may also look in your
6301 You may also look in your
6288 \family typewriter
6302 \family typewriter
6289 IPYTHONDIR
6303 IPYTHONDIR
6290 \family default
6304 \family default
6291 directory, any file whose name begins with
6305 directory, any file whose name begins with
6292 \family typewriter
6306 \family typewriter
6293 ipythonrc-
6307 ipythonrc-
6294 \family default
6308 \family default
6295 is a profile.
6309 is a profile.
6296 You can use those as examples for further customizations to suit your own
6310 You can use those as examples for further customizations to suit your own
6297 needs.
6311 needs.
6298 \layout Section
6312 \layout Section
6299
6313
6300
6314
6301 \begin_inset OptArg
6315 \begin_inset OptArg
6302 collapsed false
6316 collapsed false
6303
6317
6304 \layout Standard
6318 \layout Standard
6305
6319
6306 IPython as default...
6320 IPython as default...
6307 \end_inset
6321 \end_inset
6308
6322
6309 IPython as your default Python environment
6323 IPython as your default Python environment
6310 \layout Standard
6324 \layout Standard
6311
6325
6312 Python honors the environment variable
6326 Python honors the environment variable
6313 \family typewriter
6327 \family typewriter
6314 PYTHONSTARTUP
6328 PYTHONSTARTUP
6315 \family default
6329 \family default
6316 and will execute at startup the file referenced by this variable.
6330 and will execute at startup the file referenced by this variable.
6317 If you put at the end of this file the following two lines of code:
6331 If you put at the end of this file the following two lines of code:
6318 \layout Standard
6332 \layout Standard
6319
6333
6320
6334
6321 \family typewriter
6335 \family typewriter
6322 import IPython
6336 import IPython
6323 \newline
6337 \newline
6324 IPython.Shell.IPShell().mainloop(sys_exit=1)
6338 IPython.Shell.IPShell().mainloop(sys_exit=1)
6325 \layout Standard
6339 \layout Standard
6326
6340
6327 then IPython will be your working environment anytime you start Python.
6341 then IPython will be your working environment anytime you start Python.
6328 The
6342 The
6329 \family typewriter
6343 \family typewriter
6330 sys_exit=1
6344 sys_exit=1
6331 \family default
6345 \family default
6332 is needed to have IPython issue a call to
6346 is needed to have IPython issue a call to
6333 \family typewriter
6347 \family typewriter
6334 sys.exit()
6348 sys.exit()
6335 \family default
6349 \family default
6336 when it finishes, otherwise you'll be back at the normal Python '
6350 when it finishes, otherwise you'll be back at the normal Python '
6337 \family typewriter
6351 \family typewriter
6338 >>>
6352 >>>
6339 \family default
6353 \family default
6340 ' prompt
6354 ' prompt
6341 \begin_inset Foot
6355 \begin_inset Foot
6342 collapsed true
6356 collapsed true
6343
6357
6344 \layout Standard
6358 \layout Standard
6345
6359
6346 Based on an idea by Holger Krekel.
6360 Based on an idea by Holger Krekel.
6347 \end_inset
6361 \end_inset
6348
6362
6349 .
6363 .
6350 \layout Standard
6364 \layout Standard
6351
6365
6352 This is probably useful to developers who manage multiple Python versions
6366 This is probably useful to developers who manage multiple Python versions
6353 and don't want to have correspondingly multiple IPython versions.
6367 and don't want to have correspondingly multiple IPython versions.
6354 Note that in this mode, there is no way to pass IPython any command-line
6368 Note that in this mode, there is no way to pass IPython any command-line
6355 options, as those are trapped first by Python itself.
6369 options, as those are trapped first by Python itself.
6356 \layout Section
6370 \layout Section
6357
6371
6358
6372
6359 \begin_inset LatexCommand \label{sec:embed}
6373 \begin_inset LatexCommand \label{sec:embed}
6360
6374
6361 \end_inset
6375 \end_inset
6362
6376
6363 Embedding IPython
6377 Embedding IPython
6364 \layout Standard
6378 \layout Standard
6365
6379
6366 It is possible to start an IPython instance
6380 It is possible to start an IPython instance
6367 \emph on
6381 \emph on
6368 inside
6382 inside
6369 \emph default
6383 \emph default
6370 your own Python programs.
6384 your own Python programs.
6371 This allows you to evaluate dynamically the state of your code, operate
6385 This allows you to evaluate dynamically the state of your code, operate
6372 with your variables, analyze them, etc.
6386 with your variables, analyze them, etc.
6373 Note however that any changes you make to values while in the shell do
6387 Note however that any changes you make to values while in the shell do
6374
6388
6375 \emph on
6389 \emph on
6376 not
6390 not
6377 \emph default
6391 \emph default
6378 propagate back to the running code, so it is safe to modify your values
6392 propagate back to the running code, so it is safe to modify your values
6379 because you won't break your code in bizarre ways by doing so.
6393 because you won't break your code in bizarre ways by doing so.
6380 \layout Standard
6394 \layout Standard
6381
6395
6382 This feature allows you to easily have a fully functional python environment
6396 This feature allows you to easily have a fully functional python environment
6383 for doing object introspection anywhere in your code with a simple function
6397 for doing object introspection anywhere in your code with a simple function
6384 call.
6398 call.
6385 In some cases a simple print statement is enough, but if you need to do
6399 In some cases a simple print statement is enough, but if you need to do
6386 more detailed analysis of a code fragment this feature can be very valuable.
6400 more detailed analysis of a code fragment this feature can be very valuable.
6387 \layout Standard
6401 \layout Standard
6388
6402
6389 It can also be useful in scientific computing situations where it is common
6403 It can also be useful in scientific computing situations where it is common
6390 to need to do some automatic, computationally intensive part and then stop
6404 to need to do some automatic, computationally intensive part and then stop
6391 to look at data, plots, etc
6405 to look at data, plots, etc
6392 \begin_inset Foot
6406 \begin_inset Foot
6393 collapsed true
6407 collapsed true
6394
6408
6395 \layout Standard
6409 \layout Standard
6396
6410
6397 This functionality was inspired by IDL's combination of the
6411 This functionality was inspired by IDL's combination of the
6398 \family typewriter
6412 \family typewriter
6399 stop
6413 stop
6400 \family default
6414 \family default
6401 keyword and the
6415 keyword and the
6402 \family typewriter
6416 \family typewriter
6403 .continue
6417 .continue
6404 \family default
6418 \family default
6405 executive command, which I have found very useful in the past, and by a
6419 executive command, which I have found very useful in the past, and by a
6406 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6420 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6407 06/01 concerning similar uses of pyrepl.
6421 06/01 concerning similar uses of pyrepl.
6408 \end_inset
6422 \end_inset
6409
6423
6410 .
6424 .
6411 Opening an IPython instance will give you full access to your data and
6425 Opening an IPython instance will give you full access to your data and
6412 functions, and you can resume program execution once you are done with
6426 functions, and you can resume program execution once you are done with
6413 the interactive part (perhaps to stop again later, as many times as needed).
6427 the interactive part (perhaps to stop again later, as many times as needed).
6414 \layout Standard
6428 \layout Standard
6415
6429
6416 The following code snippet is the bare minimum you need to include in your
6430 The following code snippet is the bare minimum you need to include in your
6417 Python programs for this to work (detailed examples follow later):
6431 Python programs for this to work (detailed examples follow later):
6418 \layout LyX-Code
6432 \layout LyX-Code
6419
6433
6420 from IPython.Shell import IPShellEmbed
6434 from IPython.Shell import IPShellEmbed
6421 \layout LyX-Code
6435 \layout LyX-Code
6422
6436
6423 ipshell = IPShellEmbed()
6437 ipshell = IPShellEmbed()
6424 \layout LyX-Code
6438 \layout LyX-Code
6425
6439
6426 ipshell() # this call anywhere in your program will start IPython
6440 ipshell() # this call anywhere in your program will start IPython
6427 \layout Standard
6441 \layout Standard
6428
6442
6429 You can run embedded instances even in code which is itself being run at
6443 You can run embedded instances even in code which is itself being run at
6430 the IPython interactive prompt with '
6444 the IPython interactive prompt with '
6431 \family typewriter
6445 \family typewriter
6432 %run\SpecialChar ~
6446 %run\SpecialChar ~
6433 <filename>
6447 <filename>
6434 \family default
6448 \family default
6435 '.
6449 '.
6436 Since it's easy to get lost as to where you are (in your top-level IPython
6450 Since it's easy to get lost as to where you are (in your top-level IPython
6437 or in your embedded one), it's a good idea in such cases to set the in/out
6451 or in your embedded one), it's a good idea in such cases to set the in/out
6438 prompts to something different for the embedded instances.
6452 prompts to something different for the embedded instances.
6439 The code examples below illustrate this.
6453 The code examples below illustrate this.
6440 \layout Standard
6454 \layout Standard
6441
6455
6442 You can also have multiple IPython instances in your program and open them
6456 You can also have multiple IPython instances in your program and open them
6443 separately, for example with different options for data presentation.
6457 separately, for example with different options for data presentation.
6444 If you close and open the same instance multiple times, its prompt counters
6458 If you close and open the same instance multiple times, its prompt counters
6445 simply continue from each execution to the next.
6459 simply continue from each execution to the next.
6446 \layout Standard
6460 \layout Standard
6447
6461
6448 Please look at the docstrings in the
6462 Please look at the docstrings in the
6449 \family typewriter
6463 \family typewriter
6450 Shell.py
6464 Shell.py
6451 \family default
6465 \family default
6452 module for more details on the use of this system.
6466 module for more details on the use of this system.
6453 \layout Standard
6467 \layout Standard
6454
6468
6455 The following sample file illustrating how to use the embedding functionality
6469 The following sample file illustrating how to use the embedding functionality
6456 is provided in the examples directory as
6470 is provided in the examples directory as
6457 \family typewriter
6471 \family typewriter
6458 example-embed.py
6472 example-embed.py
6459 \family default
6473 \family default
6460 .
6474 .
6461 It should be fairly self-explanatory:
6475 It should be fairly self-explanatory:
6462 \layout Standard
6476 \layout Standard
6463
6477
6464
6478
6465 \begin_inset ERT
6479 \begin_inset ERT
6466 status Open
6480 status Open
6467
6481
6468 \layout Standard
6482 \layout Standard
6469
6483
6470 \backslash
6484 \backslash
6471 codelist{examples/example-embed.py}
6485 codelist{examples/example-embed.py}
6472 \end_inset
6486 \end_inset
6473
6487
6474
6488
6475 \layout Standard
6489 \layout Standard
6476
6490
6477 Once you understand how the system functions, you can use the following
6491 Once you understand how the system functions, you can use the following
6478 code fragments in your programs which are ready for cut and paste:
6492 code fragments in your programs which are ready for cut and paste:
6479 \layout Standard
6493 \layout Standard
6480
6494
6481
6495
6482 \begin_inset ERT
6496 \begin_inset ERT
6483 status Open
6497 status Open
6484
6498
6485 \layout Standard
6499 \layout Standard
6486
6500
6487 \backslash
6501 \backslash
6488 codelist{examples/example-embed-short.py}
6502 codelist{examples/example-embed-short.py}
6489 \end_inset
6503 \end_inset
6490
6504
6491
6505
6492 \layout Section
6506 \layout Section
6493
6507
6494
6508
6495 \begin_inset LatexCommand \label{sec:using-pdb}
6509 \begin_inset LatexCommand \label{sec:using-pdb}
6496
6510
6497 \end_inset
6511 \end_inset
6498
6512
6499 Using the Python debugger (
6513 Using the Python debugger (
6500 \family typewriter
6514 \family typewriter
6501 pdb
6515 pdb
6502 \family default
6516 \family default
6503 )
6517 )
6504 \layout Subsection
6518 \layout Subsection
6505
6519
6506 Running entire programs via
6520 Running entire programs via
6507 \family typewriter
6521 \family typewriter
6508 pdb
6522 pdb
6509 \layout Standard
6523 \layout Standard
6510
6524
6511
6525
6512 \family typewriter
6526 \family typewriter
6513 pdb
6527 pdb
6514 \family default
6528 \family default
6515 , the Python debugger, is a powerful interactive debugger which allows you
6529 , the Python debugger, is a powerful interactive debugger which allows you
6516 to step through code, set breakpoints, watch variables, etc.
6530 to step through code, set breakpoints, watch variables, etc.
6517 IPython makes it very easy to start any script under the control of
6531 IPython makes it very easy to start any script under the control of
6518 \family typewriter
6532 \family typewriter
6519 pdb
6533 pdb
6520 \family default
6534 \family default
6521 , regardless of whether you have wrapped it into a
6535 , regardless of whether you have wrapped it into a
6522 \family typewriter
6536 \family typewriter
6523 `main()'
6537 `main()'
6524 \family default
6538 \family default
6525 function or not.
6539 function or not.
6526 For this, simply type
6540 For this, simply type
6527 \family typewriter
6541 \family typewriter
6528 `%run -d myscript'
6542 `%run -d myscript'
6529 \family default
6543 \family default
6530 at an IPython prompt.
6544 at an IPython prompt.
6531 See the
6545 See the
6532 \family typewriter
6546 \family typewriter
6533 %run
6547 %run
6534 \family default
6548 \family default
6535 command's documentation (via
6549 command's documentation (via
6536 \family typewriter
6550 \family typewriter
6537 `%run?'
6551 `%run?'
6538 \family default
6552 \family default
6539 or in Sec.\SpecialChar ~
6553 or in Sec.\SpecialChar ~
6540
6554
6541 \begin_inset LatexCommand \ref{sec:magic}
6555 \begin_inset LatexCommand \ref{sec:magic}
6542
6556
6543 \end_inset
6557 \end_inset
6544
6558
6545 ) for more details, including how to control where
6559 ) for more details, including how to control where
6546 \family typewriter
6560 \family typewriter
6547 pdb
6561 pdb
6548 \family default
6562 \family default
6549 will stop execution first.
6563 will stop execution first.
6550 \layout Standard
6564 \layout Standard
6551
6565
6552 For more information on the use of the
6566 For more information on the use of the
6553 \family typewriter
6567 \family typewriter
6554 pdb
6568 pdb
6555 \family default
6569 \family default
6556 debugger, read the included
6570 debugger, read the included
6557 \family typewriter
6571 \family typewriter
6558 pdb.doc
6572 pdb.doc
6559 \family default
6573 \family default
6560 file (part of the standard Python distribution).
6574 file (part of the standard Python distribution).
6561 On a stock Linux system it is located at
6575 On a stock Linux system it is located at
6562 \family typewriter
6576 \family typewriter
6563 /usr/lib/python2.3/pdb.doc
6577 /usr/lib/python2.3/pdb.doc
6564 \family default
6578 \family default
6565 , but the easiest way to read it is by using the
6579 , but the easiest way to read it is by using the
6566 \family typewriter
6580 \family typewriter
6567 help()
6581 help()
6568 \family default
6582 \family default
6569 function of the
6583 function of the
6570 \family typewriter
6584 \family typewriter
6571 pdb
6585 pdb
6572 \family default
6586 \family default
6573 module as follows (in an IPython prompt):
6587 module as follows (in an IPython prompt):
6574 \layout Standard
6588 \layout Standard
6575
6589
6576
6590
6577 \family typewriter
6591 \family typewriter
6578 In [1]: import pdb
6592 In [1]: import pdb
6579 \newline
6593 \newline
6580 In [2]: pdb.help()
6594 In [2]: pdb.help()
6581 \layout Standard
6595 \layout Standard
6582
6596
6583 This will load the
6597 This will load the
6584 \family typewriter
6598 \family typewriter
6585 pdb.doc
6599 pdb.doc
6586 \family default
6600 \family default
6587 document in a file viewer for you automatically.
6601 document in a file viewer for you automatically.
6588 \layout Subsection
6602 \layout Subsection
6589
6603
6590 Automatic invocation of
6604 Automatic invocation of
6591 \family typewriter
6605 \family typewriter
6592 pdb
6606 pdb
6593 \family default
6607 \family default
6594 on exceptions
6608 on exceptions
6595 \layout Standard
6609 \layout Standard
6596
6610
6597 IPython, if started with the
6611 IPython, if started with the
6598 \family typewriter
6612 \family typewriter
6599 -pdb
6613 -pdb
6600 \family default
6614 \family default
6601 option (or if the option is set in your rc file) can call the Python
6615 option (or if the option is set in your rc file) can call the Python
6602 \family typewriter
6616 \family typewriter
6603 pdb
6617 pdb
6604 \family default
6618 \family default
6605 debugger every time your code triggers an uncaught exception
6619 debugger every time your code triggers an uncaught exception
6606 \begin_inset Foot
6620 \begin_inset Foot
6607 collapsed true
6621 collapsed true
6608
6622
6609 \layout Standard
6623 \layout Standard
6610
6624
6611 Many thanks to Christopher Hart for the request which prompted adding this
6625 Many thanks to Christopher Hart for the request which prompted adding this
6612 feature to IPython.
6626 feature to IPython.
6613 \end_inset
6627 \end_inset
6614
6628
6615 .
6629 .
6616 This feature can also be toggled at any time with the
6630 This feature can also be toggled at any time with the
6617 \family typewriter
6631 \family typewriter
6618 %pdb
6632 %pdb
6619 \family default
6633 \family default
6620 magic command.
6634 magic command.
6621 This can be extremely useful in order to find the origin of subtle bugs,
6635 This can be extremely useful in order to find the origin of subtle bugs,
6622 because
6636 because
6623 \family typewriter
6637 \family typewriter
6624 pdb
6638 pdb
6625 \family default
6639 \family default
6626 opens up at the point in your code which triggered the exception, and while
6640 opens up at the point in your code which triggered the exception, and while
6627 your program is at this point `dead', all the data is still available and
6641 your program is at this point `dead', all the data is still available and
6628 you can walk up and down the stack frame and understand the origin of the
6642 you can walk up and down the stack frame and understand the origin of the
6629 problem.
6643 problem.
6630 \layout Standard
6644 \layout Standard
6631
6645
6632 Furthermore, you can use these debugging facilities both with the embedded
6646 Furthermore, you can use these debugging facilities both with the embedded
6633 IPython mode and without IPython at all.
6647 IPython mode and without IPython at all.
6634 For an embedded shell (see sec.
6648 For an embedded shell (see sec.
6635
6649
6636 \begin_inset LatexCommand \ref{sec:embed}
6650 \begin_inset LatexCommand \ref{sec:embed}
6637
6651
6638 \end_inset
6652 \end_inset
6639
6653
6640 ), simply call the constructor with
6654 ), simply call the constructor with
6641 \family typewriter
6655 \family typewriter
6642 `-pdb'
6656 `-pdb'
6643 \family default
6657 \family default
6644 in the argument string and automatically
6658 in the argument string and automatically
6645 \family typewriter
6659 \family typewriter
6646 pdb
6660 pdb
6647 \family default
6661 \family default
6648 will be called if an uncaught exception is triggered by your code.
6662 will be called if an uncaught exception is triggered by your code.
6649
6663
6650 \layout Standard
6664 \layout Standard
6651
6665
6652 For stand-alone use of the feature in your programs which do not use IPython
6666 For stand-alone use of the feature in your programs which do not use IPython
6653 at all, put the following lines toward the top of your `main' routine:
6667 at all, put the following lines toward the top of your `main' routine:
6654 \layout Standard
6668 \layout Standard
6655 \align left
6669 \align left
6656
6670
6657 \family typewriter
6671 \family typewriter
6658 import sys,IPython.ultraTB
6672 import sys,IPython.ultraTB
6659 \newline
6673 \newline
6660 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6674 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6661 call_pdb=1)
6675 call_pdb=1)
6662 \layout Standard
6676 \layout Standard
6663
6677
6664 The
6678 The
6665 \family typewriter
6679 \family typewriter
6666 mode
6680 mode
6667 \family default
6681 \family default
6668 keyword can be either
6682 keyword can be either
6669 \family typewriter
6683 \family typewriter
6670 `Verbose'
6684 `Verbose'
6671 \family default
6685 \family default
6672 or
6686 or
6673 \family typewriter
6687 \family typewriter
6674 `Plain'
6688 `Plain'
6675 \family default
6689 \family default
6676 , giving either very detailed or normal tracebacks respectively.
6690 , giving either very detailed or normal tracebacks respectively.
6677 The
6691 The
6678 \family typewriter
6692 \family typewriter
6679 color_scheme
6693 color_scheme
6680 \family default
6694 \family default
6681 keyword can be one of
6695 keyword can be one of
6682 \family typewriter
6696 \family typewriter
6683 `NoColor'
6697 `NoColor'
6684 \family default
6698 \family default
6685 ,
6699 ,
6686 \family typewriter
6700 \family typewriter
6687 `Linux'
6701 `Linux'
6688 \family default
6702 \family default
6689 (default) or
6703 (default) or
6690 \family typewriter
6704 \family typewriter
6691 `LightBG'
6705 `LightBG'
6692 \family default
6706 \family default
6693 .
6707 .
6694 These are the same options which can be set in IPython with
6708 These are the same options which can be set in IPython with
6695 \family typewriter
6709 \family typewriter
6696 -colors
6710 -colors
6697 \family default
6711 \family default
6698 and
6712 and
6699 \family typewriter
6713 \family typewriter
6700 -xmode
6714 -xmode
6701 \family default
6715 \family default
6702 .
6716 .
6703 \layout Standard
6717 \layout Standard
6704
6718
6705 This will give any of your programs detailed, colored tracebacks with automatic
6719 This will give any of your programs detailed, colored tracebacks with automatic
6706 invocation of
6720 invocation of
6707 \family typewriter
6721 \family typewriter
6708 pdb
6722 pdb
6709 \family default
6723 \family default
6710 .
6724 .
6711 \layout Section
6725 \layout Section
6712
6726
6713
6727
6714 \begin_inset LatexCommand \label{sec:syntax-extensions}
6728 \begin_inset LatexCommand \label{sec:syntax-extensions}
6715
6729
6716 \end_inset
6730 \end_inset
6717
6731
6718 Extensions for syntax processing
6732 Extensions for syntax processing
6719 \layout Standard
6733 \layout Standard
6720
6734
6721 This isn't for the faint of heart, because the potential for breaking things
6735 This isn't for the faint of heart, because the potential for breaking things
6722 is quite high.
6736 is quite high.
6723 But it can be a very powerful and useful feature.
6737 But it can be a very powerful and useful feature.
6724 In a nutshell, you can redefine the way IPython processes the user input
6738 In a nutshell, you can redefine the way IPython processes the user input
6725 line to accept new, special extensions to the syntax without needing to
6739 line to accept new, special extensions to the syntax without needing to
6726 change any of IPython's own code.
6740 change any of IPython's own code.
6727 \layout Standard
6741 \layout Standard
6728
6742
6729 In the
6743 In the
6730 \family typewriter
6744 \family typewriter
6731 IPython/Extensions
6745 IPython/Extensions
6732 \family default
6746 \family default
6733 directory you will find some examples supplied, which we will briefly describe
6747 directory you will find some examples supplied, which we will briefly describe
6734 now.
6748 now.
6735 These can be used `as is' (and both provide very useful functionality),
6749 These can be used `as is' (and both provide very useful functionality),
6736 or you can use them as a starting point for writing your own extensions.
6750 or you can use them as a starting point for writing your own extensions.
6737 \layout Subsection
6751 \layout Subsection
6738
6752
6739 Pasting of code starting with
6753 Pasting of code starting with
6740 \family typewriter
6754 \family typewriter
6741 `>>>
6755 `>>>
6742 \family default
6756 \family default
6743 ' or
6757 ' or
6744 \family typewriter
6758 \family typewriter
6745 `...
6759 `...
6746
6760
6747 \family default
6761 \family default
6748 '
6762 '
6749 \layout Standard
6763 \layout Standard
6750
6764
6751 In the python tutorial it is common to find code examples which have been
6765 In the python tutorial it is common to find code examples which have been
6752 taken from real python sessions.
6766 taken from real python sessions.
6753 The problem with those is that all the lines begin with either
6767 The problem with those is that all the lines begin with either
6754 \family typewriter
6768 \family typewriter
6755 `>>>
6769 `>>>
6756 \family default
6770 \family default
6757 ' or
6771 ' or
6758 \family typewriter
6772 \family typewriter
6759 `...
6773 `...
6760
6774
6761 \family default
6775 \family default
6762 ', which makes it impossible to paste them all at once.
6776 ', which makes it impossible to paste them all at once.
6763 One must instead do a line by line manual copying, carefully removing the
6777 One must instead do a line by line manual copying, carefully removing the
6764 leading extraneous characters.
6778 leading extraneous characters.
6765 \layout Standard
6779 \layout Standard
6766
6780
6767 This extension identifies those starting characters and removes them from
6781 This extension identifies those starting characters and removes them from
6768 the input automatically, so that one can paste multi-line examples directly
6782 the input automatically, so that one can paste multi-line examples directly
6769 into IPython, saving a lot of time.
6783 into IPython, saving a lot of time.
6770 Please look at the file
6784 Please look at the file
6771 \family typewriter
6785 \family typewriter
6772 InterpreterPasteInput.py
6786 InterpreterPasteInput.py
6773 \family default
6787 \family default
6774 in the
6788 in the
6775 \family typewriter
6789 \family typewriter
6776 IPython/Extensions
6790 IPython/Extensions
6777 \family default
6791 \family default
6778 directory for details on how this is done.
6792 directory for details on how this is done.
6779 \layout Standard
6793 \layout Standard
6780
6794
6781 IPython comes with a special profile enabling this feature, called
6795 IPython comes with a special profile enabling this feature, called
6782 \family typewriter
6796 \family typewriter
6783 tutorial
6797 tutorial
6784 \family default
6798 \family default
6785 \emph on
6799 \emph on
6786 .
6800 .
6787
6801
6788 \emph default
6802 \emph default
6789 Simply start IPython via
6803 Simply start IPython via
6790 \family typewriter
6804 \family typewriter
6791 `ipython\SpecialChar ~
6805 `ipython\SpecialChar ~
6792 -p\SpecialChar ~
6806 -p\SpecialChar ~
6793 tutorial'
6807 tutorial'
6794 \family default
6808 \family default
6795 and the feature will be available.
6809 and the feature will be available.
6796 In a normal IPython session you can activate the feature by importing the
6810 In a normal IPython session you can activate the feature by importing the
6797 corresponding module with:
6811 corresponding module with:
6798 \newline
6812 \newline
6799
6813
6800 \family typewriter
6814 \family typewriter
6801 In [1]: import IPython.Extensions.InterpreterPasteInput
6815 In [1]: import IPython.Extensions.InterpreterPasteInput
6802 \layout Standard
6816 \layout Standard
6803
6817
6804 The following is a 'screenshot' of how things work when this extension is
6818 The following is a 'screenshot' of how things work when this extension is
6805 on, copying an example from the standard tutorial:
6819 on, copying an example from the standard tutorial:
6806 \layout Standard
6820 \layout Standard
6807
6821
6808
6822
6809 \family typewriter
6823 \family typewriter
6810 IPython profile: tutorial
6824 IPython profile: tutorial
6811 \newline
6825 \newline
6812 \SpecialChar ~
6826 \SpecialChar ~
6813
6827
6814 \newline
6828 \newline
6815 *** Pasting of code with ">>>" or "..." has been enabled.
6829 *** Pasting of code with ">>>" or "..." has been enabled.
6816 \newline
6830 \newline
6817 \SpecialChar ~
6831 \SpecialChar ~
6818
6832
6819 \newline
6833 \newline
6820 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6834 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6821 \newline
6835 \newline
6822
6836
6823 \begin_inset ERT
6837 \begin_inset ERT
6824 status Collapsed
6838 status Collapsed
6825
6839
6826 \layout Standard
6840 \layout Standard
6827
6841
6828 \backslash
6842 \backslash
6829 hspace*{0mm}
6843 hspace*{0mm}
6830 \end_inset
6844 \end_inset
6831
6845
6832 \SpecialChar ~
6846 \SpecialChar ~
6833 \SpecialChar ~
6847 \SpecialChar ~
6834 ...: ...\SpecialChar ~
6848 ...: ...\SpecialChar ~
6835 \SpecialChar ~
6849 \SpecialChar ~
6836 \SpecialChar ~
6850 \SpecialChar ~
6837 \SpecialChar ~
6851 \SpecialChar ~
6838 """Return a list containing the Fibonacci series up to n."""
6852 """Return a list containing the Fibonacci series up to n."""
6839 \newline
6853 \newline
6840
6854
6841 \begin_inset ERT
6855 \begin_inset ERT
6842 status Collapsed
6856 status Collapsed
6843
6857
6844 \layout Standard
6858 \layout Standard
6845
6859
6846 \backslash
6860 \backslash
6847 hspace*{0mm}
6861 hspace*{0mm}
6848 \end_inset
6862 \end_inset
6849
6863
6850 \SpecialChar ~
6864 \SpecialChar ~
6851 \SpecialChar ~
6865 \SpecialChar ~
6852 ...: ...\SpecialChar ~
6866 ...: ...\SpecialChar ~
6853 \SpecialChar ~
6867 \SpecialChar ~
6854 \SpecialChar ~
6868 \SpecialChar ~
6855 \SpecialChar ~
6869 \SpecialChar ~
6856 result = []
6870 result = []
6857 \newline
6871 \newline
6858
6872
6859 \begin_inset ERT
6873 \begin_inset ERT
6860 status Collapsed
6874 status Collapsed
6861
6875
6862 \layout Standard
6876 \layout Standard
6863
6877
6864 \backslash
6878 \backslash
6865 hspace*{0mm}
6879 hspace*{0mm}
6866 \end_inset
6880 \end_inset
6867
6881
6868 \SpecialChar ~
6882 \SpecialChar ~
6869 \SpecialChar ~
6883 \SpecialChar ~
6870 ...: ...\SpecialChar ~
6884 ...: ...\SpecialChar ~
6871 \SpecialChar ~
6885 \SpecialChar ~
6872 \SpecialChar ~
6886 \SpecialChar ~
6873 \SpecialChar ~
6887 \SpecialChar ~
6874 a, b = 0, 1
6888 a, b = 0, 1
6875 \newline
6889 \newline
6876
6890
6877 \begin_inset ERT
6891 \begin_inset ERT
6878 status Collapsed
6892 status Collapsed
6879
6893
6880 \layout Standard
6894 \layout Standard
6881
6895
6882 \backslash
6896 \backslash
6883 hspace*{0mm}
6897 hspace*{0mm}
6884 \end_inset
6898 \end_inset
6885
6899
6886 \SpecialChar ~
6900 \SpecialChar ~
6887 \SpecialChar ~
6901 \SpecialChar ~
6888 ...: ...\SpecialChar ~
6902 ...: ...\SpecialChar ~
6889 \SpecialChar ~
6903 \SpecialChar ~
6890 \SpecialChar ~
6904 \SpecialChar ~
6891 \SpecialChar ~
6905 \SpecialChar ~
6892 while b < n:
6906 while b < n:
6893 \newline
6907 \newline
6894
6908
6895 \begin_inset ERT
6909 \begin_inset ERT
6896 status Collapsed
6910 status Collapsed
6897
6911
6898 \layout Standard
6912 \layout Standard
6899
6913
6900 \backslash
6914 \backslash
6901 hspace*{0mm}
6915 hspace*{0mm}
6902 \end_inset
6916 \end_inset
6903
6917
6904 \SpecialChar ~
6918 \SpecialChar ~
6905 \SpecialChar ~
6919 \SpecialChar ~
6906 ...: ...\SpecialChar ~
6920 ...: ...\SpecialChar ~
6907 \SpecialChar ~
6921 \SpecialChar ~
6908 \SpecialChar ~
6922 \SpecialChar ~
6909 \SpecialChar ~
6923 \SpecialChar ~
6910 \SpecialChar ~
6924 \SpecialChar ~
6911 \SpecialChar ~
6925 \SpecialChar ~
6912 \SpecialChar ~
6926 \SpecialChar ~
6913 \SpecialChar ~
6927 \SpecialChar ~
6914 result.append(b)\SpecialChar ~
6928 result.append(b)\SpecialChar ~
6915 \SpecialChar ~
6929 \SpecialChar ~
6916 \SpecialChar ~
6930 \SpecialChar ~
6917 # see below
6931 # see below
6918 \newline
6932 \newline
6919
6933
6920 \begin_inset ERT
6934 \begin_inset ERT
6921 status Collapsed
6935 status Collapsed
6922
6936
6923 \layout Standard
6937 \layout Standard
6924
6938
6925 \backslash
6939 \backslash
6926 hspace*{0mm}
6940 hspace*{0mm}
6927 \end_inset
6941 \end_inset
6928
6942
6929 \SpecialChar ~
6943 \SpecialChar ~
6930 \SpecialChar ~
6944 \SpecialChar ~
6931 ...: ...\SpecialChar ~
6945 ...: ...\SpecialChar ~
6932 \SpecialChar ~
6946 \SpecialChar ~
6933 \SpecialChar ~
6947 \SpecialChar ~
6934 \SpecialChar ~
6948 \SpecialChar ~
6935 \SpecialChar ~
6949 \SpecialChar ~
6936 \SpecialChar ~
6950 \SpecialChar ~
6937 \SpecialChar ~
6951 \SpecialChar ~
6938 \SpecialChar ~
6952 \SpecialChar ~
6939 a, b = b, a+b
6953 a, b = b, a+b
6940 \newline
6954 \newline
6941
6955
6942 \begin_inset ERT
6956 \begin_inset ERT
6943 status Collapsed
6957 status Collapsed
6944
6958
6945 \layout Standard
6959 \layout Standard
6946
6960
6947 \backslash
6961 \backslash
6948 hspace*{0mm}
6962 hspace*{0mm}
6949 \end_inset
6963 \end_inset
6950
6964
6951 \SpecialChar ~
6965 \SpecialChar ~
6952 \SpecialChar ~
6966 \SpecialChar ~
6953 ...: ...\SpecialChar ~
6967 ...: ...\SpecialChar ~
6954 \SpecialChar ~
6968 \SpecialChar ~
6955 \SpecialChar ~
6969 \SpecialChar ~
6956 \SpecialChar ~
6970 \SpecialChar ~
6957 return result
6971 return result
6958 \newline
6972 \newline
6959
6973
6960 \begin_inset ERT
6974 \begin_inset ERT
6961 status Collapsed
6975 status Collapsed
6962
6976
6963 \layout Standard
6977 \layout Standard
6964
6978
6965 \backslash
6979 \backslash
6966 hspace*{0mm}
6980 hspace*{0mm}
6967 \end_inset
6981 \end_inset
6968
6982
6969 \SpecialChar ~
6983 \SpecialChar ~
6970 \SpecialChar ~
6984 \SpecialChar ~
6971 ...:
6985 ...:
6972 \newline
6986 \newline
6973 \SpecialChar ~
6987 \SpecialChar ~
6974
6988
6975 \newline
6989 \newline
6976 In [2]: fib2(10)
6990 In [2]: fib2(10)
6977 \newline
6991 \newline
6978 Out[2]: [1, 1, 2, 3, 5, 8]
6992 Out[2]: [1, 1, 2, 3, 5, 8]
6979 \layout Standard
6993 \layout Standard
6980
6994
6981 Note that as currently written, this extension does
6995 Note that as currently written, this extension does
6982 \emph on
6996 \emph on
6983 not
6997 not
6984 \emph default
6998 \emph default
6985 recognize IPython's prompts for pasting.
6999 recognize IPython's prompts for pasting.
6986 Those are more complicated, since the user can change them very easily,
7000 Those are more complicated, since the user can change them very easily,
6987 they involve numbers and can vary in length.
7001 they involve numbers and can vary in length.
6988 One could however extract all the relevant information from the IPython
7002 One could however extract all the relevant information from the IPython
6989 instance and build an appropriate regular expression.
7003 instance and build an appropriate regular expression.
6990 This is left as an exercise for the reader.
7004 This is left as an exercise for the reader.
6991 \layout Subsection
7005 \layout Subsection
6992
7006
6993 Input of physical quantities with units
7007 Input of physical quantities with units
6994 \layout Standard
7008 \layout Standard
6995
7009
6996 The module
7010 The module
6997 \family typewriter
7011 \family typewriter
6998 PhysicalQInput
7012 PhysicalQInput
6999 \family default
7013 \family default
7000 allows a simplified form of input for physical quantities with units.
7014 allows a simplified form of input for physical quantities with units.
7001 This file is meant to be used in conjunction with the
7015 This file is meant to be used in conjunction with the
7002 \family typewriter
7016 \family typewriter
7003 PhysicalQInteractive
7017 PhysicalQInteractive
7004 \family default
7018 \family default
7005 module (in the same directory) and
7019 module (in the same directory) and
7006 \family typewriter
7020 \family typewriter
7007 Physics.PhysicalQuantities
7021 Physics.PhysicalQuantities
7008 \family default
7022 \family default
7009 from Konrad Hinsen's ScientificPython (
7023 from Konrad Hinsen's ScientificPython (
7010 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
7024 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
7011
7025
7012 \end_inset
7026 \end_inset
7013
7027
7014 ).
7028 ).
7015 \layout Standard
7029 \layout Standard
7016
7030
7017 The
7031 The
7018 \family typewriter
7032 \family typewriter
7019 Physics.PhysicalQuantities
7033 Physics.PhysicalQuantities
7020 \family default
7034 \family default
7021 module defines
7035 module defines
7022 \family typewriter
7036 \family typewriter
7023 PhysicalQuantity
7037 PhysicalQuantity
7024 \family default
7038 \family default
7025 objects, but these must be declared as instances of a class.
7039 objects, but these must be declared as instances of a class.
7026 For example, to define
7040 For example, to define
7027 \family typewriter
7041 \family typewriter
7028 v
7042 v
7029 \family default
7043 \family default
7030 as a velocity of 3\SpecialChar ~
7044 as a velocity of 3\SpecialChar ~
7031 m/s, normally you would write:
7045 m/s, normally you would write:
7032 \family typewriter
7046 \family typewriter
7033
7047
7034 \newline
7048 \newline
7035 In [1]: v = PhysicalQuantity(3,'m/s')
7049 In [1]: v = PhysicalQuantity(3,'m/s')
7036 \layout Standard
7050 \layout Standard
7037
7051
7038 Using the
7052 Using the
7039 \family typewriter
7053 \family typewriter
7040 PhysicalQ_Input
7054 PhysicalQ_Input
7041 \family default
7055 \family default
7042 extension this can be input instead as:
7056 extension this can be input instead as:
7043 \family typewriter
7057 \family typewriter
7044
7058
7045 \newline
7059 \newline
7046 In [1]: v = 3 m/s
7060 In [1]: v = 3 m/s
7047 \family default
7061 \family default
7048
7062
7049 \newline
7063 \newline
7050 which is much more convenient for interactive use (even though it is blatantly
7064 which is much more convenient for interactive use (even though it is blatantly
7051 invalid Python syntax).
7065 invalid Python syntax).
7052 \layout Standard
7066 \layout Standard
7053
7067
7054 The
7068 The
7055 \family typewriter
7069 \family typewriter
7056 physics
7070 physics
7057 \family default
7071 \family default
7058 profile supplied with IPython (enabled via
7072 profile supplied with IPython (enabled via
7059 \family typewriter
7073 \family typewriter
7060 'ipython -p physics'
7074 'ipython -p physics'
7061 \family default
7075 \family default
7062 ) uses these extensions, which you can also activate with:
7076 ) uses these extensions, which you can also activate with:
7063 \layout Standard
7077 \layout Standard
7064
7078
7065
7079
7066 \family typewriter
7080 \family typewriter
7067 from math import * # math MUST be imported BEFORE PhysicalQInteractive
7081 from math import * # math MUST be imported BEFORE PhysicalQInteractive
7068 \newline
7082 \newline
7069 from IPython.Extensions.PhysicalQInteractive import *
7083 from IPython.Extensions.PhysicalQInteractive import *
7070 \newline
7084 \newline
7071 import IPython.Extensions.PhysicalQInput
7085 import IPython.Extensions.PhysicalQInput
7072 \layout Section
7086 \layout Section
7073
7087
7074
7088
7075 \begin_inset LatexCommand \label{sec:IPython-as-shell}
7089 \begin_inset LatexCommand \label{sec:IPython-as-shell}
7076
7090
7077 \end_inset
7091 \end_inset
7078
7092
7079 IPython as a system shell
7093 IPython as a system shell
7080 \layout Standard
7094 \layout Standard
7081
7095
7082 IPython ships with a special profile called
7096 IPython ships with a special profile called
7083 \family typewriter
7097 \family typewriter
7084 pysh
7098 pysh
7085 \family default
7099 \family default
7086 , which you can activate at the command line as
7100 , which you can activate at the command line as
7087 \family typewriter
7101 \family typewriter
7088 `ipython -p pysh'
7102 `ipython -p pysh'
7089 \family default
7103 \family default
7090 .
7104 .
7091 This loads
7105 This loads
7092 \family typewriter
7106 \family typewriter
7093 InterpreterExec
7107 InterpreterExec
7094 \family default
7108 \family default
7095 , along with some additional facilities and a prompt customized for filesystem
7109 , along with some additional facilities and a prompt customized for filesystem
7096 navigation.
7110 navigation.
7097 \layout Standard
7111 \layout Standard
7098
7112
7099 Note that this does
7113 Note that this does
7100 \emph on
7114 \emph on
7101 not
7115 not
7102 \emph default
7116 \emph default
7103 make IPython a full-fledged system shell.
7117 make IPython a full-fledged system shell.
7104 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
7118 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
7105 you'll suspend pysh itself, not the process you just started.
7119 you'll suspend pysh itself, not the process you just started.
7106
7120
7107 \layout Standard
7121 \layout Standard
7108
7122
7109 What the shell profile allows you to do is to use the convenient and powerful
7123 What the shell profile allows you to do is to use the convenient and powerful
7110 syntax of Python to do quick scripting at the command line.
7124 syntax of Python to do quick scripting at the command line.
7111 Below we describe some of its features.
7125 Below we describe some of its features.
7112 \layout Subsection
7126 \layout Subsection
7113
7127
7114 Aliases
7128 Aliases
7115 \layout Standard
7129 \layout Standard
7116
7130
7117 All of your
7131 All of your
7118 \family typewriter
7132 \family typewriter
7119 $PATH
7133 $PATH
7120 \family default
7134 \family default
7121 has been loaded as IPython aliases, so you should be able to type any normal
7135 has been loaded as IPython aliases, so you should be able to type any normal
7122 system command and have it executed.
7136 system command and have it executed.
7123 See
7137 See
7124 \family typewriter
7138 \family typewriter
7125 %alias?
7139 %alias?
7126 \family default
7140 \family default
7127 and
7141 and
7128 \family typewriter
7142 \family typewriter
7129 %unalias?
7143 %unalias?
7130 \family default
7144 \family default
7131 for details on the alias facilities.
7145 for details on the alias facilities.
7132 See also
7146 See also
7133 \family typewriter
7147 \family typewriter
7134 %rehash?
7148 %rehash?
7135 \family default
7149 \family default
7136 and
7150 and
7137 \family typewriter
7151 \family typewriter
7138 %rehashx?
7152 %rehashx?
7139 \family default
7153 \family default
7140 for details on the mechanism used to load
7154 for details on the mechanism used to load
7141 \family typewriter
7155 \family typewriter
7142 $PATH
7156 $PATH
7143 \family default
7157 \family default
7144 .
7158 .
7145 \layout Subsection
7159 \layout Subsection
7146
7160
7147 Special syntax
7161 Special syntax
7148 \layout Standard
7162 \layout Standard
7149
7163
7150 Any lines which begin with
7164 Any lines which begin with
7151 \family typewriter
7165 \family typewriter
7152 `~'
7166 `~'
7153 \family default
7167 \family default
7154 ,
7168 ,
7155 \family typewriter
7169 \family typewriter
7156 `/'
7170 `/'
7157 \family default
7171 \family default
7158 and
7172 and
7159 \family typewriter
7173 \family typewriter
7160 `.'
7174 `.'
7161 \family default
7175 \family default
7162 will be executed as shell commands instead of as Python code.
7176 will be executed as shell commands instead of as Python code.
7163 The special escapes below are also recognized.
7177 The special escapes below are also recognized.
7164
7178
7165 \family typewriter
7179 \family typewriter
7166 !cmd
7180 !cmd
7167 \family default
7181 \family default
7168 is valid in single or multi-line input, all others are only valid in single-lin
7182 is valid in single or multi-line input, all others are only valid in single-lin
7169 e input:
7183 e input:
7170 \layout Description
7184 \layout Description
7171
7185
7172
7186
7173 \family typewriter
7187 \family typewriter
7174 !cmd
7188 !cmd
7175 \family default
7189 \family default
7176 pass `cmd' directly to the shell
7190 pass `cmd' directly to the shell
7177 \layout Description
7191 \layout Description
7178
7192
7179
7193
7180 \family typewriter
7194 \family typewriter
7181 !!cmd
7195 !!cmd
7182 \family default
7196 \family default
7183 execute `cmd' and return output as a list (split on `
7197 execute `cmd' and return output as a list (split on `
7184 \backslash
7198 \backslash
7185 n')
7199 n')
7186 \layout Description
7200 \layout Description
7187
7201
7188
7202
7189 \family typewriter
7203 \family typewriter
7190 $var=cmd
7204 $var=cmd
7191 \family default
7205 \family default
7192 capture output of cmd into var, as a string
7206 capture output of cmd into var, as a string
7193 \layout Description
7207 \layout Description
7194
7208
7195
7209
7196 \family typewriter
7210 \family typewriter
7197 $$var=cmd
7211 $$var=cmd
7198 \family default
7212 \family default
7199 capture output of cmd into var, as a list (split on `
7213 capture output of cmd into var, as a list (split on `
7200 \backslash
7214 \backslash
7201 n')
7215 n')
7202 \layout Standard
7216 \layout Standard
7203
7217
7204 The
7218 The
7205 \family typewriter
7219 \family typewriter
7206 $
7220 $
7207 \family default
7221 \family default
7208 /
7222 /
7209 \family typewriter
7223 \family typewriter
7210 $$
7224 $$
7211 \family default
7225 \family default
7212 syntaxes make Python variables from system output, which you can later
7226 syntaxes make Python variables from system output, which you can later
7213 use for further scripting.
7227 use for further scripting.
7214 The converse is also possible: when executing an alias or calling to the
7228 The converse is also possible: when executing an alias or calling to the
7215 system via
7229 system via
7216 \family typewriter
7230 \family typewriter
7217 !
7231 !
7218 \family default
7232 \family default
7219 /
7233 /
7220 \family typewriter
7234 \family typewriter
7221 !!
7235 !!
7222 \family default
7236 \family default
7223 , you can expand any python variable or expression by prepending it with
7237 , you can expand any python variable or expression by prepending it with
7224
7238
7225 \family typewriter
7239 \family typewriter
7226 $
7240 $
7227 \family default
7241 \family default
7228 .
7242 .
7229 Full details of the allowed syntax can be found in Python's PEP 215.
7243 Full details of the allowed syntax can be found in Python's PEP 215.
7230 \layout Standard
7244 \layout Standard
7231
7245
7232 A few brief examples will illustrate these (note that the indentation below
7246 A few brief examples will illustrate these (note that the indentation below
7233 may be incorrectly displayed):
7247 may be incorrectly displayed):
7234 \layout Standard
7248 \layout Standard
7235
7249
7236
7250
7237 \family typewriter
7251 \family typewriter
7238 fperez[~/test]|3> !ls *s.py
7252 fperez[~/test]|3> !ls *s.py
7239 \newline
7253 \newline
7240 scopes.py strings.py
7254 scopes.py strings.py
7241 \layout Standard
7255 \layout Standard
7242
7256
7243 ls is an internal alias, so there's no need to use
7257 ls is an internal alias, so there's no need to use
7244 \family typewriter
7258 \family typewriter
7245 !
7259 !
7246 \family default
7260 \family default
7247 :
7261 :
7248 \layout Standard
7262 \layout Standard
7249
7263
7250
7264
7251 \family typewriter
7265 \family typewriter
7252 fperez[~/test]|4> ls *s.py
7266 fperez[~/test]|4> ls *s.py
7253 \newline
7267 \newline
7254 scopes.py* strings.py
7268 scopes.py* strings.py
7255 \layout Standard
7269 \layout Standard
7256
7270
7257 !!ls will return the output into a Python variable:
7271 !!ls will return the output into a Python variable:
7258 \layout Standard
7272 \layout Standard
7259
7273
7260
7274
7261 \family typewriter
7275 \family typewriter
7262 fperez[~/test]|5> !!ls *s.py
7276 fperez[~/test]|5> !!ls *s.py
7263 \newline
7277 \newline
7264
7278
7265 \begin_inset ERT
7279 \begin_inset ERT
7266 status Collapsed
7280 status Collapsed
7267
7281
7268 \layout Standard
7282 \layout Standard
7269
7283
7270 \backslash
7284 \backslash
7271 hspace*{0mm}
7285 hspace*{0mm}
7272 \end_inset
7286 \end_inset
7273
7287
7274 \SpecialChar ~
7288 \SpecialChar ~
7275 \SpecialChar ~
7289 \SpecialChar ~
7276 \SpecialChar ~
7290 \SpecialChar ~
7277 \SpecialChar ~
7291 \SpecialChar ~
7278 \SpecialChar ~
7292 \SpecialChar ~
7279 \SpecialChar ~
7293 \SpecialChar ~
7280 \SpecialChar ~
7294 \SpecialChar ~
7281 \SpecialChar ~
7295 \SpecialChar ~
7282 \SpecialChar ~
7296 \SpecialChar ~
7283 \SpecialChar ~
7297 \SpecialChar ~
7284 \SpecialChar ~
7298 \SpecialChar ~
7285 \SpecialChar ~
7299 \SpecialChar ~
7286 \SpecialChar ~
7300 \SpecialChar ~
7287 \SpecialChar ~
7301 \SpecialChar ~
7288 <5> ['scopes.py', 'strings.py']
7302 <5> ['scopes.py', 'strings.py']
7289 \newline
7303 \newline
7290 fperez[~/test]|6> print _5
7304 fperez[~/test]|6> print _5
7291 \newline
7305 \newline
7292 ['scopes.py', 'strings.py']
7306 ['scopes.py', 'strings.py']
7293 \layout Standard
7307 \layout Standard
7294
7308
7295
7309
7296 \family typewriter
7310 \family typewriter
7297 $
7311 $
7298 \family default
7312 \family default
7299 and
7313 and
7300 \family typewriter
7314 \family typewriter
7301 $$
7315 $$
7302 \family default
7316 \family default
7303 allow direct capture to named variables:
7317 allow direct capture to named variables:
7304 \layout Standard
7318 \layout Standard
7305
7319
7306
7320
7307 \family typewriter
7321 \family typewriter
7308 fperez[~/test]|7> $astr = ls *s.py
7322 fperez[~/test]|7> $astr = ls *s.py
7309 \newline
7323 \newline
7310 fperez[~/test]|8> astr
7324 fperez[~/test]|8> astr
7311 \newline
7325 \newline
7312
7326
7313 \begin_inset ERT
7327 \begin_inset ERT
7314 status Collapsed
7328 status Collapsed
7315
7329
7316 \layout Standard
7330 \layout Standard
7317
7331
7318 \backslash
7332 \backslash
7319 hspace*{0mm}
7333 hspace*{0mm}
7320 \end_inset
7334 \end_inset
7321
7335
7322 \SpecialChar ~
7336 \SpecialChar ~
7323 \SpecialChar ~
7337 \SpecialChar ~
7324 \SpecialChar ~
7338 \SpecialChar ~
7325 \SpecialChar ~
7339 \SpecialChar ~
7326 \SpecialChar ~
7340 \SpecialChar ~
7327 \SpecialChar ~
7341 \SpecialChar ~
7328 \SpecialChar ~
7342 \SpecialChar ~
7329 \SpecialChar ~
7343 \SpecialChar ~
7330 \SpecialChar ~
7344 \SpecialChar ~
7331 \SpecialChar ~
7345 \SpecialChar ~
7332 \SpecialChar ~
7346 \SpecialChar ~
7333 \SpecialChar ~
7347 \SpecialChar ~
7334 \SpecialChar ~
7348 \SpecialChar ~
7335 \SpecialChar ~
7349 \SpecialChar ~
7336 <8> 'scopes.py
7350 <8> 'scopes.py
7337 \backslash
7351 \backslash
7338 nstrings.py'
7352 nstrings.py'
7339 \layout Standard
7353 \layout Standard
7340
7354
7341
7355
7342 \family typewriter
7356 \family typewriter
7343 fperez[~/test]|9> $$alist = ls *s.py
7357 fperez[~/test]|9> $$alist = ls *s.py
7344 \newline
7358 \newline
7345 fperez[~/test]|10> alist
7359 fperez[~/test]|10> alist
7346 \newline
7360 \newline
7347
7361
7348 \begin_inset ERT
7362 \begin_inset ERT
7349 status Collapsed
7363 status Collapsed
7350
7364
7351 \layout Standard
7365 \layout Standard
7352
7366
7353 \backslash
7367 \backslash
7354 hspace*{0mm}
7368 hspace*{0mm}
7355 \end_inset
7369 \end_inset
7356
7370
7357 \SpecialChar ~
7371 \SpecialChar ~
7358 \SpecialChar ~
7372 \SpecialChar ~
7359 \SpecialChar ~
7373 \SpecialChar ~
7360 \SpecialChar ~
7374 \SpecialChar ~
7361 \SpecialChar ~
7375 \SpecialChar ~
7362 \SpecialChar ~
7376 \SpecialChar ~
7363 \SpecialChar ~
7377 \SpecialChar ~
7364 \SpecialChar ~
7378 \SpecialChar ~
7365 \SpecialChar ~
7379 \SpecialChar ~
7366 \SpecialChar ~
7380 \SpecialChar ~
7367 \SpecialChar ~
7381 \SpecialChar ~
7368 \SpecialChar ~
7382 \SpecialChar ~
7369 \SpecialChar ~
7383 \SpecialChar ~
7370 \SpecialChar ~
7384 \SpecialChar ~
7371 <10> ['scopes.py', 'strings.py']
7385 <10> ['scopes.py', 'strings.py']
7372 \layout Standard
7386 \layout Standard
7373
7387
7374 alist is now a normal python list you can loop over.
7388 alist is now a normal python list you can loop over.
7375 Using
7389 Using
7376 \family typewriter
7390 \family typewriter
7377 $
7391 $
7378 \family default
7392 \family default
7379 will expand back the python values when alias calls are made:
7393 will expand back the python values when alias calls are made:
7380 \layout Standard
7394 \layout Standard
7381
7395
7382
7396
7383 \family typewriter
7397 \family typewriter
7384 fperez[~/test]|11> for f in alist:
7398 fperez[~/test]|11> for f in alist:
7385 \newline
7399 \newline
7386
7400
7387 \begin_inset ERT
7401 \begin_inset ERT
7388 status Collapsed
7402 status Collapsed
7389
7403
7390 \layout Standard
7404 \layout Standard
7391
7405
7392 \backslash
7406 \backslash
7393 hspace*{0mm}
7407 hspace*{0mm}
7394 \end_inset
7408 \end_inset
7395
7409
7396 \SpecialChar ~
7410 \SpecialChar ~
7397 \SpecialChar ~
7411 \SpecialChar ~
7398 \SpecialChar ~
7412 \SpecialChar ~
7399 \SpecialChar ~
7413 \SpecialChar ~
7400 \SpecialChar ~
7414 \SpecialChar ~
7401 \SpecialChar ~
7415 \SpecialChar ~
7402 \SpecialChar ~
7416 \SpecialChar ~
7403 \SpecialChar ~
7417 \SpecialChar ~
7404 \SpecialChar ~
7418 \SpecialChar ~
7405 \SpecialChar ~
7419 \SpecialChar ~
7406 \SpecialChar ~
7420 \SpecialChar ~
7407 \SpecialChar ~
7421 \SpecialChar ~
7408 \SpecialChar ~
7422 \SpecialChar ~
7409 \SpecialChar ~
7423 \SpecialChar ~
7410 |..> \SpecialChar ~
7424 |..> \SpecialChar ~
7411 \SpecialChar ~
7425 \SpecialChar ~
7412 \SpecialChar ~
7426 \SpecialChar ~
7413 \SpecialChar ~
7427 \SpecialChar ~
7414 print 'file',f,
7428 print 'file',f,
7415 \newline
7429 \newline
7416
7430
7417 \begin_inset ERT
7431 \begin_inset ERT
7418 status Collapsed
7432 status Collapsed
7419
7433
7420 \layout Standard
7434 \layout Standard
7421
7435
7422 \backslash
7436 \backslash
7423 hspace*{0mm}
7437 hspace*{0mm}
7424 \end_inset
7438 \end_inset
7425
7439
7426 \SpecialChar ~
7440 \SpecialChar ~
7427 \SpecialChar ~
7441 \SpecialChar ~
7428 \SpecialChar ~
7442 \SpecialChar ~
7429 \SpecialChar ~
7443 \SpecialChar ~
7430 \SpecialChar ~
7444 \SpecialChar ~
7431 \SpecialChar ~
7445 \SpecialChar ~
7432 \SpecialChar ~
7446 \SpecialChar ~
7433 \SpecialChar ~
7447 \SpecialChar ~
7434 \SpecialChar ~
7448 \SpecialChar ~
7435 \SpecialChar ~
7449 \SpecialChar ~
7436 \SpecialChar ~
7450 \SpecialChar ~
7437 \SpecialChar ~
7451 \SpecialChar ~
7438 \SpecialChar ~
7452 \SpecialChar ~
7439 \SpecialChar ~
7453 \SpecialChar ~
7440 |..> \SpecialChar ~
7454 |..> \SpecialChar ~
7441 \SpecialChar ~
7455 \SpecialChar ~
7442 \SpecialChar ~
7456 \SpecialChar ~
7443 \SpecialChar ~
7457 \SpecialChar ~
7444 wc -l $f
7458 wc -l $f
7445 \newline
7459 \newline
7446
7460
7447 \begin_inset ERT
7461 \begin_inset ERT
7448 status Collapsed
7462 status Collapsed
7449
7463
7450 \layout Standard
7464 \layout Standard
7451
7465
7452 \backslash
7466 \backslash
7453 hspace*{0mm}
7467 hspace*{0mm}
7454 \end_inset
7468 \end_inset
7455
7469
7456 \SpecialChar ~
7470 \SpecialChar ~
7457 \SpecialChar ~
7471 \SpecialChar ~
7458 \SpecialChar ~
7472 \SpecialChar ~
7459 \SpecialChar ~
7473 \SpecialChar ~
7460 \SpecialChar ~
7474 \SpecialChar ~
7461 \SpecialChar ~
7475 \SpecialChar ~
7462 \SpecialChar ~
7476 \SpecialChar ~
7463 \SpecialChar ~
7477 \SpecialChar ~
7464 \SpecialChar ~
7478 \SpecialChar ~
7465 \SpecialChar ~
7479 \SpecialChar ~
7466 \SpecialChar ~
7480 \SpecialChar ~
7467 \SpecialChar ~
7481 \SpecialChar ~
7468 \SpecialChar ~
7482 \SpecialChar ~
7469 \SpecialChar ~
7483 \SpecialChar ~
7470 |..>
7484 |..>
7471 \newline
7485 \newline
7472 file scopes.py 13 scopes.py
7486 file scopes.py 13 scopes.py
7473 \newline
7487 \newline
7474 file strings.py 4 strings.py
7488 file strings.py 4 strings.py
7475 \layout Standard
7489 \layout Standard
7476
7490
7477 Note that you may need to protect your variables with braces if you want
7491 Note that you may need to protect your variables with braces if you want
7478 to append strings to their names.
7492 to append strings to their names.
7479 To copy all files in alist to
7493 To copy all files in alist to
7480 \family typewriter
7494 \family typewriter
7481 .bak
7495 .bak
7482 \family default
7496 \family default
7483 extensions, you must use:
7497 extensions, you must use:
7484 \layout Standard
7498 \layout Standard
7485
7499
7486
7500
7487 \family typewriter
7501 \family typewriter
7488 fperez[~/test]|12> for f in alist:
7502 fperez[~/test]|12> for f in alist:
7489 \newline
7503 \newline
7490
7504
7491 \begin_inset ERT
7505 \begin_inset ERT
7492 status Collapsed
7506 status Collapsed
7493
7507
7494 \layout Standard
7508 \layout Standard
7495
7509
7496 \backslash
7510 \backslash
7497 hspace*{0mm}
7511 hspace*{0mm}
7498 \end_inset
7512 \end_inset
7499
7513
7500 \SpecialChar ~
7514 \SpecialChar ~
7501 \SpecialChar ~
7515 \SpecialChar ~
7502 \SpecialChar ~
7516 \SpecialChar ~
7503 \SpecialChar ~
7517 \SpecialChar ~
7504 \SpecialChar ~
7518 \SpecialChar ~
7505 \SpecialChar ~
7519 \SpecialChar ~
7506 \SpecialChar ~
7520 \SpecialChar ~
7507 \SpecialChar ~
7521 \SpecialChar ~
7508 \SpecialChar ~
7522 \SpecialChar ~
7509 \SpecialChar ~
7523 \SpecialChar ~
7510 \SpecialChar ~
7524 \SpecialChar ~
7511 \SpecialChar ~
7525 \SpecialChar ~
7512 \SpecialChar ~
7526 \SpecialChar ~
7513 \SpecialChar ~
7527 \SpecialChar ~
7514 |..> \SpecialChar ~
7528 |..> \SpecialChar ~
7515 \SpecialChar ~
7529 \SpecialChar ~
7516 \SpecialChar ~
7530 \SpecialChar ~
7517 \SpecialChar ~
7531 \SpecialChar ~
7518 cp $f ${f}.bak
7532 cp $f ${f}.bak
7519 \layout Standard
7533 \layout Standard
7520
7534
7521 If you try using
7535 If you try using
7522 \family typewriter
7536 \family typewriter
7523 $f.bak
7537 $f.bak
7524 \family default
7538 \family default
7525 , you'll get an AttributeError exception saying that your string object
7539 , you'll get an AttributeError exception saying that your string object
7526 doesn't have a
7540 doesn't have a
7527 \family typewriter
7541 \family typewriter
7528 .bak
7542 .bak
7529 \family default
7543 \family default
7530 attribute.
7544 attribute.
7531 This is because the
7545 This is because the
7532 \family typewriter
7546 \family typewriter
7533 $
7547 $
7534 \family default
7548 \family default
7535 expansion mechanism allows you to expand full Python expressions:
7549 expansion mechanism allows you to expand full Python expressions:
7536 \layout Standard
7550 \layout Standard
7537
7551
7538
7552
7539 \family typewriter
7553 \family typewriter
7540 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7554 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7541 \newline
7555 \newline
7542 sys.platform is: linux2
7556 sys.platform is: linux2
7543 \layout Standard
7557 \layout Standard
7544
7558
7545 IPython's input history handling is still active, which allows you to rerun
7559 IPython's input history handling is still active, which allows you to rerun
7546 a single block of multi-line input by simply using exec:
7560 a single block of multi-line input by simply using exec:
7547 \newline
7561 \newline
7548
7562
7549 \family typewriter
7563 \family typewriter
7550 fperez[~/test]|14> $$alist = ls *.eps
7564 fperez[~/test]|14> $$alist = ls *.eps
7551 \newline
7565 \newline
7552 fperez[~/test]|15> exec _i11
7566 fperez[~/test]|15> exec _i11
7553 \newline
7567 \newline
7554 file image2.eps 921 image2.eps
7568 file image2.eps 921 image2.eps
7555 \newline
7569 \newline
7556 file image.eps 921 image.eps
7570 file image.eps 921 image.eps
7557 \layout Standard
7571 \layout Standard
7558
7572
7559 While these are new special-case syntaxes, they are designed to allow very
7573 While these are new special-case syntaxes, they are designed to allow very
7560 efficient use of the shell with minimal typing.
7574 efficient use of the shell with minimal typing.
7561 At an interactive shell prompt, conciseness of expression wins over readability.
7575 At an interactive shell prompt, conciseness of expression wins over readability.
7562 \layout Subsection
7576 \layout Subsection
7563
7577
7564 Useful functions and modules
7578 Useful functions and modules
7565 \layout Standard
7579 \layout Standard
7566
7580
7567 The os, sys and shutil modules from the Python standard library are automaticall
7581 The os, sys and shutil modules from the Python standard library are automaticall
7568 y loaded.
7582 y loaded.
7569 Some additional functions, useful for shell usage, are listed below.
7583 Some additional functions, useful for shell usage, are listed below.
7570 You can request more help about them with `
7584 You can request more help about them with `
7571 \family typewriter
7585 \family typewriter
7572 ?
7586 ?
7573 \family default
7587 \family default
7574 '.
7588 '.
7575 \layout Description
7589 \layout Description
7576
7590
7577
7591
7578 \family typewriter
7592 \family typewriter
7579 shell
7593 shell
7580 \family default
7594 \family default
7581 - execute a command in the underlying system shell
7595 - execute a command in the underlying system shell
7582 \layout Description
7596 \layout Description
7583
7597
7584
7598
7585 \family typewriter
7599 \family typewriter
7586 system
7600 system
7587 \family default
7601 \family default
7588 - like
7602 - like
7589 \family typewriter
7603 \family typewriter
7590 shell()
7604 shell()
7591 \family default
7605 \family default
7592 , but return the exit status of the command
7606 , but return the exit status of the command
7593 \layout Description
7607 \layout Description
7594
7608
7595
7609
7596 \family typewriter
7610 \family typewriter
7597 sout
7611 sout
7598 \family default
7612 \family default
7599 - capture the output of a command as a string
7613 - capture the output of a command as a string
7600 \layout Description
7614 \layout Description
7601
7615
7602
7616
7603 \family typewriter
7617 \family typewriter
7604 lout
7618 lout
7605 \family default
7619 \family default
7606 - capture the output of a command as a list (split on `
7620 - capture the output of a command as a list (split on `
7607 \backslash
7621 \backslash
7608 n')
7622 n')
7609 \layout Description
7623 \layout Description
7610
7624
7611
7625
7612 \family typewriter
7626 \family typewriter
7613 getoutputerror
7627 getoutputerror
7614 \family default
7628 \family default
7615 - capture (output,error) of a shell commandss
7629 - capture (output,error) of a shell commandss
7616 \layout Standard
7630 \layout Standard
7617
7631
7618
7632
7619 \family typewriter
7633 \family typewriter
7620 sout
7634 sout
7621 \family default
7635 \family default
7622 /
7636 /
7623 \family typewriter
7637 \family typewriter
7624 lout
7638 lout
7625 \family default
7639 \family default
7626 are the functional equivalents of
7640 are the functional equivalents of
7627 \family typewriter
7641 \family typewriter
7628 $
7642 $
7629 \family default
7643 \family default
7630 /
7644 /
7631 \family typewriter
7645 \family typewriter
7632 $$
7646 $$
7633 \family default
7647 \family default
7634 .
7648 .
7635 They are provided to allow you to capture system output in the middle of
7649 They are provided to allow you to capture system output in the middle of
7636 true python code, function definitions, etc (where
7650 true python code, function definitions, etc (where
7637 \family typewriter
7651 \family typewriter
7638 $
7652 $
7639 \family default
7653 \family default
7640 and
7654 and
7641 \family typewriter
7655 \family typewriter
7642 $$
7656 $$
7643 \family default
7657 \family default
7644 are invalid).
7658 are invalid).
7645 \layout Subsection
7659 \layout Subsection
7646
7660
7647 Directory management
7661 Directory management
7648 \layout Standard
7662 \layout Standard
7649
7663
7650 Since each command passed by pysh to the underlying system is executed in
7664 Since each command passed by pysh to the underlying system is executed in
7651 a subshell which exits immediately, you can NOT use !cd to navigate the
7665 a subshell which exits immediately, you can NOT use !cd to navigate the
7652 filesystem.
7666 filesystem.
7653 \layout Standard
7667 \layout Standard
7654
7668
7655 Pysh provides its own builtin
7669 Pysh provides its own builtin
7656 \family typewriter
7670 \family typewriter
7657 `%cd
7671 `%cd
7658 \family default
7672 \family default
7659 ' magic command to move in the filesystem (the
7673 ' magic command to move in the filesystem (the
7660 \family typewriter
7674 \family typewriter
7661 %
7675 %
7662 \family default
7676 \family default
7663 is not required with automagic on).
7677 is not required with automagic on).
7664 It also maintains a list of visited directories (use
7678 It also maintains a list of visited directories (use
7665 \family typewriter
7679 \family typewriter
7666 %dhist
7680 %dhist
7667 \family default
7681 \family default
7668 to see it) and allows direct switching to any of them.
7682 to see it) and allows direct switching to any of them.
7669 Type
7683 Type
7670 \family typewriter
7684 \family typewriter
7671 `cd?
7685 `cd?
7672 \family default
7686 \family default
7673 ' for more details.
7687 ' for more details.
7674 \layout Standard
7688 \layout Standard
7675
7689
7676
7690
7677 \family typewriter
7691 \family typewriter
7678 %pushd
7692 %pushd
7679 \family default
7693 \family default
7680 ,
7694 ,
7681 \family typewriter
7695 \family typewriter
7682 %popd
7696 %popd
7683 \family default
7697 \family default
7684 and
7698 and
7685 \family typewriter
7699 \family typewriter
7686 %dirs
7700 %dirs
7687 \family default
7701 \family default
7688 are provided for directory stack handling.
7702 are provided for directory stack handling.
7689 \layout Subsection
7703 \layout Subsection
7690
7704
7691 Prompt customization
7705 Prompt customization
7692 \layout Standard
7706 \layout Standard
7693
7707
7694 The supplied
7708 The supplied
7695 \family typewriter
7709 \family typewriter
7696 ipythonrc-pysh
7710 ipythonrc-pysh
7697 \family default
7711 \family default
7698 profile comes with an example of a very colored and detailed prompt, mainly
7712 profile comes with an example of a very colored and detailed prompt, mainly
7699 to serve as an illustration.
7713 to serve as an illustration.
7700 The valid escape sequences, besides color names, are:
7714 The valid escape sequences, besides color names, are:
7701 \layout Description
7715 \layout Description
7702
7716
7703
7717
7704 \backslash
7718 \backslash
7705 # - Prompt number.
7719 # - Prompt number.
7706 \layout Description
7720 \layout Description
7707
7721
7708
7722
7709 \backslash
7723 \backslash
7710 D - Dots, as many as there are digits in
7724 D - Dots, as many as there are digits in
7711 \backslash
7725 \backslash
7712 # (so they align).
7726 # (so they align).
7713 \layout Description
7727 \layout Description
7714
7728
7715
7729
7716 \backslash
7730 \backslash
7717 w - Current working directory (cwd).
7731 w - Current working directory (cwd).
7718 \layout Description
7732 \layout Description
7719
7733
7720
7734
7721 \backslash
7735 \backslash
7722 W - Basename of current working directory.
7736 W - Basename of current working directory.
7723 \layout Description
7737 \layout Description
7724
7738
7725
7739
7726 \backslash
7740 \backslash
7727 X
7741 X
7728 \emph on
7742 \emph on
7729 N
7743 N
7730 \emph default
7744 \emph default
7731 - Where
7745 - Where
7732 \emph on
7746 \emph on
7733 N
7747 N
7734 \emph default
7748 \emph default
7735 =0..5.
7749 =0..5.
7736 N terms of the cwd, with $HOME written as ~.
7750 N terms of the cwd, with $HOME written as ~.
7737 \layout Description
7751 \layout Description
7738
7752
7739
7753
7740 \backslash
7754 \backslash
7741 Y
7755 Y
7742 \emph on
7756 \emph on
7743 N
7757 N
7744 \emph default
7758 \emph default
7745 - Where
7759 - Where
7746 \emph on
7760 \emph on
7747 N
7761 N
7748 \emph default
7762 \emph default
7749 =0..5.
7763 =0..5.
7750 Like X
7764 Like X
7751 \emph on
7765 \emph on
7752 N
7766 N
7753 \emph default
7767 \emph default
7754 , but if ~ is term
7768 , but if ~ is term
7755 \emph on
7769 \emph on
7756 N
7770 N
7757 \emph default
7771 \emph default
7758 +1 it's also shown.
7772 +1 it's also shown.
7759 \layout Description
7773 \layout Description
7760
7774
7761
7775
7762 \backslash
7776 \backslash
7763 u - Username.
7777 u - Username.
7764 \layout Description
7778 \layout Description
7765
7779
7766
7780
7767 \backslash
7781 \backslash
7768 H - Full hostname.
7782 H - Full hostname.
7769 \layout Description
7783 \layout Description
7770
7784
7771
7785
7772 \backslash
7786 \backslash
7773 h - Hostname up to first '.'
7787 h - Hostname up to first '.'
7774 \layout Description
7788 \layout Description
7775
7789
7776
7790
7777 \backslash
7791 \backslash
7778 $ - Root symbol ($ or #).
7792 $ - Root symbol ($ or #).
7779
7793
7780 \layout Description
7794 \layout Description
7781
7795
7782
7796
7783 \backslash
7797 \backslash
7784 t - Current time, in H:M:S format.
7798 t - Current time, in H:M:S format.
7785 \layout Description
7799 \layout Description
7786
7800
7787
7801
7788 \backslash
7802 \backslash
7789 v - IPython release version.
7803 v - IPython release version.
7790
7804
7791 \layout Description
7805 \layout Description
7792
7806
7793
7807
7794 \backslash
7808 \backslash
7795 n - Newline.
7809 n - Newline.
7796
7810
7797 \layout Description
7811 \layout Description
7798
7812
7799
7813
7800 \backslash
7814 \backslash
7801 r - Carriage return.
7815 r - Carriage return.
7802
7816
7803 \layout Description
7817 \layout Description
7804
7818
7805
7819
7806 \backslash
7820 \backslash
7807
7821
7808 \backslash
7822 \backslash
7809 - An explicitly escaped '
7823 - An explicitly escaped '
7810 \backslash
7824 \backslash
7811 '.
7825 '.
7812 \layout Standard
7826 \layout Standard
7813
7827
7814 You can configure your prompt colors using any ANSI color escape.
7828 You can configure your prompt colors using any ANSI color escape.
7815 Each color escape sets the color for any subsequent text, until another
7829 Each color escape sets the color for any subsequent text, until another
7816 escape comes in and changes things.
7830 escape comes in and changes things.
7817 The valid color escapes are:
7831 The valid color escapes are:
7818 \layout Description
7832 \layout Description
7819
7833
7820
7834
7821 \backslash
7835 \backslash
7822 C_Black
7836 C_Black
7823 \layout Description
7837 \layout Description
7824
7838
7825
7839
7826 \backslash
7840 \backslash
7827 C_Blue
7841 C_Blue
7828 \layout Description
7842 \layout Description
7829
7843
7830
7844
7831 \backslash
7845 \backslash
7832 C_Brown
7846 C_Brown
7833 \layout Description
7847 \layout Description
7834
7848
7835
7849
7836 \backslash
7850 \backslash
7837 C_Cyan
7851 C_Cyan
7838 \layout Description
7852 \layout Description
7839
7853
7840
7854
7841 \backslash
7855 \backslash
7842 C_DarkGray
7856 C_DarkGray
7843 \layout Description
7857 \layout Description
7844
7858
7845
7859
7846 \backslash
7860 \backslash
7847 C_Green
7861 C_Green
7848 \layout Description
7862 \layout Description
7849
7863
7850
7864
7851 \backslash
7865 \backslash
7852 C_LightBlue
7866 C_LightBlue
7853 \layout Description
7867 \layout Description
7854
7868
7855
7869
7856 \backslash
7870 \backslash
7857 C_LightCyan
7871 C_LightCyan
7858 \layout Description
7872 \layout Description
7859
7873
7860
7874
7861 \backslash
7875 \backslash
7862 C_LightGray
7876 C_LightGray
7863 \layout Description
7877 \layout Description
7864
7878
7865
7879
7866 \backslash
7880 \backslash
7867 C_LightGreen
7881 C_LightGreen
7868 \layout Description
7882 \layout Description
7869
7883
7870
7884
7871 \backslash
7885 \backslash
7872 C_LightPurple
7886 C_LightPurple
7873 \layout Description
7887 \layout Description
7874
7888
7875
7889
7876 \backslash
7890 \backslash
7877 C_LightRed
7891 C_LightRed
7878 \layout Description
7892 \layout Description
7879
7893
7880
7894
7881 \backslash
7895 \backslash
7882 C_Purple
7896 C_Purple
7883 \layout Description
7897 \layout Description
7884
7898
7885
7899
7886 \backslash
7900 \backslash
7887 C_Red
7901 C_Red
7888 \layout Description
7902 \layout Description
7889
7903
7890
7904
7891 \backslash
7905 \backslash
7892 C_White
7906 C_White
7893 \layout Description
7907 \layout Description
7894
7908
7895
7909
7896 \backslash
7910 \backslash
7897 C_Yellow
7911 C_Yellow
7898 \layout Description
7912 \layout Description
7899
7913
7900
7914
7901 \backslash
7915 \backslash
7902 C_Normal Stop coloring, defaults to your terminal settings.
7916 C_Normal Stop coloring, defaults to your terminal settings.
7903 \layout Section
7917 \layout Section
7904
7918
7905
7919
7906 \begin_inset LatexCommand \label{sec:Threading-support}
7920 \begin_inset LatexCommand \label{sec:Threading-support}
7907
7921
7908 \end_inset
7922 \end_inset
7909
7923
7910 Threading support
7924 Threading support
7911 \layout Standard
7925 \layout Standard
7912
7926
7913
7927
7914 \series bold
7928 \series bold
7915 WARNING:
7929 WARNING:
7916 \series default
7930 \series default
7917 The threading support is still somewhat experimental, and it has only seen
7931 The threading support is still somewhat experimental, and it has only seen
7918 reasonable testing under Linux.
7932 reasonable testing under Linux.
7919 Threaded code is particularly tricky to debug, and it tends to show extremely
7933 Threaded code is particularly tricky to debug, and it tends to show extremely
7920 platform-dependent behavior.
7934 platform-dependent behavior.
7921 Since I only have access to Linux machines, I will have to rely on user's
7935 Since I only have access to Linux machines, I will have to rely on user's
7922 experiences and assistance for this area of IPython to improve under other
7936 experiences and assistance for this area of IPython to improve under other
7923 platforms.
7937 platforms.
7924 \layout Standard
7938 \layout Standard
7925
7939
7926 IPython, via the
7940 IPython, via the
7927 \family typewriter
7941 \family typewriter
7928 -gthread
7942 -gthread
7929 \family default
7943 \family default
7930 ,
7944 ,
7931 \family typewriter
7945 \family typewriter
7932 -qthread
7946 -qthread
7933 \family default
7947 \family default
7934 and
7948 and
7935 \family typewriter
7949 \family typewriter
7936 -wthread
7950 -wthread
7937 \family default
7951 \family default
7938 options (described in Sec.\SpecialChar ~
7952 options (described in Sec.\SpecialChar ~
7939
7953
7940 \begin_inset LatexCommand \ref{sec:threading-opts}
7954 \begin_inset LatexCommand \ref{sec:threading-opts}
7941
7955
7942 \end_inset
7956 \end_inset
7943
7957
7944 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7958 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7945 respectively.
7959 respectively.
7946 These GUI toolkits need to control the python main loop of execution, so
7960 These GUI toolkits need to control the python main loop of execution, so
7947 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7961 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7948 will immediately freeze the shell.
7962 will immediately freeze the shell.
7949
7963
7950 \layout Standard
7964 \layout Standard
7951
7965
7952 IPython, with one of these options (you can only use one at a time), separates
7966 IPython, with one of these options (you can only use one at a time), separates
7953 the graphical loop and IPython's code execution run into different threads.
7967 the graphical loop and IPython's code execution run into different threads.
7954 This allows you to test interactively (with
7968 This allows you to test interactively (with
7955 \family typewriter
7969 \family typewriter
7956 %run
7970 %run
7957 \family default
7971 \family default
7958 , for example) your GUI code without blocking.
7972 , for example) your GUI code without blocking.
7959 \layout Standard
7973 \layout Standard
7960
7974
7961 A nice mini-tutorial on using IPython along with the Qt Designer application
7975 A nice mini-tutorial on using IPython along with the Qt Designer application
7962 is available at the SciPy wiki:
7976 is available at the SciPy wiki:
7963 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7977 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7964
7978
7965 \end_inset
7979 \end_inset
7966
7980
7967 .
7981 .
7968 \layout Subsection
7982 \layout Subsection
7969
7983
7970 Tk issues
7984 Tk issues
7971 \layout Standard
7985 \layout Standard
7972
7986
7973 As indicated in Sec.\SpecialChar ~
7987 As indicated in Sec.\SpecialChar ~
7974
7988
7975 \begin_inset LatexCommand \ref{sec:threading-opts}
7989 \begin_inset LatexCommand \ref{sec:threading-opts}
7976
7990
7977 \end_inset
7991 \end_inset
7978
7992
7979 , a special
7993 , a special
7980 \family typewriter
7994 \family typewriter
7981 -tk
7995 -tk
7982 \family default
7996 \family default
7983 option is provided to try and allow Tk graphical applications to coexist
7997 option is provided to try and allow Tk graphical applications to coexist
7984 interactively with WX, Qt or GTK ones.
7998 interactively with WX, Qt or GTK ones.
7985 Whether this works at all, however, is very platform and configuration
7999 Whether this works at all, however, is very platform and configuration
7986 dependent.
8000 dependent.
7987 Please experiment with simple test cases before committing to using this
8001 Please experiment with simple test cases before committing to using this
7988 combination of Tk and GTK/Qt/WX threading in a production environment.
8002 combination of Tk and GTK/Qt/WX threading in a production environment.
7989 \layout Subsection
8003 \layout Subsection
7990
8004
7991 Signals and Threads
8005 Signals and Threads
7992 \layout Standard
8006 \layout Standard
7993
8007
7994 When any of the thread systems (GTK, Qt or WX) are active, either directly
8008 When any of the thread systems (GTK, Qt or WX) are active, either directly
7995 or via
8009 or via
7996 \family typewriter
8010 \family typewriter
7997 -pylab
8011 -pylab
7998 \family default
8012 \family default
7999 with a threaded backend, it is impossible to interrupt long-running Python
8013 with a threaded backend, it is impossible to interrupt long-running Python
8000 code via
8014 code via
8001 \family typewriter
8015 \family typewriter
8002 Ctrl-C
8016 Ctrl-C
8003 \family default
8017 \family default
8004 .
8018 .
8005 IPython can not pass the KeyboardInterrupt exception (or the underlying
8019 IPython can not pass the KeyboardInterrupt exception (or the underlying
8006
8020
8007 \family typewriter
8021 \family typewriter
8008 SIGINT
8022 SIGINT
8009 \family default
8023 \family default
8010 ) across threads, so any long-running process started from IPython will
8024 ) across threads, so any long-running process started from IPython will
8011 run to completion, or will have to be killed via an external (OS-based)
8025 run to completion, or will have to be killed via an external (OS-based)
8012 mechanism.
8026 mechanism.
8013 \layout Standard
8027 \layout Standard
8014
8028
8015 To the best of my knowledge, this limitation is imposed by the Python interprete
8029 To the best of my knowledge, this limitation is imposed by the Python interprete
8016 r itself, and it comes from the difficulty of writing portable signal/threaded
8030 r itself, and it comes from the difficulty of writing portable signal/threaded
8017 code.
8031 code.
8018 If any user is an expert on this topic and can suggest a better solution,
8032 If any user is an expert on this topic and can suggest a better solution,
8019 I would love to hear about it.
8033 I would love to hear about it.
8020 In the IPython sources, look at the
8034 In the IPython sources, look at the
8021 \family typewriter
8035 \family typewriter
8022 Shell.py
8036 Shell.py
8023 \family default
8037 \family default
8024 module, and in particular at the
8038 module, and in particular at the
8025 \family typewriter
8039 \family typewriter
8026 runcode()
8040 runcode()
8027 \family default
8041 \family default
8028 method.
8042 method.
8029
8043
8030 \layout Subsection
8044 \layout Subsection
8031
8045
8032 I/O pitfalls
8046 I/O pitfalls
8033 \layout Standard
8047 \layout Standard
8034
8048
8035 Be mindful that the Python interpreter switches between threads every
8049 Be mindful that the Python interpreter switches between threads every
8036 \begin_inset Formula $N$
8050 \begin_inset Formula $N$
8037 \end_inset
8051 \end_inset
8038
8052
8039 bytecodes, where the default value as of Python\SpecialChar ~
8053 bytecodes, where the default value as of Python\SpecialChar ~
8040 2.3 is
8054 2.3 is
8041 \begin_inset Formula $N=100.$
8055 \begin_inset Formula $N=100.$
8042 \end_inset
8056 \end_inset
8043
8057
8044 This value can be read by using the
8058 This value can be read by using the
8045 \family typewriter
8059 \family typewriter
8046 sys.getcheckinterval()
8060 sys.getcheckinterval()
8047 \family default
8061 \family default
8048 function, and it can be reset via
8062 function, and it can be reset via
8049 \family typewriter
8063 \family typewriter
8050 sys.setcheckinterval(
8064 sys.setcheckinterval(
8051 \emph on
8065 \emph on
8052 N
8066 N
8053 \emph default
8067 \emph default
8054 )
8068 )
8055 \family default
8069 \family default
8056 .
8070 .
8057 This switching of threads can cause subtly confusing effects if one of
8071 This switching of threads can cause subtly confusing effects if one of
8058 your threads is doing file I/O.
8072 your threads is doing file I/O.
8059 In text mode, most systems only flush file buffers when they encounter
8073 In text mode, most systems only flush file buffers when they encounter
8060 a
8074 a
8061 \family typewriter
8075 \family typewriter
8062 `
8076 `
8063 \backslash
8077 \backslash
8064 n'
8078 n'
8065 \family default
8079 \family default
8066 .
8080 .
8067 An instruction as simple as
8081 An instruction as simple as
8068 \family typewriter
8082 \family typewriter
8069
8083
8070 \newline
8084 \newline
8071 \SpecialChar ~
8085 \SpecialChar ~
8072 \SpecialChar ~
8086 \SpecialChar ~
8073 print >> filehandle,
8087 print >> filehandle,
8074 \begin_inset Quotes eld
8088 \begin_inset Quotes eld
8075 \end_inset
8089 \end_inset
8076
8090
8077 hello world
8091 hello world
8078 \begin_inset Quotes erd
8092 \begin_inset Quotes erd
8079 \end_inset
8093 \end_inset
8080
8094
8081
8095
8082 \family default
8096 \family default
8083
8097
8084 \newline
8098 \newline
8085 actually consists of several bytecodes, so it is possible that the newline
8099 actually consists of several bytecodes, so it is possible that the newline
8086 does not reach your file before the next thread switch.
8100 does not reach your file before the next thread switch.
8087 Similarly, if you are writing to a file in binary mode, the file won't
8101 Similarly, if you are writing to a file in binary mode, the file won't
8088 be flushed until the buffer fills, and your other thread may see apparently
8102 be flushed until the buffer fills, and your other thread may see apparently
8089 truncated files.
8103 truncated files.
8090
8104
8091 \layout Standard
8105 \layout Standard
8092
8106
8093 For this reason, if you are using IPython's thread support and have (for
8107 For this reason, if you are using IPython's thread support and have (for
8094 example) a GUI application which will read data generated by files written
8108 example) a GUI application which will read data generated by files written
8095 to from the IPython thread, the safest approach is to open all of your
8109 to from the IPython thread, the safest approach is to open all of your
8096 files in unbuffered mode (the third argument to the
8110 files in unbuffered mode (the third argument to the
8097 \family typewriter
8111 \family typewriter
8098 file/open
8112 file/open
8099 \family default
8113 \family default
8100 function is the buffering value):
8114 function is the buffering value):
8101 \newline
8115 \newline
8102
8116
8103 \family typewriter
8117 \family typewriter
8104 \SpecialChar ~
8118 \SpecialChar ~
8105 \SpecialChar ~
8119 \SpecialChar ~
8106 filehandle = open(filename,mode,0)
8120 filehandle = open(filename,mode,0)
8107 \layout Standard
8121 \layout Standard
8108
8122
8109 This is obviously a brute force way of avoiding race conditions with the
8123 This is obviously a brute force way of avoiding race conditions with the
8110 file buffering.
8124 file buffering.
8111 If you want to do it cleanly, and you have a resource which is being shared
8125 If you want to do it cleanly, and you have a resource which is being shared
8112 by the interactive IPython loop and your GUI thread, you should really
8126 by the interactive IPython loop and your GUI thread, you should really
8113 handle it with thread locking and syncrhonization properties.
8127 handle it with thread locking and syncrhonization properties.
8114 The Python documentation discusses these.
8128 The Python documentation discusses these.
8115 \layout Section
8129 \layout Section
8116
8130
8117
8131
8118 \begin_inset LatexCommand \label{sec:interactive-demos}
8132 \begin_inset LatexCommand \label{sec:interactive-demos}
8119
8133
8120 \end_inset
8134 \end_inset
8121
8135
8122 Interactive demos with IPython
8136 Interactive demos with IPython
8123 \layout Standard
8137 \layout Standard
8124
8138
8125 IPython ships with a basic system for running scripts interactively in sections,
8139 IPython ships with a basic system for running scripts interactively in sections,
8126 useful when presenting code to audiences.
8140 useful when presenting code to audiences.
8127 A few tags embedded in comments (so that the script remains valid Python
8141 A few tags embedded in comments (so that the script remains valid Python
8128 code) divide a file into separate blocks, and the demo can be run one block
8142 code) divide a file into separate blocks, and the demo can be run one block
8129 at a time, with IPython printing (with syntax highlighting) the block before
8143 at a time, with IPython printing (with syntax highlighting) the block before
8130 executing it, and returning to the interactive prompt after each block.
8144 executing it, and returning to the interactive prompt after each block.
8131 The interactive namespace is updated after each block is run with the contents
8145 The interactive namespace is updated after each block is run with the contents
8132 of the demo's namespace.
8146 of the demo's namespace.
8133 \layout Standard
8147 \layout Standard
8134
8148
8135 This allows you to show a piece of code, run it and then execute interactively
8149 This allows you to show a piece of code, run it and then execute interactively
8136 commands based on the variables just created.
8150 commands based on the variables just created.
8137 Once you want to continue, you simply execute the next block of the demo.
8151 Once you want to continue, you simply execute the next block of the demo.
8138 The following listing shows the markup necessary for dividing a script
8152 The following listing shows the markup necessary for dividing a script
8139 into sections for execution as a demo.
8153 into sections for execution as a demo.
8140 \layout Standard
8154 \layout Standard
8141
8155
8142
8156
8143 \begin_inset ERT
8157 \begin_inset ERT
8144 status Open
8158 status Open
8145
8159
8146 \layout Standard
8160 \layout Standard
8147
8161
8148 \backslash
8162 \backslash
8149 codelist{examples/example-demo.py}
8163 codelist{examples/example-demo.py}
8150 \end_inset
8164 \end_inset
8151
8165
8152
8166
8153 \layout Standard
8167 \layout Standard
8154
8168
8155 In order to run a file as a demo, you must first make a
8169 In order to run a file as a demo, you must first make a
8156 \family typewriter
8170 \family typewriter
8157 Demo
8171 Demo
8158 \family default
8172 \family default
8159 object out of it.
8173 object out of it.
8160 If the file is named
8174 If the file is named
8161 \family typewriter
8175 \family typewriter
8162 myscript.py
8176 myscript.py
8163 \family default
8177 \family default
8164 , the following code will make a demo:
8178 , the following code will make a demo:
8165 \layout LyX-Code
8179 \layout LyX-Code
8166
8180
8167 from IPython.demo import Demo
8181 from IPython.demo import Demo
8168 \layout LyX-Code
8182 \layout LyX-Code
8169
8183
8170 mydemo = Demo('myscript.py')
8184 mydemo = Demo('myscript.py')
8171 \layout Standard
8185 \layout Standard
8172
8186
8173 This creates the
8187 This creates the
8174 \family typewriter
8188 \family typewriter
8175 mydemo
8189 mydemo
8176 \family default
8190 \family default
8177 object, whose blocks you run one at a time by simply calling the object
8191 object, whose blocks you run one at a time by simply calling the object
8178 with no arguments.
8192 with no arguments.
8179 If you have autocall active in IPython (the default), all you need to do
8193 If you have autocall active in IPython (the default), all you need to do
8180 is type
8194 is type
8181 \layout LyX-Code
8195 \layout LyX-Code
8182
8196
8183 mydemo
8197 mydemo
8184 \layout Standard
8198 \layout Standard
8185
8199
8186 and IPython will call it, executing each block.
8200 and IPython will call it, executing each block.
8187 Demo objects can be restarted, you can move forward or back skipping blocks,
8201 Demo objects can be restarted, you can move forward or back skipping blocks,
8188 re-execute the last block, etc.
8202 re-execute the last block, etc.
8189 Simply use the Tab key on a demo object to see its methods, and call
8203 Simply use the Tab key on a demo object to see its methods, and call
8190 \family typewriter
8204 \family typewriter
8191 `?'
8205 `?'
8192 \family default
8206 \family default
8193 on them to see their docstrings for more usage details.
8207 on them to see their docstrings for more usage details.
8194 In addition, the
8208 In addition, the
8195 \family typewriter
8209 \family typewriter
8196 demo
8210 demo
8197 \family default
8211 \family default
8198 module itself contains a comprehensive docstring, which you can access
8212 module itself contains a comprehensive docstring, which you can access
8199 via
8213 via
8200 \layout LyX-Code
8214 \layout LyX-Code
8201
8215
8202 from IPython import demo
8216 from IPython import demo
8203 \layout LyX-Code
8217 \layout LyX-Code
8204
8218
8205 demo?
8219 demo?
8206 \layout Standard
8220 \layout Standard
8207
8221
8208
8222
8209 \series bold
8223 \series bold
8210 Limitations:
8224 Limitations:
8211 \series default
8225 \series default
8212 It is important to note that these demos are limited to fairly simple uses.
8226 It is important to note that these demos are limited to fairly simple uses.
8213 In particular, you can
8227 In particular, you can
8214 \emph on
8228 \emph on
8215 not
8229 not
8216 \emph default
8230 \emph default
8217 put division marks in indented code (loops, if statements, function definitions
8231 put division marks in indented code (loops, if statements, function definitions
8218 , etc.) Supporting something like this would basically require tracking the
8232 , etc.) Supporting something like this would basically require tracking the
8219 internal execution state of the Python interpreter, so only top-level divisions
8233 internal execution state of the Python interpreter, so only top-level divisions
8220 are allowed.
8234 are allowed.
8221 If you want to be able to open an IPython instance at an arbitrary point
8235 If you want to be able to open an IPython instance at an arbitrary point
8222 in a program, you can use IPython's embedding facilities, described in
8236 in a program, you can use IPython's embedding facilities, described in
8223 detail in Sec\SpecialChar \@.
8237 detail in Sec\SpecialChar \@.
8224 \SpecialChar ~
8238 \SpecialChar ~
8225
8239
8226 \begin_inset LatexCommand \ref{sec:embed}
8240 \begin_inset LatexCommand \ref{sec:embed}
8227
8241
8228 \end_inset
8242 \end_inset
8229
8243
8230 .
8244 .
8231 \layout Section
8245 \layout Section
8232
8246
8233
8247
8234 \begin_inset LatexCommand \label{sec:matplotlib-support}
8248 \begin_inset LatexCommand \label{sec:matplotlib-support}
8235
8249
8236 \end_inset
8250 \end_inset
8237
8251
8238 Plotting with
8252 Plotting with
8239 \family typewriter
8253 \family typewriter
8240 matplotlib
8254 matplotlib
8241 \family default
8255 \family default
8242
8256
8243 \layout Standard
8257 \layout Standard
8244
8258
8245 The matplotlib library (
8259 The matplotlib library (
8246 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
8260 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
8247
8261
8248 \end_inset
8262 \end_inset
8249
8263
8250 ) provides high quality 2D plotting for Python.
8264 ) provides high quality 2D plotting for Python.
8251 Matplotlib can produce plots on screen using a variety of GUI toolkits,
8265 Matplotlib can produce plots on screen using a variety of GUI toolkits,
8252 including Tk, GTK and WXPython.
8266 including Tk, GTK and WXPython.
8253 It also provides a number of commands useful for scientific computing,
8267 It also provides a number of commands useful for scientific computing,
8254 all with a syntax compatible with that of the popular Matlab program.
8268 all with a syntax compatible with that of the popular Matlab program.
8255 \layout Standard
8269 \layout Standard
8256
8270
8257 IPython accepts the special option
8271 IPython accepts the special option
8258 \family typewriter
8272 \family typewriter
8259 -pylab
8273 -pylab
8260 \family default
8274 \family default
8261 (Sec.\SpecialChar ~
8275 (Sec.\SpecialChar ~
8262
8276
8263 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
8277 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
8264
8278
8265 \end_inset
8279 \end_inset
8266
8280
8267 ).
8281 ).
8268 This configures it to support matplotlib, honoring the settings in the
8282 This configures it to support matplotlib, honoring the settings in the
8269
8283
8270 \family typewriter
8284 \family typewriter
8271 .matplotlibrc
8285 .matplotlibrc
8272 \family default
8286 \family default
8273 file.
8287 file.
8274 IPython will detect the user's choice of matplotlib GUI backend, and automatica
8288 IPython will detect the user's choice of matplotlib GUI backend, and automatica
8275 lly select the proper threading model to prevent blocking.
8289 lly select the proper threading model to prevent blocking.
8276 It also sets matplotlib in interactive mode and modifies
8290 It also sets matplotlib in interactive mode and modifies
8277 \family typewriter
8291 \family typewriter
8278 %run
8292 %run
8279 \family default
8293 \family default
8280 slightly, so that any matplotlib-based script can be executed using
8294 slightly, so that any matplotlib-based script can be executed using
8281 \family typewriter
8295 \family typewriter
8282 %run
8296 %run
8283 \family default
8297 \family default
8284 and the final
8298 and the final
8285 \family typewriter
8299 \family typewriter
8286 show()
8300 show()
8287 \family default
8301 \family default
8288 command does not block the interactive shell.
8302 command does not block the interactive shell.
8289 \layout Standard
8303 \layout Standard
8290
8304
8291 The
8305 The
8292 \family typewriter
8306 \family typewriter
8293 -pylab
8307 -pylab
8294 \family default
8308 \family default
8295 option must be given first in order for IPython to configure its threading
8309 option must be given first in order for IPython to configure its threading
8296 mode.
8310 mode.
8297 However, you can still issue other options afterwards.
8311 However, you can still issue other options afterwards.
8298 This allows you to have a matplotlib-based environment customized with
8312 This allows you to have a matplotlib-based environment customized with
8299 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
8313 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
8300
8314
8301 \begin_inset LatexCommand \ref{sec:profiles}
8315 \begin_inset LatexCommand \ref{sec:profiles}
8302
8316
8303 \end_inset
8317 \end_inset
8304
8318
8305 ): ``
8319 ): ``
8306 \family typewriter
8320 \family typewriter
8307 ipython -pylab -p myprofile
8321 ipython -pylab -p myprofile
8308 \family default
8322 \family default
8309 '' will load the profile defined in
8323 '' will load the profile defined in
8310 \family typewriter
8324 \family typewriter
8311 ipythonrc-myprofile
8325 ipythonrc-myprofile
8312 \family default
8326 \family default
8313 after configuring matplotlib.
8327 after configuring matplotlib.
8314 \layout Section
8328 \layout Section
8315
8329
8316
8330
8317 \begin_inset LatexCommand \label{sec:Gnuplot}
8331 \begin_inset LatexCommand \label{sec:Gnuplot}
8318
8332
8319 \end_inset
8333 \end_inset
8320
8334
8321 Plotting with
8335 Plotting with
8322 \family typewriter
8336 \family typewriter
8323 Gnuplot
8337 Gnuplot
8324 \layout Standard
8338 \layout Standard
8325
8339
8326 Through the magic extension system described in sec.
8340 Through the magic extension system described in sec.
8327
8341
8328 \begin_inset LatexCommand \ref{sec:magic}
8342 \begin_inset LatexCommand \ref{sec:magic}
8329
8343
8330 \end_inset
8344 \end_inset
8331
8345
8332 , IPython incorporates a mechanism for conveniently interfacing with the
8346 , IPython incorporates a mechanism for conveniently interfacing with the
8333 Gnuplot system (
8347 Gnuplot system (
8334 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8348 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8335
8349
8336 \end_inset
8350 \end_inset
8337
8351
8338 ).
8352 ).
8339 Gnuplot is a very complete 2D and 3D plotting package available for many
8353 Gnuplot is a very complete 2D and 3D plotting package available for many
8340 operating systems and commonly included in modern Linux distributions.
8354 operating systems and commonly included in modern Linux distributions.
8341
8355
8342 \layout Standard
8356 \layout Standard
8343
8357
8344 Besides having Gnuplot installed, this functionality requires the
8358 Besides having Gnuplot installed, this functionality requires the
8345 \family typewriter
8359 \family typewriter
8346 Gnuplot.py
8360 Gnuplot.py
8347 \family default
8361 \family default
8348 module for interfacing python with Gnuplot.
8362 module for interfacing python with Gnuplot.
8349 It can be downloaded from:
8363 It can be downloaded from:
8350 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8364 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8351
8365
8352 \end_inset
8366 \end_inset
8353
8367
8354 .
8368 .
8355 \layout Subsection
8369 \layout Subsection
8356
8370
8357 Proper Gnuplot configuration
8371 Proper Gnuplot configuration
8358 \layout Standard
8372 \layout Standard
8359
8373
8360 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8374 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8361 However, as of
8375 However, as of
8362 \family typewriter
8376 \family typewriter
8363 Gnuplot.py
8377 Gnuplot.py
8364 \family default
8378 \family default
8365 version 1.7, a new option was added to communicate between Python and Gnuplot
8379 version 1.7, a new option was added to communicate between Python and Gnuplot
8366 via FIFOs (pipes).
8380 via FIFOs (pipes).
8367 This mechanism, while fast, also breaks the mouse system.
8381 This mechanism, while fast, also breaks the mouse system.
8368 You must therefore set the variable
8382 You must therefore set the variable
8369 \family typewriter
8383 \family typewriter
8370 prefer_fifo_data
8384 prefer_fifo_data
8371 \family default
8385 \family default
8372 to
8386 to
8373 \family typewriter
8387 \family typewriter
8374 0
8388 0
8375 \family default
8389 \family default
8376 in file
8390 in file
8377 \family typewriter
8391 \family typewriter
8378 gp_unix.py
8392 gp_unix.py
8379 \family default
8393 \family default
8380 if you wish to keep the interactive mouse and keyboard features working
8394 if you wish to keep the interactive mouse and keyboard features working
8381 properly (
8395 properly (
8382 \family typewriter
8396 \family typewriter
8383 prefer_inline_data
8397 prefer_inline_data
8384 \family default
8398 \family default
8385 also must be
8399 also must be
8386 \family typewriter
8400 \family typewriter
8387 0
8401 0
8388 \family default
8402 \family default
8389 , but this is the default so unless you've changed it manually you should
8403 , but this is the default so unless you've changed it manually you should
8390 be fine).
8404 be fine).
8391 \layout Standard
8405 \layout Standard
8392
8406
8393 'Out of the box', Gnuplot is configured with a rather poor set of size,
8407 'Out of the box', Gnuplot is configured with a rather poor set of size,
8394 color and linewidth choices which make the graphs fairly hard to read on
8408 color and linewidth choices which make the graphs fairly hard to read on
8395 modern high-resolution displays (although they work fine on old 640x480
8409 modern high-resolution displays (although they work fine on old 640x480
8396 ones).
8410 ones).
8397 Below is a section of my
8411 Below is a section of my
8398 \family typewriter
8412 \family typewriter
8399 .Xdefaults
8413 .Xdefaults
8400 \family default
8414 \family default
8401 file which I use for having a more convenient Gnuplot setup.
8415 file which I use for having a more convenient Gnuplot setup.
8402 Remember to load it by running
8416 Remember to load it by running
8403 \family typewriter
8417 \family typewriter
8404 `xrdb .Xdefaults`
8418 `xrdb .Xdefaults`
8405 \family default
8419 \family default
8406 :
8420 :
8407 \layout Standard
8421 \layout Standard
8408
8422
8409
8423
8410 \family typewriter
8424 \family typewriter
8411 !******************************************************************
8425 !******************************************************************
8412 \newline
8426 \newline
8413 ! gnuplot options
8427 ! gnuplot options
8414 \newline
8428 \newline
8415 ! modify this for a convenient window size
8429 ! modify this for a convenient window size
8416 \newline
8430 \newline
8417 gnuplot*geometry: 780x580
8431 gnuplot*geometry: 780x580
8418 \layout Standard
8432 \layout Standard
8419
8433
8420
8434
8421 \family typewriter
8435 \family typewriter
8422 ! on-screen font (not for PostScript)
8436 ! on-screen font (not for PostScript)
8423 \newline
8437 \newline
8424 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8438 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8425 \layout Standard
8439 \layout Standard
8426
8440
8427
8441
8428 \family typewriter
8442 \family typewriter
8429 ! color options
8443 ! color options
8430 \newline
8444 \newline
8431 gnuplot*background: black
8445 gnuplot*background: black
8432 \newline
8446 \newline
8433 gnuplot*textColor: white
8447 gnuplot*textColor: white
8434 \newline
8448 \newline
8435 gnuplot*borderColor: white
8449 gnuplot*borderColor: white
8436 \newline
8450 \newline
8437 gnuplot*axisColor: white
8451 gnuplot*axisColor: white
8438 \newline
8452 \newline
8439 gnuplot*line1Color: red
8453 gnuplot*line1Color: red
8440 \newline
8454 \newline
8441 gnuplot*line2Color: green
8455 gnuplot*line2Color: green
8442 \newline
8456 \newline
8443 gnuplot*line3Color: blue
8457 gnuplot*line3Color: blue
8444 \newline
8458 \newline
8445 gnuplot*line4Color: magenta
8459 gnuplot*line4Color: magenta
8446 \newline
8460 \newline
8447 gnuplot*line5Color: cyan
8461 gnuplot*line5Color: cyan
8448 \newline
8462 \newline
8449 gnuplot*line6Color: sienna
8463 gnuplot*line6Color: sienna
8450 \newline
8464 \newline
8451 gnuplot*line7Color: orange
8465 gnuplot*line7Color: orange
8452 \newline
8466 \newline
8453 gnuplot*line8Color: coral
8467 gnuplot*line8Color: coral
8454 \layout Standard
8468 \layout Standard
8455
8469
8456
8470
8457 \family typewriter
8471 \family typewriter
8458 ! multiplicative factor for point styles
8472 ! multiplicative factor for point styles
8459 \newline
8473 \newline
8460 gnuplot*pointsize: 2
8474 gnuplot*pointsize: 2
8461 \layout Standard
8475 \layout Standard
8462
8476
8463
8477
8464 \family typewriter
8478 \family typewriter
8465 ! line width options (in pixels)
8479 ! line width options (in pixels)
8466 \newline
8480 \newline
8467 gnuplot*borderWidth: 2
8481 gnuplot*borderWidth: 2
8468 \newline
8482 \newline
8469 gnuplot*axisWidth: 2
8483 gnuplot*axisWidth: 2
8470 \newline
8484 \newline
8471 gnuplot*line1Width: 2
8485 gnuplot*line1Width: 2
8472 \newline
8486 \newline
8473 gnuplot*line2Width: 2
8487 gnuplot*line2Width: 2
8474 \newline
8488 \newline
8475 gnuplot*line3Width: 2
8489 gnuplot*line3Width: 2
8476 \newline
8490 \newline
8477 gnuplot*line4Width: 2
8491 gnuplot*line4Width: 2
8478 \newline
8492 \newline
8479 gnuplot*line5Width: 2
8493 gnuplot*line5Width: 2
8480 \newline
8494 \newline
8481 gnuplot*line6Width: 2
8495 gnuplot*line6Width: 2
8482 \newline
8496 \newline
8483 gnuplot*line7Width: 2
8497 gnuplot*line7Width: 2
8484 \newline
8498 \newline
8485 gnuplot*line8Width: 2
8499 gnuplot*line8Width: 2
8486 \layout Subsection
8500 \layout Subsection
8487
8501
8488 The
8502 The
8489 \family typewriter
8503 \family typewriter
8490 IPython.GnuplotRuntime
8504 IPython.GnuplotRuntime
8491 \family default
8505 \family default
8492 module
8506 module
8493 \layout Standard
8507 \layout Standard
8494
8508
8495 IPython includes a module called
8509 IPython includes a module called
8496 \family typewriter
8510 \family typewriter
8497 Gnuplot2.py
8511 Gnuplot2.py
8498 \family default
8512 \family default
8499 which extends and improves the default
8513 which extends and improves the default
8500 \family typewriter
8514 \family typewriter
8501 Gnuplot
8515 Gnuplot
8502 \family default
8516 \family default
8503 .
8517 .
8504 \family typewriter
8518 \family typewriter
8505 py
8519 py
8506 \family default
8520 \family default
8507 (which it still relies upon).
8521 (which it still relies upon).
8508 For example, the new
8522 For example, the new
8509 \family typewriter
8523 \family typewriter
8510 plot
8524 plot
8511 \family default
8525 \family default
8512 function adds several improvements to the original making it more convenient
8526 function adds several improvements to the original making it more convenient
8513 for interactive use, and
8527 for interactive use, and
8514 \family typewriter
8528 \family typewriter
8515 hardcopy
8529 hardcopy
8516 \family default
8530 \family default
8517 fixes a bug in the original which under some circumstances blocks the creation
8531 fixes a bug in the original which under some circumstances blocks the creation
8518 of PostScript output.
8532 of PostScript output.
8519 \layout Standard
8533 \layout Standard
8520
8534
8521 For scripting use,
8535 For scripting use,
8522 \family typewriter
8536 \family typewriter
8523 GnuplotRuntime.py
8537 GnuplotRuntime.py
8524 \family default
8538 \family default
8525 is provided, which wraps
8539 is provided, which wraps
8526 \family typewriter
8540 \family typewriter
8527 Gnuplot2.py
8541 Gnuplot2.py
8528 \family default
8542 \family default
8529 and creates a series of global aliases.
8543 and creates a series of global aliases.
8530 These make it easy to control Gnuplot plotting jobs through the Python
8544 These make it easy to control Gnuplot plotting jobs through the Python
8531 language.
8545 language.
8532 \layout Standard
8546 \layout Standard
8533
8547
8534 Below is some example code which illustrates how to configure Gnuplot inside
8548 Below is some example code which illustrates how to configure Gnuplot inside
8535 your own programs but have it available for further interactive use through
8549 your own programs but have it available for further interactive use through
8536 an embedded IPython instance.
8550 an embedded IPython instance.
8537 Simply run this file at a system prompt.
8551 Simply run this file at a system prompt.
8538 This file is provided as
8552 This file is provided as
8539 \family typewriter
8553 \family typewriter
8540 example-gnuplot.py
8554 example-gnuplot.py
8541 \family default
8555 \family default
8542 in the examples directory:
8556 in the examples directory:
8543 \layout Standard
8557 \layout Standard
8544
8558
8545
8559
8546 \begin_inset ERT
8560 \begin_inset ERT
8547 status Open
8561 status Open
8548
8562
8549 \layout Standard
8563 \layout Standard
8550
8564
8551 \backslash
8565 \backslash
8552 codelist{examples/example-gnuplot.py}
8566 codelist{examples/example-gnuplot.py}
8553 \end_inset
8567 \end_inset
8554
8568
8555
8569
8556 \layout Subsection
8570 \layout Subsection
8557
8571
8558 The
8572 The
8559 \family typewriter
8573 \family typewriter
8560 numeric
8574 numeric
8561 \family default
8575 \family default
8562 profile: a scientific computing environment
8576 profile: a scientific computing environment
8563 \layout Standard
8577 \layout Standard
8564
8578
8565 The
8579 The
8566 \family typewriter
8580 \family typewriter
8567 numeric
8581 numeric
8568 \family default
8582 \family default
8569 IPython profile, which you can activate with
8583 IPython profile, which you can activate with
8570 \family typewriter
8584 \family typewriter
8571 `ipython -p numeric
8585 `ipython -p numeric
8572 \family default
8586 \family default
8573 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8587 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8574 other useful things for numerical computing), contained in the
8588 other useful things for numerical computing), contained in the
8575 \family typewriter
8589 \family typewriter
8576 IPython.GnuplotInteractive
8590 IPython.GnuplotInteractive
8577 \family default
8591 \family default
8578 module.
8592 module.
8579 This will create the globals
8593 This will create the globals
8580 \family typewriter
8594 \family typewriter
8581 Gnuplot
8595 Gnuplot
8582 \family default
8596 \family default
8583 (an alias to the improved Gnuplot2 module),
8597 (an alias to the improved Gnuplot2 module),
8584 \family typewriter
8598 \family typewriter
8585 gp
8599 gp
8586 \family default
8600 \family default
8587 (a Gnuplot active instance), the new magic commands
8601 (a Gnuplot active instance), the new magic commands
8588 \family typewriter
8602 \family typewriter
8589 %gpc
8603 %gpc
8590 \family default
8604 \family default
8591 and
8605 and
8592 \family typewriter
8606 \family typewriter
8593 %gp_set_instance
8607 %gp_set_instance
8594 \family default
8608 \family default
8595 and several other convenient globals.
8609 and several other convenient globals.
8596 Type
8610 Type
8597 \family typewriter
8611 \family typewriter
8598 gphelp()
8612 gphelp()
8599 \family default
8613 \family default
8600 for further details.
8614 for further details.
8601 \layout Standard
8615 \layout Standard
8602
8616
8603 This should turn IPython into a convenient environment for numerical computing,
8617 This should turn IPython into a convenient environment for numerical computing,
8604 with all the functions in the NumPy library and the Gnuplot facilities
8618 with all the functions in the NumPy library and the Gnuplot facilities
8605 for plotting.
8619 for plotting.
8606 Further improvements can be obtained by loading the SciPy libraries for
8620 Further improvements can be obtained by loading the SciPy libraries for
8607 scientific computing, available at
8621 scientific computing, available at
8608 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8622 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8609
8623
8610 \end_inset
8624 \end_inset
8611
8625
8612 .
8626 .
8613 \layout Standard
8627 \layout Standard
8614
8628
8615 If you are in the middle of a working session with numerical objects and
8629 If you are in the middle of a working session with numerical objects and
8616 need to plot them but you didn't start the
8630 need to plot them but you didn't start the
8617 \family typewriter
8631 \family typewriter
8618 numeric
8632 numeric
8619 \family default
8633 \family default
8620 profile, you can load these extensions at any time by typing
8634 profile, you can load these extensions at any time by typing
8621 \newline
8635 \newline
8622
8636
8623 \family typewriter
8637 \family typewriter
8624 from IPython.GnuplotInteractive import *
8638 from IPython.GnuplotInteractive import *
8625 \newline
8639 \newline
8626
8640
8627 \family default
8641 \family default
8628 at the IPython prompt.
8642 at the IPython prompt.
8629 This will allow you to keep your objects intact and start using Gnuplot
8643 This will allow you to keep your objects intact and start using Gnuplot
8630 to view them.
8644 to view them.
8631 \layout Section
8645 \layout Section
8632
8646
8633 Reporting bugs
8647 Reporting bugs
8634 \layout Subsection*
8648 \layout Subsection*
8635
8649
8636 Automatic crash reports
8650 Automatic crash reports
8637 \layout Standard
8651 \layout Standard
8638
8652
8639 Ideally, IPython itself shouldn't crash.
8653 Ideally, IPython itself shouldn't crash.
8640 It will catch exceptions produced by you, but bugs in its internals will
8654 It will catch exceptions produced by you, but bugs in its internals will
8641 still crash it.
8655 still crash it.
8642 \layout Standard
8656 \layout Standard
8643
8657
8644 In such a situation, IPython will leave a file named
8658 In such a situation, IPython will leave a file named
8645 \family typewriter
8659 \family typewriter
8646 IPython_crash_report.txt
8660 IPython_crash_report.txt
8647 \family default
8661 \family default
8648 in your IPYTHONDIR directory (that way if crashes happen several times
8662 in your IPYTHONDIR directory (that way if crashes happen several times
8649 it won't litter many directories, the post-mortem file is always located
8663 it won't litter many directories, the post-mortem file is always located
8650 in the same place and new occurrences just overwrite the previous one).
8664 in the same place and new occurrences just overwrite the previous one).
8651 If you can mail this file to the developers (see sec.
8665 If you can mail this file to the developers (see sec.
8652
8666
8653 \begin_inset LatexCommand \ref{sec:credits}
8667 \begin_inset LatexCommand \ref{sec:credits}
8654
8668
8655 \end_inset
8669 \end_inset
8656
8670
8657 for names and addresses), it will help us
8671 for names and addresses), it will help us
8658 \emph on
8672 \emph on
8659 a lot
8673 a lot
8660 \emph default
8674 \emph default
8661 in understanding the cause of the problem and fixing it sooner.
8675 in understanding the cause of the problem and fixing it sooner.
8662 \layout Subsection*
8676 \layout Subsection*
8663
8677
8664 The bug tracker
8678 The bug tracker
8665 \layout Standard
8679 \layout Standard
8666
8680
8667 IPython also has an online bug-tracker, located at
8681 IPython also has an online bug-tracker, located at
8668 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8682 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8669
8683
8670 \end_inset
8684 \end_inset
8671
8685
8672 .
8686 .
8673 In addition to mailing the developers, it would be a good idea to file
8687 In addition to mailing the developers, it would be a good idea to file
8674 a bug report here.
8688 a bug report here.
8675 This will ensure that the issue is properly followed to conclusion.
8689 This will ensure that the issue is properly followed to conclusion.
8676 \layout Standard
8690 \layout Standard
8677
8691
8678 You can also use this bug tracker to file feature requests.
8692 You can also use this bug tracker to file feature requests.
8679 \layout Section
8693 \layout Section
8680
8694
8681 Brief history
8695 Brief history
8682 \layout Subsection
8696 \layout Subsection
8683
8697
8684 Origins
8698 Origins
8685 \layout Standard
8699 \layout Standard
8686
8700
8687 The current IPython system grew out of the following three projects:
8701 The current IPython system grew out of the following three projects:
8688 \layout List
8702 \layout List
8689 \labelwidthstring 00.00.0000
8703 \labelwidthstring 00.00.0000
8690
8704
8691 ipython by Fernando P
8705 ipython by Fernando P
8692 \begin_inset ERT
8706 \begin_inset ERT
8693 status Collapsed
8707 status Collapsed
8694
8708
8695 \layout Standard
8709 \layout Standard
8696
8710
8697 \backslash
8711 \backslash
8698 '{e}
8712 '{e}
8699 \end_inset
8713 \end_inset
8700
8714
8701 rez.
8715 rez.
8702 I was working on adding Mathematica-type prompts and a flexible configuration
8716 I was working on adding Mathematica-type prompts and a flexible configuration
8703 system (something better than
8717 system (something better than
8704 \family typewriter
8718 \family typewriter
8705 $PYTHONSTARTUP
8719 $PYTHONSTARTUP
8706 \family default
8720 \family default
8707 ) to the standard Python interactive interpreter.
8721 ) to the standard Python interactive interpreter.
8708 \layout List
8722 \layout List
8709 \labelwidthstring 00.00.0000
8723 \labelwidthstring 00.00.0000
8710
8724
8711 IPP by Janko Hauser.
8725 IPP by Janko Hauser.
8712 Very well organized, great usability.
8726 Very well organized, great usability.
8713 Had an old help system.
8727 Had an old help system.
8714 IPP was used as the `container' code into which I added the functionality
8728 IPP was used as the `container' code into which I added the functionality
8715 from ipython and LazyPython.
8729 from ipython and LazyPython.
8716 \layout List
8730 \layout List
8717 \labelwidthstring 00.00.0000
8731 \labelwidthstring 00.00.0000
8718
8732
8719 LazyPython by Nathan Gray.
8733 LazyPython by Nathan Gray.
8720 Simple but
8734 Simple but
8721 \emph on
8735 \emph on
8722 very
8736 very
8723 \emph default
8737 \emph default
8724 powerful.
8738 powerful.
8725 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8739 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8726 were all taken from here.
8740 were all taken from here.
8727 \layout Standard
8741 \layout Standard
8728
8742
8729 When I found out (see sec.
8743 When I found out (see sec.
8730
8744
8731 \begin_inset LatexCommand \ref{figgins}
8745 \begin_inset LatexCommand \ref{figgins}
8732
8746
8733 \end_inset
8747 \end_inset
8734
8748
8735 ) about IPP and LazyPython I tried to join all three into a unified system.
8749 ) about IPP and LazyPython I tried to join all three into a unified system.
8736 I thought this could provide a very nice working environment, both for
8750 I thought this could provide a very nice working environment, both for
8737 regular programming and scientific computing: shell-like features, IDL/Matlab
8751 regular programming and scientific computing: shell-like features, IDL/Matlab
8738 numerics, Mathematica-type prompt history and great object introspection
8752 numerics, Mathematica-type prompt history and great object introspection
8739 and help facilities.
8753 and help facilities.
8740 I think it worked reasonably well, though it was a lot more work than I
8754 I think it worked reasonably well, though it was a lot more work than I
8741 had initially planned.
8755 had initially planned.
8742 \layout Subsection
8756 \layout Subsection
8743
8757
8744 Current status
8758 Current status
8745 \layout Standard
8759 \layout Standard
8746
8760
8747 The above listed features work, and quite well for the most part.
8761 The above listed features work, and quite well for the most part.
8748 But until a major internal restructuring is done (see below), only bug
8762 But until a major internal restructuring is done (see below), only bug
8749 fixing will be done, no other features will be added (unless very minor
8763 fixing will be done, no other features will be added (unless very minor
8750 and well localized in the cleaner parts of the code).
8764 and well localized in the cleaner parts of the code).
8751 \layout Standard
8765 \layout Standard
8752
8766
8753 IPython consists of some 18000 lines of pure python code, of which roughly
8767 IPython consists of some 18000 lines of pure python code, of which roughly
8754 two thirds is reasonably clean.
8768 two thirds is reasonably clean.
8755 The rest is, messy code which needs a massive restructuring before any
8769 The rest is, messy code which needs a massive restructuring before any
8756 further major work is done.
8770 further major work is done.
8757 Even the messy code is fairly well documented though, and most of the problems
8771 Even the messy code is fairly well documented though, and most of the problems
8758 in the (non-existent) class design are well pointed to by a PyChecker run.
8772 in the (non-existent) class design are well pointed to by a PyChecker run.
8759 So the rewriting work isn't that bad, it will just be time-consuming.
8773 So the rewriting work isn't that bad, it will just be time-consuming.
8760 \layout Subsection
8774 \layout Subsection
8761
8775
8762 Future
8776 Future
8763 \layout Standard
8777 \layout Standard
8764
8778
8765 See the separate
8779 See the separate
8766 \family typewriter
8780 \family typewriter
8767 new_design
8781 new_design
8768 \family default
8782 \family default
8769 document for details.
8783 document for details.
8770 Ultimately, I would like to see IPython become part of the standard Python
8784 Ultimately, I would like to see IPython become part of the standard Python
8771 distribution as a `big brother with batteries' to the standard Python interacti
8785 distribution as a `big brother with batteries' to the standard Python interacti
8772 ve interpreter.
8786 ve interpreter.
8773 But that will never happen with the current state of the code, so all contribut
8787 But that will never happen with the current state of the code, so all contribut
8774 ions are welcome.
8788 ions are welcome.
8775 \layout Section
8789 \layout Section
8776
8790
8777 License
8791 License
8778 \layout Standard
8792 \layout Standard
8779
8793
8780 IPython is released under the terms of the BSD license, whose general form
8794 IPython is released under the terms of the BSD license, whose general form
8781 can be found at:
8795 can be found at:
8782 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8796 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8783
8797
8784 \end_inset
8798 \end_inset
8785
8799
8786 .
8800 .
8787 The full text of the IPython license is reproduced below:
8801 The full text of the IPython license is reproduced below:
8788 \layout Quote
8802 \layout Quote
8789
8803
8790
8804
8791 \family typewriter
8805 \family typewriter
8792 \size small
8806 \size small
8793 IPython is released under a BSD-type license.
8807 IPython is released under a BSD-type license.
8794 \layout Quote
8808 \layout Quote
8795
8809
8796
8810
8797 \family typewriter
8811 \family typewriter
8798 \size small
8812 \size small
8799 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8813 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8800 \layout Quote
8814 \layout Quote
8801
8815
8802
8816
8803 \family typewriter
8817 \family typewriter
8804 \size small
8818 \size small
8805 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8819 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8806 \newline
8820 \newline
8807 Nathaniel Gray <n8gray@caltech.edu>.
8821 Nathaniel Gray <n8gray@caltech.edu>.
8808 \layout Quote
8822 \layout Quote
8809
8823
8810
8824
8811 \family typewriter
8825 \family typewriter
8812 \size small
8826 \size small
8813 All rights reserved.
8827 All rights reserved.
8814 \layout Quote
8828 \layout Quote
8815
8829
8816
8830
8817 \family typewriter
8831 \family typewriter
8818 \size small
8832 \size small
8819 Redistribution and use in source and binary forms, with or without modification,
8833 Redistribution and use in source and binary forms, with or without modification,
8820 are permitted provided that the following conditions are met:
8834 are permitted provided that the following conditions are met:
8821 \layout Quote
8835 \layout Quote
8822
8836
8823
8837
8824 \family typewriter
8838 \family typewriter
8825 \size small
8839 \size small
8826 a.
8840 a.
8827 Redistributions of source code must retain the above copyright notice,
8841 Redistributions of source code must retain the above copyright notice,
8828 this list of conditions and the following disclaimer.
8842 this list of conditions and the following disclaimer.
8829 \layout Quote
8843 \layout Quote
8830
8844
8831
8845
8832 \family typewriter
8846 \family typewriter
8833 \size small
8847 \size small
8834 b.
8848 b.
8835 Redistributions in binary form must reproduce the above copyright notice,
8849 Redistributions in binary form must reproduce the above copyright notice,
8836 this list of conditions and the following disclaimer in the documentation
8850 this list of conditions and the following disclaimer in the documentation
8837 and/or other materials provided with the distribution.
8851 and/or other materials provided with the distribution.
8838 \layout Quote
8852 \layout Quote
8839
8853
8840
8854
8841 \family typewriter
8855 \family typewriter
8842 \size small
8856 \size small
8843 c.
8857 c.
8844 Neither the name of the copyright holders nor the names of any contributors
8858 Neither the name of the copyright holders nor the names of any contributors
8845 to this software may be used to endorse or promote products derived from
8859 to this software may be used to endorse or promote products derived from
8846 this software without specific prior written permission.
8860 this software without specific prior written permission.
8847 \layout Quote
8861 \layout Quote
8848
8862
8849
8863
8850 \family typewriter
8864 \family typewriter
8851 \size small
8865 \size small
8852 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8866 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8853 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8867 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8854 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8868 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8855 PURPOSE ARE DISCLAIMED.
8869 PURPOSE ARE DISCLAIMED.
8856 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8870 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8857 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8871 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8858 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8872 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8859 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8873 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8860 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8874 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8861 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8875 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8862 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8876 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8863
8877
8864 \layout Standard
8878 \layout Standard
8865
8879
8866 Individual authors are the holders of the copyright for their code and are
8880 Individual authors are the holders of the copyright for their code and are
8867 listed in each file.
8881 listed in each file.
8868 \layout Standard
8882 \layout Standard
8869
8883
8870 Some files (
8884 Some files (
8871 \family typewriter
8885 \family typewriter
8872 DPyGetOpt.py
8886 DPyGetOpt.py
8873 \family default
8887 \family default
8874 , for example) may be licensed under different conditions.
8888 , for example) may be licensed under different conditions.
8875 Ultimately each file indicates clearly the conditions under which its author/au
8889 Ultimately each file indicates clearly the conditions under which its author/au
8876 thors have decided to publish the code.
8890 thors have decided to publish the code.
8877 \layout Standard
8891 \layout Standard
8878
8892
8879 Versions of IPython up to and including 0.6.3 were released under the GNU
8893 Versions of IPython up to and including 0.6.3 were released under the GNU
8880 Lesser General Public License (LGPL), available at
8894 Lesser General Public License (LGPL), available at
8881 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8895 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8882
8896
8883 \end_inset
8897 \end_inset
8884
8898
8885 .
8899 .
8886 \layout Section
8900 \layout Section
8887
8901
8888
8902
8889 \begin_inset LatexCommand \label{sec:credits}
8903 \begin_inset LatexCommand \label{sec:credits}
8890
8904
8891 \end_inset
8905 \end_inset
8892
8906
8893 Credits
8907 Credits
8894 \layout Standard
8908 \layout Standard
8895
8909
8896 IPython is mainly developed by Fernando P
8910 IPython is mainly developed by Fernando P
8897 \begin_inset ERT
8911 \begin_inset ERT
8898 status Collapsed
8912 status Collapsed
8899
8913
8900 \layout Standard
8914 \layout Standard
8901
8915
8902 \backslash
8916 \backslash
8903 '{e}
8917 '{e}
8904 \end_inset
8918 \end_inset
8905
8919
8906 rez
8920 rez
8907 \family typewriter
8921 \family typewriter
8908 <fperez@colorado.edu>
8922 <Fernando.Perez@colorado.edu>
8909 \family default
8923 \family default
8910 , but the project was born from mixing in Fernando's code with the IPP project
8924 , but the project was born from mixing in Fernando's code with the IPP project
8911 by Janko Hauser
8925 by Janko Hauser
8912 \family typewriter
8926 \family typewriter
8913 <jhauser-AT-zscout.de>
8927 <jhauser-AT-zscout.de>
8914 \family default
8928 \family default
8915 and LazyPython by Nathan Gray
8929 and LazyPython by Nathan Gray
8916 \family typewriter
8930 \family typewriter
8917 <n8gray-AT-caltech.edu>
8931 <n8gray-AT-caltech.edu>
8918 \family default
8932 \family default
8919 .
8933 .
8920 For all IPython-related requests, please contact Fernando.
8934 For all IPython-related requests, please contact Fernando.
8921
8935
8922 \layout Standard
8936 \layout Standard
8923
8937
8924 As of late 2005, the following developers have joined the core team:
8938 As of early 2006, the following developers have joined the core team:
8925 \layout List
8939 \layout List
8926 \labelwidthstring 00.00.0000
8940 \labelwidthstring 00.00.0000
8927
8941
8928 Robert\SpecialChar ~
8942 Robert\SpecialChar ~
8929 Kern
8943 Kern
8930 \family typewriter
8944 \family typewriter
8931 <rkern-AT-enthought.com>
8945 <rkern-AT-enthought.com>
8932 \family default
8946 \family default
8933 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8947 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8934 ve notebooks (XML documents) and graphical interface.
8948 ve notebooks (XML documents) and graphical interface.
8935 This project was awarded to the students Tzanko Matev
8949 This project was awarded to the students Tzanko Matev
8936 \family typewriter
8950 \family typewriter
8937 <tsanko-AT-gmail.com>
8951 <tsanko-AT-gmail.com>
8938 \family default
8952 \family default
8939 and Toni Alatalo
8953 and Toni Alatalo
8940 \family typewriter
8954 \family typewriter
8941 <antont-AT-an.org>
8955 <antont-AT-an.org>
8942 \layout List
8956 \layout List
8943 \labelwidthstring 00.00.0000
8957 \labelwidthstring 00.00.0000
8944
8958
8945 Brian\SpecialChar ~
8959 Brian\SpecialChar ~
8946 Granger
8960 Granger
8947 \family typewriter
8961 \family typewriter
8948 <bgranger-AT-scu.edu>
8962 <bgranger-AT-scu.edu>
8949 \family default
8963 \family default
8950 : extending IPython to allow support for interactive parallel computing.
8964 : extending IPython to allow support for interactive parallel computing.
8951 \layout List
8965 \layout List
8952 \labelwidthstring 00.00.0000
8966 \labelwidthstring 00.00.0000
8953
8967
8954 Ville\SpecialChar ~
8968 Ville\SpecialChar ~
8955 Vainio
8969 Vainio
8956 \family typewriter
8970 \family typewriter
8957 <vivainio-AT-gmail.com>
8971 <vivainio-AT-gmail.com>
8958 \family default
8972 \family default
8959 : Ville is the new maintainer for the main trunk of IPython as of version
8973 : Ville is the new maintainer for the main trunk of IPython after version
8960 0.7.1.
8974 0.7.1.
8961 \layout Standard
8975 \layout Standard
8962
8976
8963 User or development help should be requested via the IPython mailing lists:
8977 User or development help should be requested via the IPython mailing lists:
8964 \layout Description
8978 \layout Description
8965
8979
8966 User\SpecialChar ~
8980 User\SpecialChar ~
8967 list:
8981 list:
8968 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8982 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8969
8983
8970 \end_inset
8984 \end_inset
8971
8985
8972
8986
8973 \layout Description
8987 \layout Description
8974
8988
8975 Developer's\SpecialChar ~
8989 Developer's\SpecialChar ~
8976 list:
8990 list:
8977 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8991 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8978
8992
8979 \end_inset
8993 \end_inset
8980
8994
8981
8995
8982 \layout Standard
8996 \layout Standard
8983
8997
8984 The IPython project is also very grateful to
8998 The IPython project is also very grateful to
8985 \begin_inset Foot
8999 \begin_inset Foot
8986 collapsed true
9000 collapsed true
8987
9001
8988 \layout Standard
9002 \layout Standard
8989
9003
8990 I've mangled email addresses to reduce spam, since the IPython manuals can
9004 I've mangled email addresses to reduce spam, since the IPython manuals can
8991 be accessed online.
9005 be accessed online.
8992 \end_inset
9006 \end_inset
8993
9007
8994 :
9008 :
8995 \layout Standard
9009 \layout Standard
8996
9010
8997 Bill Bumgarner
9011 Bill Bumgarner
8998 \family typewriter
9012 \family typewriter
8999 <bbum-AT-friday.com>
9013 <bbum-AT-friday.com>
9000 \family default
9014 \family default
9001 : for providing the DPyGetOpt module which gives very powerful and convenient
9015 : for providing the DPyGetOpt module which gives very powerful and convenient
9002 handling of command-line options (light years ahead of what Python 2.1.1's
9016 handling of command-line options (light years ahead of what Python 2.1.1's
9003 getopt module does).
9017 getopt module does).
9004 \layout Standard
9018 \layout Standard
9005
9019
9006 Ka-Ping Yee
9020 Ka-Ping Yee
9007 \family typewriter
9021 \family typewriter
9008 <ping-AT-lfw.org>
9022 <ping-AT-lfw.org>
9009 \family default
9023 \family default
9010 : for providing the Itpl module for convenient and powerful string interpolation
9024 : for providing the Itpl module for convenient and powerful string interpolation
9011 with a much nicer syntax than formatting through the '%' operator.
9025 with a much nicer syntax than formatting through the '%' operator.
9012 \layout Standard
9026 \layout Standard
9013
9027
9014 Arnd Baecker
9028 Arnd Baecker
9015 \family typewriter
9029 \family typewriter
9016 <baecker-AT-physik.tu-dresden.de>
9030 <baecker-AT-physik.tu-dresden.de>
9017 \family default
9031 \family default
9018 : for his many very useful suggestions and comments, and lots of help with
9032 : for his many very useful suggestions and comments, and lots of help with
9019 testing and documentation checking.
9033 testing and documentation checking.
9020 Many of IPython's newer features are a result of discussions with him (bugs
9034 Many of IPython's newer features are a result of discussions with him (bugs
9021 are still my fault, not his).
9035 are still my fault, not his).
9022 \layout Standard
9036 \layout Standard
9023
9037
9024 Obviously Guido van\SpecialChar ~
9038 Obviously Guido van\SpecialChar ~
9025 Rossum and the whole Python development team, that goes
9039 Rossum and the whole Python development team, that goes
9026 without saying.
9040 without saying.
9027 \layout Standard
9041 \layout Standard
9028
9042
9029 IPython's website is generously hosted at
9043 IPython's website is generously hosted at
9030 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
9044 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
9031
9045
9032 \end_inset
9046 \end_inset
9033
9047
9034 by Enthought (
9048 by Enthought (
9035 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
9049 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
9036
9050
9037 \end_inset
9051 \end_inset
9038
9052
9039 ).
9053 ).
9040 I am very grateful to them and all of the SciPy team for their contribution.
9054 I am very grateful to them and all of the SciPy team for their contribution.
9041 \layout Standard
9055 \layout Standard
9042
9056
9043
9057
9044 \begin_inset LatexCommand \label{figgins}
9058 \begin_inset LatexCommand \label{figgins}
9045
9059
9046 \end_inset
9060 \end_inset
9047
9061
9048 Fernando would also like to thank Stephen Figgins
9062 Fernando would also like to thank Stephen Figgins
9049 \family typewriter
9063 \family typewriter
9050 <fig-AT-monitor.net>
9064 <fig-AT-monitor.net>
9051 \family default
9065 \family default
9052 , an O'Reilly Python editor.
9066 , an O'Reilly Python editor.
9053 His Oct/11/2001 article about IPP and LazyPython, was what got this project
9067 His Oct/11/2001 article about IPP and LazyPython, was what got this project
9054 started.
9068 started.
9055 You can read it at:
9069 You can read it at:
9056 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
9070 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
9057
9071
9058 \end_inset
9072 \end_inset
9059
9073
9060 .
9074 .
9061 \layout Standard
9075 \layout Standard
9062
9076
9063 And last but not least, all the kind IPython users who have emailed new
9077 And last but not least, all the kind IPython users who have emailed new
9064 code, bug reports, fixes, comments and ideas.
9078 code, bug reports, fixes, comments and ideas.
9065 A brief list follows, please let me know if I have ommitted your name by
9079 A brief list follows, please let me know if I have ommitted your name by
9066 accident:
9080 accident:
9067 \layout List
9081 \layout List
9068 \labelwidthstring 00.00.0000
9082 \labelwidthstring 00.00.0000
9069
9083
9070 Jack\SpecialChar ~
9084 Jack\SpecialChar ~
9071 Moffit
9085 Moffit
9072 \family typewriter
9086 \family typewriter
9073 <jack-AT-xiph.org>
9087 <jack-AT-xiph.org>
9074 \family default
9088 \family default
9075 Bug fixes, including the infamous color problem.
9089 Bug fixes, including the infamous color problem.
9076 This bug alone caused many lost hours and frustration, many thanks to him
9090 This bug alone caused many lost hours and frustration, many thanks to him
9077 for the fix.
9091 for the fix.
9078 I've always been a fan of Ogg & friends, now I have one more reason to
9092 I've always been a fan of Ogg & friends, now I have one more reason to
9079 like these folks.
9093 like these folks.
9080 \newline
9094 \newline
9081 Jack is also contributing with Debian packaging and many other things.
9095 Jack is also contributing with Debian packaging and many other things.
9082 \layout List
9096 \layout List
9083 \labelwidthstring 00.00.0000
9097 \labelwidthstring 00.00.0000
9084
9098
9085 Alexander\SpecialChar ~
9099 Alexander\SpecialChar ~
9086 Schmolck
9100 Schmolck
9087 \family typewriter
9101 \family typewriter
9088 <a.schmolck-AT-gmx.net>
9102 <a.schmolck-AT-gmx.net>
9089 \family default
9103 \family default
9090 Emacs work, bug reports, bug fixes, ideas, lots more.
9104 Emacs work, bug reports, bug fixes, ideas, lots more.
9091 The ipython.el mode for (X)Emacs is Alex's code, providing full support
9105 The ipython.el mode for (X)Emacs is Alex's code, providing full support
9092 for IPython under (X)Emacs.
9106 for IPython under (X)Emacs.
9093 \layout List
9107 \layout List
9094 \labelwidthstring 00.00.0000
9108 \labelwidthstring 00.00.0000
9095
9109
9096 Andrea\SpecialChar ~
9110 Andrea\SpecialChar ~
9097 Riciputi
9111 Riciputi
9098 \family typewriter
9112 \family typewriter
9099 <andrea.riciputi-AT-libero.it>
9113 <andrea.riciputi-AT-libero.it>
9100 \family default
9114 \family default
9101 Mac OSX information, Fink package management.
9115 Mac OSX information, Fink package management.
9102 \layout List
9116 \layout List
9103 \labelwidthstring 00.00.0000
9117 \labelwidthstring 00.00.0000
9104
9118
9105 Gary\SpecialChar ~
9119 Gary\SpecialChar ~
9106 Bishop
9120 Bishop
9107 \family typewriter
9121 \family typewriter
9108 <gb-AT-cs.unc.edu>
9122 <gb-AT-cs.unc.edu>
9109 \family default
9123 \family default
9110 Bug reports, and patches to work around the exception handling idiosyncracies
9124 Bug reports, and patches to work around the exception handling idiosyncracies
9111 of WxPython.
9125 of WxPython.
9112 Readline and color support for Windows.
9126 Readline and color support for Windows.
9113 \layout List
9127 \layout List
9114 \labelwidthstring 00.00.0000
9128 \labelwidthstring 00.00.0000
9115
9129
9116 Jeffrey\SpecialChar ~
9130 Jeffrey\SpecialChar ~
9117 Collins
9131 Collins
9118 \family typewriter
9132 \family typewriter
9119 <Jeff.Collins-AT-vexcel.com>
9133 <Jeff.Collins-AT-vexcel.com>
9120 \family default
9134 \family default
9121 Bug reports.
9135 Bug reports.
9122 Much improved readline support, including fixes for Python 2.3.
9136 Much improved readline support, including fixes for Python 2.3.
9123 \layout List
9137 \layout List
9124 \labelwidthstring 00.00.0000
9138 \labelwidthstring 00.00.0000
9125
9139
9126 Dryice\SpecialChar ~
9140 Dryice\SpecialChar ~
9127 Liu
9141 Liu
9128 \family typewriter
9142 \family typewriter
9129 <dryice-AT-liu.com.cn>
9143 <dryice-AT-liu.com.cn>
9130 \family default
9144 \family default
9131 FreeBSD port.
9145 FreeBSD port.
9132 \layout List
9146 \layout List
9133 \labelwidthstring 00.00.0000
9147 \labelwidthstring 00.00.0000
9134
9148
9135 Mike\SpecialChar ~
9149 Mike\SpecialChar ~
9136 Heeter
9150 Heeter
9137 \family typewriter
9151 \family typewriter
9138 <korora-AT-SDF.LONESTAR.ORG>
9152 <korora-AT-SDF.LONESTAR.ORG>
9139 \layout List
9153 \layout List
9140 \labelwidthstring 00.00.0000
9154 \labelwidthstring 00.00.0000
9141
9155
9142 Christopher\SpecialChar ~
9156 Christopher\SpecialChar ~
9143 Hart
9157 Hart
9144 \family typewriter
9158 \family typewriter
9145 <hart-AT-caltech.edu>
9159 <hart-AT-caltech.edu>
9146 \family default
9160 \family default
9147 PDB integration.
9161 PDB integration.
9148 \layout List
9162 \layout List
9149 \labelwidthstring 00.00.0000
9163 \labelwidthstring 00.00.0000
9150
9164
9151 Milan\SpecialChar ~
9165 Milan\SpecialChar ~
9152 Zamazal
9166 Zamazal
9153 \family typewriter
9167 \family typewriter
9154 <pdm-AT-zamazal.org>
9168 <pdm-AT-zamazal.org>
9155 \family default
9169 \family default
9156 Emacs info.
9170 Emacs info.
9157 \layout List
9171 \layout List
9158 \labelwidthstring 00.00.0000
9172 \labelwidthstring 00.00.0000
9159
9173
9160 Philip\SpecialChar ~
9174 Philip\SpecialChar ~
9161 Hisley
9175 Hisley
9162 \family typewriter
9176 \family typewriter
9163 <compsys-AT-starpower.net>
9177 <compsys-AT-starpower.net>
9164 \layout List
9178 \layout List
9165 \labelwidthstring 00.00.0000
9179 \labelwidthstring 00.00.0000
9166
9180
9167 Holger\SpecialChar ~
9181 Holger\SpecialChar ~
9168 Krekel
9182 Krekel
9169 \family typewriter
9183 \family typewriter
9170 <pyth-AT-devel.trillke.net>
9184 <pyth-AT-devel.trillke.net>
9171 \family default
9185 \family default
9172 Tab completion, lots more.
9186 Tab completion, lots more.
9173 \layout List
9187 \layout List
9174 \labelwidthstring 00.00.0000
9188 \labelwidthstring 00.00.0000
9175
9189
9176 Robin\SpecialChar ~
9190 Robin\SpecialChar ~
9177 Siebler
9191 Siebler
9178 \family typewriter
9192 \family typewriter
9179 <robinsiebler-AT-starband.net>
9193 <robinsiebler-AT-starband.net>
9180 \layout List
9194 \layout List
9181 \labelwidthstring 00.00.0000
9195 \labelwidthstring 00.00.0000
9182
9196
9183 Ralf\SpecialChar ~
9197 Ralf\SpecialChar ~
9184 Ahlbrink
9198 Ahlbrink
9185 \family typewriter
9199 \family typewriter
9186 <ralf_ahlbrink-AT-web.de>
9200 <ralf_ahlbrink-AT-web.de>
9187 \layout List
9201 \layout List
9188 \labelwidthstring 00.00.0000
9202 \labelwidthstring 00.00.0000
9189
9203
9190 Thorsten\SpecialChar ~
9204 Thorsten\SpecialChar ~
9191 Kampe
9205 Kampe
9192 \family typewriter
9206 \family typewriter
9193 <thorsten-AT-thorstenkampe.de>
9207 <thorsten-AT-thorstenkampe.de>
9194 \layout List
9208 \layout List
9195 \labelwidthstring 00.00.0000
9209 \labelwidthstring 00.00.0000
9196
9210
9197 Fredrik\SpecialChar ~
9211 Fredrik\SpecialChar ~
9198 Kant
9212 Kant
9199 \family typewriter
9213 \family typewriter
9200 <fredrik.kant-AT-front.com>
9214 <fredrik.kant-AT-front.com>
9201 \family default
9215 \family default
9202 Windows setup.
9216 Windows setup.
9203 \layout List
9217 \layout List
9204 \labelwidthstring 00.00.0000
9218 \labelwidthstring 00.00.0000
9205
9219
9206 Syver\SpecialChar ~
9220 Syver\SpecialChar ~
9207 Enstad
9221 Enstad
9208 \family typewriter
9222 \family typewriter
9209 <syver-en-AT-online.no>
9223 <syver-en-AT-online.no>
9210 \family default
9224 \family default
9211 Windows setup.
9225 Windows setup.
9212 \layout List
9226 \layout List
9213 \labelwidthstring 00.00.0000
9227 \labelwidthstring 00.00.0000
9214
9228
9215 Richard
9229 Richard
9216 \family typewriter
9230 \family typewriter
9217 <rxe-AT-renre-europe.com>
9231 <rxe-AT-renre-europe.com>
9218 \family default
9232 \family default
9219 Global embedding.
9233 Global embedding.
9220 \layout List
9234 \layout List
9221 \labelwidthstring 00.00.0000
9235 \labelwidthstring 00.00.0000
9222
9236
9223 Hayden\SpecialChar ~
9237 Hayden\SpecialChar ~
9224 Callow
9238 Callow
9225 \family typewriter
9239 \family typewriter
9226 <h.callow-AT-elec.canterbury.ac.nz>
9240 <h.callow-AT-elec.canterbury.ac.nz>
9227 \family default
9241 \family default
9228 Gnuplot.py 1.6 compatibility.
9242 Gnuplot.py 1.6 compatibility.
9229 \layout List
9243 \layout List
9230 \labelwidthstring 00.00.0000
9244 \labelwidthstring 00.00.0000
9231
9245
9232 Leonardo\SpecialChar ~
9246 Leonardo\SpecialChar ~
9233 Santagada
9247 Santagada
9234 \family typewriter
9248 \family typewriter
9235 <retype-AT-terra.com.br>
9249 <retype-AT-terra.com.br>
9236 \family default
9250 \family default
9237 Fixes for Windows installation.
9251 Fixes for Windows installation.
9238 \layout List
9252 \layout List
9239 \labelwidthstring 00.00.0000
9253 \labelwidthstring 00.00.0000
9240
9254
9241 Christopher\SpecialChar ~
9255 Christopher\SpecialChar ~
9242 Armstrong
9256 Armstrong
9243 \family typewriter
9257 \family typewriter
9244 <radix-AT-twistedmatrix.com>
9258 <radix-AT-twistedmatrix.com>
9245 \family default
9259 \family default
9246 Bugfixes.
9260 Bugfixes.
9247 \layout List
9261 \layout List
9248 \labelwidthstring 00.00.0000
9262 \labelwidthstring 00.00.0000
9249
9263
9250 Francois\SpecialChar ~
9264 Francois\SpecialChar ~
9251 Pinard
9265 Pinard
9252 \family typewriter
9266 \family typewriter
9253 <pinard-AT-iro.umontreal.ca>
9267 <pinard-AT-iro.umontreal.ca>
9254 \family default
9268 \family default
9255 Code and documentation fixes.
9269 Code and documentation fixes.
9256 \layout List
9270 \layout List
9257 \labelwidthstring 00.00.0000
9271 \labelwidthstring 00.00.0000
9258
9272
9259 Cory\SpecialChar ~
9273 Cory\SpecialChar ~
9260 Dodt
9274 Dodt
9261 \family typewriter
9275 \family typewriter
9262 <cdodt-AT-fcoe.k12.ca.us>
9276 <cdodt-AT-fcoe.k12.ca.us>
9263 \family default
9277 \family default
9264 Bug reports and Windows ideas.
9278 Bug reports and Windows ideas.
9265 Patches for Windows installer.
9279 Patches for Windows installer.
9266 \layout List
9280 \layout List
9267 \labelwidthstring 00.00.0000
9281 \labelwidthstring 00.00.0000
9268
9282
9269 Olivier\SpecialChar ~
9283 Olivier\SpecialChar ~
9270 Aubert
9284 Aubert
9271 \family typewriter
9285 \family typewriter
9272 <oaubert-AT-bat710.univ-lyon1.fr>
9286 <oaubert-AT-bat710.univ-lyon1.fr>
9273 \family default
9287 \family default
9274 New magics.
9288 New magics.
9275 \layout List
9289 \layout List
9276 \labelwidthstring 00.00.0000
9290 \labelwidthstring 00.00.0000
9277
9291
9278 King\SpecialChar ~
9292 King\SpecialChar ~
9279 C.\SpecialChar ~
9293 C.\SpecialChar ~
9280 Shu
9294 Shu
9281 \family typewriter
9295 \family typewriter
9282 <kingshu-AT-myrealbox.com>
9296 <kingshu-AT-myrealbox.com>
9283 \family default
9297 \family default
9284 Autoindent patch.
9298 Autoindent patch.
9285 \layout List
9299 \layout List
9286 \labelwidthstring 00.00.0000
9300 \labelwidthstring 00.00.0000
9287
9301
9288 Chris\SpecialChar ~
9302 Chris\SpecialChar ~
9289 Drexler
9303 Drexler
9290 \family typewriter
9304 \family typewriter
9291 <chris-AT-ac-drexler.de>
9305 <chris-AT-ac-drexler.de>
9292 \family default
9306 \family default
9293 Readline packages for Win32/CygWin.
9307 Readline packages for Win32/CygWin.
9294 \layout List
9308 \layout List
9295 \labelwidthstring 00.00.0000
9309 \labelwidthstring 00.00.0000
9296
9310
9297 Gustavo\SpecialChar ~
9311 Gustavo\SpecialChar ~
9298 Cordova\SpecialChar ~
9312 Cordova\SpecialChar ~
9299 Avila
9313 Avila
9300 \family typewriter
9314 \family typewriter
9301 <gcordova-AT-sismex.com>
9315 <gcordova-AT-sismex.com>
9302 \family default
9316 \family default
9303 EvalDict code for nice, lightweight string interpolation.
9317 EvalDict code for nice, lightweight string interpolation.
9304 \layout List
9318 \layout List
9305 \labelwidthstring 00.00.0000
9319 \labelwidthstring 00.00.0000
9306
9320
9307 Kasper\SpecialChar ~
9321 Kasper\SpecialChar ~
9308 Souren
9322 Souren
9309 \family typewriter
9323 \family typewriter
9310 <Kasper.Souren-AT-ircam.fr>
9324 <Kasper.Souren-AT-ircam.fr>
9311 \family default
9325 \family default
9312 Bug reports, ideas.
9326 Bug reports, ideas.
9313 \layout List
9327 \layout List
9314 \labelwidthstring 00.00.0000
9328 \labelwidthstring 00.00.0000
9315
9329
9316 Gever\SpecialChar ~
9330 Gever\SpecialChar ~
9317 Tulley
9331 Tulley
9318 \family typewriter
9332 \family typewriter
9319 <gever-AT-helium.com>
9333 <gever-AT-helium.com>
9320 \family default
9334 \family default
9321 Code contributions.
9335 Code contributions.
9322 \layout List
9336 \layout List
9323 \labelwidthstring 00.00.0000
9337 \labelwidthstring 00.00.0000
9324
9338
9325 Ralf\SpecialChar ~
9339 Ralf\SpecialChar ~
9326 Schmitt
9340 Schmitt
9327 \family typewriter
9341 \family typewriter
9328 <ralf-AT-brainbot.com>
9342 <ralf-AT-brainbot.com>
9329 \family default
9343 \family default
9330 Bug reports & fixes.
9344 Bug reports & fixes.
9331 \layout List
9345 \layout List
9332 \labelwidthstring 00.00.0000
9346 \labelwidthstring 00.00.0000
9333
9347
9334 Oliver\SpecialChar ~
9348 Oliver\SpecialChar ~
9335 Sander
9349 Sander
9336 \family typewriter
9350 \family typewriter
9337 <osander-AT-gmx.de>
9351 <osander-AT-gmx.de>
9338 \family default
9352 \family default
9339 Bug reports.
9353 Bug reports.
9340 \layout List
9354 \layout List
9341 \labelwidthstring 00.00.0000
9355 \labelwidthstring 00.00.0000
9342
9356
9343 Rod\SpecialChar ~
9357 Rod\SpecialChar ~
9344 Holland
9358 Holland
9345 \family typewriter
9359 \family typewriter
9346 <rhh-AT-structurelabs.com>
9360 <rhh-AT-structurelabs.com>
9347 \family default
9361 \family default
9348 Bug reports and fixes to logging module.
9362 Bug reports and fixes to logging module.
9349 \layout List
9363 \layout List
9350 \labelwidthstring 00.00.0000
9364 \labelwidthstring 00.00.0000
9351
9365
9352 Daniel\SpecialChar ~
9366 Daniel\SpecialChar ~
9353 'Dang'\SpecialChar ~
9367 'Dang'\SpecialChar ~
9354 Griffith
9368 Griffith
9355 \family typewriter
9369 \family typewriter
9356 <pythondev-dang-AT-lazytwinacres.net>
9370 <pythondev-dang-AT-lazytwinacres.net>
9357 \family default
9371 \family default
9358 Fixes, enhancement suggestions for system shell use.
9372 Fixes, enhancement suggestions for system shell use.
9359 \layout List
9373 \layout List
9360 \labelwidthstring 00.00.0000
9374 \labelwidthstring 00.00.0000
9361
9375
9362 Viktor\SpecialChar ~
9376 Viktor\SpecialChar ~
9363 Ransmayr
9377 Ransmayr
9364 \family typewriter
9378 \family typewriter
9365 <viktor.ransmayr-AT-t-online.de>
9379 <viktor.ransmayr-AT-t-online.de>
9366 \family default
9380 \family default
9367 Tests and reports on Windows installation issues.
9381 Tests and reports on Windows installation issues.
9368 Contributed a true Windows binary installer.
9382 Contributed a true Windows binary installer.
9369 \layout List
9383 \layout List
9370 \labelwidthstring 00.00.0000
9384 \labelwidthstring 00.00.0000
9371
9385
9372 Mike\SpecialChar ~
9386 Mike\SpecialChar ~
9373 Salib
9387 Salib
9374 \family typewriter
9388 \family typewriter
9375 <msalib-AT-mit.edu>
9389 <msalib-AT-mit.edu>
9376 \family default
9390 \family default
9377 Help fixing a subtle bug related to traceback printing.
9391 Help fixing a subtle bug related to traceback printing.
9378 \layout List
9392 \layout List
9379 \labelwidthstring 00.00.0000
9393 \labelwidthstring 00.00.0000
9380
9394
9381 W.J.\SpecialChar ~
9395 W.J.\SpecialChar ~
9382 van\SpecialChar ~
9396 van\SpecialChar ~
9383 der\SpecialChar ~
9397 der\SpecialChar ~
9384 Laan
9398 Laan
9385 \family typewriter
9399 \family typewriter
9386 <gnufnork-AT-hetdigitalegat.nl>
9400 <gnufnork-AT-hetdigitalegat.nl>
9387 \family default
9401 \family default
9388 Bash-like prompt specials.
9402 Bash-like prompt specials.
9389 \layout List
9403 \layout List
9390 \labelwidthstring 00.00.0000
9404 \labelwidthstring 00.00.0000
9391
9405
9392 Antoon\SpecialChar ~
9406 Antoon\SpecialChar ~
9393 Pardon
9407 Pardon
9394 \family typewriter
9408 \family typewriter
9395 <Antoon.Pardon-AT-rece.vub.ac.be>
9409 <Antoon.Pardon-AT-rece.vub.ac.be>
9396 \family default
9410 \family default
9397 Critical fix for the multithreaded IPython.
9411 Critical fix for the multithreaded IPython.
9398 \layout List
9412 \layout List
9399 \labelwidthstring 00.00.0000
9413 \labelwidthstring 00.00.0000
9400
9414
9401 John\SpecialChar ~
9415 John\SpecialChar ~
9402 Hunter
9416 Hunter
9403 \family typewriter
9417 \family typewriter
9404 <jdhunter-AT-nitace.bsd.uchicago.edu>
9418 <jdhunter-AT-nitace.bsd.uchicago.edu>
9405 \family default
9419 \family default
9406 Matplotlib author, helped with all the development of support for matplotlib
9420 Matplotlib author, helped with all the development of support for matplotlib
9407 in IPyhton, including making necessary changes to matplotlib itself.
9421 in IPyhton, including making necessary changes to matplotlib itself.
9408 \layout List
9422 \layout List
9409 \labelwidthstring 00.00.0000
9423 \labelwidthstring 00.00.0000
9410
9424
9411 Matthew\SpecialChar ~
9425 Matthew\SpecialChar ~
9412 Arnison
9426 Arnison
9413 \family typewriter
9427 \family typewriter
9414 <maffew-AT-cat.org.au>
9428 <maffew-AT-cat.org.au>
9415 \family default
9429 \family default
9416 Bug reports, `
9430 Bug reports, `
9417 \family typewriter
9431 \family typewriter
9418 %run -d
9432 %run -d
9419 \family default
9433 \family default
9420 ' idea.
9434 ' idea.
9421 \layout List
9435 \layout List
9422 \labelwidthstring 00.00.0000
9436 \labelwidthstring 00.00.0000
9423
9437
9424 Prabhu\SpecialChar ~
9438 Prabhu\SpecialChar ~
9425 Ramachandran
9439 Ramachandran
9426 \family typewriter
9440 \family typewriter
9427 <prabhu_r-AT-users.sourceforge.net>
9441 <prabhu_r-AT-users.sourceforge.net>
9428 \family default
9442 \family default
9429 Help with (X)Emacs support, threading patches, ideas...
9443 Help with (X)Emacs support, threading patches, ideas...
9430 \layout List
9444 \layout List
9431 \labelwidthstring 00.00.0000
9445 \labelwidthstring 00.00.0000
9432
9446
9433 Norbert\SpecialChar ~
9447 Norbert\SpecialChar ~
9434 Tretkowski
9448 Tretkowski
9435 \family typewriter
9449 \family typewriter
9436 <tretkowski-AT-inittab.de>
9450 <tretkowski-AT-inittab.de>
9437 \family default
9451 \family default
9438 help with Debian packaging and distribution.
9452 help with Debian packaging and distribution.
9439 \layout List
9453 \layout List
9440 \labelwidthstring 00.00.0000
9454 \labelwidthstring 00.00.0000
9441
9455
9442 George\SpecialChar ~
9456 George\SpecialChar ~
9443 Sakkis <
9457 Sakkis <
9444 \family typewriter
9458 \family typewriter
9445 gsakkis-AT-eden.rutgers.edu>
9459 gsakkis-AT-eden.rutgers.edu>
9446 \family default
9460 \family default
9447 New matcher for tab-completing named arguments of user-defined functions.
9461 New matcher for tab-completing named arguments of user-defined functions.
9448 \layout List
9462 \layout List
9449 \labelwidthstring 00.00.0000
9463 \labelwidthstring 00.00.0000
9450
9464
9451 J�rgen\SpecialChar ~
9465 J�rgen\SpecialChar ~
9452 Stenarson
9466 Stenarson
9453 \family typewriter
9467 \family typewriter
9454 <jorgen.stenarson-AT-bostream.nu>
9468 <jorgen.stenarson-AT-bostream.nu>
9455 \family default
9469 \family default
9456 Wildcard support implementation for searching namespaces.
9470 Wildcard support implementation for searching namespaces.
9457 \layout List
9471 \layout List
9458 \labelwidthstring 00.00.0000
9472 \labelwidthstring 00.00.0000
9459
9473
9460 Vivian\SpecialChar ~
9474 Vivian\SpecialChar ~
9461 De\SpecialChar ~
9475 De\SpecialChar ~
9462 Smedt
9476 Smedt
9463 \family typewriter
9477 \family typewriter
9464 <vivian-AT-vdesmedt.com>
9478 <vivian-AT-vdesmedt.com>
9465 \family default
9479 \family default
9466 Debugger enhancements, so that when pdb is activated from within IPython,
9480 Debugger enhancements, so that when pdb is activated from within IPython,
9467 coloring, tab completion and other features continue to work seamlessly.
9481 coloring, tab completion and other features continue to work seamlessly.
9468 \layout List
9482 \layout List
9469 \labelwidthstring 00.00.0000
9483 \labelwidthstring 00.00.0000
9470
9484
9471 Scott\SpecialChar ~
9485 Scott\SpecialChar ~
9472 Tsai
9486 Tsai
9473 \family typewriter
9487 \family typewriter
9474 <scottt958-AT-yahoo.com.tw>
9488 <scottt958-AT-yahoo.com.tw>
9475 \family default
9489 \family default
9476 Support for automatic editor invocation on syntax errors (see
9490 Support for automatic editor invocation on syntax errors (see
9477 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
9491 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
9478
9492
9479 \end_inset
9493 \end_inset
9480
9494
9481 ).
9495 ).
9482 \layout List
9496 \layout List
9483 \labelwidthstring 00.00.0000
9497 \labelwidthstring 00.00.0000
9484
9498
9485 Alexander\SpecialChar ~
9499 Alexander\SpecialChar ~
9486 Belchenko
9500 Belchenko
9487 \family typewriter
9501 \family typewriter
9488 <bialix-AT-ukr.net>
9502 <bialix-AT-ukr.net>
9489 \family default
9503 \family default
9490 Improvements for win32 paging system.
9504 Improvements for win32 paging system.
9491 \the_end
9505 \the_end
@@ -1,103 +1,102 b''
1 #!/bin/sh
1 #!/bin/sh
2 # IPython release script
2 # IPython release script
3
3
4 PYVER=`python -V 2>&1 | awk '{print $2}' | awk -F '.' '{print $1$2}' `
4 PYVER=`python -V 2>&1 | awk '{print $2}' | awk -F '.' '{print $1$2}' `
5 version=`ipython -Version`
5 version=`ipython -Version`
6 ipdir=~/ipython/ipython
6 ipdir=~/ipython/ipython
7
7
8 echo
8 echo
9 echo "Releasing IPython version $version"
9 echo "Releasing IPython version $version"
10 echo "=================================="
10 echo "=================================="
11
11
12 echo "Marking ChangeLog with release information and making NEWS file..."
12 echo "Marking ChangeLog with release information and making NEWS file..."
13
13
14 # Stamp changelog and save a copy of the status at each version, in case later
14 # Stamp changelog and save a copy of the status at each version, in case later
15 # we want the NEWS file to start from a point before the very last release (if
15 # we want the NEWS file to start from a point before the very last release (if
16 # very small interim releases have no significant changes).
16 # very small interim releases have no significant changes).
17
17
18 cd $ipdir/doc
18 cd $ipdir/doc
19 cp ChangeLog ChangeLog.old
19 cp ChangeLog ChangeLog.old
20 cp ChangeLog ChangeLog.$version
20 cp ChangeLog ChangeLog.$version
21 daystamp=`date +%Y-%m-%d`
21 daystamp=`date +%Y-%m-%d`
22 echo $daystamp " ***" Released version $version > ChangeLog
22 echo $daystamp " ***" Released version $version > ChangeLog
23 echo >> ChangeLog
23 echo >> ChangeLog
24 cat ChangeLog.old >> ChangeLog
24 cat ChangeLog.old >> ChangeLog
25 rm ChangeLog.old
25 rm ChangeLog.old
26
26
27 # Build NEWS file
27 # Build NEWS file
28 echo "Changes between the last two releases (major or minor)" > NEWS
28 echo "Changes between the last two releases (major or minor)" > NEWS
29 echo "Note that this is an auto-generated diff of the ChangeLogs" >> NEWS
29 echo "Note that this is an auto-generated diff of the ChangeLogs" >> NEWS
30 echo >> NEWS
30 echo >> NEWS
31 diff ChangeLog.previous ChangeLog | grep -v '^0a' | sed 's/^> //g' >> NEWS
31 diff ChangeLog.previous ChangeLog | grep -v '^0a' | sed 's/^> //g' >> NEWS
32 cp ChangeLog ChangeLog.previous
32 cp ChangeLog ChangeLog.previous
33
33
34 # Clean up build/dist directories
34 # Clean up build/dist directories
35 rm -rf $ipdir/build/*
35 rm -rf $ipdir/build/*
36 rm -rf $ipdir/dist/*
36 rm -rf $ipdir/dist/*
37
37
38 # Perform local backup
38 # Perform local backup
39 cd $ipdir/tools
39 cd $ipdir/tools
40 ./bkp.py
40 ./bkp.py
41
41
42 # Build source and binary distros
42 # Build source and binary distros
43 cd $ipdir
43 cd $ipdir
44 ./setup.py sdist --formats=gztar
44 ./setup.py sdist --formats=gztar
45 #./setup.py bdist_rpm --release=py$PYVER
45 #./setup.py bdist_rpm --release=py$PYVER
46 python2.3 ./setup.py bdist_rpm --release=py23 --python=/usr/bin/python2.3
46 python2.3 ./setup.py bdist_rpm --release=py23 --python=/usr/bin/python2.3
47
47
48 # A 2.4-specific RPM, where we must use the --python option to ensure that
48 # A 2.4-specific RPM, where we must use the --python option to ensure that
49 # the resulting RPM is really built with 2.4 (so things go to
49 # the resulting RPM is really built with 2.4 (so things go to
50 # lib/python2.4/...)
50 # lib/python2.4/...)
51 python2.4 ./setup.py bdist_rpm --release=py24 --python=/usr/bin/python2.4
51 python2.4 ./setup.py bdist_rpm --release=py24 --python=/usr/bin/python2.4
52
52
53 # Build eggs
53 # Build eggs
54 python2.3 ./setup_bdist_egg.py
54 python2.3 ./eggsetup.py bdist_egg
55 python2.4 ./setup_bdist_egg.py
55 python2.4 ./eggsetup.py bdist_egg
56
56
57 # Call the windows build separately, so that the extra Windows scripts don't
57 # Call the windows build separately, so that the extra Windows scripts don't
58 # get pulled into Unix builds (setup.py has code which checks for
58 # get pulled into Unix builds (setup.py has code which checks for
59 # bdist_wininst)
59 # bdist_wininst)
60 #./setup.py bdist_wininst --install-script=ipython_win_post_install.py
60 #./setup.py bdist_wininst --install-script=ipython_win_post_install.py
61
61
62 # For now, make the win32 installer with a hand-built 2.3.5 python, which is
62 # For now, make the win32 installer with a hand-built 2.3.5 python, which is
63 # the only one that fixes a crash in the post-install phase.
63 # the only one that fixes a crash in the post-install phase.
64 $HOME/tmp/local/bin/python2.3 setup.py bdist_wininst \
64 $HOME/tmp/local/bin/python2.3 setup.py bdist_wininst \
65 --install-script=ipython_win_post_install.py
65 --install-script=ipython_win_post_install.py
66
66
67
68 # Register with the Python Package Index (PyPI)
67 # Register with the Python Package Index (PyPI)
69 echo "Registering with PyPI..."
68 echo "Registering with PyPI..."
70 cd $ipdir
69 cd $ipdir
71 ./setup.py register
70 ./setup.py register
72
71
73 # Upload all files
72 # Upload all files
74 cd $ipdir/dist
73 cd $ipdir/dist
75 echo "Uploading distribution files..."
74 echo "Uploading distribution files..."
76 scp * ipython@ipython.scipy.org:www/dist/
75 scp * ipython@ipython.scipy.org:www/dist/
77
76
78 echo "Uploading backup files..."
77 echo "Uploading backup files..."
79 cd ~/ipython/backup
78 cd ~/ipython/backup
80 scp `ls -1tr | tail -1` ipython@ipython.scipy.org:www/backup/
79 scp `ls -1tr | tail -1` ipython@ipython.scipy.org:www/backup/
81
80
82 echo "Updating webpage..."
81 echo "Updating webpage..."
83 cd $ipdir/doc
82 cd $ipdir/doc
84 www=~/ipython/homepage
83 www=~/ipython/homepage
85 cp ChangeLog NEWS $www
84 cp ChangeLog NEWS $www
86 rm -rf $www/doc/*
85 rm -rf $www/doc/*
87 cp -r manual.pdf manual/ $www/doc
86 cp -r manual.pdf manual/ $www/doc
88 cd $www
87 cd $www
89 ./update
88 ./update
90
89
91 # Alert package maintainers
90 # Alert package maintainers
92 echo "Alerting package maintainers..."
91 echo "Alerting package maintainers..."
93 maintainers='fperez@colorado.edu ariciputi@users.sourceforge.net jack@xiph.org tretkowski@inittab.de dryice@hotpop.com'
92 maintainers='fperez@colorado.edu ariciputi@users.sourceforge.net jack@xiph.org tretkowski@inittab.de dryice@hotpop.com'
94 #maintainers='fperez@colorado.edu'
93 #maintainers='fperez@colorado.edu'
95
94
96 for email in $maintainers
95 for email in $maintainers
97 do
96 do
98 echo "Emailing $email..."
97 echo "Emailing $email..."
99 mail -s "[Package maintainer notice] A new IPython is out. Version: $version" \
98 mail -s "[Package maintainer notice] A new IPython is out. Version: $version" \
100 $email < NEWS
99 $email < NEWS
101 done
100 done
102
101
103 echo "Done!"
102 echo "Done!"
@@ -1,28 +1,28 b''
1 #!/bin/sh
1 #!/bin/sh
2
2
3 # release test
3 # release test
4
4
5 # clean up build/dist directories
5 # clean up build/dist directories
6 rm -rf ~/ipython/ipython/build/*
6 rm -rf ~/ipython/ipython/build/*
7 rm -rf ~/ipython/ipython/dist/*
7 rm -rf ~/ipython/ipython/dist/*
8
8
9 # build source distros
9 # build source distros
10 cd ~/ipython/ipython
10 cd ~/ipython/ipython
11
11
12 ./setup.py sdist --formats=gztar
12 ./setup.py sdist --formats=gztar
13
13
14 python2.3 ./setup.py bdist_rpm --release=py23 --python=/usr/bin/python2.3
14 python2.3 ./setup.py bdist_rpm --release=py23 --python=/usr/bin/python2.3
15 python2.4 ./setup.py bdist_rpm --release=py24 --python=/usr/bin/python2.4
15 python2.4 ./setup.py bdist_rpm --release=py24 --python=/usr/bin/python2.4
16
16
17 # Build eggs
17 # Build eggs
18 python2.3 ./setup_bdist_egg.py
18 python2.3 ./eggsetup.py bdist_egg
19 python2.4 ./setup_bdist_egg.py
19 python2.4 ./eggsetup.py bdist_egg
20
20
21 # Call the windows build separately, so that the extra Windows scripts don't
21 # Call the windows build separately, so that the extra Windows scripts don't
22 # get pulled into Unix builds (setup.py has code which checks for
22 # get pulled into Unix builds (setup.py has code which checks for
23 # bdist_wininst)
23 # bdist_wininst)
24
24
25 # For now, make the win32 installer with a hand-built 2.3.5 python, which is
25 # For now, make the win32 installer with a hand-built 2.3.5 python, which is
26 # the only one that fixes a crash in the post-install phase.
26 # the only one that fixes a crash in the post-install phase.
27 $HOME/tmp/local/bin/python2.3 setup.py bdist_wininst \
27 $HOME/tmp/local/bin/python2.3 setup.py bdist_wininst \
28 --install-script=ipython_win_post_install.py
28 --install-script=ipython_win_post_install.py
General Comments 0
You need to be logged in to leave comments. Login now