##// END OF EJS Templates
Merged 1071-1076 from banches/0.7.1
vivainio -
Show More
@@ -1,233 +1,234 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 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 9 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
10 10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 #****************************************************************************
17 17 # Modules and globals
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>\n%s <%s>' % \
21 21 ( Release.authors['Janko'] + Release.authors['Fernando'] )
22 22 __license__ = Release.license
23 23
24 24 # Python standard modules
25 25 import glob
26 26 import os
27 27 import time
28 28
29 29 #****************************************************************************
30 30 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
31 31 # ipython and does input cache management. Finish cleanup later...
32 32
33 33 class Logger(object):
34 34 """A Logfile class with different policies for file creation"""
35 35
36 36 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
37 37
38 38 self._i00,self._i,self._ii,self._iii = '','','',''
39 39
40 40 # this is the full ipython instance, we need some attributes from it
41 41 # which won't exist until later. What a mess, clean up later...
42 42 self.shell = shell
43 43
44 44 self.logfname = logfname
45 45 self.loghead = loghead
46 46 self.logmode = logmode
47 47 self.logfile = None
48 48
49 49 # whether to also log output
50 50 self.log_output = False
51 51
52 52 # whether to put timestamps before each log entry
53 53 self.timestamp = False
54 54
55 55 # activity control flags
56 56 self.log_active = False
57 57
58 58 # logmode is a validated property
59 59 def _set_mode(self,mode):
60 60 if mode not in ['append','backup','global','over','rotate']:
61 61 raise ValueError,'invalid log mode %s given' % mode
62 62 self._logmode = mode
63 63
64 64 def _get_mode(self):
65 65 return self._logmode
66 66
67 67 logmode = property(_get_mode,_set_mode)
68 68
69 69 def logstart(self,logfname=None,loghead=None,logmode=None,
70 70 log_output=False,timestamp=False):
71 71 """Generate a new log-file with a default header.
72 72
73 73 Raises RuntimeError if the log has already been started"""
74 74
75 75 if self.logfile is not None:
76 76 raise RuntimeError('Log file is already active: %s' %
77 77 self.logfname)
78 78
79 79 self.log_active = True
80 80
81 81 # The three parameters can override constructor defaults
82 82 if logfname: self.logfname = logfname
83 83 if loghead: self.loghead = loghead
84 84 if logmode: self.logmode = logmode
85 85 self.timestamp = timestamp
86 86 self.log_output = log_output
87 87
88 88 # init depending on the log mode requested
89 89 isfile = os.path.isfile
90 90 logmode = self.logmode
91 91
92 92 if logmode == 'append':
93 93 self.logfile = open(self.logfname,'a')
94 94
95 95 elif logmode == 'backup':
96 96 if isfile(self.logfname):
97 97 backup_logname = self.logfname+'~'
98 98 # Manually remove any old backup, since os.rename may fail
99 99 # under Windows.
100 100 if isfile(backup_logname):
101 101 os.remove(backup_logname)
102 102 os.rename(self.logfname,backup_logname)
103 103 self.logfile = open(self.logfname,'w')
104 104
105 105 elif logmode == 'global':
106 106 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
107 107 self.logfile = open(self.logfname, 'a')
108 108
109 109 elif logmode == 'over':
110 110 if isfile(self.logfname):
111 111 os.remove(self.logfname)
112 112 self.logfile = open(self.logfname,'w')
113 113
114 114 elif logmode == 'rotate':
115 115 if isfile(self.logfname):
116 116 if isfile(self.logfname+'.001~'):
117 117 old = glob.glob(self.logfname+'.*~')
118 118 old.sort()
119 119 old.reverse()
120 120 for f in old:
121 121 root, ext = os.path.splitext(f)
122 122 num = int(ext[1:-1])+1
123 123 os.rename(f, root+'.'+`num`.zfill(3)+'~')
124 124 os.rename(self.logfname, self.logfname+'.001~')
125 125 self.logfile = open(self.logfname,'w')
126 126
127 127 if logmode != 'append':
128 128 self.logfile.write(self.loghead)
129 129
130 130 self.logfile.flush()
131 131
132 132 def switch_log(self,val):
133 133 """Switch logging on/off. val should be ONLY a boolean."""
134 134
135 135 if val not in [False,True,0,1]:
136 136 raise ValueError, \
137 137 'Call switch_log ONLY with a boolean argument, not with:',val
138 138
139 139 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
140 140
141 141 if self.logfile is None:
142 142 print """
143 143 Logging hasn't been started yet (use logstart for that).
144 144
145 145 %logon/%logoff are for temporarily starting and stopping logging for a logfile
146 146 which already exists. But you must first start the logging process with
147 147 %logstart (optionally giving a logfile name)."""
148 148
149 149 else:
150 150 if self.log_active == val:
151 151 print 'Logging is already',label[val]
152 152 else:
153 153 print 'Switching logging',label[val]
154 154 self.log_active = not self.log_active
155 155 self.log_active_out = self.log_active
156 156
157 157 def logstate(self):
158 158 """Print a status message about the logger."""
159 159 if self.logfile is None:
160 160 print 'Logging has not been activated.'
161 161 else:
162 162 state = self.log_active and 'active' or 'temporarily suspended'
163 163 print 'Filename :',self.logfname
164 164 print 'Mode :',self.logmode
165 165 print 'Output logging :',self.log_output
166 166 print 'Timestamping :',self.timestamp
167 167 print 'State :',state
168 168
169 169 def log(self, line,continuation=None):
170 170 """Write the line to a log and create input cache variables _i*."""
171 171
172 172 # update the auto _i tables
173 173 #print '***logging line',line # dbg
174 174 #print '***cache_count', self.shell.outputcache.prompt_count # dbg
175 175 try:
176 176 input_hist = self.shell.user_ns['_ih']
177 177 except:
178 178 print 'userns:',self.shell.user_ns.keys()
179 179 return
180 180
181 181 if not continuation and line:
182 182 self._iii = self._ii
183 183 self._ii = self._i
184 184 self._i = self._i00
185 185 # put back the final \n of every input line
186 186 self._i00 = line+'\n'
187 187 #print 'Logging input:<%s>' % line # dbg
188 188 input_hist.append(self._i00)
189 189 #print '---[%s]' % (len(input_hist)-1,) # dbg
190 190
191 191 # hackish access to top-level namespace to create _i1,_i2... dynamically
192 192 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
193 193 if self.shell.outputcache.do_full_cache:
194 194 in_num = self.shell.outputcache.prompt_count
195 195 # add blank lines if the input cache fell out of sync. This can
196 196 # happen for embedded instances which get killed via C-D and then
197 197 # get resumed.
198 198 while in_num >= len(input_hist):
199 199 input_hist.append('\n')
200 200 # but if the opposite is true (a macro can produce multiple inputs
201 201 # with no output display called), then bring the output counter in
202 202 # sync:
203 203 last_num = len(input_hist)-1
204 204 if in_num != last_num:
205 205 in_num = self.shell.outputcache.prompt_count = last_num
206 206 new_i = '_i%s' % in_num
207 207 if continuation:
208 208 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line)
209 209 input_hist[in_num] = self._i00
210 210 to_main[new_i] = self._i00
211 211 self.shell.user_ns.update(to_main)
212 212 self.log_write(line)
213 213
214 214 def log_write(self,data,kind='input'):
215 215 """Write data to the log file, if active"""
216 216
217 #print 'data: %r' % data # dbg
217 218 if self.log_active and data:
218 219 write = self.logfile.write
219 220 if kind=='input':
220 221 if self.timestamp:
221 222 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
222 223 time.localtime()))
223 224 write('%s\n' % data)
224 225 elif kind=='output' and self.log_output:
225 226 odata = '\n'.join(['#[Out]# %s' % s
226 227 for s in data.split('\n')])
227 228 write('%s\n' % odata)
228 229 self.logfile.flush()
229 230
230 231 def close_log(self):
231 232 self.logfile.close()
232 233 self.logfile = None
233 234 self.logfname = ''
@@ -1,2809 +1,2824 b''
1 1 # -*- coding: utf-8 -*-
2 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 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 import textwrap
35 35 from cStringIO import StringIO
36 36 from getopt import getopt
37 37 from pprint import pprint, pformat
38 38
39 39 # profile isn't bundled by default in Debian for license reasons
40 40 try:
41 41 import profile,pstats
42 42 except ImportError:
43 43 profile = pstats = None
44 44
45 45 # Homebrewed
46 46 from IPython import Debugger, OInspect, wildcard
47 47 from IPython.FakeModule import FakeModule
48 48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 49 from IPython.PyColorize import Parser
50 50 from IPython.ipstruct import Struct
51 51 from IPython.macro import Macro
52 52 from IPython.genutils import *
53 53 from IPython import platutils
54 54
55 55 #***************************************************************************
56 56 # Utility functions
57 57 def on_off(tag):
58 58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 59 return ['OFF','ON'][tag]
60 60
61 61 class Bunch: pass
62 62
63 63 #***************************************************************************
64 64 # Main class implementing Magic functionality
65 65 class Magic:
66 66 """Magic functions for InteractiveShell.
67 67
68 68 Shell functions which can be reached as %function_name. All magic
69 69 functions should accept a string, which they can parse for their own
70 70 needs. This can make some functions easier to type, eg `%cd ../`
71 71 vs. `%cd("../")`
72 72
73 73 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 74 at the command line, but it is is needed in the definition. """
75 75
76 76 # class globals
77 77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 78 'Automagic is ON, % prefix NOT needed for magic functions.']
79 79
80 80 #......................................................................
81 81 # some utility functions
82 82
83 83 def __init__(self,shell):
84 84
85 85 self.options_table = {}
86 86 if profile is None:
87 87 self.magic_prun = self.profile_missing_notice
88 88 self.shell = shell
89 89
90 90 # namespace for holding state we may need
91 91 self._magic_state = Bunch()
92 92
93 93 def profile_missing_notice(self, *args, **kwargs):
94 94 error("""\
95 95 The profile module could not be found. If you are a Debian user,
96 96 it has been removed from the standard Debian package because of its non-free
97 97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98 98
99 99 def default_option(self,fn,optstr):
100 100 """Make an entry in the options_table for fn, with value optstr"""
101 101
102 102 if fn not in self.lsmagic():
103 103 error("%s is not a magic function" % fn)
104 104 self.options_table[fn] = optstr
105 105
106 106 def lsmagic(self):
107 107 """Return a list of currently available magic functions.
108 108
109 109 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 110 ['magic_ls','magic_cd',...]"""
111 111
112 112 # FIXME. This needs a cleanup, in the way the magics list is built.
113 113
114 114 # magics in class definition
115 115 class_magic = lambda fn: fn.startswith('magic_') and \
116 116 callable(Magic.__dict__[fn])
117 117 # in instance namespace (run-time user additions)
118 118 inst_magic = lambda fn: fn.startswith('magic_') and \
119 119 callable(self.__dict__[fn])
120 120 # and bound magics by user (so they can access self):
121 121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 122 callable(self.__class__.__dict__[fn])
123 123 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 124 filter(inst_magic,self.__dict__.keys()) + \
125 125 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 126 out = []
127 127 for fn in magics:
128 128 out.append(fn.replace('magic_','',1))
129 129 out.sort()
130 130 return out
131 131
132 132 def extract_input_slices(self,slices):
133 133 """Return as a string a set of input history slices.
134 134
135 135 The set of slices is given as a list of strings (like ['1','4:8','9'],
136 136 since this function is for use by magic functions which get their
137 137 arguments as strings.
138 138
139 139 Note that slices can be called with two notations:
140 140
141 141 N:M -> standard python form, means including items N...(M-1).
142 142
143 143 N-M -> include items N..M (closed endpoint)."""
144 144
145 145 cmds = []
146 146 for chunk in slices:
147 147 if ':' in chunk:
148 148 ini,fin = map(int,chunk.split(':'))
149 149 elif '-' in chunk:
150 150 ini,fin = map(int,chunk.split('-'))
151 151 fin += 1
152 152 else:
153 153 ini = int(chunk)
154 154 fin = ini+1
155 155 cmds.append(self.shell.input_hist[ini:fin])
156 156 return cmds
157 157
158 158 def _ofind(self,oname):
159 159 """Find an object in the available namespaces.
160 160
161 161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
162 162
163 163 Has special code to detect magic functions.
164 164 """
165 165
166 166 oname = oname.strip()
167 167
168 168 # Namespaces to search in:
169 169 user_ns = self.shell.user_ns
170 170 internal_ns = self.shell.internal_ns
171 171 builtin_ns = __builtin__.__dict__
172 172 alias_ns = self.shell.alias_table
173 173
174 174 # Put them in a list. The order is important so that we find things in
175 175 # the same order that Python finds them.
176 176 namespaces = [ ('Interactive',user_ns),
177 177 ('IPython internal',internal_ns),
178 178 ('Python builtin',builtin_ns),
179 179 ('Alias',alias_ns),
180 180 ]
181 181
182 182 # initialize results to 'null'
183 183 found = 0; obj = None; ospace = None; ds = None;
184 184 ismagic = 0; isalias = 0
185 185
186 186 # Look for the given name by splitting it in parts. If the head is
187 187 # found, then we look for all the remaining parts as members, and only
188 188 # declare success if we can find them all.
189 189 oname_parts = oname.split('.')
190 190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
191 191 for nsname,ns in namespaces:
192 192 try:
193 193 obj = ns[oname_head]
194 194 except KeyError:
195 195 continue
196 196 else:
197 197 for part in oname_rest:
198 198 try:
199 199 obj = getattr(obj,part)
200 200 except:
201 201 # Blanket except b/c some badly implemented objects
202 202 # allow __getattr__ to raise exceptions other than
203 203 # AttributeError, which then crashes IPython.
204 204 break
205 205 else:
206 206 # If we finish the for loop (no break), we got all members
207 207 found = 1
208 208 ospace = nsname
209 209 if ns == alias_ns:
210 210 isalias = 1
211 211 break # namespace loop
212 212
213 213 # Try to see if it's magic
214 214 if not found:
215 215 if oname.startswith(self.shell.ESC_MAGIC):
216 216 oname = oname[1:]
217 217 obj = getattr(self,'magic_'+oname,None)
218 218 if obj is not None:
219 219 found = 1
220 220 ospace = 'IPython internal'
221 221 ismagic = 1
222 222
223 223 # Last try: special-case some literals like '', [], {}, etc:
224 224 if not found and oname_head in ["''",'""','[]','{}','()']:
225 225 obj = eval(oname_head)
226 226 found = 1
227 227 ospace = 'Interactive'
228 228
229 229 return {'found':found, 'obj':obj, 'namespace':ospace,
230 230 'ismagic':ismagic, 'isalias':isalias}
231 231
232 232 def arg_err(self,func):
233 233 """Print docstring if incorrect arguments were passed"""
234 234 print 'Error in arguments:'
235 235 print OInspect.getdoc(func)
236 236
237 237 def format_latex(self,strng):
238 238 """Format a string for latex inclusion."""
239 239
240 240 # Characters that need to be escaped for latex:
241 241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
242 242 # Magic command names as headers:
243 243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
244 244 re.MULTILINE)
245 245 # Magic commands
246 246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
247 247 re.MULTILINE)
248 248 # Paragraph continue
249 249 par_re = re.compile(r'\\$',re.MULTILINE)
250 250
251 251 # The "\n" symbol
252 252 newline_re = re.compile(r'\\n')
253 253
254 254 # Now build the string for output:
255 255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
256 256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
257 257 strng)
258 258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
259 259 strng = par_re.sub(r'\\\\',strng)
260 260 strng = escape_re.sub(r'\\\1',strng)
261 261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
262 262 return strng
263 263
264 264 def format_screen(self,strng):
265 265 """Format a string for screen printing.
266 266
267 267 This removes some latex-type format codes."""
268 268 # Paragraph continue
269 269 par_re = re.compile(r'\\$',re.MULTILINE)
270 270 strng = par_re.sub('',strng)
271 271 return strng
272 272
273 273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
274 274 """Parse options passed to an argument string.
275 275
276 276 The interface is similar to that of getopt(), but it returns back a
277 277 Struct with the options as keys and the stripped argument string still
278 278 as a string.
279 279
280 280 arg_str is quoted as a true sys.argv vector by using shlex.split.
281 281 This allows us to easily expand variables, glob files, quote
282 282 arguments, etc.
283 283
284 284 Options:
285 285 -mode: default 'string'. If given as 'list', the argument string is
286 286 returned as a list (split on whitespace) instead of a string.
287 287
288 288 -list_all: put all option values in lists. Normally only options
289 289 appearing more than once are put in a list."""
290 290
291 291 # inject default options at the beginning of the input line
292 292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
293 293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
294 294
295 295 mode = kw.get('mode','string')
296 296 if mode not in ['string','list']:
297 297 raise ValueError,'incorrect mode given: %s' % mode
298 298 # Get options
299 299 list_all = kw.get('list_all',0)
300 300
301 301 # Check if we have more than one argument to warrant extra processing:
302 302 odict = {} # Dictionary with options
303 303 args = arg_str.split()
304 304 if len(args) >= 1:
305 305 # If the list of inputs only has 0 or 1 thing in it, there's no
306 306 # need to look for options
307 307 argv = shlex_split(arg_str)
308 308 # Do regular option processing
309 309 opts,args = getopt(argv,opt_str,*long_opts)
310 310 for o,a in opts:
311 311 if o.startswith('--'):
312 312 o = o[2:]
313 313 else:
314 314 o = o[1:]
315 315 try:
316 316 odict[o].append(a)
317 317 except AttributeError:
318 318 odict[o] = [odict[o],a]
319 319 except KeyError:
320 320 if list_all:
321 321 odict[o] = [a]
322 322 else:
323 323 odict[o] = a
324 324
325 325 # Prepare opts,args for return
326 326 opts = Struct(odict)
327 327 if mode == 'string':
328 328 args = ' '.join(args)
329 329
330 330 return opts,args
331 331
332 332 #......................................................................
333 333 # And now the actual magic functions
334 334
335 335 # Functions for IPython shell work (vars,funcs, config, etc)
336 336 def magic_lsmagic(self, parameter_s = ''):
337 337 """List currently available magic functions."""
338 338 mesc = self.shell.ESC_MAGIC
339 339 print 'Available magic functions:\n'+mesc+\
340 340 (' '+mesc).join(self.lsmagic())
341 341 print '\n' + Magic.auto_status[self.shell.rc.automagic]
342 342 return None
343 343
344 344 def magic_magic(self, parameter_s = ''):
345 345 """Print information about the magic function system."""
346 346
347 347 mode = ''
348 348 try:
349 349 if parameter_s.split()[0] == '-latex':
350 350 mode = 'latex'
351 351 except:
352 352 pass
353 353
354 354 magic_docs = []
355 355 for fname in self.lsmagic():
356 356 mname = 'magic_' + fname
357 357 for space in (Magic,self,self.__class__):
358 358 try:
359 359 fn = space.__dict__[mname]
360 360 except KeyError:
361 361 pass
362 362 else:
363 363 break
364 364 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
365 365 fname,fn.__doc__))
366 366 magic_docs = ''.join(magic_docs)
367 367
368 368 if mode == 'latex':
369 369 print self.format_latex(magic_docs)
370 370 return
371 371 else:
372 372 magic_docs = self.format_screen(magic_docs)
373 373
374 374 outmsg = """
375 375 IPython's 'magic' functions
376 376 ===========================
377 377
378 378 The magic function system provides a series of functions which allow you to
379 379 control the behavior of IPython itself, plus a lot of system-type
380 380 features. All these functions are prefixed with a % character, but parameters
381 381 are given without parentheses or quotes.
382 382
383 383 NOTE: If you have 'automagic' enabled (via the command line option or with the
384 384 %automagic function), you don't need to type in the % explicitly. By default,
385 385 IPython ships with automagic on, so you should only rarely need the % escape.
386 386
387 387 Example: typing '%cd mydir' (without the quotes) changes you working directory
388 388 to 'mydir', if it exists.
389 389
390 390 You can define your own magic functions to extend the system. See the supplied
391 391 ipythonrc and example-magic.py files for details (in your ipython
392 392 configuration directory, typically $HOME/.ipython/).
393 393
394 394 You can also define your own aliased names for magic functions. In your
395 395 ipythonrc file, placing a line like:
396 396
397 397 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
398 398
399 399 will define %pf as a new name for %profile.
400 400
401 401 You can also call magics in code using the ipmagic() function, which IPython
402 402 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
403 403
404 404 For a list of the available magic functions, use %lsmagic. For a description
405 405 of any of them, type %magic_name?, e.g. '%cd?'.
406 406
407 407 Currently the magic system has the following functions:\n"""
408 408
409 409 mesc = self.shell.ESC_MAGIC
410 410 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
411 411 "\n\n%s%s\n\n%s" % (outmsg,
412 412 magic_docs,mesc,mesc,
413 413 (' '+mesc).join(self.lsmagic()),
414 414 Magic.auto_status[self.shell.rc.automagic] ) )
415 415
416 416 page(outmsg,screen_lines=self.shell.rc.screen_length)
417 417
418 418 def magic_automagic(self, parameter_s = ''):
419 419 """Make magic functions callable without having to type the initial %.
420 420
421 421 Toggles on/off (when off, you must call it as %automagic, of
422 422 course). Note that magic functions have lowest priority, so if there's
423 423 a variable whose name collides with that of a magic fn, automagic
424 424 won't work for that function (you get the variable instead). However,
425 425 if you delete the variable (del var), the previously shadowed magic
426 426 function becomes visible to automagic again."""
427 427
428 428 rc = self.shell.rc
429 429 rc.automagic = not rc.automagic
430 430 print '\n' + Magic.auto_status[rc.automagic]
431 431
432 432 def magic_autocall(self, parameter_s = ''):
433 433 """Make functions callable without having to type parentheses.
434 434
435 435 Usage:
436 436
437 437 %autocall [mode]
438 438
439 439 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
440 440 value is toggled on and off (remembering the previous state)."""
441 441
442 442 rc = self.shell.rc
443 443
444 444 if parameter_s:
445 445 arg = int(parameter_s)
446 446 else:
447 447 arg = 'toggle'
448 448
449 449 if not arg in (0,1,2,'toggle'):
450 450 error('Valid modes: (0->Off, 1->Smart, 2->Full')
451 451 return
452 452
453 453 if arg in (0,1,2):
454 454 rc.autocall = arg
455 455 else: # toggle
456 456 if rc.autocall:
457 457 self._magic_state.autocall_save = rc.autocall
458 458 rc.autocall = 0
459 459 else:
460 460 try:
461 461 rc.autocall = self._magic_state.autocall_save
462 462 except AttributeError:
463 463 rc.autocall = self._magic_state.autocall_save = 1
464 464
465 465 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
466 466
467 467 def magic_autoindent(self, parameter_s = ''):
468 468 """Toggle autoindent on/off (if available)."""
469 469
470 470 self.shell.set_autoindent()
471 471 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
472 472
473 473 def magic_system_verbose(self, parameter_s = ''):
474 474 """Toggle verbose printing of system calls on/off."""
475 475
476 476 self.shell.rc_set_toggle('system_verbose')
477 477 print "System verbose printing is:",\
478 478 ['OFF','ON'][self.shell.rc.system_verbose]
479 479
480 480 def magic_history(self, parameter_s = ''):
481 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)\\
484 %history [-n] n -> print at most n inputs\\
485 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
486
483 %history -> print at most 40 inputs (some may be multi-line)\\
484 %history n -> print at most n inputs\\
485 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
486
487 487 Each input's number <n> is shown, and is accessible as the
488 488 automatically generated variable _i<n>. Multi-line statements are
489 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
492 you want to get a printout of many lines which can be directly pasted
493 into a text editor.
494 -n: do NOT print line numbers. This is useful if you want to get a
495 printout of many lines which can be directly pasted into a text
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 508 shell = self.shell
498 509 if not shell.outputcache.do_full_cache:
499 510 print 'This feature is only available if numbered prompts are in use.'
500 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 519 default_length = 40
505 520 if len(args) == 0:
506 521 final = len(input_hist)
507 522 init = max(1,final-default_length)
508 523 elif len(args) == 1:
509 524 final = len(input_hist)
510 525 init = max(1,final-int(args[0]))
511 526 elif len(args) == 2:
512 527 init,final = map(int,args)
513 528 else:
514 529 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
515 530 print self.magic_hist.__doc__
516 531 return
517 532 width = len(str(final))
518 533 line_sep = ['','\n']
519 534 print_nums = not opts.has_key('n')
520 535 for in_num in range(init,final):
521 536 inline = input_hist[in_num]
522 537 multiline = int(inline.count('\n') > 1)
523 538 if print_nums:
524 539 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
525 540 print inline,
526 541
527 542 def magic_hist(self, parameter_s=''):
528 543 """Alternate name for %history."""
529 544 return self.magic_history(parameter_s)
530 545
531 546 def magic_p(self, parameter_s=''):
532 547 """Just a short alias for Python's 'print'."""
533 548 exec 'print ' + parameter_s in self.shell.user_ns
534 549
535 550 def magic_r(self, parameter_s=''):
536 551 """Repeat previous input.
537 552
538 553 If given an argument, repeats the previous command which starts with
539 554 the same string, otherwise it just repeats the previous input.
540 555
541 556 Shell escaped commands (with ! as first character) are not recognized
542 557 by this system, only pure python code and magic commands.
543 558 """
544 559
545 560 start = parameter_s.strip()
546 561 esc_magic = self.shell.ESC_MAGIC
547 562 # Identify magic commands even if automagic is on (which means
548 563 # the in-memory version is different from that typed by the user).
549 564 if self.shell.rc.automagic:
550 565 start_magic = esc_magic+start
551 566 else:
552 567 start_magic = start
553 568 # Look through the input history in reverse
554 569 for n in range(len(self.shell.input_hist)-2,0,-1):
555 570 input = self.shell.input_hist[n]
556 571 # skip plain 'r' lines so we don't recurse to infinity
557 572 if input != 'ipmagic("r")\n' and \
558 573 (input.startswith(start) or input.startswith(start_magic)):
559 574 #print 'match',`input` # dbg
560 575 print 'Executing:',input,
561 576 self.shell.runlines(input)
562 577 return
563 578 print 'No previous input matching `%s` found.' % start
564 579
565 580 def magic_page(self, parameter_s=''):
566 581 """Pretty print the object and display it through a pager.
567 582
568 583 If no parameter is given, use _ (last output)."""
569 584 # After a function contributed by Olivier Aubert, slightly modified.
570 585
571 586 oname = parameter_s and parameter_s or '_'
572 587 info = self._ofind(oname)
573 588 if info['found']:
574 589 page(pformat(info['obj']))
575 590 else:
576 591 print 'Object `%s` not found' % oname
577 592
578 593 def magic_profile(self, parameter_s=''):
579 594 """Print your currently active IPyhton profile."""
580 595 if self.shell.rc.profile:
581 596 printpl('Current IPython profile: $self.shell.rc.profile.')
582 597 else:
583 598 print 'No profile active.'
584 599
585 600 def _inspect(self,meth,oname,**kw):
586 601 """Generic interface to the inspector system.
587 602
588 603 This function is meant to be called by pdef, pdoc & friends."""
589 604
590 605 oname = oname.strip()
591 606 info = Struct(self._ofind(oname))
592 607 if info.found:
593 608 pmethod = getattr(self.shell.inspector,meth)
594 609 formatter = info.ismagic and self.format_screen or None
595 610 if meth == 'pdoc':
596 611 pmethod(info.obj,oname,formatter)
597 612 elif meth == 'pinfo':
598 613 pmethod(info.obj,oname,formatter,info,**kw)
599 614 else:
600 615 pmethod(info.obj,oname)
601 616 else:
602 617 print 'Object `%s` not found.' % oname
603 618 return 'not found' # so callers can take other action
604 619
605 620 def magic_pdef(self, parameter_s=''):
606 621 """Print the definition header for any callable object.
607 622
608 623 If the object is a class, print the constructor information."""
609 624 self._inspect('pdef',parameter_s)
610 625
611 626 def magic_pdoc(self, parameter_s=''):
612 627 """Print the docstring for an object.
613 628
614 629 If the given object is a class, it will print both the class and the
615 630 constructor docstrings."""
616 631 self._inspect('pdoc',parameter_s)
617 632
618 633 def magic_psource(self, parameter_s=''):
619 634 """Print (or run through pager) the source code for an object."""
620 635 self._inspect('psource',parameter_s)
621 636
622 637 def magic_pfile(self, parameter_s=''):
623 638 """Print (or run through pager) the file where an object is defined.
624 639
625 640 The file opens at the line where the object definition begins. IPython
626 641 will honor the environment variable PAGER if set, and otherwise will
627 642 do its best to print the file in a convenient form.
628 643
629 644 If the given argument is not an object currently defined, IPython will
630 645 try to interpret it as a filename (automatically adding a .py extension
631 646 if needed). You can thus use %pfile as a syntax highlighting code
632 647 viewer."""
633 648
634 649 # first interpret argument as an object name
635 650 out = self._inspect('pfile',parameter_s)
636 651 # if not, try the input as a filename
637 652 if out == 'not found':
638 653 try:
639 654 filename = get_py_filename(parameter_s)
640 655 except IOError,msg:
641 656 print msg
642 657 return
643 658 page(self.shell.inspector.format(file(filename).read()))
644 659
645 660 def magic_pinfo(self, parameter_s=''):
646 661 """Provide detailed information about an object.
647 662
648 663 '%pinfo object' is just a synonym for object? or ?object."""
649 664
650 665 #print 'pinfo par: <%s>' % parameter_s # dbg
651 666
652 667 # detail_level: 0 -> obj? , 1 -> obj??
653 668 detail_level = 0
654 669 # We need to detect if we got called as 'pinfo pinfo foo', which can
655 670 # happen if the user types 'pinfo foo?' at the cmd line.
656 671 pinfo,qmark1,oname,qmark2 = \
657 672 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
658 673 if pinfo or qmark1 or qmark2:
659 674 detail_level = 1
660 675 if "*" in oname:
661 676 self.magic_psearch(oname)
662 677 else:
663 678 self._inspect('pinfo',oname,detail_level=detail_level)
664 679
665 680 def magic_psearch(self, parameter_s=''):
666 681 """Search for object in namespaces by wildcard.
667 682
668 683 %psearch [options] PATTERN [OBJECT TYPE]
669 684
670 685 Note: ? can be used as a synonym for %psearch, at the beginning or at
671 686 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
672 687 rest of the command line must be unchanged (options come first), so
673 688 for example the following forms are equivalent
674 689
675 690 %psearch -i a* function
676 691 -i a* function?
677 692 ?-i a* function
678 693
679 694 Arguments:
680 695
681 696 PATTERN
682 697
683 698 where PATTERN is a string containing * as a wildcard similar to its
684 699 use in a shell. The pattern is matched in all namespaces on the
685 700 search path. By default objects starting with a single _ are not
686 701 matched, many IPython generated objects have a single
687 702 underscore. The default is case insensitive matching. Matching is
688 703 also done on the attributes of objects and not only on the objects
689 704 in a module.
690 705
691 706 [OBJECT TYPE]
692 707
693 708 Is the name of a python type from the types module. The name is
694 709 given in lowercase without the ending type, ex. StringType is
695 710 written string. By adding a type here only objects matching the
696 711 given type are matched. Using all here makes the pattern match all
697 712 types (this is the default).
698 713
699 714 Options:
700 715
701 716 -a: makes the pattern match even objects whose names start with a
702 717 single underscore. These names are normally ommitted from the
703 718 search.
704 719
705 720 -i/-c: make the pattern case insensitive/sensitive. If neither of
706 721 these options is given, the default is read from your ipythonrc
707 722 file. The option name which sets this value is
708 723 'wildcards_case_sensitive'. If this option is not specified in your
709 724 ipythonrc file, IPython's internal default is to do a case sensitive
710 725 search.
711 726
712 727 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
713 728 specifiy can be searched in any of the following namespaces:
714 729 'builtin', 'user', 'user_global','internal', 'alias', where
715 730 'builtin' and 'user' are the search defaults. Note that you should
716 731 not use quotes when specifying namespaces.
717 732
718 733 'Builtin' contains the python module builtin, 'user' contains all
719 734 user data, 'alias' only contain the shell aliases and no python
720 735 objects, 'internal' contains objects used by IPython. The
721 736 'user_global' namespace is only used by embedded IPython instances,
722 737 and it contains module-level globals. You can add namespaces to the
723 738 search with -s or exclude them with -e (these options can be given
724 739 more than once).
725 740
726 741 Examples:
727 742
728 743 %psearch a* -> objects beginning with an a
729 744 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
730 745 %psearch a* function -> all functions beginning with an a
731 746 %psearch re.e* -> objects beginning with an e in module re
732 747 %psearch r*.e* -> objects that start with e in modules starting in r
733 748 %psearch r*.* string -> all strings in modules beginning with r
734 749
735 750 Case sensitve search:
736 751
737 752 %psearch -c a* list all object beginning with lower case a
738 753
739 754 Show objects beginning with a single _:
740 755
741 756 %psearch -a _* list objects beginning with a single underscore"""
742 757
743 758 # default namespaces to be searched
744 759 def_search = ['user','builtin']
745 760
746 761 # Process options/args
747 762 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
748 763 opt = opts.get
749 764 shell = self.shell
750 765 psearch = shell.inspector.psearch
751 766
752 767 # select case options
753 768 if opts.has_key('i'):
754 769 ignore_case = True
755 770 elif opts.has_key('c'):
756 771 ignore_case = False
757 772 else:
758 773 ignore_case = not shell.rc.wildcards_case_sensitive
759 774
760 775 # Build list of namespaces to search from user options
761 776 def_search.extend(opt('s',[]))
762 777 ns_exclude = ns_exclude=opt('e',[])
763 778 ns_search = [nm for nm in def_search if nm not in ns_exclude]
764 779
765 780 # Call the actual search
766 781 try:
767 782 psearch(args,shell.ns_table,ns_search,
768 783 show_all=opt('a'),ignore_case=ignore_case)
769 784 except:
770 785 shell.showtraceback()
771 786
772 787 def magic_who_ls(self, parameter_s=''):
773 788 """Return a sorted list of all interactive variables.
774 789
775 790 If arguments are given, only variables of types matching these
776 791 arguments are returned."""
777 792
778 793 user_ns = self.shell.user_ns
779 794 internal_ns = self.shell.internal_ns
780 795 user_config_ns = self.shell.user_config_ns
781 796 out = []
782 797 typelist = parameter_s.split()
783 798
784 799 for i in user_ns:
785 800 if not (i.startswith('_') or i.startswith('_i')) \
786 801 and not (i in internal_ns or i in user_config_ns):
787 802 if typelist:
788 803 if type(user_ns[i]).__name__ in typelist:
789 804 out.append(i)
790 805 else:
791 806 out.append(i)
792 807 out.sort()
793 808 return out
794 809
795 810 def magic_who(self, parameter_s=''):
796 811 """Print all interactive variables, with some minimal formatting.
797 812
798 813 If any arguments are given, only variables whose type matches one of
799 814 these are printed. For example:
800 815
801 816 %who function str
802 817
803 818 will only list functions and strings, excluding all other types of
804 819 variables. To find the proper type names, simply use type(var) at a
805 820 command line to see how python prints type names. For example:
806 821
807 822 In [1]: type('hello')\\
808 823 Out[1]: <type 'str'>
809 824
810 825 indicates that the type name for strings is 'str'.
811 826
812 827 %who always excludes executed names loaded through your configuration
813 828 file and things which are internal to IPython.
814 829
815 830 This is deliberate, as typically you may load many modules and the
816 831 purpose of %who is to show you only what you've manually defined."""
817 832
818 833 varlist = self.magic_who_ls(parameter_s)
819 834 if not varlist:
820 835 print 'Interactive namespace is empty.'
821 836 return
822 837
823 838 # if we have variables, move on...
824 839
825 840 # stupid flushing problem: when prompts have no separators, stdout is
826 841 # getting lost. I'm starting to think this is a python bug. I'm having
827 842 # to force a flush with a print because even a sys.stdout.flush
828 843 # doesn't seem to do anything!
829 844
830 845 count = 0
831 846 for i in varlist:
832 847 print i+'\t',
833 848 count += 1
834 849 if count > 8:
835 850 count = 0
836 851 print
837 852 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
838 853
839 854 print # well, this does force a flush at the expense of an extra \n
840 855
841 856 def magic_whos(self, parameter_s=''):
842 857 """Like %who, but gives some extra information about each variable.
843 858
844 859 The same type filtering of %who can be applied here.
845 860
846 861 For all variables, the type is printed. Additionally it prints:
847 862
848 863 - For {},[],(): their length.
849 864
850 865 - For Numeric arrays, a summary with shape, number of elements,
851 866 typecode and size in memory.
852 867
853 868 - Everything else: a string representation, snipping their middle if
854 869 too long."""
855 870
856 871 varnames = self.magic_who_ls(parameter_s)
857 872 if not varnames:
858 873 print 'Interactive namespace is empty.'
859 874 return
860 875
861 876 # if we have variables, move on...
862 877
863 878 # for these types, show len() instead of data:
864 879 seq_types = [types.DictType,types.ListType,types.TupleType]
865 880
866 881 # for Numeric arrays, display summary info
867 882 try:
868 883 import Numeric
869 884 except ImportError:
870 885 array_type = None
871 886 else:
872 887 array_type = Numeric.ArrayType.__name__
873 888
874 889 # Find all variable names and types so we can figure out column sizes
875 890 get_vars = lambda i: self.shell.user_ns[i]
876 891 type_name = lambda v: type(v).__name__
877 892 varlist = map(get_vars,varnames)
878 893
879 894 typelist = []
880 895 for vv in varlist:
881 896 tt = type_name(vv)
882 897 if tt=='instance':
883 898 typelist.append(str(vv.__class__))
884 899 else:
885 900 typelist.append(tt)
886 901
887 902 # column labels and # of spaces as separator
888 903 varlabel = 'Variable'
889 904 typelabel = 'Type'
890 905 datalabel = 'Data/Info'
891 906 colsep = 3
892 907 # variable format strings
893 908 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
894 909 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
895 910 aformat = "%s: %s elems, type `%s`, %s bytes"
896 911 # find the size of the columns to format the output nicely
897 912 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
898 913 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
899 914 # table header
900 915 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
901 916 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
902 917 # and the table itself
903 918 kb = 1024
904 919 Mb = 1048576 # kb**2
905 920 for vname,var,vtype in zip(varnames,varlist,typelist):
906 921 print itpl(vformat),
907 922 if vtype in seq_types:
908 923 print len(var)
909 924 elif vtype==array_type:
910 925 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
911 926 vsize = Numeric.size(var)
912 927 vbytes = vsize*var.itemsize()
913 928 if vbytes < 100000:
914 929 print aformat % (vshape,vsize,var.typecode(),vbytes)
915 930 else:
916 931 print aformat % (vshape,vsize,var.typecode(),vbytes),
917 932 if vbytes < Mb:
918 933 print '(%s kb)' % (vbytes/kb,)
919 934 else:
920 935 print '(%s Mb)' % (vbytes/Mb,)
921 936 else:
922 937 vstr = str(var).replace('\n','\\n')
923 938 if len(vstr) < 50:
924 939 print vstr
925 940 else:
926 941 printpl(vfmt_short)
927 942
928 943 def magic_reset(self, parameter_s=''):
929 944 """Resets the namespace by removing all names defined by the user.
930 945
931 946 Input/Output history are left around in case you need them."""
932 947
933 948 ans = raw_input(
934 949 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
935 950 if not ans.lower() == 'y':
936 951 print 'Nothing done.'
937 952 return
938 953 user_ns = self.shell.user_ns
939 954 for i in self.magic_who_ls():
940 955 del(user_ns[i])
941 956
942 957 def magic_config(self,parameter_s=''):
943 958 """Show IPython's internal configuration."""
944 959
945 960 page('Current configuration structure:\n'+
946 961 pformat(self.shell.rc.dict()))
947 962
948 963 def magic_logstart(self,parameter_s=''):
949 964 """Start logging anywhere in a session.
950 965
951 966 %logstart [-o|-t] [log_name [log_mode]]
952 967
953 968 If no name is given, it defaults to a file named 'ipython_log.py' in your
954 969 current directory, in 'rotate' mode (see below).
955 970
956 971 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
957 972 history up to that point and then continues logging.
958 973
959 974 %logstart takes a second optional parameter: logging mode. This can be one
960 975 of (note that the modes are given unquoted):\\
961 976 append: well, that says it.\\
962 977 backup: rename (if exists) to name~ and start name.\\
963 978 global: single logfile in your home dir, appended to.\\
964 979 over : overwrite existing log.\\
965 980 rotate: create rotating logs name.1~, name.2~, etc.
966 981
967 982 Options:
968 983
969 984 -o: log also IPython's output. In this mode, all commands which
970 985 generate an Out[NN] prompt are recorded to the logfile, right after
971 986 their corresponding input line. The output lines are always
972 987 prepended with a '#[Out]# ' marker, so that the log remains valid
973 988 Python code.
974 989
975 990 Since this marker is always the same, filtering only the output from
976 991 a log is very easy, using for example a simple awk call:
977 992
978 993 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
979 994
980 995 -t: put timestamps before each input line logged (these are put in
981 996 comments)."""
982 997
983 998 opts,par = self.parse_options(parameter_s,'ot')
984 999 log_output = 'o' in opts
985 1000 timestamp = 't' in opts
986 1001
987 1002 rc = self.shell.rc
988 1003 logger = self.shell.logger
989 1004
990 1005 # if no args are given, the defaults set in the logger constructor by
991 1006 # ipytohn remain valid
992 1007 if par:
993 1008 try:
994 1009 logfname,logmode = par.split()
995 1010 except:
996 1011 logfname = par
997 1012 logmode = 'backup'
998 1013 else:
999 1014 logfname = logger.logfname
1000 1015 logmode = logger.logmode
1001 1016 # put logfname into rc struct as if it had been called on the command
1002 1017 # line, so it ends up saved in the log header Save it in case we need
1003 1018 # to restore it...
1004 1019 old_logfile = rc.opts.get('logfile','')
1005 1020 if logfname:
1006 1021 logfname = os.path.expanduser(logfname)
1007 1022 rc.opts.logfile = logfname
1008 1023 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1009 1024 try:
1010 1025 started = logger.logstart(logfname,loghead,logmode,
1011 1026 log_output,timestamp)
1012 1027 except:
1013 1028 rc.opts.logfile = old_logfile
1014 1029 warn("Couldn't start log: %s" % sys.exc_info()[1])
1015 1030 else:
1016 1031 # log input history up to this point, optionally interleaving
1017 1032 # output if requested
1018 1033
1019 1034 if timestamp:
1020 1035 # disable timestamping for the previous history, since we've
1021 1036 # lost those already (no time machine here).
1022 1037 logger.timestamp = False
1023 1038 if log_output:
1024 1039 log_write = logger.log_write
1025 1040 input_hist = self.shell.input_hist
1026 1041 output_hist = self.shell.output_hist
1027 1042 for n in range(1,len(input_hist)-1):
1028 1043 log_write(input_hist[n].rstrip())
1029 1044 if n in output_hist:
1030 1045 log_write(repr(output_hist[n]),'output')
1031 1046 else:
1032 1047 logger.log_write(self.shell.input_hist[1:])
1033 1048 if timestamp:
1034 1049 # re-enable timestamping
1035 1050 logger.timestamp = True
1036 1051
1037 1052 print ('Activating auto-logging. '
1038 1053 'Current session state plus future input saved.')
1039 1054 logger.logstate()
1040 1055
1041 1056 def magic_logoff(self,parameter_s=''):
1042 1057 """Temporarily stop logging.
1043 1058
1044 1059 You must have previously started logging."""
1045 1060 self.shell.logger.switch_log(0)
1046 1061
1047 1062 def magic_logon(self,parameter_s=''):
1048 1063 """Restart logging.
1049 1064
1050 1065 This function is for restarting logging which you've temporarily
1051 1066 stopped with %logoff. For starting logging for the first time, you
1052 1067 must use the %logstart function, which allows you to specify an
1053 1068 optional log filename."""
1054 1069
1055 1070 self.shell.logger.switch_log(1)
1056 1071
1057 1072 def magic_logstate(self,parameter_s=''):
1058 1073 """Print the status of the logging system."""
1059 1074
1060 1075 self.shell.logger.logstate()
1061 1076
1062 1077 def magic_pdb(self, parameter_s=''):
1063 1078 """Control the calling of the pdb interactive debugger.
1064 1079
1065 1080 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1066 1081 argument it works as a toggle.
1067 1082
1068 1083 When an exception is triggered, IPython can optionally call the
1069 1084 interactive pdb debugger after the traceback printout. %pdb toggles
1070 1085 this feature on and off."""
1071 1086
1072 1087 par = parameter_s.strip().lower()
1073 1088
1074 1089 if par:
1075 1090 try:
1076 1091 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1077 1092 except KeyError:
1078 1093 print ('Incorrect argument. Use on/1, off/0, '
1079 1094 'or nothing for a toggle.')
1080 1095 return
1081 1096 else:
1082 1097 # toggle
1083 1098 new_pdb = not self.shell.InteractiveTB.call_pdb
1084 1099
1085 1100 # set on the shell
1086 1101 self.shell.call_pdb = new_pdb
1087 1102 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1088 1103
1089 1104 def magic_prun(self, parameter_s ='',user_mode=1,
1090 1105 opts=None,arg_lst=None,prog_ns=None):
1091 1106
1092 1107 """Run a statement through the python code profiler.
1093 1108
1094 1109 Usage:\\
1095 1110 %prun [options] statement
1096 1111
1097 1112 The given statement (which doesn't require quote marks) is run via the
1098 1113 python profiler in a manner similar to the profile.run() function.
1099 1114 Namespaces are internally managed to work correctly; profile.run
1100 1115 cannot be used in IPython because it makes certain assumptions about
1101 1116 namespaces which do not hold under IPython.
1102 1117
1103 1118 Options:
1104 1119
1105 1120 -l <limit>: you can place restrictions on what or how much of the
1106 1121 profile gets printed. The limit value can be:
1107 1122
1108 1123 * A string: only information for function names containing this string
1109 1124 is printed.
1110 1125
1111 1126 * An integer: only these many lines are printed.
1112 1127
1113 1128 * A float (between 0 and 1): this fraction of the report is printed
1114 1129 (for example, use a limit of 0.4 to see the topmost 40% only).
1115 1130
1116 1131 You can combine several limits with repeated use of the option. For
1117 1132 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1118 1133 information about class constructors.
1119 1134
1120 1135 -r: return the pstats.Stats object generated by the profiling. This
1121 1136 object has all the information about the profile in it, and you can
1122 1137 later use it for further analysis or in other functions.
1123 1138
1124 1139 Since magic functions have a particular form of calling which prevents
1125 1140 you from writing something like:\\
1126 1141 In [1]: p = %prun -r print 4 # invalid!\\
1127 1142 you must instead use IPython's automatic variables to assign this:\\
1128 1143 In [1]: %prun -r print 4 \\
1129 1144 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1130 1145 In [2]: stats = _
1131 1146
1132 1147 If you really need to assign this value via an explicit function call,
1133 1148 you can always tap directly into the true name of the magic function
1134 1149 by using the ipmagic function (which IPython automatically adds to the
1135 1150 builtins):\\
1136 1151 In [3]: stats = ipmagic('prun','-r print 4')
1137 1152
1138 1153 You can type ipmagic? for more details on ipmagic.
1139 1154
1140 1155 -s <key>: sort profile by given key. You can provide more than one key
1141 1156 by using the option several times: '-s key1 -s key2 -s key3...'. The
1142 1157 default sorting key is 'time'.
1143 1158
1144 1159 The following is copied verbatim from the profile documentation
1145 1160 referenced below:
1146 1161
1147 1162 When more than one key is provided, additional keys are used as
1148 1163 secondary criteria when the there is equality in all keys selected
1149 1164 before them.
1150 1165
1151 1166 Abbreviations can be used for any key names, as long as the
1152 1167 abbreviation is unambiguous. The following are the keys currently
1153 1168 defined:
1154 1169
1155 1170 Valid Arg Meaning\\
1156 1171 "calls" call count\\
1157 1172 "cumulative" cumulative time\\
1158 1173 "file" file name\\
1159 1174 "module" file name\\
1160 1175 "pcalls" primitive call count\\
1161 1176 "line" line number\\
1162 1177 "name" function name\\
1163 1178 "nfl" name/file/line\\
1164 1179 "stdname" standard name\\
1165 1180 "time" internal time
1166 1181
1167 1182 Note that all sorts on statistics are in descending order (placing
1168 1183 most time consuming items first), where as name, file, and line number
1169 1184 searches are in ascending order (i.e., alphabetical). The subtle
1170 1185 distinction between "nfl" and "stdname" is that the standard name is a
1171 1186 sort of the name as printed, which means that the embedded line
1172 1187 numbers get compared in an odd way. For example, lines 3, 20, and 40
1173 1188 would (if the file names were the same) appear in the string order
1174 1189 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1175 1190 line numbers. In fact, sort_stats("nfl") is the same as
1176 1191 sort_stats("name", "file", "line").
1177 1192
1178 1193 -T <filename>: save profile results as shown on screen to a text
1179 1194 file. The profile is still shown on screen.
1180 1195
1181 1196 -D <filename>: save (via dump_stats) profile statistics to given
1182 1197 filename. This data is in a format understod by the pstats module, and
1183 1198 is generated by a call to the dump_stats() method of profile
1184 1199 objects. The profile is still shown on screen.
1185 1200
1186 1201 If you want to run complete programs under the profiler's control, use
1187 1202 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1188 1203 contains profiler specific options as described here.
1189 1204
1190 1205 You can read the complete documentation for the profile module with:\\
1191 1206 In [1]: import profile; profile.help() """
1192 1207
1193 1208 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1194 1209 # protect user quote marks
1195 1210 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1196 1211
1197 1212 if user_mode: # regular user call
1198 1213 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1199 1214 list_all=1)
1200 1215 namespace = self.shell.user_ns
1201 1216 else: # called to run a program by %run -p
1202 1217 try:
1203 1218 filename = get_py_filename(arg_lst[0])
1204 1219 except IOError,msg:
1205 1220 error(msg)
1206 1221 return
1207 1222
1208 1223 arg_str = 'execfile(filename,prog_ns)'
1209 1224 namespace = locals()
1210 1225
1211 1226 opts.merge(opts_def)
1212 1227
1213 1228 prof = profile.Profile()
1214 1229 try:
1215 1230 prof = prof.runctx(arg_str,namespace,namespace)
1216 1231 sys_exit = ''
1217 1232 except SystemExit:
1218 1233 sys_exit = """*** SystemExit exception caught in code being profiled."""
1219 1234
1220 1235 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1221 1236
1222 1237 lims = opts.l
1223 1238 if lims:
1224 1239 lims = [] # rebuild lims with ints/floats/strings
1225 1240 for lim in opts.l:
1226 1241 try:
1227 1242 lims.append(int(lim))
1228 1243 except ValueError:
1229 1244 try:
1230 1245 lims.append(float(lim))
1231 1246 except ValueError:
1232 1247 lims.append(lim)
1233 1248
1234 1249 # trap output
1235 1250 sys_stdout = sys.stdout
1236 1251 stdout_trap = StringIO()
1237 1252 try:
1238 1253 sys.stdout = stdout_trap
1239 1254 stats.print_stats(*lims)
1240 1255 finally:
1241 1256 sys.stdout = sys_stdout
1242 1257 output = stdout_trap.getvalue()
1243 1258 output = output.rstrip()
1244 1259
1245 1260 page(output,screen_lines=self.shell.rc.screen_length)
1246 1261 print sys_exit,
1247 1262
1248 1263 dump_file = opts.D[0]
1249 1264 text_file = opts.T[0]
1250 1265 if dump_file:
1251 1266 prof.dump_stats(dump_file)
1252 1267 print '\n*** Profile stats marshalled to file',\
1253 1268 `dump_file`+'.',sys_exit
1254 1269 if text_file:
1255 1270 file(text_file,'w').write(output)
1256 1271 print '\n*** Profile printout saved to text file',\
1257 1272 `text_file`+'.',sys_exit
1258 1273
1259 1274 if opts.has_key('r'):
1260 1275 return stats
1261 1276 else:
1262 1277 return None
1263 1278
1264 1279 def magic_run(self, parameter_s ='',runner=None):
1265 1280 """Run the named file inside IPython as a program.
1266 1281
1267 1282 Usage:\\
1268 1283 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1269 1284
1270 1285 Parameters after the filename are passed as command-line arguments to
1271 1286 the program (put in sys.argv). Then, control returns to IPython's
1272 1287 prompt.
1273 1288
1274 1289 This is similar to running at a system prompt:\\
1275 1290 $ python file args\\
1276 1291 but with the advantage of giving you IPython's tracebacks, and of
1277 1292 loading all variables into your interactive namespace for further use
1278 1293 (unless -p is used, see below).
1279 1294
1280 1295 The file is executed in a namespace initially consisting only of
1281 1296 __name__=='__main__' and sys.argv constructed as indicated. It thus
1282 1297 sees its environment as if it were being run as a stand-alone
1283 1298 program. But after execution, the IPython interactive namespace gets
1284 1299 updated with all variables defined in the program (except for __name__
1285 1300 and sys.argv). This allows for very convenient loading of code for
1286 1301 interactive work, while giving each program a 'clean sheet' to run in.
1287 1302
1288 1303 Options:
1289 1304
1290 1305 -n: __name__ is NOT set to '__main__', but to the running file's name
1291 1306 without extension (as python does under import). This allows running
1292 1307 scripts and reloading the definitions in them without calling code
1293 1308 protected by an ' if __name__ == "__main__" ' clause.
1294 1309
1295 1310 -i: run the file in IPython's namespace instead of an empty one. This
1296 1311 is useful if you are experimenting with code written in a text editor
1297 1312 which depends on variables defined interactively.
1298 1313
1299 1314 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1300 1315 being run. This is particularly useful if IPython is being used to
1301 1316 run unittests, which always exit with a sys.exit() call. In such
1302 1317 cases you are interested in the output of the test results, not in
1303 1318 seeing a traceback of the unittest module.
1304 1319
1305 1320 -t: print timing information at the end of the run. IPython will give
1306 1321 you an estimated CPU time consumption for your script, which under
1307 1322 Unix uses the resource module to avoid the wraparound problems of
1308 1323 time.clock(). Under Unix, an estimate of time spent on system tasks
1309 1324 is also given (for Windows platforms this is reported as 0.0).
1310 1325
1311 1326 If -t is given, an additional -N<N> option can be given, where <N>
1312 1327 must be an integer indicating how many times you want the script to
1313 1328 run. The final timing report will include total and per run results.
1314 1329
1315 1330 For example (testing the script uniq_stable.py):
1316 1331
1317 1332 In [1]: run -t uniq_stable
1318 1333
1319 1334 IPython CPU timings (estimated):\\
1320 1335 User : 0.19597 s.\\
1321 1336 System: 0.0 s.\\
1322 1337
1323 1338 In [2]: run -t -N5 uniq_stable
1324 1339
1325 1340 IPython CPU timings (estimated):\\
1326 1341 Total runs performed: 5\\
1327 1342 Times : Total Per run\\
1328 1343 User : 0.910862 s, 0.1821724 s.\\
1329 1344 System: 0.0 s, 0.0 s.
1330 1345
1331 1346 -d: run your program under the control of pdb, the Python debugger.
1332 1347 This allows you to execute your program step by step, watch variables,
1333 1348 etc. Internally, what IPython does is similar to calling:
1334 1349
1335 1350 pdb.run('execfile("YOURFILENAME")')
1336 1351
1337 1352 with a breakpoint set on line 1 of your file. You can change the line
1338 1353 number for this automatic breakpoint to be <N> by using the -bN option
1339 1354 (where N must be an integer). For example:
1340 1355
1341 1356 %run -d -b40 myscript
1342 1357
1343 1358 will set the first breakpoint at line 40 in myscript.py. Note that
1344 1359 the first breakpoint must be set on a line which actually does
1345 1360 something (not a comment or docstring) for it to stop execution.
1346 1361
1347 1362 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1348 1363 first enter 'c' (without qoutes) to start execution up to the first
1349 1364 breakpoint.
1350 1365
1351 1366 Entering 'help' gives information about the use of the debugger. You
1352 1367 can easily see pdb's full documentation with "import pdb;pdb.help()"
1353 1368 at a prompt.
1354 1369
1355 1370 -p: run program under the control of the Python profiler module (which
1356 1371 prints a detailed report of execution times, function calls, etc).
1357 1372
1358 1373 You can pass other options after -p which affect the behavior of the
1359 1374 profiler itself. See the docs for %prun for details.
1360 1375
1361 1376 In this mode, the program's variables do NOT propagate back to the
1362 1377 IPython interactive namespace (because they remain in the namespace
1363 1378 where the profiler executes them).
1364 1379
1365 1380 Internally this triggers a call to %prun, see its documentation for
1366 1381 details on the options available specifically for profiling."""
1367 1382
1368 1383 # get arguments and set sys.argv for program to be run.
1369 1384 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1370 1385 mode='list',list_all=1)
1371 1386
1372 1387 try:
1373 1388 filename = get_py_filename(arg_lst[0])
1374 1389 except IndexError:
1375 1390 warn('you must provide at least a filename.')
1376 1391 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1377 1392 return
1378 1393 except IOError,msg:
1379 1394 error(msg)
1380 1395 return
1381 1396
1382 1397 # Control the response to exit() calls made by the script being run
1383 1398 exit_ignore = opts.has_key('e')
1384 1399
1385 1400 # Make sure that the running script gets a proper sys.argv as if it
1386 1401 # were run from a system shell.
1387 1402 save_argv = sys.argv # save it for later restoring
1388 1403 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1389 1404
1390 1405 if opts.has_key('i'):
1391 1406 prog_ns = self.shell.user_ns
1392 1407 __name__save = self.shell.user_ns['__name__']
1393 1408 prog_ns['__name__'] = '__main__'
1394 1409 else:
1395 1410 if opts.has_key('n'):
1396 1411 name = os.path.splitext(os.path.basename(filename))[0]
1397 1412 else:
1398 1413 name = '__main__'
1399 1414 prog_ns = {'__name__':name}
1400 1415
1401 1416 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1402 1417 # set the __file__ global in the script's namespace
1403 1418 prog_ns['__file__'] = filename
1404 1419
1405 1420 # pickle fix. See iplib for an explanation. But we need to make sure
1406 1421 # that, if we overwrite __main__, we replace it at the end
1407 1422 if prog_ns['__name__'] == '__main__':
1408 1423 restore_main = sys.modules['__main__']
1409 1424 else:
1410 1425 restore_main = False
1411 1426
1412 1427 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1413 1428
1414 1429 stats = None
1415 1430 try:
1416 1431 if opts.has_key('p'):
1417 1432 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1418 1433 else:
1419 1434 if opts.has_key('d'):
1420 1435 deb = Debugger.Pdb(self.shell.rc.colors)
1421 1436 # reset Breakpoint state, which is moronically kept
1422 1437 # in a class
1423 1438 bdb.Breakpoint.next = 1
1424 1439 bdb.Breakpoint.bplist = {}
1425 1440 bdb.Breakpoint.bpbynumber = [None]
1426 1441 # Set an initial breakpoint to stop execution
1427 1442 maxtries = 10
1428 1443 bp = int(opts.get('b',[1])[0])
1429 1444 checkline = deb.checkline(filename,bp)
1430 1445 if not checkline:
1431 1446 for bp in range(bp+1,bp+maxtries+1):
1432 1447 if deb.checkline(filename,bp):
1433 1448 break
1434 1449 else:
1435 1450 msg = ("\nI failed to find a valid line to set "
1436 1451 "a breakpoint\n"
1437 1452 "after trying up to line: %s.\n"
1438 1453 "Please set a valid breakpoint manually "
1439 1454 "with the -b option." % bp)
1440 1455 error(msg)
1441 1456 return
1442 1457 # if we find a good linenumber, set the breakpoint
1443 1458 deb.do_break('%s:%s' % (filename,bp))
1444 1459 # Start file run
1445 1460 print "NOTE: Enter 'c' at the",
1446 1461 print "ipdb> prompt to start your script."
1447 1462 try:
1448 1463 deb.run('execfile("%s")' % filename,prog_ns)
1449 1464 except:
1450 1465 etype, value, tb = sys.exc_info()
1451 1466 # Skip three frames in the traceback: the %run one,
1452 1467 # one inside bdb.py, and the command-line typed by the
1453 1468 # user (run by exec in pdb itself).
1454 1469 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1455 1470 else:
1456 1471 if runner is None:
1457 1472 runner = self.shell.safe_execfile
1458 1473 if opts.has_key('t'):
1459 1474 try:
1460 1475 nruns = int(opts['N'][0])
1461 1476 if nruns < 1:
1462 1477 error('Number of runs must be >=1')
1463 1478 return
1464 1479 except (KeyError):
1465 1480 nruns = 1
1466 1481 if nruns == 1:
1467 1482 t0 = clock2()
1468 1483 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1469 1484 t1 = clock2()
1470 1485 t_usr = t1[0]-t0[0]
1471 1486 t_sys = t1[1]-t1[1]
1472 1487 print "\nIPython CPU timings (estimated):"
1473 1488 print " User : %10s s." % t_usr
1474 1489 print " System: %10s s." % t_sys
1475 1490 else:
1476 1491 runs = range(nruns)
1477 1492 t0 = clock2()
1478 1493 for nr in runs:
1479 1494 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1480 1495 t1 = clock2()
1481 1496 t_usr = t1[0]-t0[0]
1482 1497 t_sys = t1[1]-t1[1]
1483 1498 print "\nIPython CPU timings (estimated):"
1484 1499 print "Total runs performed:",nruns
1485 1500 print " Times : %10s %10s" % ('Total','Per run')
1486 1501 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1487 1502 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1488 1503
1489 1504 else:
1490 1505 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1491 1506 if opts.has_key('i'):
1492 1507 self.shell.user_ns['__name__'] = __name__save
1493 1508 else:
1494 1509 # update IPython interactive namespace
1495 1510 del prog_ns['__name__']
1496 1511 self.shell.user_ns.update(prog_ns)
1497 1512 finally:
1498 1513 sys.argv = save_argv
1499 1514 if restore_main:
1500 1515 sys.modules['__main__'] = restore_main
1501 1516 return stats
1502 1517
1503 1518 def magic_runlog(self, parameter_s =''):
1504 1519 """Run files as logs.
1505 1520
1506 1521 Usage:\\
1507 1522 %runlog file1 file2 ...
1508 1523
1509 1524 Run the named files (treating them as log files) in sequence inside
1510 1525 the interpreter, and return to the prompt. This is much slower than
1511 1526 %run because each line is executed in a try/except block, but it
1512 1527 allows running files with syntax errors in them.
1513 1528
1514 1529 Normally IPython will guess when a file is one of its own logfiles, so
1515 1530 you can typically use %run even for logs. This shorthand allows you to
1516 1531 force any file to be treated as a log file."""
1517 1532
1518 1533 for f in parameter_s.split():
1519 1534 self.shell.safe_execfile(f,self.shell.user_ns,
1520 1535 self.shell.user_ns,islog=1)
1521 1536
1522 1537 def magic_time(self,parameter_s = ''):
1523 1538 """Time execution of a Python statement or expression.
1524 1539
1525 1540 The CPU and wall clock times are printed, and the value of the
1526 1541 expression (if any) is returned. Note that under Win32, system time
1527 1542 is always reported as 0, since it can not be measured.
1528 1543
1529 1544 This function provides very basic timing functionality. In Python
1530 1545 2.3, the timeit module offers more control and sophistication, but for
1531 1546 now IPython supports Python 2.2, so we can not rely on timeit being
1532 1547 present.
1533 1548
1534 1549 Some examples:
1535 1550
1536 1551 In [1]: time 2**128
1537 1552 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1538 1553 Wall time: 0.00
1539 1554 Out[1]: 340282366920938463463374607431768211456L
1540 1555
1541 1556 In [2]: n = 1000000
1542 1557
1543 1558 In [3]: time sum(range(n))
1544 1559 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1545 1560 Wall time: 1.37
1546 1561 Out[3]: 499999500000L
1547 1562
1548 1563 In [4]: time print 'hello world'
1549 1564 hello world
1550 1565 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1551 1566 Wall time: 0.00
1552 1567 """
1553 1568
1554 1569 # fail immediately if the given expression can't be compiled
1555 1570 try:
1556 1571 mode = 'eval'
1557 1572 code = compile(parameter_s,'<timed eval>',mode)
1558 1573 except SyntaxError:
1559 1574 mode = 'exec'
1560 1575 code = compile(parameter_s,'<timed exec>',mode)
1561 1576 # skew measurement as little as possible
1562 1577 glob = self.shell.user_ns
1563 1578 clk = clock2
1564 1579 wtime = time.time
1565 1580 # time execution
1566 1581 wall_st = wtime()
1567 1582 if mode=='eval':
1568 1583 st = clk()
1569 1584 out = eval(code,glob)
1570 1585 end = clk()
1571 1586 else:
1572 1587 st = clk()
1573 1588 exec code in glob
1574 1589 end = clk()
1575 1590 out = None
1576 1591 wall_end = wtime()
1577 1592 # Compute actual times and report
1578 1593 wall_time = wall_end-wall_st
1579 1594 cpu_user = end[0]-st[0]
1580 1595 cpu_sys = end[1]-st[1]
1581 1596 cpu_tot = cpu_user+cpu_sys
1582 1597 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1583 1598 (cpu_user,cpu_sys,cpu_tot)
1584 1599 print "Wall time: %.2f" % wall_time
1585 1600 return out
1586 1601
1587 1602 def magic_macro(self,parameter_s = ''):
1588 1603 """Define a set of input lines as a macro for future re-execution.
1589 1604
1590 1605 Usage:\\
1591 1606 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1592 1607
1593 1608 This will define a global variable called `name` which is a string
1594 1609 made of joining the slices and lines you specify (n1,n2,... numbers
1595 1610 above) from your input history into a single string. This variable
1596 1611 acts like an automatic function which re-executes those lines as if
1597 1612 you had typed them. You just type 'name' at the prompt and the code
1598 1613 executes.
1599 1614
1600 1615 The notation for indicating number ranges is: n1-n2 means 'use line
1601 1616 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1602 1617 using the lines numbered 5,6 and 7.
1603 1618
1604 1619 Note: as a 'hidden' feature, you can also use traditional python slice
1605 1620 notation, where N:M means numbers N through M-1.
1606 1621
1607 1622 For example, if your history contains (%hist prints it):
1608 1623
1609 1624 44: x=1\\
1610 1625 45: y=3\\
1611 1626 46: z=x+y\\
1612 1627 47: print x\\
1613 1628 48: a=5\\
1614 1629 49: print 'x',x,'y',y\\
1615 1630
1616 1631 you can create a macro with lines 44 through 47 (included) and line 49
1617 1632 called my_macro with:
1618 1633
1619 1634 In [51]: %macro my_macro 44-47 49
1620 1635
1621 1636 Now, typing `my_macro` (without quotes) will re-execute all this code
1622 1637 in one pass.
1623 1638
1624 1639 You don't need to give the line-numbers in order, and any given line
1625 1640 number can appear multiple times. You can assemble macros with any
1626 1641 lines from your input history in any order.
1627 1642
1628 1643 The macro is a simple object which holds its value in an attribute,
1629 1644 but IPython's display system checks for macros and executes them as
1630 1645 code instead of printing them when you type their name.
1631 1646
1632 1647 You can view a macro's contents by explicitly printing it with:
1633 1648
1634 1649 'print macro_name'.
1635 1650
1636 1651 For one-off cases which DON'T contain magic function calls in them you
1637 1652 can obtain similar results by explicitly executing slices from your
1638 1653 input history with:
1639 1654
1640 1655 In [60]: exec In[44:48]+In[49]"""
1641 1656
1642 1657 args = parameter_s.split()
1643 1658 name,ranges = args[0], args[1:]
1644 1659 #print 'rng',ranges # dbg
1645 1660 lines = self.extract_input_slices(ranges)
1646 1661 macro = Macro(lines)
1647 1662 self.shell.user_ns.update({name:macro})
1648 1663 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1649 1664 print 'Macro contents:'
1650 1665 print macro,
1651 1666
1652 1667 def magic_save(self,parameter_s = ''):
1653 1668 """Save a set of lines to a given filename.
1654 1669
1655 1670 Usage:\\
1656 1671 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1657 1672
1658 1673 This function uses the same syntax as %macro for line extraction, but
1659 1674 instead of creating a macro it saves the resulting string to the
1660 1675 filename you specify.
1661 1676
1662 1677 It adds a '.py' extension to the file if you don't do so yourself, and
1663 1678 it asks for confirmation before overwriting existing files."""
1664 1679
1665 1680 args = parameter_s.split()
1666 1681 fname,ranges = args[0], args[1:]
1667 1682 if not fname.endswith('.py'):
1668 1683 fname += '.py'
1669 1684 if os.path.isfile(fname):
1670 1685 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1671 1686 if ans.lower() not in ['y','yes']:
1672 1687 print 'Operation cancelled.'
1673 1688 return
1674 1689 cmds = ''.join(self.extract_input_slices(ranges))
1675 1690 f = file(fname,'w')
1676 1691 f.write(cmds)
1677 1692 f.close()
1678 1693 print 'The following commands were written to file `%s`:' % fname
1679 1694 print cmds
1680 1695
1681 1696 def _edit_macro(self,mname,macro):
1682 1697 """open an editor with the macro data in a file"""
1683 1698 filename = self.shell.mktempfile(macro.value)
1684 1699 self.shell.hooks.editor(filename)
1685 1700
1686 1701 # and make a new macro object, to replace the old one
1687 1702 mfile = open(filename)
1688 1703 mvalue = mfile.read()
1689 1704 mfile.close()
1690 1705 self.shell.user_ns[mname] = Macro(mvalue)
1691 1706
1692 1707 def magic_ed(self,parameter_s=''):
1693 1708 """Alias to %edit."""
1694 1709 return self.magic_edit(parameter_s)
1695 1710
1696 1711 def magic_edit(self,parameter_s='',last_call=['','']):
1697 1712 """Bring up an editor and execute the resulting code.
1698 1713
1699 1714 Usage:
1700 1715 %edit [options] [args]
1701 1716
1702 1717 %edit runs IPython's editor hook. The default version of this hook is
1703 1718 set to call the __IPYTHON__.rc.editor command. This is read from your
1704 1719 environment variable $EDITOR. If this isn't found, it will default to
1705 1720 vi under Linux/Unix and to notepad under Windows. See the end of this
1706 1721 docstring for how to change the editor hook.
1707 1722
1708 1723 You can also set the value of this editor via the command line option
1709 1724 '-editor' or in your ipythonrc file. This is useful if you wish to use
1710 1725 specifically for IPython an editor different from your typical default
1711 1726 (and for Windows users who typically don't set environment variables).
1712 1727
1713 1728 This command allows you to conveniently edit multi-line code right in
1714 1729 your IPython session.
1715 1730
1716 1731 If called without arguments, %edit opens up an empty editor with a
1717 1732 temporary file and will execute the contents of this file when you
1718 1733 close it (don't forget to save it!).
1719 1734
1720 1735
1721 1736 Options:
1722 1737
1723 1738 -p: this will call the editor with the same data as the previous time
1724 1739 it was used, regardless of how long ago (in your current session) it
1725 1740 was.
1726 1741
1727 1742 -x: do not execute the edited code immediately upon exit. This is
1728 1743 mainly useful if you are editing programs which need to be called with
1729 1744 command line arguments, which you can then do using %run.
1730 1745
1731 1746
1732 1747 Arguments:
1733 1748
1734 1749 If arguments are given, the following possibilites exist:
1735 1750
1736 1751 - The arguments are numbers or pairs of colon-separated numbers (like
1737 1752 1 4:8 9). These are interpreted as lines of previous input to be
1738 1753 loaded into the editor. The syntax is the same of the %macro command.
1739 1754
1740 1755 - If the argument doesn't start with a number, it is evaluated as a
1741 1756 variable and its contents loaded into the editor. You can thus edit
1742 1757 any string which contains python code (including the result of
1743 1758 previous edits).
1744 1759
1745 1760 - If the argument is the name of an object (other than a string),
1746 1761 IPython will try to locate the file where it was defined and open the
1747 1762 editor at the point where it is defined. You can use `%edit function`
1748 1763 to load an editor exactly at the point where 'function' is defined,
1749 1764 edit it and have the file be executed automatically.
1750 1765
1751 1766 If the object is a macro (see %macro for details), this opens up your
1752 1767 specified editor with a temporary file containing the macro's data.
1753 1768 Upon exit, the macro is reloaded with the contents of the file.
1754 1769
1755 1770 Note: opening at an exact line is only supported under Unix, and some
1756 1771 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1757 1772 '+NUMBER' parameter necessary for this feature. Good editors like
1758 1773 (X)Emacs, vi, jed, pico and joe all do.
1759 1774
1760 1775 - If the argument is not found as a variable, IPython will look for a
1761 1776 file with that name (adding .py if necessary) and load it into the
1762 1777 editor. It will execute its contents with execfile() when you exit,
1763 1778 loading any code in the file into your interactive namespace.
1764 1779
1765 1780 After executing your code, %edit will return as output the code you
1766 1781 typed in the editor (except when it was an existing file). This way
1767 1782 you can reload the code in further invocations of %edit as a variable,
1768 1783 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1769 1784 the output.
1770 1785
1771 1786 Note that %edit is also available through the alias %ed.
1772 1787
1773 1788 This is an example of creating a simple function inside the editor and
1774 1789 then modifying it. First, start up the editor:
1775 1790
1776 1791 In [1]: ed\\
1777 1792 Editing... done. Executing edited code...\\
1778 1793 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1779 1794
1780 1795 We can then call the function foo():
1781 1796
1782 1797 In [2]: foo()\\
1783 1798 foo() was defined in an editing session
1784 1799
1785 1800 Now we edit foo. IPython automatically loads the editor with the
1786 1801 (temporary) file where foo() was previously defined:
1787 1802
1788 1803 In [3]: ed foo\\
1789 1804 Editing... done. Executing edited code...
1790 1805
1791 1806 And if we call foo() again we get the modified version:
1792 1807
1793 1808 In [4]: foo()\\
1794 1809 foo() has now been changed!
1795 1810
1796 1811 Here is an example of how to edit a code snippet successive
1797 1812 times. First we call the editor:
1798 1813
1799 1814 In [8]: ed\\
1800 1815 Editing... done. Executing edited code...\\
1801 1816 hello\\
1802 1817 Out[8]: "print 'hello'\\n"
1803 1818
1804 1819 Now we call it again with the previous output (stored in _):
1805 1820
1806 1821 In [9]: ed _\\
1807 1822 Editing... done. Executing edited code...\\
1808 1823 hello world\\
1809 1824 Out[9]: "print 'hello world'\\n"
1810 1825
1811 1826 Now we call it with the output #8 (stored in _8, also as Out[8]):
1812 1827
1813 1828 In [10]: ed _8\\
1814 1829 Editing... done. Executing edited code...\\
1815 1830 hello again\\
1816 1831 Out[10]: "print 'hello again'\\n"
1817 1832
1818 1833
1819 1834 Changing the default editor hook:
1820 1835
1821 1836 If you wish to write your own editor hook, you can put it in a
1822 1837 configuration file which you load at startup time. The default hook
1823 1838 is defined in the IPython.hooks module, and you can use that as a
1824 1839 starting example for further modifications. That file also has
1825 1840 general instructions on how to set a new hook for use once you've
1826 1841 defined it."""
1827 1842
1828 1843 # FIXME: This function has become a convoluted mess. It needs a
1829 1844 # ground-up rewrite with clean, simple logic.
1830 1845
1831 1846 def make_filename(arg):
1832 1847 "Make a filename from the given args"
1833 1848 try:
1834 1849 filename = get_py_filename(arg)
1835 1850 except IOError:
1836 1851 if args.endswith('.py'):
1837 1852 filename = arg
1838 1853 else:
1839 1854 filename = None
1840 1855 return filename
1841 1856
1842 1857 # custom exceptions
1843 1858 class DataIsObject(Exception): pass
1844 1859
1845 1860 opts,args = self.parse_options(parameter_s,'px')
1846 1861
1847 1862 # Default line number value
1848 1863 lineno = None
1849 1864 if opts.has_key('p'):
1850 1865 args = '_%s' % last_call[0]
1851 1866 if not self.shell.user_ns.has_key(args):
1852 1867 args = last_call[1]
1853 1868
1854 1869 # use last_call to remember the state of the previous call, but don't
1855 1870 # let it be clobbered by successive '-p' calls.
1856 1871 try:
1857 1872 last_call[0] = self.shell.outputcache.prompt_count
1858 1873 if not opts.has_key('p'):
1859 1874 last_call[1] = parameter_s
1860 1875 except:
1861 1876 pass
1862 1877
1863 1878 # by default this is done with temp files, except when the given
1864 1879 # arg is a filename
1865 1880 use_temp = 1
1866 1881
1867 1882 if re.match(r'\d',args):
1868 1883 # Mode where user specifies ranges of lines, like in %macro.
1869 1884 # This means that you can't edit files whose names begin with
1870 1885 # numbers this way. Tough.
1871 1886 ranges = args.split()
1872 1887 data = ''.join(self.extract_input_slices(ranges))
1873 1888 elif args.endswith('.py'):
1874 1889 filename = make_filename(args)
1875 1890 data = ''
1876 1891 use_temp = 0
1877 1892 elif args:
1878 1893 try:
1879 1894 # Load the parameter given as a variable. If not a string,
1880 1895 # process it as an object instead (below)
1881 1896
1882 1897 #print '*** args',args,'type',type(args) # dbg
1883 1898 data = eval(args,self.shell.user_ns)
1884 1899 if not type(data) in StringTypes:
1885 1900 raise DataIsObject
1886 1901
1887 1902 except (NameError,SyntaxError):
1888 1903 # given argument is not a variable, try as a filename
1889 1904 filename = make_filename(args)
1890 1905 if filename is None:
1891 1906 warn("Argument given (%s) can't be found as a variable "
1892 1907 "or as a filename." % args)
1893 1908 return
1894 1909
1895 1910 data = ''
1896 1911 use_temp = 0
1897 1912 except DataIsObject:
1898 1913
1899 1914 # macros have a special edit function
1900 1915 if isinstance(data,Macro):
1901 1916 self._edit_macro(args,data)
1902 1917 return
1903 1918
1904 1919 # For objects, try to edit the file where they are defined
1905 1920 try:
1906 1921 filename = inspect.getabsfile(data)
1907 1922 datafile = 1
1908 1923 except TypeError:
1909 1924 filename = make_filename(args)
1910 1925 datafile = 1
1911 1926 warn('Could not find file where `%s` is defined.\n'
1912 1927 'Opening a file named `%s`' % (args,filename))
1913 1928 # Now, make sure we can actually read the source (if it was in
1914 1929 # a temp file it's gone by now).
1915 1930 if datafile:
1916 1931 try:
1917 1932 lineno = inspect.getsourcelines(data)[1]
1918 1933 except IOError:
1919 1934 filename = make_filename(args)
1920 1935 if filename is None:
1921 1936 warn('The file `%s` where `%s` was defined cannot '
1922 1937 'be read.' % (filename,data))
1923 1938 return
1924 1939 use_temp = 0
1925 1940 else:
1926 1941 data = ''
1927 1942
1928 1943 if use_temp:
1929 1944 filename = self.shell.mktempfile(data)
1930 1945 print 'IPython will make a temporary file named:',filename
1931 1946
1932 1947 # do actual editing here
1933 1948 print 'Editing...',
1934 1949 sys.stdout.flush()
1935 1950 self.shell.hooks.editor(filename,lineno)
1936 1951 if opts.has_key('x'): # -x prevents actual execution
1937 1952 print
1938 1953 else:
1939 1954 print 'done. Executing edited code...'
1940 1955 self.shell.safe_execfile(filename,self.shell.user_ns)
1941 1956 if use_temp:
1942 1957 try:
1943 1958 return open(filename).read()
1944 1959 except IOError,msg:
1945 1960 if msg.filename == filename:
1946 1961 warn('File not found. Did you forget to save?')
1947 1962 return
1948 1963 else:
1949 1964 self.shell.showtraceback()
1950 1965
1951 1966 def magic_xmode(self,parameter_s = ''):
1952 1967 """Switch modes for the exception handlers.
1953 1968
1954 1969 Valid modes: Plain, Context and Verbose.
1955 1970
1956 1971 If called without arguments, acts as a toggle."""
1957 1972
1958 1973 def xmode_switch_err(name):
1959 1974 warn('Error changing %s exception modes.\n%s' %
1960 1975 (name,sys.exc_info()[1]))
1961 1976
1962 1977 shell = self.shell
1963 1978 new_mode = parameter_s.strip().capitalize()
1964 1979 try:
1965 1980 shell.InteractiveTB.set_mode(mode=new_mode)
1966 1981 print 'Exception reporting mode:',shell.InteractiveTB.mode
1967 1982 except:
1968 1983 xmode_switch_err('user')
1969 1984
1970 1985 # threaded shells use a special handler in sys.excepthook
1971 1986 if shell.isthreaded:
1972 1987 try:
1973 1988 shell.sys_excepthook.set_mode(mode=new_mode)
1974 1989 except:
1975 1990 xmode_switch_err('threaded')
1976 1991
1977 1992 def magic_colors(self,parameter_s = ''):
1978 1993 """Switch color scheme for prompts, info system and exception handlers.
1979 1994
1980 1995 Currently implemented schemes: NoColor, Linux, LightBG.
1981 1996
1982 1997 Color scheme names are not case-sensitive."""
1983 1998
1984 1999 def color_switch_err(name):
1985 2000 warn('Error changing %s color schemes.\n%s' %
1986 2001 (name,sys.exc_info()[1]))
1987 2002
1988 2003
1989 2004 new_scheme = parameter_s.strip()
1990 2005 if not new_scheme:
1991 2006 print 'You must specify a color scheme.'
1992 2007 return
1993 2008 # Under Windows, check for Gary Bishop's readline, which is necessary
1994 2009 # for ANSI coloring
1995 2010 if os.name in ['nt','dos']:
1996 2011 try:
1997 2012 import readline
1998 2013 except ImportError:
1999 2014 has_readline = 0
2000 2015 else:
2001 2016 try:
2002 2017 readline.GetOutputFile()
2003 2018 except AttributeError:
2004 2019 has_readline = 0
2005 2020 else:
2006 2021 has_readline = 1
2007 2022 if not has_readline:
2008 2023 msg = """\
2009 2024 Proper color support under MS Windows requires Gary Bishop's readline library.
2010 2025 You can find it at:
2011 2026 http://sourceforge.net/projects/uncpythontools
2012 2027 Gary's readline needs the ctypes module, from:
2013 2028 http://starship.python.net/crew/theller/ctypes
2014 2029
2015 2030 Defaulting color scheme to 'NoColor'"""
2016 2031 new_scheme = 'NoColor'
2017 2032 warn(msg)
2018 2033 # local shortcut
2019 2034 shell = self.shell
2020 2035
2021 2036 # Set prompt colors
2022 2037 try:
2023 2038 shell.outputcache.set_colors(new_scheme)
2024 2039 except:
2025 2040 color_switch_err('prompt')
2026 2041 else:
2027 2042 shell.rc.colors = \
2028 2043 shell.outputcache.color_table.active_scheme_name
2029 2044 # Set exception colors
2030 2045 try:
2031 2046 shell.InteractiveTB.set_colors(scheme = new_scheme)
2032 2047 shell.SyntaxTB.set_colors(scheme = new_scheme)
2033 2048 except:
2034 2049 color_switch_err('exception')
2035 2050
2036 2051 # threaded shells use a verbose traceback in sys.excepthook
2037 2052 if shell.isthreaded:
2038 2053 try:
2039 2054 shell.sys_excepthook.set_colors(scheme=new_scheme)
2040 2055 except:
2041 2056 color_switch_err('system exception handler')
2042 2057
2043 2058 # Set info (for 'object?') colors
2044 2059 if shell.rc.color_info:
2045 2060 try:
2046 2061 shell.inspector.set_active_scheme(new_scheme)
2047 2062 except:
2048 2063 color_switch_err('object inspector')
2049 2064 else:
2050 2065 shell.inspector.set_active_scheme('NoColor')
2051 2066
2052 2067 def magic_color_info(self,parameter_s = ''):
2053 2068 """Toggle color_info.
2054 2069
2055 2070 The color_info configuration parameter controls whether colors are
2056 2071 used for displaying object details (by things like %psource, %pfile or
2057 2072 the '?' system). This function toggles this value with each call.
2058 2073
2059 2074 Note that unless you have a fairly recent pager (less works better
2060 2075 than more) in your system, using colored object information displays
2061 2076 will not work properly. Test it and see."""
2062 2077
2063 2078 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2064 2079 self.magic_colors(self.shell.rc.colors)
2065 2080 print 'Object introspection functions have now coloring:',
2066 2081 print ['OFF','ON'][self.shell.rc.color_info]
2067 2082
2068 2083 def magic_Pprint(self, parameter_s=''):
2069 2084 """Toggle pretty printing on/off."""
2070 2085
2071 2086 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2072 2087 print 'Pretty printing has been turned', \
2073 2088 ['OFF','ON'][self.shell.outputcache.Pprint]
2074 2089
2075 2090 def magic_exit(self, parameter_s=''):
2076 2091 """Exit IPython, confirming if configured to do so.
2077 2092
2078 2093 You can configure whether IPython asks for confirmation upon exit by
2079 2094 setting the confirm_exit flag in the ipythonrc file."""
2080 2095
2081 2096 self.shell.exit()
2082 2097
2083 2098 def magic_quit(self, parameter_s=''):
2084 2099 """Exit IPython, confirming if configured to do so (like %exit)"""
2085 2100
2086 2101 self.shell.exit()
2087 2102
2088 2103 def magic_Exit(self, parameter_s=''):
2089 2104 """Exit IPython without confirmation."""
2090 2105
2091 2106 self.shell.exit_now = True
2092 2107
2093 2108 def magic_Quit(self, parameter_s=''):
2094 2109 """Exit IPython without confirmation (like %Exit)."""
2095 2110
2096 2111 self.shell.exit_now = True
2097 2112
2098 2113 #......................................................................
2099 2114 # Functions to implement unix shell-type things
2100 2115
2101 2116 def magic_alias(self, parameter_s = ''):
2102 2117 """Define an alias for a system command.
2103 2118
2104 2119 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2105 2120
2106 2121 Then, typing 'alias_name params' will execute the system command 'cmd
2107 2122 params' (from your underlying operating system).
2108 2123
2109 2124 Aliases have lower precedence than magic functions and Python normal
2110 2125 variables, so if 'foo' is both a Python variable and an alias, the
2111 2126 alias can not be executed until 'del foo' removes the Python variable.
2112 2127
2113 2128 You can use the %l specifier in an alias definition to represent the
2114 2129 whole line when the alias is called. For example:
2115 2130
2116 2131 In [2]: alias all echo "Input in brackets: <%l>"\\
2117 2132 In [3]: all hello world\\
2118 2133 Input in brackets: <hello world>
2119 2134
2120 2135 You can also define aliases with parameters using %s specifiers (one
2121 2136 per parameter):
2122 2137
2123 2138 In [1]: alias parts echo first %s second %s\\
2124 2139 In [2]: %parts A B\\
2125 2140 first A second B\\
2126 2141 In [3]: %parts A\\
2127 2142 Incorrect number of arguments: 2 expected.\\
2128 2143 parts is an alias to: 'echo first %s second %s'
2129 2144
2130 2145 Note that %l and %s are mutually exclusive. You can only use one or
2131 2146 the other in your aliases.
2132 2147
2133 2148 Aliases expand Python variables just like system calls using ! or !!
2134 2149 do: all expressions prefixed with '$' get expanded. For details of
2135 2150 the semantic rules, see PEP-215:
2136 2151 http://www.python.org/peps/pep-0215.html. This is the library used by
2137 2152 IPython for variable expansion. If you want to access a true shell
2138 2153 variable, an extra $ is necessary to prevent its expansion by IPython:
2139 2154
2140 2155 In [6]: alias show echo\\
2141 2156 In [7]: PATH='A Python string'\\
2142 2157 In [8]: show $PATH\\
2143 2158 A Python string\\
2144 2159 In [9]: show $$PATH\\
2145 2160 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2146 2161
2147 2162 You can use the alias facility to acess all of $PATH. See the %rehash
2148 2163 and %rehashx functions, which automatically create aliases for the
2149 2164 contents of your $PATH.
2150 2165
2151 2166 If called with no parameters, %alias prints the current alias table."""
2152 2167
2153 2168 par = parameter_s.strip()
2154 2169 if not par:
2155 2170 if self.shell.rc.automagic:
2156 2171 prechar = ''
2157 2172 else:
2158 2173 prechar = self.shell.ESC_MAGIC
2159 2174 print 'Alias\t\tSystem Command\n'+'-'*30
2160 2175 atab = self.shell.alias_table
2161 2176 aliases = atab.keys()
2162 2177 aliases.sort()
2163 2178 for alias in aliases:
2164 2179 print prechar+alias+'\t\t'+atab[alias][1]
2165 2180 print '-'*30+'\nTotal number of aliases:',len(aliases)
2166 2181 return
2167 2182 try:
2168 2183 alias,cmd = par.split(None,1)
2169 2184 except:
2170 2185 print OInspect.getdoc(self.magic_alias)
2171 2186 else:
2172 2187 nargs = cmd.count('%s')
2173 2188 if nargs>0 and cmd.find('%l')>=0:
2174 2189 error('The %s and %l specifiers are mutually exclusive '
2175 2190 'in alias definitions.')
2176 2191 else: # all looks OK
2177 2192 self.shell.alias_table[alias] = (nargs,cmd)
2178 2193 self.shell.alias_table_validate(verbose=1)
2179 2194 # end magic_alias
2180 2195
2181 2196 def magic_unalias(self, parameter_s = ''):
2182 2197 """Remove an alias"""
2183 2198
2184 2199 aname = parameter_s.strip()
2185 2200 if aname in self.shell.alias_table:
2186 2201 del self.shell.alias_table[aname]
2187 2202
2188 2203 def magic_rehash(self, parameter_s = ''):
2189 2204 """Update the alias table with all entries in $PATH.
2190 2205
2191 2206 This version does no checks on execute permissions or whether the
2192 2207 contents of $PATH are truly files (instead of directories or something
2193 2208 else). For such a safer (but slower) version, use %rehashx."""
2194 2209
2195 2210 # This function (and rehashx) manipulate the alias_table directly
2196 2211 # rather than calling magic_alias, for speed reasons. A rehash on a
2197 2212 # typical Linux box involves several thousand entries, so efficiency
2198 2213 # here is a top concern.
2199 2214
2200 2215 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2201 2216 alias_table = self.shell.alias_table
2202 2217 for pdir in path:
2203 2218 for ff in os.listdir(pdir):
2204 2219 # each entry in the alias table must be (N,name), where
2205 2220 # N is the number of positional arguments of the alias.
2206 2221 alias_table[ff] = (0,ff)
2207 2222 # Make sure the alias table doesn't contain keywords or builtins
2208 2223 self.shell.alias_table_validate()
2209 2224 # Call again init_auto_alias() so we get 'rm -i' and other modified
2210 2225 # aliases since %rehash will probably clobber them
2211 2226 self.shell.init_auto_alias()
2212 2227
2213 2228 def magic_rehashx(self, parameter_s = ''):
2214 2229 """Update the alias table with all executable files in $PATH.
2215 2230
2216 2231 This version explicitly checks that every entry in $PATH is a file
2217 2232 with execute access (os.X_OK), so it is much slower than %rehash.
2218 2233
2219 2234 Under Windows, it checks executability as a match agains a
2220 2235 '|'-separated string of extensions, stored in the IPython config
2221 2236 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2222 2237
2223 2238 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2224 2239 alias_table = self.shell.alias_table
2225 2240
2226 2241 if os.name == 'posix':
2227 2242 isexec = lambda fname:os.path.isfile(fname) and \
2228 2243 os.access(fname,os.X_OK)
2229 2244 else:
2230 2245
2231 2246 try:
2232 2247 winext = os.environ['pathext'].replace(';','|').replace('.','')
2233 2248 except KeyError:
2234 2249 winext = 'exe|com|bat'
2235 2250
2236 2251 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2237 2252 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2238 2253 savedir = os.getcwd()
2239 2254 try:
2240 2255 # write the whole loop for posix/Windows so we don't have an if in
2241 2256 # the innermost part
2242 2257 if os.name == 'posix':
2243 2258 for pdir in path:
2244 2259 os.chdir(pdir)
2245 2260 for ff in os.listdir(pdir):
2246 2261 if isexec(ff):
2247 2262 # each entry in the alias table must be (N,name),
2248 2263 # where N is the number of positional arguments of the
2249 2264 # alias.
2250 2265 alias_table[ff] = (0,ff)
2251 2266 else:
2252 2267 for pdir in path:
2253 2268 os.chdir(pdir)
2254 2269 for ff in os.listdir(pdir):
2255 2270 if isexec(ff):
2256 2271 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2257 2272 # Make sure the alias table doesn't contain keywords or builtins
2258 2273 self.shell.alias_table_validate()
2259 2274 # Call again init_auto_alias() so we get 'rm -i' and other
2260 2275 # modified aliases since %rehashx will probably clobber them
2261 2276 self.shell.init_auto_alias()
2262 2277 finally:
2263 2278 os.chdir(savedir)
2264 2279
2265 2280 def magic_pwd(self, parameter_s = ''):
2266 2281 """Return the current working directory path."""
2267 2282 return os.getcwd()
2268 2283
2269 2284 def magic_cd(self, parameter_s=''):
2270 2285 """Change the current working directory.
2271 2286
2272 2287 This command automatically maintains an internal list of directories
2273 2288 you visit during your IPython session, in the variable _dh. The
2274 2289 command %dhist shows this history nicely formatted.
2275 2290
2276 2291 Usage:
2277 2292
2278 2293 cd 'dir': changes to directory 'dir'.
2279 2294
2280 2295 cd -: changes to the last visited directory.
2281 2296
2282 2297 cd -<n>: changes to the n-th directory in the directory history.
2283 2298
2284 2299 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2285 2300 (note: cd <bookmark_name> is enough if there is no
2286 2301 directory <bookmark_name>, but a bookmark with the name exists.)
2287 2302
2288 2303 Options:
2289 2304
2290 2305 -q: quiet. Do not print the working directory after the cd command is
2291 2306 executed. By default IPython's cd command does print this directory,
2292 2307 since the default prompts do not display path information.
2293 2308
2294 2309 Note that !cd doesn't work for this purpose because the shell where
2295 2310 !command runs is immediately discarded after executing 'command'."""
2296 2311
2297 2312 parameter_s = parameter_s.strip()
2298 2313 bkms = self.shell.persist.get("bookmarks",{})
2299 2314
2300 2315 numcd = re.match(r'(-)(\d+)$',parameter_s)
2301 2316 # jump in directory history by number
2302 2317 if numcd:
2303 2318 nn = int(numcd.group(2))
2304 2319 try:
2305 2320 ps = self.shell.user_ns['_dh'][nn]
2306 2321 except IndexError:
2307 2322 print 'The requested directory does not exist in history.'
2308 2323 return
2309 2324 else:
2310 2325 opts = {}
2311 2326 else:
2312 2327 #turn all non-space-escaping backslashes to slashes,
2313 2328 # for c:\windows\directory\names\
2314 2329 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2315 2330 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2316 2331 # jump to previous
2317 2332 if ps == '-':
2318 2333 try:
2319 2334 ps = self.shell.user_ns['_dh'][-2]
2320 2335 except IndexError:
2321 2336 print 'No previous directory to change to.'
2322 2337 return
2323 2338 # jump to bookmark
2324 2339 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2325 2340 if bkms.has_key(ps):
2326 2341 target = bkms[ps]
2327 2342 print '(bookmark:%s) -> %s' % (ps,target)
2328 2343 ps = target
2329 2344 else:
2330 2345 if bkms:
2331 2346 error("Bookmark '%s' not found. "
2332 2347 "Use '%%bookmark -l' to see your bookmarks." % ps)
2333 2348 else:
2334 2349 print "Bookmarks not set - use %bookmark <bookmarkname>"
2335 2350 return
2336 2351
2337 2352 # at this point ps should point to the target dir
2338 2353 if ps:
2339 2354 try:
2340 2355 os.chdir(os.path.expanduser(ps))
2341 2356 ttitle = ("IPy:" + (
2342 2357 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2343 2358 platutils.set_term_title(ttitle)
2344 2359 except OSError:
2345 2360 print sys.exc_info()[1]
2346 2361 else:
2347 2362 self.shell.user_ns['_dh'].append(os.getcwd())
2348 2363 else:
2349 2364 os.chdir(self.shell.home_dir)
2350 2365 platutils.set_term_title("IPy:~")
2351 2366 self.shell.user_ns['_dh'].append(os.getcwd())
2352 2367 if not 'q' in opts:
2353 2368 print self.shell.user_ns['_dh'][-1]
2354 2369
2355 2370 def magic_dhist(self, parameter_s=''):
2356 2371 """Print your history of visited directories.
2357 2372
2358 2373 %dhist -> print full history\\
2359 2374 %dhist n -> print last n entries only\\
2360 2375 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2361 2376
2362 2377 This history is automatically maintained by the %cd command, and
2363 2378 always available as the global list variable _dh. You can use %cd -<n>
2364 2379 to go to directory number <n>."""
2365 2380
2366 2381 dh = self.shell.user_ns['_dh']
2367 2382 if parameter_s:
2368 2383 try:
2369 2384 args = map(int,parameter_s.split())
2370 2385 except:
2371 2386 self.arg_err(Magic.magic_dhist)
2372 2387 return
2373 2388 if len(args) == 1:
2374 2389 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2375 2390 elif len(args) == 2:
2376 2391 ini,fin = args
2377 2392 else:
2378 2393 self.arg_err(Magic.magic_dhist)
2379 2394 return
2380 2395 else:
2381 2396 ini,fin = 0,len(dh)
2382 2397 nlprint(dh,
2383 2398 header = 'Directory history (kept in _dh)',
2384 2399 start=ini,stop=fin)
2385 2400
2386 2401 def magic_env(self, parameter_s=''):
2387 2402 """List environment variables."""
2388 2403
2389 2404 return os.environ.data
2390 2405
2391 2406 def magic_pushd(self, parameter_s=''):
2392 2407 """Place the current dir on stack and change directory.
2393 2408
2394 2409 Usage:\\
2395 2410 %pushd ['dirname']
2396 2411
2397 2412 %pushd with no arguments does a %pushd to your home directory.
2398 2413 """
2399 2414 if parameter_s == '': parameter_s = '~'
2400 2415 dir_s = self.shell.dir_stack
2401 2416 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2402 2417 os.path.expanduser(self.shell.dir_stack[0]):
2403 2418 try:
2404 2419 self.magic_cd(parameter_s)
2405 2420 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2406 2421 self.magic_dirs()
2407 2422 except:
2408 2423 print 'Invalid directory'
2409 2424 else:
2410 2425 print 'You are already there!'
2411 2426
2412 2427 def magic_popd(self, parameter_s=''):
2413 2428 """Change to directory popped off the top of the stack.
2414 2429 """
2415 2430 if len (self.shell.dir_stack) > 1:
2416 2431 self.shell.dir_stack.pop(0)
2417 2432 self.magic_cd(self.shell.dir_stack[0])
2418 2433 print self.shell.dir_stack[0]
2419 2434 else:
2420 2435 print "You can't remove the starting directory from the stack:",\
2421 2436 self.shell.dir_stack
2422 2437
2423 2438 def magic_dirs(self, parameter_s=''):
2424 2439 """Return the current directory stack."""
2425 2440
2426 2441 return self.shell.dir_stack[:]
2427 2442
2428 2443 def magic_sc(self, parameter_s=''):
2429 2444 """Shell capture - execute a shell command and capture its output.
2430 2445
2431 2446 %sc [options] varname=command
2432 2447
2433 2448 IPython will run the given command using commands.getoutput(), and
2434 2449 will then update the user's interactive namespace with a variable
2435 2450 called varname, containing the value of the call. Your command can
2436 2451 contain shell wildcards, pipes, etc.
2437 2452
2438 2453 The '=' sign in the syntax is mandatory, and the variable name you
2439 2454 supply must follow Python's standard conventions for valid names.
2440 2455
2441 2456 Options:
2442 2457
2443 2458 -l: list output. Split the output on newlines into a list before
2444 2459 assigning it to the given variable. By default the output is stored
2445 2460 as a single string.
2446 2461
2447 2462 -v: verbose. Print the contents of the variable.
2448 2463
2449 2464 In most cases you should not need to split as a list, because the
2450 2465 returned value is a special type of string which can automatically
2451 2466 provide its contents either as a list (split on newlines) or as a
2452 2467 space-separated string. These are convenient, respectively, either
2453 2468 for sequential processing or to be passed to a shell command.
2454 2469
2455 2470 For example:
2456 2471
2457 2472 # Capture into variable a
2458 2473 In [9]: sc a=ls *py
2459 2474
2460 2475 # a is a string with embedded newlines
2461 2476 In [10]: a
2462 2477 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2463 2478
2464 2479 # which can be seen as a list:
2465 2480 In [11]: a.l
2466 2481 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2467 2482
2468 2483 # or as a whitespace-separated string:
2469 2484 In [12]: a.s
2470 2485 Out[12]: 'setup.py win32_manual_post_install.py'
2471 2486
2472 2487 # a.s is useful to pass as a single command line:
2473 2488 In [13]: !wc -l $a.s
2474 2489 146 setup.py
2475 2490 130 win32_manual_post_install.py
2476 2491 276 total
2477 2492
2478 2493 # while the list form is useful to loop over:
2479 2494 In [14]: for f in a.l:
2480 2495 ....: !wc -l $f
2481 2496 ....:
2482 2497 146 setup.py
2483 2498 130 win32_manual_post_install.py
2484 2499
2485 2500 Similiarly, the lists returned by the -l option are also special, in
2486 2501 the sense that you can equally invoke the .s attribute on them to
2487 2502 automatically get a whitespace-separated string from their contents:
2488 2503
2489 2504 In [1]: sc -l b=ls *py
2490 2505
2491 2506 In [2]: b
2492 2507 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2493 2508
2494 2509 In [3]: b.s
2495 2510 Out[3]: 'setup.py win32_manual_post_install.py'
2496 2511
2497 2512 In summary, both the lists and strings used for ouptut capture have
2498 2513 the following special attributes:
2499 2514
2500 2515 .l (or .list) : value as list.
2501 2516 .n (or .nlstr): value as newline-separated string.
2502 2517 .s (or .spstr): value as space-separated string.
2503 2518 """
2504 2519
2505 2520 opts,args = self.parse_options(parameter_s,'lv')
2506 2521 # Try to get a variable name and command to run
2507 2522 try:
2508 2523 # the variable name must be obtained from the parse_options
2509 2524 # output, which uses shlex.split to strip options out.
2510 2525 var,_ = args.split('=',1)
2511 2526 var = var.strip()
2512 2527 # But the the command has to be extracted from the original input
2513 2528 # parameter_s, not on what parse_options returns, to avoid the
2514 2529 # quote stripping which shlex.split performs on it.
2515 2530 _,cmd = parameter_s.split('=',1)
2516 2531 except ValueError:
2517 2532 var,cmd = '',''
2518 2533 if not var:
2519 2534 error('you must specify a variable to assign the command to.')
2520 2535 return
2521 2536 # If all looks ok, proceed
2522 2537 out,err = self.shell.getoutputerror(cmd)
2523 2538 if err:
2524 2539 print >> Term.cerr,err
2525 2540 if opts.has_key('l'):
2526 2541 out = SList(out.split('\n'))
2527 2542 else:
2528 2543 out = LSString(out)
2529 2544 if opts.has_key('v'):
2530 2545 print '%s ==\n%s' % (var,pformat(out))
2531 2546 self.shell.user_ns.update({var:out})
2532 2547
2533 2548 def magic_sx(self, parameter_s=''):
2534 2549 """Shell execute - run a shell command and capture its output.
2535 2550
2536 2551 %sx command
2537 2552
2538 2553 IPython will run the given command using commands.getoutput(), and
2539 2554 return the result formatted as a list (split on '\\n'). Since the
2540 2555 output is _returned_, it will be stored in ipython's regular output
2541 2556 cache Out[N] and in the '_N' automatic variables.
2542 2557
2543 2558 Notes:
2544 2559
2545 2560 1) If an input line begins with '!!', then %sx is automatically
2546 2561 invoked. That is, while:
2547 2562 !ls
2548 2563 causes ipython to simply issue system('ls'), typing
2549 2564 !!ls
2550 2565 is a shorthand equivalent to:
2551 2566 %sx ls
2552 2567
2553 2568 2) %sx differs from %sc in that %sx automatically splits into a list,
2554 2569 like '%sc -l'. The reason for this is to make it as easy as possible
2555 2570 to process line-oriented shell output via further python commands.
2556 2571 %sc is meant to provide much finer control, but requires more
2557 2572 typing.
2558 2573
2559 2574 3) Just like %sc -l, this is a list with special attributes:
2560 2575
2561 2576 .l (or .list) : value as list.
2562 2577 .n (or .nlstr): value as newline-separated string.
2563 2578 .s (or .spstr): value as whitespace-separated string.
2564 2579
2565 2580 This is very useful when trying to use such lists as arguments to
2566 2581 system commands."""
2567 2582
2568 2583 if parameter_s:
2569 2584 out,err = self.shell.getoutputerror(parameter_s)
2570 2585 if err:
2571 2586 print >> Term.cerr,err
2572 2587 return SList(out.split('\n'))
2573 2588
2574 2589 def magic_bg(self, parameter_s=''):
2575 2590 """Run a job in the background, in a separate thread.
2576 2591
2577 2592 For example,
2578 2593
2579 2594 %bg myfunc(x,y,z=1)
2580 2595
2581 2596 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2582 2597 execution starts, a message will be printed indicating the job
2583 2598 number. If your job number is 5, you can use
2584 2599
2585 2600 myvar = jobs.result(5) or myvar = jobs[5].result
2586 2601
2587 2602 to assign this result to variable 'myvar'.
2588 2603
2589 2604 IPython has a job manager, accessible via the 'jobs' object. You can
2590 2605 type jobs? to get more information about it, and use jobs.<TAB> to see
2591 2606 its attributes. All attributes not starting with an underscore are
2592 2607 meant for public use.
2593 2608
2594 2609 In particular, look at the jobs.new() method, which is used to create
2595 2610 new jobs. This magic %bg function is just a convenience wrapper
2596 2611 around jobs.new(), for expression-based jobs. If you want to create a
2597 2612 new job with an explicit function object and arguments, you must call
2598 2613 jobs.new() directly.
2599 2614
2600 2615 The jobs.new docstring also describes in detail several important
2601 2616 caveats associated with a thread-based model for background job
2602 2617 execution. Type jobs.new? for details.
2603 2618
2604 2619 You can check the status of all jobs with jobs.status().
2605 2620
2606 2621 The jobs variable is set by IPython into the Python builtin namespace.
2607 2622 If you ever declare a variable named 'jobs', you will shadow this
2608 2623 name. You can either delete your global jobs variable to regain
2609 2624 access to the job manager, or make a new name and assign it manually
2610 2625 to the manager (stored in IPython's namespace). For example, to
2611 2626 assign the job manager to the Jobs name, use:
2612 2627
2613 2628 Jobs = __builtins__.jobs"""
2614 2629
2615 2630 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2616 2631
2617 2632 def magic_store(self, parameter_s=''):
2618 2633 """Lightweight persistence for python variables.
2619 2634
2620 2635 Example:
2621 2636
2622 2637 ville@badger[~]|1> A = ['hello',10,'world']\\
2623 2638 ville@badger[~]|2> %store A\\
2624 2639 ville@badger[~]|3> Exit
2625 2640
2626 2641 (IPython session is closed and started again...)
2627 2642
2628 2643 ville@badger:~$ ipython -p pysh\\
2629 2644 ville@badger[~]|1> print A
2630 2645
2631 2646 ['hello', 10, 'world']
2632 2647
2633 2648 Usage:
2634 2649
2635 2650 %store - Show list of all variables and their current values\\
2636 2651 %store <var> - Store the *current* value of the variable to disk\\
2637 2652 %store -d <var> - Remove the variable and its value from storage\\
2638 2653 %store -r - Remove all variables from storage
2639 2654
2640 2655 It should be noted that if you change the value of a variable, you
2641 2656 need to %store it again if you want to persist the new value.
2642 2657
2643 2658 Note also that the variables will need to be pickleable; most basic
2644 2659 python types can be safely %stored.
2645 2660 """
2646 2661
2647 2662 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2648 2663 # delete
2649 2664 if opts.has_key('d'):
2650 2665 try:
2651 2666 todel = args[0]
2652 2667 except IndexError:
2653 2668 error('You must provide the variable to forget')
2654 2669 else:
2655 2670 try:
2656 2671 del self.shell.persist['S:' + todel]
2657 2672 except:
2658 2673 error("Can't delete variable '%s'" % todel)
2659 2674 # reset
2660 2675 elif opts.has_key('r'):
2661 2676 for k in self.shell.persist.keys():
2662 2677 if k.startswith('S:'):
2663 2678 del self.shell.persist[k]
2664 2679
2665 2680 # run without arguments -> list variables & values
2666 2681 elif not args:
2667 2682 vars = [v[2:] for v in self.shell.persist.keys()
2668 2683 if v.startswith('S:')]
2669 2684 vars.sort()
2670 2685 if vars:
2671 2686 size = max(map(len,vars))
2672 2687 else:
2673 2688 size = 0
2674 2689
2675 2690 print 'Stored variables and their in-memory values:'
2676 2691 fmt = '%-'+str(size)+'s -> %s'
2677 2692 get = self.shell.user_ns.get
2678 2693 for var in vars:
2679 2694 # print 30 first characters from every var
2680 2695 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2681 2696
2682 2697 # default action - store the variable
2683 2698 else:
2684 2699 obj = self.shell.user_ns[args[0] ]
2685 2700 if isinstance(inspect.getmodule(obj), FakeModule):
2686 2701 print textwrap.dedent("""\
2687 2702 Warning:%s is %s
2688 2703 Proper storage of interactively declared classes (or instances
2689 2704 of those classes) is not possible! Only instances
2690 2705 of classes in real modules on file system can be %%store'd.
2691 2706 """ % (args[0], obj) )
2692 2707 return
2693 2708 pickled = pickle.dumps(obj)
2694 2709 self.shell.persist[ 'S:' + args[0] ] = pickled
2695 2710 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2696 2711
2697 2712 def magic_bookmark(self, parameter_s=''):
2698 2713 """Manage IPython's bookmark system.
2699 2714
2700 2715 %bookmark <name> - set bookmark to current dir
2701 2716 %bookmark <name> <dir> - set bookmark to <dir>
2702 2717 %bookmark -l - list all bookmarks
2703 2718 %bookmark -d <name> - remove bookmark
2704 2719 %bookmark -r - remove all bookmarks
2705 2720
2706 2721 You can later on access a bookmarked folder with:
2707 2722 %cd -b <name>
2708 2723 or simply '%cd <name>' if there is no directory called <name> AND
2709 2724 there is such a bookmark defined.
2710 2725
2711 2726 Your bookmarks persist through IPython sessions, but they are
2712 2727 associated with each profile."""
2713 2728
2714 2729 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2715 2730 if len(args) > 2:
2716 2731 error('You can only give at most two arguments')
2717 2732 return
2718 2733
2719 2734 bkms = self.shell.persist.get('bookmarks',{})
2720 2735
2721 2736 if opts.has_key('d'):
2722 2737 try:
2723 2738 todel = args[0]
2724 2739 except IndexError:
2725 2740 error('You must provide a bookmark to delete')
2726 2741 else:
2727 2742 try:
2728 2743 del bkms[todel]
2729 2744 except:
2730 2745 error("Can't delete bookmark '%s'" % todel)
2731 2746 elif opts.has_key('r'):
2732 2747 bkms = {}
2733 2748 elif opts.has_key('l'):
2734 2749 bks = bkms.keys()
2735 2750 bks.sort()
2736 2751 if bks:
2737 2752 size = max(map(len,bks))
2738 2753 else:
2739 2754 size = 0
2740 2755 fmt = '%-'+str(size)+'s -> %s'
2741 2756 print 'Current bookmarks:'
2742 2757 for bk in bks:
2743 2758 print fmt % (bk,bkms[bk])
2744 2759 else:
2745 2760 if not args:
2746 2761 error("You must specify the bookmark name")
2747 2762 elif len(args)==1:
2748 2763 bkms[args[0]] = os.getcwd()
2749 2764 elif len(args)==2:
2750 2765 bkms[args[0]] = args[1]
2751 2766 self.shell.persist['bookmarks'] = bkms
2752 2767
2753 2768 def magic_pycat(self, parameter_s=''):
2754 2769 """Show a syntax-highlighted file through a pager.
2755 2770
2756 2771 This magic is similar to the cat utility, but it will assume the file
2757 2772 to be Python source and will show it with syntax highlighting. """
2758 2773
2759 2774 filename = get_py_filename(parameter_s)
2760 2775 page(self.shell.pycolorize(file_read(filename)),
2761 2776 screen_lines=self.shell.rc.screen_length)
2762 2777
2763 2778 def magic_cpaste(self, parameter_s=''):
2764 2779 """Allows you to paste & execute a pre-formatted code block from
2765 2780 clipboard.
2766 2781
2767 2782 You must terminate the block with '--' (two minus-signs) alone on the
2768 2783 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2769 2784 is the new sentinel for this operation)
2770 2785
2771 2786 The block is dedented prior to execution to enable execution of
2772 2787 method definitions. The executed block is also assigned to variable
2773 2788 named 'pasted_block' for later editing with '%edit pasted_block'.
2774 2789
2775 2790 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2776 2791 This assigns the pasted block to variable 'foo' as string, without
2777 2792 dedenting or executing it.
2778 2793
2779 2794 Do not be alarmed by garbled output on Windows (it's a readline bug).
2780 2795 Just press enter and type -- (and press enter again) and the block
2781 2796 will be what was just pasted.
2782 2797
2783 2798 IPython statements (magics, shell escapes) are not supported (yet).
2784 2799 """
2785 2800 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2786 2801 par = args.strip()
2787 2802 sentinel = opts.get('s','--')
2788 2803
2789 2804 from IPython import iplib
2790 2805 lines = []
2791 2806 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2792 2807 while 1:
2793 2808 l = iplib.raw_input_original(':')
2794 2809 if l ==sentinel:
2795 2810 break
2796 2811 lines.append(l)
2797 2812 block = "\n".join(lines)
2798 2813 #print "block:\n",block
2799 2814 if not par:
2800 2815 b = textwrap.dedent(block)
2801 2816 exec b in self.user_ns
2802 2817 self.user_ns['pasted_block'] = b
2803 2818 else:
2804 2819 self.user_ns[par] = block
2805 2820 print "Block assigned to '%s'" % par
2806 2821
2807 2822
2808 2823
2809 2824 # end Magic
@@ -1,77 +1,78 b''
1 1 # -*- coding: utf-8 -*-
2 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 7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 8 #
9 9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
10 10 # <n8gray@caltech.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 # Name of the package for release purposes. This is the name which labels
17 17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
18 18 name = 'ipython'
19 19
20 20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
21 21 # the new substring. We have to avoid using either dashes or underscores,
22 22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 23 # bdist_deb does not accept underscores (a Debian convention).
24 24
25
25 26 version = '0.7.2.svn'
26 27
27 revision = '$Revision: 1058 $'
28 revision = '$Revision: 1077 $'
28 29
29 30 description = "An enhanced interactive Python shell."
30 31
31 32 long_description = \
32 33 """
33 34 IPython provides a replacement for the interactive Python interpreter with
34 35 extra functionality.
35 36
36 37 Main features:
37 38
38 39 * Comprehensive object introspection.
39 40
40 41 * Input history, persistent across sessions.
41 42
42 43 * Caching of output results during a session with automatically generated
43 44 references.
44 45
45 46 * Readline based name completion.
46 47
47 48 * Extensible system of 'magic' commands for controlling the environment and
48 49 performing many tasks related either to IPython or the operating system.
49 50
50 51 * Configuration system with easy switching between different setups (simpler
51 52 than changing $PYTHONSTARTUP environment variables every time).
52 53
53 54 * Session logging and reloading.
54 55
55 56 * Extensible syntax processing for special purpose situations.
56 57
57 58 * Access to the system shell with user-extensible alias system.
58 59
59 60 * Easily embeddable in other Python programs.
60 61
61 62 * Integrated access to the pdb debugger and the Python profiler. """
62 63
63 64 license = 'BSD'
64 65
65 66 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
66 67 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
67 68 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
68 69 'Ville' : ('Ville Vainio','vivainio@gmail.com')
69 70 }
70 71
71 72 url = 'http://ipython.scipy.org'
72 73
73 74 download_url = 'http://ipython.scipy.org/dist'
74 75
75 76 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
76 77
77 78 keywords = ['Interactive','Interpreter','Shell']
@@ -1,562 +1,562 b''
1 1 """Word completion for IPython.
2 2
3 3 This module is a fork of the rlcompleter module in the Python standard
4 4 library. The original enhancements made to rlcompleter have been sent
5 5 upstream and were accepted as of Python 2.3, but we need a lot more
6 6 functionality specific to IPython, so this module will continue to live as an
7 7 IPython-specific utility.
8 8
9 9 ---------------------------------------------------------------------------
10 10 Original rlcompleter documentation:
11 11
12 12 This requires the latest extension to the readline module (the
13 13 completes keywords, built-ins and globals in __main__; when completing
14 14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 15 completes its attributes.
16 16
17 17 It's very cool to do "import string" type "string.", hit the
18 18 completion key (twice), and see the list of names defined by the
19 19 string module!
20 20
21 21 Tip: to use the tab key as the completion key, call
22 22
23 23 readline.parse_and_bind("tab: complete")
24 24
25 25 Notes:
26 26
27 27 - Exceptions raised by the completer function are *ignored* (and
28 28 generally cause the completion to fail). This is a feature -- since
29 29 readline sets the tty device in raw (or cbreak) mode, printing a
30 30 traceback wouldn't work well without some complicated hoopla to save,
31 31 reset and restore the tty state.
32 32
33 33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 34 application defined code to be executed if an object with a
35 35 __getattr__ hook is found. Since it is the responsibility of the
36 36 application (or the user) to enable this feature, I consider this an
37 37 acceptable risk. More complicated expressions (e.g. function calls or
38 38 indexing operations) are *not* evaluated.
39 39
40 40 - GNU readline is also used by the built-in functions input() and
41 41 raw_input(), and thus these also benefit/suffer from the completer
42 42 features. Clearly an interactive application can benefit by
43 43 specifying its own completer function and using raw_input() for all
44 44 its input.
45 45
46 46 - When the original stdin is not a tty device, GNU readline is never
47 47 used, and this module (and the readline module) are silently inactive.
48 48
49 49 """
50 50
51 51 #*****************************************************************************
52 52 #
53 53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 54 # module which is part of the standard Python distribution, I assume that the
55 55 # proper procedure is to maintain its copyright as belonging to the Python
56 56 # Software Foundation (in addition to my own, for all new code).
57 57 #
58 58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
60 60 #
61 61 # Distributed under the terms of the BSD License. The full license is in
62 62 # the file COPYING, distributed as part of this software.
63 63 #
64 64 #*****************************************************************************
65 65
66 66 import __builtin__
67 67 import __main__
68 68 import glob
69 69 import keyword
70 70 import os
71 71 import re
72 72 import readline
73 73 import sys
74 74 import types
75 75
76 76 # Python 2.4 offers sets as a builtin
77 77 try:
78 78 set([1,2])
79 79 except NameError:
80 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 85 __all__ = ['Completer','IPCompleter']
86 86
87 87 def get_class_members(cls):
88 88 ret = dir(cls)
89 89 if hasattr(cls,'__bases__'):
90 90 for base in cls.__bases__:
91 91 ret.extend(get_class_members(base))
92 92 return ret
93 93
94 94 class Completer:
95 95 def __init__(self,namespace=None,global_namespace=None):
96 96 """Create a new completer for the command line.
97 97
98 98 Completer([namespace,global_namespace]) -> completer instance.
99 99
100 100 If unspecified, the default namespace where completions are performed
101 101 is __main__ (technically, __main__.__dict__). Namespaces should be
102 102 given as dictionaries.
103 103
104 104 An optional second namespace can be given. This allows the completer
105 105 to handle cases where both the local and global scopes need to be
106 106 distinguished.
107 107
108 108 Completer instances should be used as the completion mechanism of
109 109 readline via the set_completer() call:
110 110
111 111 readline.set_completer(Completer(my_namespace).complete)
112 112 """
113 113
114 114 # some minimal strict typechecks. For some core data structures, I
115 115 # want actual basic python types, not just anything that looks like
116 116 # one. This is especially true for namespaces.
117 117 for ns in (namespace,global_namespace):
118 118 if ns is not None and type(ns) != types.DictType:
119 119 raise TypeError,'namespace must be a dictionary'
120 120
121 121 # Don't bind to namespace quite yet, but flag whether the user wants a
122 122 # specific namespace or to use __main__.__dict__. This will allow us
123 123 # to bind to __main__.__dict__ at completion time, not now.
124 124 if namespace is None:
125 125 self.use_main_ns = 1
126 126 else:
127 127 self.use_main_ns = 0
128 128 self.namespace = namespace
129 129
130 130 # The global namespace, if given, can be bound directly
131 131 if global_namespace is None:
132 132 self.global_namespace = {}
133 133 else:
134 134 self.global_namespace = global_namespace
135 135
136 136 def complete(self, text, state):
137 137 """Return the next possible completion for 'text'.
138 138
139 139 This is called successively with state == 0, 1, 2, ... until it
140 140 returns None. The completion should begin with 'text'.
141 141
142 142 """
143 143 if self.use_main_ns:
144 144 self.namespace = __main__.__dict__
145 145
146 146 if state == 0:
147 147 if "." in text:
148 148 self.matches = self.attr_matches(text)
149 149 else:
150 150 self.matches = self.global_matches(text)
151 151 try:
152 152 return self.matches[state]
153 153 except IndexError:
154 154 return None
155 155
156 156 def global_matches(self, text):
157 157 """Compute matches when text is a simple name.
158 158
159 159 Return a list of all keywords, built-in functions and names currently
160 160 defined in self.namespace or self.global_namespace that match.
161 161
162 162 """
163 163 matches = []
164 164 match_append = matches.append
165 165 n = len(text)
166 166 for lst in [keyword.kwlist,
167 167 __builtin__.__dict__.keys(),
168 168 self.namespace.keys(),
169 169 self.global_namespace.keys()]:
170 170 for word in lst:
171 171 if word[:n] == text and word != "__builtins__":
172 172 match_append(word)
173 173 return matches
174 174
175 175 def attr_matches(self, text):
176 176 """Compute matches when text contains a dot.
177 177
178 178 Assuming the text is of the form NAME.NAME....[NAME], and is
179 179 evaluatable in self.namespace or self.global_namespace, it will be
180 180 evaluated and its attributes (as revealed by dir()) are used as
181 181 possible completions. (For class instances, class members are are
182 182 also considered.)
183 183
184 184 WARNING: this can still invoke arbitrary C code, if an object
185 185 with a __getattr__ hook is evaluated.
186 186
187 187 """
188 188 import re
189 189
190 190 # Another option, seems to work great. Catches things like ''.<tab>
191 191 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
192 192
193 193 if not m:
194 194 return []
195 195
196 196 expr, attr = m.group(1, 3)
197 197 try:
198 198 object = eval(expr, self.namespace)
199 199 except:
200 200 object = eval(expr, self.global_namespace)
201 201
202 202 # Start building the attribute list via dir(), and then complete it
203 203 # with a few extra special-purpose calls.
204 204 words = dir(object)
205 205
206 206 if hasattr(object,'__class__'):
207 207 words.append('__class__')
208 208 words.extend(get_class_members(object.__class__))
209 209
210 210 # this is the 'dir' function for objects with Enthought's traits
211 211 if hasattr(object, 'trait_names'):
212 212 try:
213 213 words.extend(object.trait_names())
214 214 # eliminate possible duplicates, as some traits may also
215 215 # appear as normal attributes in the dir() call.
216 216 words = set(words)
217 217 except TypeError:
218 218 # This will happen if `object` is a class and not an instance.
219 219 pass
220 220
221 221 # filter out non-string attributes which may be stuffed by dir() calls
222 222 # and poor coding in third-party modules
223 223 words = [w for w in words
224 224 if isinstance(w, basestring) and w != "__builtins__"]
225 225 # Build match list to return
226 226 n = len(attr)
227 227 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
228 228
229 229 class IPCompleter(Completer):
230 230 """Extension of the completer class with IPython-specific features"""
231 231
232 232 def __init__(self,shell,namespace=None,global_namespace=None,
233 233 omit__names=0,alias_table=None):
234 234 """IPCompleter() -> completer
235 235
236 236 Return a completer object suitable for use by the readline library
237 237 via readline.set_completer().
238 238
239 239 Inputs:
240 240
241 241 - shell: a pointer to the ipython shell itself. This is needed
242 242 because this completer knows about magic functions, and those can
243 243 only be accessed via the ipython instance.
244 244
245 245 - namespace: an optional dict where completions are performed.
246 246
247 247 - global_namespace: secondary optional dict for completions, to
248 248 handle cases (such as IPython embedded inside functions) where
249 249 both Python scopes are visible.
250 250
251 251 - The optional omit__names parameter sets the completer to omit the
252 252 'magic' names (__magicname__) for python objects unless the text
253 253 to be completed explicitly starts with one or more underscores.
254 254
255 255 - If alias_table is supplied, it should be a dictionary of aliases
256 256 to complete. """
257 257
258 258 Completer.__init__(self,namespace,global_namespace)
259 259 self.magic_prefix = shell.name+'.magic_'
260 260 self.magic_escape = shell.ESC_MAGIC
261 261 self.readline = readline
262 262 delims = self.readline.get_completer_delims()
263 263 delims = delims.replace(self.magic_escape,'')
264 264 self.readline.set_completer_delims(delims)
265 265 self.get_line_buffer = self.readline.get_line_buffer
266 266 self.omit__names = omit__names
267 267 self.merge_completions = shell.rc.readline_merge_completions
268 268
269 269 if alias_table is None:
270 270 alias_table = {}
271 271 self.alias_table = alias_table
272 272 # Regexp to split filenames with spaces in them
273 273 self.space_name_re = re.compile(r'([^\\] )')
274 274 # Hold a local ref. to glob.glob for speed
275 275 self.glob = glob.glob
276 276
277 277 # Determine if we are running on 'dumb' terminals, like (X)Emacs
278 278 # buffers, to avoid completion problems.
279 279 term = os.environ.get('TERM','xterm')
280 280 self.dumb_terminal = term in ['dumb','emacs']
281 281
282 282 # Special handling of backslashes needed in win32 platforms
283 283 if sys.platform == "win32":
284 284 self.clean_glob = self._clean_glob_win32
285 285 else:
286 286 self.clean_glob = self._clean_glob
287 287 self.matchers = [self.python_matches,
288 288 self.file_matches,
289 289 self.alias_matches,
290 290 self.python_func_kw_matches]
291 291
292 292 # Code contributed by Alex Schmolck, for ipython/emacs integration
293 293 def all_completions(self, text):
294 294 """Return all possible completions for the benefit of emacs."""
295 295
296 296 completions = []
297 297 comp_append = completions.append
298 298 try:
299 299 for i in xrange(sys.maxint):
300 300 res = self.complete(text, i)
301 301
302 302 if not res: break
303 303
304 304 comp_append(res)
305 305 #XXX workaround for ``notDefined.<tab>``
306 306 except NameError:
307 307 pass
308 308 return completions
309 309 # /end Alex Schmolck code.
310 310
311 311 def _clean_glob(self,text):
312 312 return self.glob("%s*" % text)
313 313
314 314 def _clean_glob_win32(self,text):
315 315 return [f.replace("\\","/")
316 316 for f in self.glob("%s*" % text)]
317 317
318 318 def file_matches(self, text):
319 319 """Match filneames, expanding ~USER type strings.
320 320
321 321 Most of the seemingly convoluted logic in this completer is an
322 322 attempt to handle filenames with spaces in them. And yet it's not
323 323 quite perfect, because Python's readline doesn't expose all of the
324 324 GNU readline details needed for this to be done correctly.
325 325
326 326 For a filename with a space in it, the printed completions will be
327 327 only the parts after what's already been typed (instead of the
328 328 full completions, as is normally done). I don't think with the
329 329 current (as of Python 2.3) Python readline it's possible to do
330 330 better."""
331 331
332 332 #print 'Completer->file_matches: <%s>' % text # dbg
333 333
334 334 # chars that require escaping with backslash - i.e. chars
335 335 # that readline treats incorrectly as delimiters, but we
336 336 # don't want to treat as delimiters in filename matching
337 337 # when escaped with backslash
338 338
339 339 protectables = ' ()[]{}'
340 340
341 341 def protect_filename(s):
342 342 return "".join([(ch in protectables and '\\' + ch or ch)
343 343 for ch in s])
344 344
345 345 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
346 346 open_quotes = 0 # track strings with open quotes
347 347 try:
348 348 lsplit = shlex_split(lbuf)[-1]
349 349 except ValueError:
350 350 # typically an unmatched ", or backslash without escaped char.
351 351 if lbuf.count('"')==1:
352 352 open_quotes = 1
353 353 lsplit = lbuf.split('"')[-1]
354 354 elif lbuf.count("'")==1:
355 355 open_quotes = 1
356 356 lsplit = lbuf.split("'")[-1]
357 357 else:
358 358 return None
359 359 except IndexError:
360 360 # tab pressed on empty line
361 361 lsplit = ""
362 362
363 363 if lsplit != protect_filename(lsplit):
364 364 # if protectables are found, do matching on the whole escaped
365 365 # name
366 366 has_protectables = 1
367 367 text0,text = text,lsplit
368 368 else:
369 369 has_protectables = 0
370 370 text = os.path.expanduser(text)
371 371
372 372 if text == "":
373 373 return [protect_filename(f) for f in self.glob("*")]
374 374
375 375 m0 = self.clean_glob(text.replace('\\',''))
376 376 if has_protectables:
377 377 # If we had protectables, we need to revert our changes to the
378 378 # beginning of filename so that we don't double-write the part
379 379 # of the filename we have so far
380 380 len_lsplit = len(lsplit)
381 381 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
382 382 else:
383 383 if open_quotes:
384 384 # if we have a string with an open quote, we don't need to
385 385 # protect the names at all (and we _shouldn't_, as it
386 386 # would cause bugs when the filesystem call is made).
387 387 matches = m0
388 388 else:
389 389 matches = [protect_filename(f) for f in m0]
390 390 if len(matches) == 1 and os.path.isdir(matches[0]):
391 391 # Takes care of links to directories also. Use '/'
392 392 # explicitly, even under Windows, so that name completions
393 393 # don't end up escaped.
394 394 matches[0] += '/'
395 395 return matches
396 396
397 397 def alias_matches(self, text):
398 398 """Match internal system aliases"""
399 399
400 400 #print 'Completer->alias_matches:',text # dbg
401 401 text = os.path.expanduser(text)
402 402 aliases = self.alias_table.keys()
403 403 if text == "":
404 404 return aliases
405 405 else:
406 406 return [alias for alias in aliases if alias.startswith(text)]
407 407
408 408 def python_matches(self,text):
409 409 """Match attributes or global python names"""
410 410
411 411 #print 'Completer->python_matches, txt=<%s>' % text # dbg
412 412 if "." in text:
413 413 try:
414 414 matches = self.attr_matches(text)
415 415 if text.endswith('.') and self.omit__names:
416 416 if self.omit__names == 1:
417 417 # true if txt is _not_ a __ name, false otherwise:
418 418 no__name = (lambda txt:
419 419 re.match(r'.*\.__.*?__',txt) is None)
420 420 else:
421 421 # true if txt is _not_ a _ name, false otherwise:
422 422 no__name = (lambda txt:
423 423 re.match(r'.*\._.*?',txt) is None)
424 424 matches = filter(no__name, matches)
425 425 except NameError:
426 426 # catches <undefined attributes>.<tab>
427 427 matches = []
428 428 else:
429 429 matches = self.global_matches(text)
430 430 # this is so completion finds magics when automagic is on:
431 431 if matches == [] and not text.startswith(os.sep):
432 432 matches = self.attr_matches(self.magic_prefix+text)
433 433 return matches
434 434
435 435 def _default_arguments(self, obj):
436 436 """Return the list of default arguments of obj if it is callable,
437 437 or empty list otherwise."""
438 438
439 439 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
440 440 # for classes, check for __init__,__new__
441 441 if inspect.isclass(obj):
442 442 obj = (getattr(obj,'__init__',None) or
443 443 getattr(obj,'__new__',None))
444 444 # for all others, check if they are __call__able
445 445 elif hasattr(obj, '__call__'):
446 446 obj = obj.__call__
447 447 # XXX: is there a way to handle the builtins ?
448 448 try:
449 449 args,_,_1,defaults = inspect.getargspec(obj)
450 450 if defaults:
451 451 return args[-len(defaults):]
452 452 except TypeError: pass
453 453 return []
454 454
455 455 def python_func_kw_matches(self,text):
456 456 """Match named parameters (kwargs) of the last open function"""
457 457
458 458 if "." in text: # a parameter cannot be dotted
459 459 return []
460 460 try: regexp = self.__funcParamsRegex
461 461 except AttributeError:
462 462 regexp = self.__funcParamsRegex = re.compile(r'''
463 463 '.*?' | # single quoted strings or
464 464 ".*?" | # double quoted strings or
465 465 \w+ | # identifier
466 466 \S # other characters
467 467 ''', re.VERBOSE | re.DOTALL)
468 468 # 1. find the nearest identifier that comes before an unclosed
469 469 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
470 470 tokens = regexp.findall(self.get_line_buffer())
471 471 tokens.reverse()
472 472 iterTokens = iter(tokens); openPar = 0
473 473 for token in iterTokens:
474 474 if token == ')':
475 475 openPar -= 1
476 476 elif token == '(':
477 477 openPar += 1
478 478 if openPar > 0:
479 479 # found the last unclosed parenthesis
480 480 break
481 481 else:
482 482 return []
483 483 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
484 484 ids = []
485 485 isId = re.compile(r'\w+$').match
486 486 while True:
487 487 try:
488 488 ids.append(iterTokens.next())
489 489 if not isId(ids[-1]):
490 490 ids.pop(); break
491 491 if not iterTokens.next() == '.':
492 492 break
493 493 except StopIteration:
494 494 break
495 495 # lookup the candidate callable matches either using global_matches
496 496 # or attr_matches for dotted names
497 497 if len(ids) == 1:
498 498 callableMatches = self.global_matches(ids[0])
499 499 else:
500 500 callableMatches = self.attr_matches('.'.join(ids[::-1]))
501 501 argMatches = []
502 502 for callableMatch in callableMatches:
503 503 try: namedArgs = self._default_arguments(eval(callableMatch,
504 504 self.namespace))
505 505 except: continue
506 506 for namedArg in namedArgs:
507 507 if namedArg.startswith(text):
508 508 argMatches.append("%s=" %namedArg)
509 509 return argMatches
510 510
511 511 def complete(self, text, state):
512 512 """Return the next possible completion for 'text'.
513 513
514 514 This is called successively with state == 0, 1, 2, ... until it
515 515 returns None. The completion should begin with 'text'. """
516 516
517 517 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
518 518
519 519 # if there is only a tab on a line with only whitespace, instead
520 520 # of the mostly useless 'do you want to see all million
521 521 # completions' message, just do the right thing and give the user
522 522 # his tab! Incidentally, this enables pasting of tabbed text from
523 523 # an editor (as long as autoindent is off).
524 524
525 525 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
526 526 # don't interfere with their own tab-completion mechanism.
527 527 if not (self.dumb_terminal or self.get_line_buffer().strip()):
528 528 self.readline.insert_text('\t')
529 529 return None
530 530
531 531 magic_escape = self.magic_escape
532 532 magic_prefix = self.magic_prefix
533 533
534 534 try:
535 535 if text.startswith(magic_escape):
536 536 text = text.replace(magic_escape,magic_prefix)
537 537 elif text.startswith('~'):
538 538 text = os.path.expanduser(text)
539 539 if state == 0:
540 540 # Extend the list of completions with the results of each
541 541 # matcher, so we return results to the user from all
542 542 # namespaces.
543 543 if self.merge_completions:
544 544 self.matches = []
545 545 for matcher in self.matchers:
546 546 self.matches.extend(matcher(text))
547 547 else:
548 548 for matcher in self.matchers:
549 549 self.matches = matcher(text)
550 550 if self.matches:
551 551 break
552 552
553 553 try:
554 554 return self.matches[state].replace(magic_prefix,magic_escape)
555 555 except IndexError:
556 556 return None
557 557 except:
558 558 #from IPython.ultraTB import AutoFormattedTB; # dbg
559 559 #tb=AutoFormattedTB('Verbose');tb() #dbg
560 560
561 561 # If completion fails, don't annoy the user.
562 562 return None
@@ -1,1772 +1,1773 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 General purpose utilities.
4 4
5 5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 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 11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 from __future__ import generators # 2.2 compatibility
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 #****************************************************************************
24 24 # required modules from the Python standard library
25 25 import __main__
26 26 import commands
27 27 import os
28 28 import re
29 29 import shlex
30 30 import shutil
31 31 import sys
32 32 import tempfile
33 33 import time
34 34 import types
35 35
36 36 # Other IPython utilities
37 37 from IPython.Itpl import Itpl,itpl,printpl
38 38 from IPython import DPyGetOpt
39 39 from IPython.path import path
40 40 if os.name == "nt":
41 41 from IPython.winconsole import get_console_size
42 42
43 43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 44 # 2.2-friendly
45 45 try:
46 46 basestring
47 47 except NameError:
48 48 import types
49 49 basestring = (types.StringType, types.UnicodeType)
50 50 True = 1==1
51 51 False = 1==0
52 52
53 53 def enumerate(obj):
54 54 i = -1
55 55 for item in obj:
56 56 i += 1
57 57 yield i, item
58 58
59 59 # add these to the builtin namespace, so that all modules find them
60 60 import __builtin__
61 61 __builtin__.basestring = basestring
62 62 __builtin__.True = True
63 63 __builtin__.False = False
64 64 __builtin__.enumerate = enumerate
65 65
66 66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 68 try:
69 69 shlex_split = shlex.split
70 70 except AttributeError:
71 71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
76 76 % os.sep)
77 77
78 78 def shlex_split(s):
79 79 """Simplified backport to Python 2.2 of shlex.split().
80 80
81 81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 82 several of the features needed to really match the functionality of
83 83 shlex.split() in 2.3."""
84 84
85 85 lex = shlex.shlex(StringIO(s))
86 86 # Try to get options, extensions and path separators as characters
87 87 lex.wordchars = _wordchars
88 88 lex.commenters = ''
89 89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 90 # iterator.
91 91 lout = []
92 92 while 1:
93 93 token = lex.get_token()
94 94 if token == '':
95 95 break
96 96 # Try to handle quoted tokens correctly
97 97 quotes = _quotesre.match(token)
98 98 if quotes:
99 99 token = quotes.group(1)
100 100 lout.append(token)
101 101 return lout
102 102
103 103 #****************************************************************************
104 104 # Exceptions
105 105 class Error(Exception):
106 106 """Base class for exceptions in this module."""
107 107 pass
108 108
109 109 #----------------------------------------------------------------------------
110 110 class IOStream:
111 111 def __init__(self,stream,fallback):
112 112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 113 stream = fallback
114 114 self.stream = stream
115 115 self._swrite = stream.write
116 116 self.flush = stream.flush
117 117
118 118 def write(self,data):
119 119 try:
120 120 self._swrite(data)
121 121 except:
122 122 try:
123 123 # print handles some unicode issues which may trip a plain
124 124 # write() call. Attempt to emulate write() by using a
125 125 # trailing comma
126 126 print >> self.stream, data,
127 127 except:
128 128 # if we get here, something is seriously broken.
129 129 print >> sys.stderr, \
130 130 'ERROR - failed to write data to stream:', stream
131 131
132 132 class IOTerm:
133 133 """ Term holds the file or file-like objects for handling I/O operations.
134 134
135 135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 136 Windows they can can replaced to allow editing the strings before they are
137 137 displayed."""
138 138
139 139 # In the future, having IPython channel all its I/O operations through
140 140 # this class will make it easier to embed it into other environments which
141 141 # are not a normal terminal (such as a GUI-based shell)
142 142 def __init__(self,cin=None,cout=None,cerr=None):
143 143 self.cin = IOStream(cin,sys.stdin)
144 144 self.cout = IOStream(cout,sys.stdout)
145 145 self.cerr = IOStream(cerr,sys.stderr)
146 146
147 147 # Global variable to be used for all I/O
148 148 Term = IOTerm()
149 149
150 150 # Windows-specific code to load Gary Bishop's readline and configure it
151 151 # automatically for the users
152 152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
153 153 # windows. Cygwin returns 'cygwin' for sys.platform.
154 154 if os.name == 'nt':
155 155 try:
156 156 import readline
157 157 except ImportError:
158 158 pass
159 159 else:
160 160 try:
161 161 _out = readline.GetOutputFile()
162 162 except AttributeError:
163 163 pass
164 164 else:
165 165 # Remake Term to use the readline i/o facilities
166 166 Term = IOTerm(cout=_out,cerr=_out)
167 167 del _out
168 168
169 169 #****************************************************************************
170 170 # Generic warning/error printer, used by everything else
171 171 def warn(msg,level=2,exit_val=1):
172 172 """Standard warning printer. Gives formatting consistency.
173 173
174 174 Output is sent to Term.cerr (sys.stderr by default).
175 175
176 176 Options:
177 177
178 178 -level(2): allows finer control:
179 179 0 -> Do nothing, dummy function.
180 180 1 -> Print message.
181 181 2 -> Print 'WARNING:' + message. (Default level).
182 182 3 -> Print 'ERROR:' + message.
183 183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184 184
185 185 -exit_val (1): exit value returned by sys.exit() for a level 4
186 186 warning. Ignored for all other levels."""
187 187
188 188 if level>0:
189 189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 190 print >> Term.cerr, '%s%s' % (header[level],msg)
191 191 if level == 4:
192 192 print >> Term.cerr,'Exiting.\n'
193 193 sys.exit(exit_val)
194 194
195 195 def info(msg):
196 196 """Equivalent to warn(msg,level=1)."""
197 197
198 198 warn(msg,level=1)
199 199
200 200 def error(msg):
201 201 """Equivalent to warn(msg,level=3)."""
202 202
203 203 warn(msg,level=3)
204 204
205 205 def fatal(msg,exit_val=1):
206 206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207 207
208 208 warn(msg,exit_val=exit_val,level=4)
209 209
210
211 # useful for debugging
212 def debugp(expr,pre_msg=''):
210 #---------------------------------------------------------------------------
211 # Debugging routines
212 #
213 def debugx(expr,pre_msg=''):
213 214 """Print the value of an expression from the caller's frame.
214 215
215 216 Takes an expression, evaluates it in the caller's frame and prints both
216 217 the given expression and the resulting value (as well as a debug mark
217 218 indicating the name of the calling function. The input must be of a form
218 219 suitable for eval().
219 220
220 221 An optional message can be passed, which will be prepended to the printed
221 222 expr->value pair."""
222 223
223 224 cf = sys._getframe(1)
224 225 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
225 226 eval(expr,cf.f_globals,cf.f_locals))
226 227
227 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 232 StringTypes = types.StringTypes
232 233
233 234 # Basic timing functionality
234 235
235 236 # If possible (Unix), use the resource module instead of time.clock()
236 237 try:
237 238 import resource
238 239 def clock():
239 240 """clock() -> floating point number
240 241
241 242 Return the CPU time in seconds (user time only, system time is
242 243 ignored) since the start of the process. This is done via a call to
243 244 resource.getrusage, so it avoids the wraparound problems in
244 245 time.clock()."""
245 246
246 247 return resource.getrusage(resource.RUSAGE_SELF)[0]
247 248
248 249 def clock2():
249 250 """clock2() -> (t_user,t_system)
250 251
251 252 Similar to clock(), but return a tuple of user/system times."""
252 253 return resource.getrusage(resource.RUSAGE_SELF)[:2]
253 254
254 255 except ImportError:
255 256 clock = time.clock
256 257 def clock2():
257 258 """Under windows, system CPU time can't be measured.
258 259
259 260 This just returns clock() and zero."""
260 261 return time.clock(),0.0
261 262
262 263 def timings_out(reps,func,*args,**kw):
263 264 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
264 265
265 266 Execute a function reps times, return a tuple with the elapsed total
266 267 CPU time in seconds, the time per call and the function's output.
267 268
268 269 Under Unix, the return value is the sum of user+system time consumed by
269 270 the process, computed via the resource module. This prevents problems
270 271 related to the wraparound effect which the time.clock() function has.
271 272
272 273 Under Windows the return value is in wall clock seconds. See the
273 274 documentation for the time module for more details."""
274 275
275 276 reps = int(reps)
276 277 assert reps >=1, 'reps must be >= 1'
277 278 if reps==1:
278 279 start = clock()
279 280 out = func(*args,**kw)
280 281 tot_time = clock()-start
281 282 else:
282 283 rng = xrange(reps-1) # the last time is executed separately to store output
283 284 start = clock()
284 285 for dummy in rng: func(*args,**kw)
285 286 out = func(*args,**kw) # one last time
286 287 tot_time = clock()-start
287 288 av_time = tot_time / reps
288 289 return tot_time,av_time,out
289 290
290 291 def timings(reps,func,*args,**kw):
291 292 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
292 293
293 294 Execute a function reps times, return a tuple with the elapsed total CPU
294 295 time in seconds and the time per call. These are just the first two values
295 296 in timings_out()."""
296 297
297 298 return timings_out(reps,func,*args,**kw)[0:2]
298 299
299 300 def timing(func,*args,**kw):
300 301 """timing(func,*args,**kw) -> t_total
301 302
302 303 Execute a function once, return the elapsed total CPU time in
303 304 seconds. This is just the first value in timings_out()."""
304 305
305 306 return timings_out(1,func,*args,**kw)[0]
306 307
307 308 #****************************************************************************
308 309 # file and system
309 310
310 311 def system(cmd,verbose=0,debug=0,header=''):
311 312 """Execute a system command, return its exit status.
312 313
313 314 Options:
314 315
315 316 - verbose (0): print the command to be executed.
316 317
317 318 - debug (0): only print, do not actually execute.
318 319
319 320 - header (''): Header to print on screen prior to the executed command (it
320 321 is only prepended to the command, no newlines are added).
321 322
322 323 Note: a stateful version of this function is available through the
323 324 SystemExec class."""
324 325
325 326 stat = 0
326 327 if verbose or debug: print header+cmd
327 328 sys.stdout.flush()
328 329 if not debug: stat = os.system(cmd)
329 330 return stat
330 331
331 332 # This function is used by ipython in a lot of places to make system calls.
332 333 # We need it to be slightly different under win32, due to the vagaries of
333 334 # 'network shares'. A win32 override is below.
334 335
335 336 def shell(cmd,verbose=0,debug=0,header=''):
336 337 """Execute a command in the system shell, always return None.
337 338
338 339 Options:
339 340
340 341 - verbose (0): print the command to be executed.
341 342
342 343 - debug (0): only print, do not actually execute.
343 344
344 345 - header (''): Header to print on screen prior to the executed command (it
345 346 is only prepended to the command, no newlines are added).
346 347
347 348 Note: this is similar to genutils.system(), but it returns None so it can
348 349 be conveniently used in interactive loops without getting the return value
349 350 (typically 0) printed many times."""
350 351
351 352 stat = 0
352 353 if verbose or debug: print header+cmd
353 354 # flush stdout so we don't mangle python's buffering
354 355 sys.stdout.flush()
355 356 if not debug:
356 357 os.system(cmd)
357 358
358 359 # override shell() for win32 to deal with network shares
359 360 if os.name in ('nt','dos'):
360 361
361 362 shell_ori = shell
362 363
363 364 def shell(cmd,verbose=0,debug=0,header=''):
364 365 if os.getcwd().startswith(r"\\"):
365 366 path = os.getcwd()
366 367 # change to c drive (cannot be on UNC-share when issuing os.system,
367 368 # as cmd.exe cannot handle UNC addresses)
368 369 os.chdir("c:")
369 370 # issue pushd to the UNC-share and then run the command
370 371 try:
371 372 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
372 373 finally:
373 374 os.chdir(path)
374 375 else:
375 376 shell_ori(cmd,verbose,debug,header)
376 377
377 378 shell.__doc__ = shell_ori.__doc__
378 379
379 380 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
380 381 """Dummy substitute for perl's backquotes.
381 382
382 383 Executes a command and returns the output.
383 384
384 385 Accepts the same arguments as system(), plus:
385 386
386 387 - split(0): if true, the output is returned as a list split on newlines.
387 388
388 389 Note: a stateful version of this function is available through the
389 390 SystemExec class."""
390 391
391 392 if verbose or debug: print header+cmd
392 393 if not debug:
393 394 output = commands.getoutput(cmd)
394 395 if split:
395 396 return output.split('\n')
396 397 else:
397 398 return output
398 399
399 400 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
400 401 """Return (standard output,standard error) of executing cmd in a shell.
401 402
402 403 Accepts the same arguments as system(), plus:
403 404
404 405 - split(0): if true, each of stdout/err is returned as a list split on
405 406 newlines.
406 407
407 408 Note: a stateful version of this function is available through the
408 409 SystemExec class."""
409 410
410 411 if verbose or debug: print header+cmd
411 412 if not cmd:
412 413 if split:
413 414 return [],[]
414 415 else:
415 416 return '',''
416 417 if not debug:
417 418 pin,pout,perr = os.popen3(cmd)
418 419 tout = pout.read().rstrip()
419 420 terr = perr.read().rstrip()
420 421 pin.close()
421 422 pout.close()
422 423 perr.close()
423 424 if split:
424 425 return tout.split('\n'),terr.split('\n')
425 426 else:
426 427 return tout,terr
427 428
428 429 # for compatibility with older naming conventions
429 430 xsys = system
430 431 bq = getoutput
431 432
432 433 class SystemExec:
433 434 """Access the system and getoutput functions through a stateful interface.
434 435
435 436 Note: here we refer to the system and getoutput functions from this
436 437 library, not the ones from the standard python library.
437 438
438 439 This class offers the system and getoutput functions as methods, but the
439 440 verbose, debug and header parameters can be set for the instance (at
440 441 creation time or later) so that they don't need to be specified on each
441 442 call.
442 443
443 444 For efficiency reasons, there's no way to override the parameters on a
444 445 per-call basis other than by setting instance attributes. If you need
445 446 local overrides, it's best to directly call system() or getoutput().
446 447
447 448 The following names are provided as alternate options:
448 449 - xsys: alias to system
449 450 - bq: alias to getoutput
450 451
451 452 An instance can then be created as:
452 453 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
453 454
454 455 And used as:
455 456 >>> sysexec.xsys('pwd')
456 457 >>> dirlist = sysexec.bq('ls -l')
457 458 """
458 459
459 460 def __init__(self,verbose=0,debug=0,header='',split=0):
460 461 """Specify the instance's values for verbose, debug and header."""
461 462 setattr_list(self,'verbose debug header split')
462 463
463 464 def system(self,cmd):
464 465 """Stateful interface to system(), with the same keyword parameters."""
465 466
466 467 system(cmd,self.verbose,self.debug,self.header)
467 468
468 469 def shell(self,cmd):
469 470 """Stateful interface to shell(), with the same keyword parameters."""
470 471
471 472 shell(cmd,self.verbose,self.debug,self.header)
472 473
473 474 xsys = system # alias
474 475
475 476 def getoutput(self,cmd):
476 477 """Stateful interface to getoutput()."""
477 478
478 479 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
479 480
480 481 def getoutputerror(self,cmd):
481 482 """Stateful interface to getoutputerror()."""
482 483
483 484 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
484 485
485 486 bq = getoutput # alias
486 487
487 488 #-----------------------------------------------------------------------------
488 489 def mutex_opts(dict,ex_op):
489 490 """Check for presence of mutually exclusive keys in a dict.
490 491
491 492 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
492 493 for op1,op2 in ex_op:
493 494 if op1 in dict and op2 in dict:
494 495 raise ValueError,'\n*** ERROR in Arguments *** '\
495 496 'Options '+op1+' and '+op2+' are mutually exclusive.'
496 497
497 498 #-----------------------------------------------------------------------------
498 499 def get_py_filename(name):
499 500 """Return a valid python filename in the current directory.
500 501
501 502 If the given name is not a file, it adds '.py' and searches again.
502 503 Raises IOError with an informative message if the file isn't found."""
503 504
504 505 name = os.path.expanduser(name)
505 506 if not os.path.isfile(name) and not name.endswith('.py'):
506 507 name += '.py'
507 508 if os.path.isfile(name):
508 509 return name
509 510 else:
510 511 raise IOError,'File `%s` not found.' % name
511 512
512 513 #-----------------------------------------------------------------------------
513 514 def filefind(fname,alt_dirs = None):
514 515 """Return the given filename either in the current directory, if it
515 516 exists, or in a specified list of directories.
516 517
517 518 ~ expansion is done on all file and directory names.
518 519
519 520 Upon an unsuccessful search, raise an IOError exception."""
520 521
521 522 if alt_dirs is None:
522 523 try:
523 524 alt_dirs = get_home_dir()
524 525 except HomeDirError:
525 526 alt_dirs = os.getcwd()
526 527 search = [fname] + list_strings(alt_dirs)
527 528 search = map(os.path.expanduser,search)
528 529 #print 'search list for',fname,'list:',search # dbg
529 530 fname = search[0]
530 531 if os.path.isfile(fname):
531 532 return fname
532 533 for direc in search[1:]:
533 534 testname = os.path.join(direc,fname)
534 535 #print 'testname',testname # dbg
535 536 if os.path.isfile(testname):
536 537 return testname
537 538 raise IOError,'File' + `fname` + \
538 539 ' not found in current or supplied directories:' + `alt_dirs`
539 540
540 541 #----------------------------------------------------------------------------
541 542 def file_read(filename):
542 543 """Read a file and close it. Returns the file source."""
543 544 fobj=open(filename,'r');
544 545 source = fobj.read();
545 546 fobj.close()
546 547 return source
547 548
548 549 #----------------------------------------------------------------------------
549 550 def target_outdated(target,deps):
550 551 """Determine whether a target is out of date.
551 552
552 553 target_outdated(target,deps) -> 1/0
553 554
554 555 deps: list of filenames which MUST exist.
555 556 target: single filename which may or may not exist.
556 557
557 558 If target doesn't exist or is older than any file listed in deps, return
558 559 true, otherwise return false.
559 560 """
560 561 try:
561 562 target_time = os.path.getmtime(target)
562 563 except os.error:
563 564 return 1
564 565 for dep in deps:
565 566 dep_time = os.path.getmtime(dep)
566 567 if dep_time > target_time:
567 568 #print "For target",target,"Dep failed:",dep # dbg
568 569 #print "times (dep,tar):",dep_time,target_time # dbg
569 570 return 1
570 571 return 0
571 572
572 573 #-----------------------------------------------------------------------------
573 574 def target_update(target,deps,cmd):
574 575 """Update a target with a given command given a list of dependencies.
575 576
576 577 target_update(target,deps,cmd) -> runs cmd if target is outdated.
577 578
578 579 This is just a wrapper around target_outdated() which calls the given
579 580 command if target is outdated."""
580 581
581 582 if target_outdated(target,deps):
582 583 xsys(cmd)
583 584
584 585 #----------------------------------------------------------------------------
585 586 def unquote_ends(istr):
586 587 """Remove a single pair of quotes from the endpoints of a string."""
587 588
588 589 if not istr:
589 590 return istr
590 591 if (istr[0]=="'" and istr[-1]=="'") or \
591 592 (istr[0]=='"' and istr[-1]=='"'):
592 593 return istr[1:-1]
593 594 else:
594 595 return istr
595 596
596 597 #----------------------------------------------------------------------------
597 598 def process_cmdline(argv,names=[],defaults={},usage=''):
598 599 """ Process command-line options and arguments.
599 600
600 601 Arguments:
601 602
602 603 - argv: list of arguments, typically sys.argv.
603 604
604 605 - names: list of option names. See DPyGetOpt docs for details on options
605 606 syntax.
606 607
607 608 - defaults: dict of default values.
608 609
609 610 - usage: optional usage notice to print if a wrong argument is passed.
610 611
611 612 Return a dict of options and a list of free arguments."""
612 613
613 614 getopt = DPyGetOpt.DPyGetOpt()
614 615 getopt.setIgnoreCase(0)
615 616 getopt.parseConfiguration(names)
616 617
617 618 try:
618 619 getopt.processArguments(argv)
619 620 except:
620 621 print usage
621 622 warn(`sys.exc_value`,level=4)
622 623
623 624 defaults.update(getopt.optionValues)
624 625 args = getopt.freeValues
625 626
626 627 return defaults,args
627 628
628 629 #----------------------------------------------------------------------------
629 630 def optstr2types(ostr):
630 631 """Convert a string of option names to a dict of type mappings.
631 632
632 633 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
633 634
634 635 This is used to get the types of all the options in a string formatted
635 636 with the conventions of DPyGetOpt. The 'type' None is used for options
636 637 which are strings (they need no further conversion). This function's main
637 638 use is to get a typemap for use with read_dict().
638 639 """
639 640
640 641 typeconv = {None:'',int:'',float:''}
641 642 typemap = {'s':None,'i':int,'f':float}
642 643 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
643 644
644 645 for w in ostr.split():
645 646 oname,alias,otype = opt_re.match(w).groups()
646 647 if otype == '' or alias == '!': # simple switches are integers too
647 648 otype = 'i'
648 649 typeconv[typemap[otype]] += oname + ' '
649 650 return typeconv
650 651
651 652 #----------------------------------------------------------------------------
652 653 def read_dict(filename,type_conv=None,**opt):
653 654
654 655 """Read a dictionary of key=value pairs from an input file, optionally
655 656 performing conversions on the resulting values.
656 657
657 658 read_dict(filename,type_conv,**opt) -> dict
658 659
659 660 Only one value per line is accepted, the format should be
660 661 # optional comments are ignored
661 662 key value\n
662 663
663 664 Args:
664 665
665 666 - type_conv: A dictionary specifying which keys need to be converted to
666 667 which types. By default all keys are read as strings. This dictionary
667 668 should have as its keys valid conversion functions for strings
668 669 (int,long,float,complex, or your own). The value for each key
669 670 (converter) should be a whitespace separated string containing the names
670 671 of all the entries in the file to be converted using that function. For
671 672 keys to be left alone, use None as the conversion function (only needed
672 673 with purge=1, see below).
673 674
674 675 - opt: dictionary with extra options as below (default in parens)
675 676
676 677 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
677 678 of the dictionary to be returned. If purge is going to be used, the
678 679 set of keys to be left as strings also has to be explicitly specified
679 680 using the (non-existent) conversion function None.
680 681
681 682 fs(None): field separator. This is the key/value separator to be used
682 683 when parsing the file. The None default means any whitespace [behavior
683 684 of string.split()].
684 685
685 686 strip(0): if 1, strip string values of leading/trailinig whitespace.
686 687
687 688 warn(1): warning level if requested keys are not found in file.
688 689 - 0: silently ignore.
689 690 - 1: inform but proceed.
690 691 - 2: raise KeyError exception.
691 692
692 693 no_empty(0): if 1, remove keys with whitespace strings as a value.
693 694
694 695 unique([]): list of keys (or space separated string) which can't be
695 696 repeated. If one such key is found in the file, each new instance
696 697 overwrites the previous one. For keys not listed here, the behavior is
697 698 to make a list of all appearances.
698 699
699 700 Example:
700 701 If the input file test.ini has:
701 702 i 3
702 703 x 4.5
703 704 y 5.5
704 705 s hi ho
705 706 Then:
706 707
707 708 >>> type_conv={int:'i',float:'x',None:'s'}
708 709 >>> read_dict('test.ini')
709 710 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
710 711 >>> read_dict('test.ini',type_conv)
711 712 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
712 713 >>> read_dict('test.ini',type_conv,purge=1)
713 714 {'i': 3, 's': 'hi ho', 'x': 4.5}
714 715 """
715 716
716 717 # starting config
717 718 opt.setdefault('purge',0)
718 719 opt.setdefault('fs',None) # field sep defaults to any whitespace
719 720 opt.setdefault('strip',0)
720 721 opt.setdefault('warn',1)
721 722 opt.setdefault('no_empty',0)
722 723 opt.setdefault('unique','')
723 724 if type(opt['unique']) in StringTypes:
724 725 unique_keys = qw(opt['unique'])
725 726 elif type(opt['unique']) in (types.TupleType,types.ListType):
726 727 unique_keys = opt['unique']
727 728 else:
728 729 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
729 730
730 731 dict = {}
731 732 # first read in table of values as strings
732 733 file = open(filename,'r')
733 734 for line in file.readlines():
734 735 line = line.strip()
735 736 if len(line) and line[0]=='#': continue
736 737 if len(line)>0:
737 738 lsplit = line.split(opt['fs'],1)
738 739 try:
739 740 key,val = lsplit
740 741 except ValueError:
741 742 key,val = lsplit[0],''
742 743 key = key.strip()
743 744 if opt['strip']: val = val.strip()
744 745 if val == "''" or val == '""': val = ''
745 746 if opt['no_empty'] and (val=='' or val.isspace()):
746 747 continue
747 748 # if a key is found more than once in the file, build a list
748 749 # unless it's in the 'unique' list. In that case, last found in file
749 750 # takes precedence. User beware.
750 751 try:
751 752 if dict[key] and key in unique_keys:
752 753 dict[key] = val
753 754 elif type(dict[key]) is types.ListType:
754 755 dict[key].append(val)
755 756 else:
756 757 dict[key] = [dict[key],val]
757 758 except KeyError:
758 759 dict[key] = val
759 760 # purge if requested
760 761 if opt['purge']:
761 762 accepted_keys = qwflat(type_conv.values())
762 763 for key in dict.keys():
763 764 if key in accepted_keys: continue
764 765 del(dict[key])
765 766 # now convert if requested
766 767 if type_conv==None: return dict
767 768 conversions = type_conv.keys()
768 769 try: conversions.remove(None)
769 770 except: pass
770 771 for convert in conversions:
771 772 for val in qw(type_conv[convert]):
772 773 try:
773 774 dict[val] = convert(dict[val])
774 775 except KeyError,e:
775 776 if opt['warn'] == 0:
776 777 pass
777 778 elif opt['warn'] == 1:
778 779 print >>sys.stderr, 'Warning: key',val,\
779 780 'not found in file',filename
780 781 elif opt['warn'] == 2:
781 782 raise KeyError,e
782 783 else:
783 784 raise ValueError,'Warning level must be 0,1 or 2'
784 785
785 786 return dict
786 787
787 788 #----------------------------------------------------------------------------
788 789 def flag_calls(func):
789 790 """Wrap a function to detect and flag when it gets called.
790 791
791 792 This is a decorator which takes a function and wraps it in a function with
792 793 a 'called' attribute. wrapper.called is initialized to False.
793 794
794 795 The wrapper.called attribute is set to False right before each call to the
795 796 wrapped function, so if the call fails it remains False. After the call
796 797 completes, wrapper.called is set to True and the output is returned.
797 798
798 799 Testing for truth in wrapper.called allows you to determine if a call to
799 800 func() was attempted and succeeded."""
800 801
801 802 def wrapper(*args,**kw):
802 803 wrapper.called = False
803 804 out = func(*args,**kw)
804 805 wrapper.called = True
805 806 return out
806 807
807 808 wrapper.called = False
808 809 wrapper.__doc__ = func.__doc__
809 810 return wrapper
810 811
811 812 #----------------------------------------------------------------------------
812 813 class HomeDirError(Error):
813 814 pass
814 815
815 816 def get_home_dir():
816 817 """Return the closest possible equivalent to a 'home' directory.
817 818
818 819 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
819 820
820 821 Currently only Posix and NT are implemented, a HomeDirError exception is
821 822 raised for all other OSes. """
822 823
823 824 isdir = os.path.isdir
824 825 env = os.environ
825 826 try:
826 827 homedir = env['HOME']
827 828 if not isdir(homedir):
828 829 # in case a user stuck some string which does NOT resolve to a
829 830 # valid path, it's as good as if we hadn't foud it
830 831 raise KeyError
831 832 return homedir
832 833 except KeyError:
833 834 if os.name == 'posix':
834 835 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
835 836 elif os.name == 'nt':
836 837 # For some strange reason, win9x returns 'nt' for os.name.
837 838 try:
838 839 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
839 840 if not isdir(homedir):
840 841 homedir = os.path.join(env['USERPROFILE'])
841 842 if not isdir(homedir):
842 843 raise HomeDirError
843 844 return homedir
844 845 except:
845 846 try:
846 847 # Use the registry to get the 'My Documents' folder.
847 848 import _winreg as wreg
848 849 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
849 850 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
850 851 homedir = wreg.QueryValueEx(key,'Personal')[0]
851 852 key.Close()
852 853 if not isdir(homedir):
853 854 e = ('Invalid "Personal" folder registry key '
854 855 'typically "My Documents".\n'
855 856 'Value: %s\n'
856 857 'This is not a valid directory on your system.' %
857 858 homedir)
858 859 raise HomeDirError(e)
859 860 return homedir
860 861 except HomeDirError:
861 862 raise
862 863 except:
863 864 return 'C:\\'
864 865 elif os.name == 'dos':
865 866 # Desperate, may do absurd things in classic MacOS. May work under DOS.
866 867 return 'C:\\'
867 868 else:
868 869 raise HomeDirError,'support for your operating system not implemented.'
869 870
870 871 #****************************************************************************
871 872 # strings and text
872 873
873 874 class LSString(str):
874 875 """String derivative with a special access attributes.
875 876
876 877 These are normal strings, but with the special attributes:
877 878
878 879 .l (or .list) : value as list (split on newlines).
879 880 .n (or .nlstr): original value (the string itself).
880 881 .s (or .spstr): value as whitespace-separated string.
881 882
882 883 Any values which require transformations are computed only once and
883 884 cached.
884 885
885 886 Such strings are very useful to efficiently interact with the shell, which
886 887 typically only understands whitespace-separated options for commands."""
887 888
888 889 def get_list(self):
889 890 try:
890 891 return self.__list
891 892 except AttributeError:
892 893 self.__list = self.split('\n')
893 894 return self.__list
894 895
895 896 l = list = property(get_list)
896 897
897 898 def get_spstr(self):
898 899 try:
899 900 return self.__spstr
900 901 except AttributeError:
901 902 self.__spstr = self.replace('\n',' ')
902 903 return self.__spstr
903 904
904 905 s = spstr = property(get_spstr)
905 906
906 907 def get_nlstr(self):
907 908 return self
908 909
909 910 n = nlstr = property(get_nlstr)
910 911
911 912 def get_paths(self):
912 913 try:
913 914 return self.__paths
914 915 except AttributeError:
915 916 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
916 917 return self.__paths
917 918
918 919 p = paths = property(get_paths)
919 920
920 921
921 922 #----------------------------------------------------------------------------
922 923 class SList(list):
923 924 """List derivative with a special access attributes.
924 925
925 926 These are normal lists, but with the special attributes:
926 927
927 928 .l (or .list) : value as list (the list itself).
928 929 .n (or .nlstr): value as a string, joined on newlines.
929 930 .s (or .spstr): value as a string, joined on spaces.
930 931
931 932 Any values which require transformations are computed only once and
932 933 cached."""
933 934
934 935 def get_list(self):
935 936 return self
936 937
937 938 l = list = property(get_list)
938 939
939 940 def get_spstr(self):
940 941 try:
941 942 return self.__spstr
942 943 except AttributeError:
943 944 self.__spstr = ' '.join(self)
944 945 return self.__spstr
945 946
946 947 s = spstr = property(get_spstr)
947 948
948 949 def get_nlstr(self):
949 950 try:
950 951 return self.__nlstr
951 952 except AttributeError:
952 953 self.__nlstr = '\n'.join(self)
953 954 return self.__nlstr
954 955
955 956 n = nlstr = property(get_nlstr)
956 957
957 958 def get_paths(self):
958 959 try:
959 960 return self.__paths
960 961 except AttributeError:
961 962 self.__paths = [path(p) for p in self if os.path.exists(p)]
962 963 return self.__paths
963 964
964 965 p = paths = property(get_paths)
965 966
966 967 #----------------------------------------------------------------------------
967 968 def esc_quotes(strng):
968 969 """Return the input string with single and double quotes escaped out"""
969 970
970 971 return strng.replace('"','\\"').replace("'","\\'")
971 972
972 973 #----------------------------------------------------------------------------
973 974 def make_quoted_expr(s):
974 975 """Return string s in appropriate quotes, using raw string if possible.
975 976
976 977 Effectively this turns string: cd \ao\ao\
977 978 to: r"cd \ao\ao\_"[:-1]
978 979
979 980 Note the use of raw string and padding at the end to allow trailing backslash.
980 981
981 982 """
982 983
983 984 tail = ''
984 985 tailpadding = ''
985 986 raw = ''
986 987 if "\\" in s:
987 988 raw = 'r'
988 989 if s.endswith('\\'):
989 990 tail = '[:-1]'
990 991 tailpadding = '_'
991 992 if '"' not in s:
992 993 quote = '"'
993 994 elif "'" not in s:
994 995 quote = "'"
995 996 elif '"""' not in s and not s.endswith('"'):
996 997 quote = '"""'
997 998 elif "'''" not in s and not s.endswith("'"):
998 999 quote = "'''"
999 1000 else:
1000 1001 # give up, backslash-escaped string will do
1001 1002 return '"%s"' % esc_quotes(s)
1002 1003 res = itpl("$raw$quote$s$tailpadding$quote$tail")
1003 1004 return res
1004 1005
1005 1006
1006 1007 #----------------------------------------------------------------------------
1007 1008 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1008 1009 """Take multiple lines of input.
1009 1010
1010 1011 A list with each line of input as a separate element is returned when a
1011 1012 termination string is entered (defaults to a single '.'). Input can also
1012 1013 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1013 1014
1014 1015 Lines of input which end in \\ are joined into single entries (and a
1015 1016 secondary continuation prompt is issued as long as the user terminates
1016 1017 lines with \\). This allows entering very long strings which are still
1017 1018 meant to be treated as single entities.
1018 1019 """
1019 1020
1020 1021 try:
1021 1022 if header:
1022 1023 header += '\n'
1023 1024 lines = [raw_input(header + ps1)]
1024 1025 except EOFError:
1025 1026 return []
1026 1027 terminate = [terminate_str]
1027 1028 try:
1028 1029 while lines[-1:] != terminate:
1029 1030 new_line = raw_input(ps1)
1030 1031 while new_line.endswith('\\'):
1031 1032 new_line = new_line[:-1] + raw_input(ps2)
1032 1033 lines.append(new_line)
1033 1034
1034 1035 return lines[:-1] # don't return the termination command
1035 1036 except EOFError:
1036 1037 print
1037 1038 return lines
1038 1039
1039 1040 #----------------------------------------------------------------------------
1040 1041 def raw_input_ext(prompt='', ps2='... '):
1041 1042 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1042 1043
1043 1044 line = raw_input(prompt)
1044 1045 while line.endswith('\\'):
1045 1046 line = line[:-1] + raw_input(ps2)
1046 1047 return line
1047 1048
1048 1049 #----------------------------------------------------------------------------
1049 1050 def ask_yes_no(prompt,default=None):
1050 1051 """Asks a question and returns an integer 1/0 (y/n) answer.
1051 1052
1052 1053 If default is given (one of 'y','n'), it is used if the user input is
1053 1054 empty. Otherwise the question is repeated until an answer is given.
1054 1055 If EOF occurs 20 times consecutively, the default answer is assumed,
1055 1056 or if there is no default, an exception is raised to prevent infinite
1056 1057 loops.
1057 1058
1058 1059 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1059 1060
1060 1061 answers = {'y':True,'n':False,'yes':True,'no':False}
1061 1062 ans = None
1062 1063 eofs, max_eofs = 0, 20
1063 1064 while ans not in answers.keys():
1064 1065 try:
1065 1066 ans = raw_input(prompt+' ').lower()
1066 1067 if not ans: # response was an empty string
1067 1068 ans = default
1068 1069 eofs = 0
1069 1070 except (EOFError,KeyboardInterrupt):
1070 1071 eofs = eofs + 1
1071 1072 if eofs >= max_eofs:
1072 1073 if default in answers.keys():
1073 1074 ans = default
1074 1075 else:
1075 1076 raise
1076 1077
1077 1078 return answers[ans]
1078 1079
1079 1080 #----------------------------------------------------------------------------
1080 1081 def marquee(txt='',width=78,mark='*'):
1081 1082 """Return the input string centered in a 'marquee'."""
1082 1083 if not txt:
1083 1084 return (mark*width)[:width]
1084 1085 nmark = (width-len(txt)-2)/len(mark)/2
1085 1086 if nmark < 0: nmark =0
1086 1087 marks = mark*nmark
1087 1088 return '%s %s %s' % (marks,txt,marks)
1088 1089
1089 1090 #----------------------------------------------------------------------------
1090 1091 class EvalDict:
1091 1092 """
1092 1093 Emulate a dict which evaluates its contents in the caller's frame.
1093 1094
1094 1095 Usage:
1095 1096 >>>number = 19
1096 1097 >>>text = "python"
1097 1098 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1098 1099 """
1099 1100
1100 1101 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1101 1102 # modified (shorter) version of:
1102 1103 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1103 1104 # Skip Montanaro (skip@pobox.com).
1104 1105
1105 1106 def __getitem__(self, name):
1106 1107 frame = sys._getframe(1)
1107 1108 return eval(name, frame.f_globals, frame.f_locals)
1108 1109
1109 1110 EvalString = EvalDict # for backwards compatibility
1110 1111 #----------------------------------------------------------------------------
1111 1112 def qw(words,flat=0,sep=None,maxsplit=-1):
1112 1113 """Similar to Perl's qw() operator, but with some more options.
1113 1114
1114 1115 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1115 1116
1116 1117 words can also be a list itself, and with flat=1, the output will be
1117 1118 recursively flattened. Examples:
1118 1119
1119 1120 >>> qw('1 2')
1120 1121 ['1', '2']
1121 1122 >>> qw(['a b','1 2',['m n','p q']])
1122 1123 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1123 1124 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1124 1125 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1125 1126
1126 1127 if type(words) in StringTypes:
1127 1128 return [word.strip() for word in words.split(sep,maxsplit)
1128 1129 if word and not word.isspace() ]
1129 1130 if flat:
1130 1131 return flatten(map(qw,words,[1]*len(words)))
1131 1132 return map(qw,words)
1132 1133
1133 1134 #----------------------------------------------------------------------------
1134 1135 def qwflat(words,sep=None,maxsplit=-1):
1135 1136 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1136 1137 return qw(words,1,sep,maxsplit)
1137 1138
1138 1139 #----------------------------------------------------------------------------
1139 1140 def qw_lol(indata):
1140 1141 """qw_lol('a b') -> [['a','b']],
1141 1142 otherwise it's just a call to qw().
1142 1143
1143 1144 We need this to make sure the modules_some keys *always* end up as a
1144 1145 list of lists."""
1145 1146
1146 1147 if type(indata) in StringTypes:
1147 1148 return [qw(indata)]
1148 1149 else:
1149 1150 return qw(indata)
1150 1151
1151 1152 #-----------------------------------------------------------------------------
1152 1153 def list_strings(arg):
1153 1154 """Always return a list of strings, given a string or list of strings
1154 1155 as input."""
1155 1156
1156 1157 if type(arg) in StringTypes: return [arg]
1157 1158 else: return arg
1158 1159
1159 1160 #----------------------------------------------------------------------------
1160 1161 def grep(pat,list,case=1):
1161 1162 """Simple minded grep-like function.
1162 1163 grep(pat,list) returns occurrences of pat in list, None on failure.
1163 1164
1164 1165 It only does simple string matching, with no support for regexps. Use the
1165 1166 option case=0 for case-insensitive matching."""
1166 1167
1167 1168 # This is pretty crude. At least it should implement copying only references
1168 1169 # to the original data in case it's big. Now it copies the data for output.
1169 1170 out=[]
1170 1171 if case:
1171 1172 for term in list:
1172 1173 if term.find(pat)>-1: out.append(term)
1173 1174 else:
1174 1175 lpat=pat.lower()
1175 1176 for term in list:
1176 1177 if term.lower().find(lpat)>-1: out.append(term)
1177 1178
1178 1179 if len(out): return out
1179 1180 else: return None
1180 1181
1181 1182 #----------------------------------------------------------------------------
1182 1183 def dgrep(pat,*opts):
1183 1184 """Return grep() on dir()+dir(__builtins__).
1184 1185
1185 1186 A very common use of grep() when working interactively."""
1186 1187
1187 1188 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1188 1189
1189 1190 #----------------------------------------------------------------------------
1190 1191 def idgrep(pat):
1191 1192 """Case-insensitive dgrep()"""
1192 1193
1193 1194 return dgrep(pat,0)
1194 1195
1195 1196 #----------------------------------------------------------------------------
1196 1197 def igrep(pat,list):
1197 1198 """Synonym for case-insensitive grep."""
1198 1199
1199 1200 return grep(pat,list,case=0)
1200 1201
1201 1202 #----------------------------------------------------------------------------
1202 1203 def indent(str,nspaces=4,ntabs=0):
1203 1204 """Indent a string a given number of spaces or tabstops.
1204 1205
1205 1206 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1206 1207 """
1207 1208 if str is None:
1208 1209 return
1209 1210 ind = '\t'*ntabs+' '*nspaces
1210 1211 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1211 1212 if outstr.endswith(os.linesep+ind):
1212 1213 return outstr[:-len(ind)]
1213 1214 else:
1214 1215 return outstr
1215 1216
1216 1217 #-----------------------------------------------------------------------------
1217 1218 def native_line_ends(filename,backup=1):
1218 1219 """Convert (in-place) a file to line-ends native to the current OS.
1219 1220
1220 1221 If the optional backup argument is given as false, no backup of the
1221 1222 original file is left. """
1222 1223
1223 1224 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1224 1225
1225 1226 bak_filename = filename + backup_suffixes[os.name]
1226 1227
1227 1228 original = open(filename).read()
1228 1229 shutil.copy2(filename,bak_filename)
1229 1230 try:
1230 1231 new = open(filename,'wb')
1231 1232 new.write(os.linesep.join(original.splitlines()))
1232 1233 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1233 1234 new.close()
1234 1235 except:
1235 1236 os.rename(bak_filename,filename)
1236 1237 if not backup:
1237 1238 try:
1238 1239 os.remove(bak_filename)
1239 1240 except:
1240 1241 pass
1241 1242
1242 1243 #----------------------------------------------------------------------------
1243 1244 def get_pager_cmd(pager_cmd = None):
1244 1245 """Return a pager command.
1245 1246
1246 1247 Makes some attempts at finding an OS-correct one."""
1247 1248
1248 1249 if os.name == 'posix':
1249 1250 default_pager_cmd = 'less -r' # -r for color control sequences
1250 1251 elif os.name in ['nt','dos']:
1251 1252 default_pager_cmd = 'type'
1252 1253
1253 1254 if pager_cmd is None:
1254 1255 try:
1255 1256 pager_cmd = os.environ['PAGER']
1256 1257 except:
1257 1258 pager_cmd = default_pager_cmd
1258 1259 return pager_cmd
1259 1260
1260 1261 #-----------------------------------------------------------------------------
1261 1262 def get_pager_start(pager,start):
1262 1263 """Return the string for paging files with an offset.
1263 1264
1264 1265 This is the '+N' argument which less and more (under Unix) accept.
1265 1266 """
1266 1267
1267 1268 if pager in ['less','more']:
1268 1269 if start:
1269 1270 start_string = '+' + str(start)
1270 1271 else:
1271 1272 start_string = ''
1272 1273 else:
1273 1274 start_string = ''
1274 1275 return start_string
1275 1276
1276 1277 #----------------------------------------------------------------------------
1277 1278 if os.name == "nt":
1278 1279 import msvcrt
1279 1280 def page_more():
1280 1281 """ Smart pausing between pages
1281 1282
1282 1283 @return: True if need print more lines, False if quit
1283 1284 """
1284 1285 Term.cout.write('---Return to continue, q to quit--- ')
1285 1286 ans = msvcrt.getch()
1286 1287 if ans in ("q", "Q"):
1287 1288 result = False
1288 1289 else:
1289 1290 result = True
1290 1291 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1291 1292 return result
1292 1293 else:
1293 1294 def page_more():
1294 1295 ans = raw_input('---Return to continue, q to quit--- ')
1295 1296 if ans.lower().startswith('q'):
1296 1297 return False
1297 1298 else:
1298 1299 return True
1299 1300
1300 1301 esc_re = re.compile(r"(\x1b[^m]+m)")
1301 1302
1302 1303 def page_dumb(strng,start=0,screen_lines=25):
1303 1304 """Very dumb 'pager' in Python, for when nothing else works.
1304 1305
1305 1306 Only moves forward, same interface as page(), except for pager_cmd and
1306 1307 mode."""
1307 1308
1308 1309 out_ln = strng.splitlines()[start:]
1309 1310 screens = chop(out_ln,screen_lines-1)
1310 1311 if len(screens) == 1:
1311 1312 print >>Term.cout, os.linesep.join(screens[0])
1312 1313 else:
1313 1314 last_escape = ""
1314 1315 for scr in screens[0:-1]:
1315 1316 hunk = os.linesep.join(scr)
1316 1317 print >>Term.cout, last_escape + hunk
1317 1318 if not page_more():
1318 1319 return
1319 1320 esc_list = esc_re.findall(hunk)
1320 1321 if len(esc_list) > 0:
1321 1322 last_escape = esc_list[-1]
1322 1323 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1323 1324
1324 1325 #----------------------------------------------------------------------------
1325 1326 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1326 1327 """Print a string, piping through a pager after a certain length.
1327 1328
1328 1329 The screen_lines parameter specifies the number of *usable* lines of your
1329 1330 terminal screen (total lines minus lines you need to reserve to show other
1330 1331 information).
1331 1332
1332 1333 If you set screen_lines to a number <=0, page() will try to auto-determine
1333 1334 your screen size and will only use up to (screen_size+screen_lines) for
1334 1335 printing, paging after that. That is, if you want auto-detection but need
1335 1336 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1336 1337 auto-detection without any lines reserved simply use screen_lines = 0.
1337 1338
1338 1339 If a string won't fit in the allowed lines, it is sent through the
1339 1340 specified pager command. If none given, look for PAGER in the environment,
1340 1341 and ultimately default to less.
1341 1342
1342 1343 If no system pager works, the string is sent through a 'dumb pager'
1343 1344 written in python, very simplistic.
1344 1345 """
1345 1346
1346 1347 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1347 1348 TERM = os.environ.get('TERM','dumb')
1348 1349 if TERM in ['dumb','emacs'] and os.name != 'nt':
1349 1350 print strng
1350 1351 return
1351 1352 # chop off the topmost part of the string we don't want to see
1352 1353 str_lines = strng.split(os.linesep)[start:]
1353 1354 str_toprint = os.linesep.join(str_lines)
1354 1355 num_newlines = len(str_lines)
1355 1356 len_str = len(str_toprint)
1356 1357
1357 1358 # Dumb heuristics to guesstimate number of on-screen lines the string
1358 1359 # takes. Very basic, but good enough for docstrings in reasonable
1359 1360 # terminals. If someone later feels like refining it, it's not hard.
1360 1361 numlines = max(num_newlines,int(len_str/80)+1)
1361 1362
1362 1363 if os.name == "nt":
1363 1364 screen_lines_def = get_console_size(defaulty=25)[1]
1364 1365 else:
1365 1366 screen_lines_def = 25 # default value if we can't auto-determine
1366 1367
1367 1368 # auto-determine screen size
1368 1369 if screen_lines <= 0:
1369 1370 if TERM=='xterm':
1370 1371 try:
1371 1372 import curses
1372 1373 if hasattr(curses,'initscr'):
1373 1374 use_curses = 1
1374 1375 else:
1375 1376 use_curses = 0
1376 1377 except ImportError:
1377 1378 use_curses = 0
1378 1379 else:
1379 1380 # curses causes problems on many terminals other than xterm.
1380 1381 use_curses = 0
1381 1382 if use_curses:
1382 1383 scr = curses.initscr()
1383 1384 screen_lines_real,screen_cols = scr.getmaxyx()
1384 1385 curses.endwin()
1385 1386 screen_lines += screen_lines_real
1386 1387 #print '***Screen size:',screen_lines_real,'lines x',\
1387 1388 #screen_cols,'columns.' # dbg
1388 1389 else:
1389 1390 screen_lines += screen_lines_def
1390 1391
1391 1392 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1392 1393 if numlines <= screen_lines :
1393 1394 #print '*** normal print' # dbg
1394 1395 print >>Term.cout, str_toprint
1395 1396 else:
1396 1397 # Try to open pager and default to internal one if that fails.
1397 1398 # All failure modes are tagged as 'retval=1', to match the return
1398 1399 # value of a failed system command. If any intermediate attempt
1399 1400 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1400 1401 pager_cmd = get_pager_cmd(pager_cmd)
1401 1402 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1402 1403 if os.name == 'nt':
1403 1404 if pager_cmd.startswith('type'):
1404 1405 # The default WinXP 'type' command is failing on complex strings.
1405 1406 retval = 1
1406 1407 else:
1407 1408 tmpname = tempfile.mktemp('.txt')
1408 1409 tmpfile = file(tmpname,'wt')
1409 1410 tmpfile.write(strng)
1410 1411 tmpfile.close()
1411 1412 cmd = "%s < %s" % (pager_cmd,tmpname)
1412 1413 if os.system(cmd):
1413 1414 retval = 1
1414 1415 else:
1415 1416 retval = None
1416 1417 os.remove(tmpname)
1417 1418 else:
1418 1419 try:
1419 1420 retval = None
1420 1421 # if I use popen4, things hang. No idea why.
1421 1422 #pager,shell_out = os.popen4(pager_cmd)
1422 1423 pager = os.popen(pager_cmd,'w')
1423 1424 pager.write(strng)
1424 1425 pager.close()
1425 1426 retval = pager.close() # success returns None
1426 1427 except IOError,msg: # broken pipe when user quits
1427 1428 if msg.args == (32,'Broken pipe'):
1428 1429 retval = None
1429 1430 else:
1430 1431 retval = 1
1431 1432 except OSError:
1432 1433 # Other strange problems, sometimes seen in Win2k/cygwin
1433 1434 retval = 1
1434 1435 if retval is not None:
1435 1436 page_dumb(strng,screen_lines=screen_lines)
1436 1437
1437 1438 #----------------------------------------------------------------------------
1438 1439 def page_file(fname,start = 0, pager_cmd = None):
1439 1440 """Page a file, using an optional pager command and starting line.
1440 1441 """
1441 1442
1442 1443 pager_cmd = get_pager_cmd(pager_cmd)
1443 1444 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1444 1445
1445 1446 try:
1446 1447 if os.environ['TERM'] in ['emacs','dumb']:
1447 1448 raise EnvironmentError
1448 1449 xsys(pager_cmd + ' ' + fname)
1449 1450 except:
1450 1451 try:
1451 1452 if start > 0:
1452 1453 start -= 1
1453 1454 page(open(fname).read(),start)
1454 1455 except:
1455 1456 print 'Unable to show file',`fname`
1456 1457
1457 1458 #----------------------------------------------------------------------------
1458 1459 def snip_print(str,width = 75,print_full = 0,header = ''):
1459 1460 """Print a string snipping the midsection to fit in width.
1460 1461
1461 1462 print_full: mode control:
1462 1463 - 0: only snip long strings
1463 1464 - 1: send to page() directly.
1464 1465 - 2: snip long strings and ask for full length viewing with page()
1465 1466 Return 1 if snipping was necessary, 0 otherwise."""
1466 1467
1467 1468 if print_full == 1:
1468 1469 page(header+str)
1469 1470 return 0
1470 1471
1471 1472 print header,
1472 1473 if len(str) < width:
1473 1474 print str
1474 1475 snip = 0
1475 1476 else:
1476 1477 whalf = int((width -5)/2)
1477 1478 print str[:whalf] + ' <...> ' + str[-whalf:]
1478 1479 snip = 1
1479 1480 if snip and print_full == 2:
1480 1481 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1481 1482 page(str)
1482 1483 return snip
1483 1484
1484 1485 #****************************************************************************
1485 1486 # lists, dicts and structures
1486 1487
1487 1488 def belong(candidates,checklist):
1488 1489 """Check whether a list of items appear in a given list of options.
1489 1490
1490 1491 Returns a list of 1 and 0, one for each candidate given."""
1491 1492
1492 1493 return [x in checklist for x in candidates]
1493 1494
1494 1495 #----------------------------------------------------------------------------
1495 1496 def uniq_stable(elems):
1496 1497 """uniq_stable(elems) -> list
1497 1498
1498 1499 Return from an iterable, a list of all the unique elements in the input,
1499 1500 but maintaining the order in which they first appear.
1500 1501
1501 1502 A naive solution to this problem which just makes a dictionary with the
1502 1503 elements as keys fails to respect the stability condition, since
1503 1504 dictionaries are unsorted by nature.
1504 1505
1505 1506 Note: All elements in the input must be valid dictionary keys for this
1506 1507 routine to work, as it internally uses a dictionary for efficiency
1507 1508 reasons."""
1508 1509
1509 1510 unique = []
1510 1511 unique_dict = {}
1511 1512 for nn in elems:
1512 1513 if nn not in unique_dict:
1513 1514 unique.append(nn)
1514 1515 unique_dict[nn] = None
1515 1516 return unique
1516 1517
1517 1518 #----------------------------------------------------------------------------
1518 1519 class NLprinter:
1519 1520 """Print an arbitrarily nested list, indicating index numbers.
1520 1521
1521 1522 An instance of this class called nlprint is available and callable as a
1522 1523 function.
1523 1524
1524 1525 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1525 1526 and using 'sep' to separate the index from the value. """
1526 1527
1527 1528 def __init__(self):
1528 1529 self.depth = 0
1529 1530
1530 1531 def __call__(self,lst,pos='',**kw):
1531 1532 """Prints the nested list numbering levels."""
1532 1533 kw.setdefault('indent',' ')
1533 1534 kw.setdefault('sep',': ')
1534 1535 kw.setdefault('start',0)
1535 1536 kw.setdefault('stop',len(lst))
1536 1537 # we need to remove start and stop from kw so they don't propagate
1537 1538 # into a recursive call for a nested list.
1538 1539 start = kw['start']; del kw['start']
1539 1540 stop = kw['stop']; del kw['stop']
1540 1541 if self.depth == 0 and 'header' in kw.keys():
1541 1542 print kw['header']
1542 1543
1543 1544 for idx in range(start,stop):
1544 1545 elem = lst[idx]
1545 1546 if type(elem)==type([]):
1546 1547 self.depth += 1
1547 1548 self.__call__(elem,itpl('$pos$idx,'),**kw)
1548 1549 self.depth -= 1
1549 1550 else:
1550 1551 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1551 1552
1552 1553 nlprint = NLprinter()
1553 1554 #----------------------------------------------------------------------------
1554 1555 def all_belong(candidates,checklist):
1555 1556 """Check whether a list of items ALL appear in a given list of options.
1556 1557
1557 1558 Returns a single 1 or 0 value."""
1558 1559
1559 1560 return 1-(0 in [x in checklist for x in candidates])
1560 1561
1561 1562 #----------------------------------------------------------------------------
1562 1563 def sort_compare(lst1,lst2,inplace = 1):
1563 1564 """Sort and compare two lists.
1564 1565
1565 1566 By default it does it in place, thus modifying the lists. Use inplace = 0
1566 1567 to avoid that (at the cost of temporary copy creation)."""
1567 1568 if not inplace:
1568 1569 lst1 = lst1[:]
1569 1570 lst2 = lst2[:]
1570 1571 lst1.sort(); lst2.sort()
1571 1572 return lst1 == lst2
1572 1573
1573 1574 #----------------------------------------------------------------------------
1574 1575 def mkdict(**kwargs):
1575 1576 """Return a dict from a keyword list.
1576 1577
1577 1578 It's just syntactic sugar for making ditcionary creation more convenient:
1578 1579 # the standard way
1579 1580 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1580 1581 # a cleaner way
1581 1582 >>>data = dict(red=1, green=2, blue=3)
1582 1583
1583 1584 If you need more than this, look at the Struct() class."""
1584 1585
1585 1586 return kwargs
1586 1587
1587 1588 #----------------------------------------------------------------------------
1588 1589 def list2dict(lst):
1589 1590 """Takes a list of (key,value) pairs and turns it into a dict."""
1590 1591
1591 1592 dic = {}
1592 1593 for k,v in lst: dic[k] = v
1593 1594 return dic
1594 1595
1595 1596 #----------------------------------------------------------------------------
1596 1597 def list2dict2(lst,default=''):
1597 1598 """Takes a list and turns it into a dict.
1598 1599 Much slower than list2dict, but more versatile. This version can take
1599 1600 lists with sublists of arbitrary length (including sclars)."""
1600 1601
1601 1602 dic = {}
1602 1603 for elem in lst:
1603 1604 if type(elem) in (types.ListType,types.TupleType):
1604 1605 size = len(elem)
1605 1606 if size == 0:
1606 1607 pass
1607 1608 elif size == 1:
1608 1609 dic[elem] = default
1609 1610 else:
1610 1611 k,v = elem[0], elem[1:]
1611 1612 if len(v) == 1: v = v[0]
1612 1613 dic[k] = v
1613 1614 else:
1614 1615 dic[elem] = default
1615 1616 return dic
1616 1617
1617 1618 #----------------------------------------------------------------------------
1618 1619 def flatten(seq):
1619 1620 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1620 1621
1621 1622 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1622 1623
1623 1624 # if the x=0 isn't made, a *global* variable x is left over after calling
1624 1625 # this function, with the value of the last element in the return
1625 1626 # list. This does seem like a bug big time to me.
1626 1627
1627 1628 # the problem is fixed with the x=0, which seems to force the creation of
1628 1629 # a local name
1629 1630
1630 1631 x = 0
1631 1632 return [x for subseq in seq for x in subseq]
1632 1633
1633 1634 #----------------------------------------------------------------------------
1634 1635 def get_slice(seq,start=0,stop=None,step=1):
1635 1636 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1636 1637 if stop == None:
1637 1638 stop = len(seq)
1638 1639 item = lambda i: seq[i]
1639 1640 return map(item,xrange(start,stop,step))
1640 1641
1641 1642 #----------------------------------------------------------------------------
1642 1643 def chop(seq,size):
1643 1644 """Chop a sequence into chunks of the given size."""
1644 1645 chunk = lambda i: seq[i:i+size]
1645 1646 return map(chunk,xrange(0,len(seq),size))
1646 1647
1647 1648 #----------------------------------------------------------------------------
1648 1649 def with(object, **args):
1649 1650 """Set multiple attributes for an object, similar to Pascal's with.
1650 1651
1651 1652 Example:
1652 1653 with(jim,
1653 1654 born = 1960,
1654 1655 haircolour = 'Brown',
1655 1656 eyecolour = 'Green')
1656 1657
1657 1658 Credit: Greg Ewing, in
1658 1659 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1659 1660
1660 1661 object.__dict__.update(args)
1661 1662
1662 1663 #----------------------------------------------------------------------------
1663 1664 def setattr_list(obj,alist,nspace = None):
1664 1665 """Set a list of attributes for an object taken from a namespace.
1665 1666
1666 1667 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1667 1668 alist with their values taken from nspace, which must be a dict (something
1668 1669 like locals() will often do) If nspace isn't given, locals() of the
1669 1670 *caller* is used, so in most cases you can omit it.
1670 1671
1671 1672 Note that alist can be given as a string, which will be automatically
1672 1673 split into a list on whitespace. If given as a list, it must be a list of
1673 1674 *strings* (the variable names themselves), not of variables."""
1674 1675
1675 1676 # this grabs the local variables from the *previous* call frame -- that is
1676 1677 # the locals from the function that called setattr_list().
1677 1678 # - snipped from weave.inline()
1678 1679 if nspace is None:
1679 1680 call_frame = sys._getframe().f_back
1680 1681 nspace = call_frame.f_locals
1681 1682
1682 1683 if type(alist) in StringTypes:
1683 1684 alist = alist.split()
1684 1685 for attr in alist:
1685 1686 val = eval(attr,nspace)
1686 1687 setattr(obj,attr,val)
1687 1688
1688 1689 #----------------------------------------------------------------------------
1689 1690 def getattr_list(obj,alist,*args):
1690 1691 """getattr_list(obj,alist[, default]) -> attribute list.
1691 1692
1692 1693 Get a list of named attributes for an object. When a default argument is
1693 1694 given, it is returned when the attribute doesn't exist; without it, an
1694 1695 exception is raised in that case.
1695 1696
1696 1697 Note that alist can be given as a string, which will be automatically
1697 1698 split into a list on whitespace. If given as a list, it must be a list of
1698 1699 *strings* (the variable names themselves), not of variables."""
1699 1700
1700 1701 if type(alist) in StringTypes:
1701 1702 alist = alist.split()
1702 1703 if args:
1703 1704 if len(args)==1:
1704 1705 default = args[0]
1705 1706 return map(lambda attr: getattr(obj,attr,default),alist)
1706 1707 else:
1707 1708 raise ValueError,'getattr_list() takes only one optional argument'
1708 1709 else:
1709 1710 return map(lambda attr: getattr(obj,attr),alist)
1710 1711
1711 1712 #----------------------------------------------------------------------------
1712 1713 def map_method(method,object_list,*argseq,**kw):
1713 1714 """map_method(method,object_list,*args,**kw) -> list
1714 1715
1715 1716 Return a list of the results of applying the methods to the items of the
1716 1717 argument sequence(s). If more than one sequence is given, the method is
1717 1718 called with an argument list consisting of the corresponding item of each
1718 1719 sequence. All sequences must be of the same length.
1719 1720
1720 1721 Keyword arguments are passed verbatim to all objects called.
1721 1722
1722 1723 This is Python code, so it's not nearly as fast as the builtin map()."""
1723 1724
1724 1725 out_list = []
1725 1726 idx = 0
1726 1727 for object in object_list:
1727 1728 try:
1728 1729 handler = getattr(object, method)
1729 1730 except AttributeError:
1730 1731 out_list.append(None)
1731 1732 else:
1732 1733 if argseq:
1733 1734 args = map(lambda lst:lst[idx],argseq)
1734 1735 #print 'ob',object,'hand',handler,'ar',args # dbg
1735 1736 out_list.append(handler(args,**kw))
1736 1737 else:
1737 1738 out_list.append(handler(**kw))
1738 1739 idx += 1
1739 1740 return out_list
1740 1741
1741 1742 #----------------------------------------------------------------------------
1742 1743 def import_fail_info(mod_name,fns=None):
1743 1744 """Inform load failure for a module."""
1744 1745
1745 1746 if fns == None:
1746 1747 warn("Loading of %s failed.\n" % (mod_name,))
1747 1748 else:
1748 1749 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1749 1750
1750 1751 #----------------------------------------------------------------------------
1751 1752 # Proposed popitem() extension, written as a method
1752 1753
1753 1754 class NotGiven: pass
1754 1755
1755 1756 def popkey(dct,key,default=NotGiven):
1756 1757 """Return dct[key] and delete dct[key].
1757 1758
1758 1759 If default is given, return it if dct[key] doesn't exist, otherwise raise
1759 1760 KeyError. """
1760 1761
1761 1762 try:
1762 1763 val = dct[key]
1763 1764 except KeyError:
1764 1765 if default is NotGiven:
1765 1766 raise
1766 1767 else:
1767 1768 return default
1768 1769 else:
1769 1770 del dct[key]
1770 1771 return val
1771 1772 #*************************** end of file <genutils.py> **********************
1772 1773
@@ -1,174 +1,174 b''
1 1 ''' IPython customization API
2 2
3 3 Your one-stop module for configuring & extending ipython
4 4
5 5 The API will probably break when ipython 1.0 is released, but so
6 6 will the other configuration method (rc files).
7 7
8 8 All names prefixed by underscores are for internal use, not part
9 9 of the public api.
10 10
11 11 Below is an example that you can just put to a module and import from ipython.
12 12
13 13 A good practice is to install the config script below as e.g.
14 14
15 15 ~/.ipython/my_private_conf.py
16 16
17 17 And do
18 18
19 19 import_mod my_private_conf
20 20
21 21 in ~/.ipython/ipythonrc
22 22
23 23 That way the module is imported at startup and you can have all your
24 24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 25 stuff) in there.
26 26
27 27 -----------------------------------------------
28 28 import IPython.ipapi as ip
29 29
30 30 def ankka_f(self, arg):
31 31 print "Ankka",self,"says uppercase:",arg.upper()
32 32
33 33 ip.expose_magic("ankka",ankka_f)
34 34
35 35 ip.magic('alias sayhi echo "Testing, hi ok"')
36 36 ip.magic('alias helloworld echo "Hello world"')
37 37 ip.system('pwd')
38 38
39 39 ip.ex('import re')
40 40 ip.ex("""
41 41 def funcci(a,b):
42 42 print a+b
43 43 print funcci(3,4)
44 44 """)
45 45 ip.ex("funcci(348,9)")
46 46
47 47 def jed_editor(self,filename, linenum=None):
48 48 print "Calling my own editor, jed ... via hook!"
49 49 import os
50 50 if linenum is None: linenum = 0
51 51 os.system('jed +%d %s' % (linenum, filename))
52 52 print "exiting jed"
53 53
54 54 ip.set_hook('editor',jed_editor)
55 55
56 56 o = ip.options()
57 57 o.autocall = 2 # FULL autocall mode
58 58
59 59 print "done!"
60 60
61 61 '''
62 62
63 63
64 64 class TryNext(Exception):
65 65 """ Try next hook exception.
66 66
67 67 Raise this in your hook function to indicate that the next
68 68 hook handler should be used to handle the operation.
69 69 """
70 70
71 71
72 72
73 73 __IP = None
74 74
75 75 def _init_with_shell(ip):
76 76 global magic
77 77 magic = ip.ipmagic
78 78 global system
79 79 system = ip.ipsystem
80 80 global set_hook
81 81 set_hook = ip.set_hook
82 82
83 83 global __IP
84 84 __IP = ip
85 85
86 86 def options():
87 87 """ All configurable variables """
88 88 return __IP.rc
89 89
90 90 def user_ns():
91 91 return __IP.user_ns
92 92
93 93 def expose_magic(magicname, func):
94 94 ''' Expose own function as magic function for ipython
95 95
96 96 def foo_impl(self,parameter_s=''):
97 97 """My very own magic!. (Use docstrings, IPython reads them)."""
98 98 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
99 99 print 'The self object is:',self
100 100
101 101 ipapi.expose_magic("foo",foo_impl)
102 102 '''
103 103
104 104 from IPython import Magic
105 105 import new
106 106 im = new.instancemethod(func,__IP, __IP.__class__)
107 107 setattr(__IP, "magic_" + magicname, im)
108 108
109 109 class asmagic:
110 110 """ Decorator for exposing magics in a friendly 2.4 decorator form
111 111
112 112 @ip.asmagic("foo")
113 113 def f(self,arg):
114 114 pring "arg given:",arg
115 115
116 116 After this, %foo is a magic function.
117 117 """
118 118
119 119 def __init__(self,magicname):
120 120 self.name = magicname
121 121
122 122 def __call__(self,f):
123 123 expose_magic(self.name, f)
124 124 return f
125 125
126 126 class ashook:
127 127 """ Decorator for exposing magics in a friendly 2.4 decorator form
128 128
129 129 @ip.ashook("editor")
130 130 def jed_editor(self,filename, linenum=None):
131 131 import os
132 132 if linenum is None: linenum = 0
133 133 os.system('jed +%d %s' % (linenum, filename))
134 134
135 135 """
136 136
137 137 def __init__(self,name,priority=50):
138 138 self.name = name
139 139 self.prio = priority
140 140
141 141 def __call__(self,f):
142 142 set_hook(self.name, f, self.prio)
143 143 return f
144 144
145 145
146 146 def ex(cmd):
147 147 """ Execute a normal python statement in user namespace """
148 148 exec cmd in user_ns()
149 149
150 150 def ev(expr):
151 151 """ Evaluate python expression expr in user namespace
152 152
153 153 Returns the result """
154 154 return eval(expr,user_ns())
155 155
156 156 def launch_new_instance():
157 """ Creata and start a new ipython instance.
157 """ Create and start a new ipython instance.
158 158
159 159 This can be called even without having an already initialized
160 160 ipython session running.
161 161
162 162 """
163 163 import IPython
164 164
165 165 IPython.Shell.start().mainloop()
166 166
167 167 def is_ipython_session():
168 168 """ Return a true value if running inside IPython.
169 169
170 170 """
171 171
172 172 # Yes, this is the shell object or None - however, it's an implementation
173 173 # detail and should not be relied on, only truth value matters.
174 174 return __IP
@@ -1,2229 +1,2234 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.3 or newer.
6 6
7 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 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import tempfile
59 59 import traceback
60 60 import types
61 61
62 62 from pprint import pprint, pformat
63 63
64 64 # IPython's own modules
65 65 import IPython
66 66 from IPython import OInspect,PyColorize,ultraTB
67 67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 68 from IPython.FakeModule import FakeModule
69 69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 70 from IPython.Logger import Logger
71 71 from IPython.Magic import Magic
72 72 from IPython.Prompts import CachedOutput
73 73 from IPython.ipstruct import Struct
74 74 from IPython.background_jobs import BackgroundJobManager
75 75 from IPython.usage import cmd_line_usage,interactive_usage
76 76 from IPython.genutils import *
77 77 import IPython.ipapi
78 78
79 79 # Globals
80 80
81 81 # store the builtin raw_input globally, and use this always, in case user code
82 82 # overwrites it (like wx.py.PyShell does)
83 83 raw_input_original = raw_input
84 84
85 85 # compiled regexps for autoindent management
86 86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 87
88 88
89 89 #****************************************************************************
90 90 # Some utility function definitions
91 91
92 92 ini_spaces_re = re.compile(r'^(\s+)')
93 93
94 94 def num_ini_spaces(strng):
95 95 """Return the number of initial spaces in a string"""
96 96
97 97 ini_spaces = ini_spaces_re.match(strng)
98 98 if ini_spaces:
99 99 return ini_spaces.end()
100 100 else:
101 101 return 0
102 102
103 103 def softspace(file, newvalue):
104 104 """Copied from code.py, to remove the dependency"""
105 105
106 106 oldvalue = 0
107 107 try:
108 108 oldvalue = file.softspace
109 109 except AttributeError:
110 110 pass
111 111 try:
112 112 file.softspace = newvalue
113 113 except (AttributeError, TypeError):
114 114 # "attribute-less object" or "read-only attributes"
115 115 pass
116 116 return oldvalue
117 117
118 118
119 119 #****************************************************************************
120 120 # Local use exceptions
121 121 class SpaceInInput(exceptions.Exception): pass
122 122
123 123
124 124 #****************************************************************************
125 125 # Local use classes
126 126 class Bunch: pass
127 127
128 128 class Undefined: pass
129 129
130 130 class InputList(list):
131 131 """Class to store user input.
132 132
133 133 It's basically a list, but slices return a string instead of a list, thus
134 134 allowing things like (assuming 'In' is an instance):
135 135
136 136 exec In[4:7]
137 137
138 138 or
139 139
140 140 exec In[5:9] + In[14] + In[21:25]"""
141 141
142 142 def __getslice__(self,i,j):
143 143 return ''.join(list.__getslice__(self,i,j))
144 144
145 145 class SyntaxTB(ultraTB.ListTB):
146 146 """Extension which holds some state: the last exception value"""
147 147
148 148 def __init__(self,color_scheme = 'NoColor'):
149 149 ultraTB.ListTB.__init__(self,color_scheme)
150 150 self.last_syntax_error = None
151 151
152 152 def __call__(self, etype, value, elist):
153 153 self.last_syntax_error = value
154 154 ultraTB.ListTB.__call__(self,etype,value,elist)
155 155
156 156 def clear_err_state(self):
157 157 """Return the current error state and clear it"""
158 158 e = self.last_syntax_error
159 159 self.last_syntax_error = None
160 160 return e
161 161
162 162 #****************************************************************************
163 163 # Main IPython class
164 164
165 165 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
166 166 # until a full rewrite is made. I've cleaned all cross-class uses of
167 167 # attributes and methods, but too much user code out there relies on the
168 168 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
169 169 #
170 170 # But at least now, all the pieces have been separated and we could, in
171 171 # principle, stop using the mixin. This will ease the transition to the
172 172 # chainsaw branch.
173 173
174 174 # For reference, the following is the list of 'self.foo' uses in the Magic
175 175 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
176 176 # class, to prevent clashes.
177 177
178 178 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
179 179 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
180 180 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
181 181 # 'self.value']
182 182
183 183 class InteractiveShell(object,Magic):
184 184 """An enhanced console for Python."""
185 185
186 186 # class attribute to indicate whether the class supports threads or not.
187 187 # Subclasses with thread support should override this as needed.
188 188 isthreaded = False
189 189
190 190 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
191 191 user_ns = None,user_global_ns=None,banner2='',
192 192 custom_exceptions=((),None),embedded=False):
193 193
194 194 # log system
195 195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
196 196
197 197 # introduce ourselves to IPython.ipapi which is uncallable
198 198 # before it knows an InteractiveShell object.
199 199 IPython.ipapi._init_with_shell(self)
200 200
201 201 # some minimal strict typechecks. For some core data structures, I
202 202 # want actual basic python types, not just anything that looks like
203 203 # one. This is especially true for namespaces.
204 204 for ns in (user_ns,user_global_ns):
205 205 if ns is not None and type(ns) != types.DictType:
206 206 raise TypeError,'namespace must be a dictionary'
207 207
208 208 # Job manager (for jobs run as background threads)
209 209 self.jobs = BackgroundJobManager()
210 210
211 211 # track which builtins we add, so we can clean up later
212 212 self.builtins_added = {}
213 213 # This method will add the necessary builtins for operation, but
214 214 # tracking what it did via the builtins_added dict.
215 215 self.add_builtins()
216 216
217 217 # Do the intuitively correct thing for quit/exit: we remove the
218 218 # builtins if they exist, and our own magics will deal with this
219 219 try:
220 220 del __builtin__.exit, __builtin__.quit
221 221 except AttributeError:
222 222 pass
223 223
224 224 # Store the actual shell's name
225 225 self.name = name
226 226
227 227 # We need to know whether the instance is meant for embedding, since
228 228 # global/local namespaces need to be handled differently in that case
229 229 self.embedded = embedded
230 230
231 231 # command compiler
232 232 self.compile = codeop.CommandCompiler()
233 233
234 234 # User input buffer
235 235 self.buffer = []
236 236
237 237 # Default name given in compilation of code
238 238 self.filename = '<ipython console>'
239 239
240 240 # Make an empty namespace, which extension writers can rely on both
241 241 # existing and NEVER being used by ipython itself. This gives them a
242 242 # convenient location for storing additional information and state
243 243 # their extensions may require, without fear of collisions with other
244 244 # ipython names that may develop later.
245 245 self.meta = Bunch()
246 246
247 247 # Create the namespace where the user will operate. user_ns is
248 248 # normally the only one used, and it is passed to the exec calls as
249 249 # the locals argument. But we do carry a user_global_ns namespace
250 250 # given as the exec 'globals' argument, This is useful in embedding
251 251 # situations where the ipython shell opens in a context where the
252 252 # distinction between locals and globals is meaningful.
253 253
254 254 # FIXME. For some strange reason, __builtins__ is showing up at user
255 255 # level as a dict instead of a module. This is a manual fix, but I
256 256 # should really track down where the problem is coming from. Alex
257 257 # Schmolck reported this problem first.
258 258
259 259 # A useful post by Alex Martelli on this topic:
260 260 # Re: inconsistent value from __builtins__
261 261 # Von: Alex Martelli <aleaxit@yahoo.com>
262 262 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
263 263 # Gruppen: comp.lang.python
264 264
265 265 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
266 266 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
267 267 # > <type 'dict'>
268 268 # > >>> print type(__builtins__)
269 269 # > <type 'module'>
270 270 # > Is this difference in return value intentional?
271 271
272 272 # Well, it's documented that '__builtins__' can be either a dictionary
273 273 # or a module, and it's been that way for a long time. Whether it's
274 274 # intentional (or sensible), I don't know. In any case, the idea is
275 275 # that if you need to access the built-in namespace directly, you
276 276 # should start with "import __builtin__" (note, no 's') which will
277 277 # definitely give you a module. Yeah, it's somewhat confusing:-(.
278 278
279 279 if user_ns is None:
280 280 # Set __name__ to __main__ to better match the behavior of the
281 281 # normal interpreter.
282 282 user_ns = {'__name__' :'__main__',
283 283 '__builtins__' : __builtin__,
284 284 }
285 285
286 286 if user_global_ns is None:
287 287 user_global_ns = {}
288 288
289 289 # Assign namespaces
290 290 # This is the namespace where all normal user variables live
291 291 self.user_ns = user_ns
292 292 # Embedded instances require a separate namespace for globals.
293 293 # Normally this one is unused by non-embedded instances.
294 294 self.user_global_ns = user_global_ns
295 295 # A namespace to keep track of internal data structures to prevent
296 296 # them from cluttering user-visible stuff. Will be updated later
297 297 self.internal_ns = {}
298 298
299 299 # Namespace of system aliases. Each entry in the alias
300 300 # table must be a 2-tuple of the form (N,name), where N is the number
301 301 # of positional arguments of the alias.
302 302 self.alias_table = {}
303 303
304 304 # A table holding all the namespaces IPython deals with, so that
305 305 # introspection facilities can search easily.
306 306 self.ns_table = {'user':user_ns,
307 307 'user_global':user_global_ns,
308 308 'alias':self.alias_table,
309 309 'internal':self.internal_ns,
310 310 'builtin':__builtin__.__dict__
311 311 }
312 312
313 313 # The user namespace MUST have a pointer to the shell itself.
314 314 self.user_ns[name] = self
315 315
316 316 # We need to insert into sys.modules something that looks like a
317 317 # module but which accesses the IPython namespace, for shelve and
318 318 # pickle to work interactively. Normally they rely on getting
319 319 # everything out of __main__, but for embedding purposes each IPython
320 320 # instance has its own private namespace, so we can't go shoving
321 321 # everything into __main__.
322 322
323 323 # note, however, that we should only do this for non-embedded
324 324 # ipythons, which really mimic the __main__.__dict__ with their own
325 325 # namespace. Embedded instances, on the other hand, should not do
326 326 # this because they need to manage the user local/global namespaces
327 327 # only, but they live within a 'normal' __main__ (meaning, they
328 328 # shouldn't overtake the execution environment of the script they're
329 329 # embedded in).
330 330
331 331 if not embedded:
332 332 try:
333 333 main_name = self.user_ns['__name__']
334 334 except KeyError:
335 335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 336 else:
337 337 #print "pickle hack in place" # dbg
338 338 #print 'main_name:',main_name # dbg
339 339 sys.modules[main_name] = FakeModule(self.user_ns)
340 340
341 341 # List of input with multi-line handling.
342 342 # Fill its zero entry, user counter starts at 1
343 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 349 # list of visited directories
346 350 try:
347 351 self.dir_hist = [os.getcwd()]
348 352 except IOError, e:
349 353 self.dir_hist = []
350 354
351 355 # dict of output history
352 356 self.output_hist = {}
353 357
354 358 # dict of things NOT to alias (keywords, builtins and some magics)
355 359 no_alias = {}
356 360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
357 361 for key in keyword.kwlist + no_alias_magics:
358 362 no_alias[key] = 1
359 363 no_alias.update(__builtin__.__dict__)
360 364 self.no_alias = no_alias
361 365
362 366 # make global variables for user access to these
363 367 self.user_ns['_ih'] = self.input_hist
364 368 self.user_ns['_oh'] = self.output_hist
365 369 self.user_ns['_dh'] = self.dir_hist
366 370
367 371 # user aliases to input and output histories
368 372 self.user_ns['In'] = self.input_hist
369 373 self.user_ns['Out'] = self.output_hist
370 374
371 375 # Object variable to store code object waiting execution. This is
372 376 # used mainly by the multithreaded shells, but it can come in handy in
373 377 # other situations. No need to use a Queue here, since it's a single
374 378 # item which gets cleared once run.
375 379 self.code_to_run = None
376 380
377 381 # escapes for automatic behavior on the command line
378 382 self.ESC_SHELL = '!'
379 383 self.ESC_HELP = '?'
380 384 self.ESC_MAGIC = '%'
381 385 self.ESC_QUOTE = ','
382 386 self.ESC_QUOTE2 = ';'
383 387 self.ESC_PAREN = '/'
384 388
385 389 # And their associated handlers
386 390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
387 391 self.ESC_QUOTE : self.handle_auto,
388 392 self.ESC_QUOTE2 : self.handle_auto,
389 393 self.ESC_MAGIC : self.handle_magic,
390 394 self.ESC_HELP : self.handle_help,
391 395 self.ESC_SHELL : self.handle_shell_escape,
392 396 }
393 397
394 398 # class initializations
395 399 Magic.__init__(self,self)
396 400
397 401 # Python source parser/formatter for syntax highlighting
398 402 pyformat = PyColorize.Parser().format
399 403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
400 404
401 405 # hooks holds pointers used for user-side customizations
402 406 self.hooks = Struct()
403 407
404 408 # Set all default hooks, defined in the IPython.hooks module.
405 409 hooks = IPython.hooks
406 410 for hook_name in hooks.__all__:
407 411 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
408 412 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
409 413
410 414 # Flag to mark unconditional exit
411 415 self.exit_now = False
412 416
413 417 self.usage_min = """\
414 418 An enhanced console for Python.
415 419 Some of its features are:
416 420 - Readline support if the readline library is present.
417 421 - Tab completion in the local namespace.
418 422 - Logging of input, see command-line options.
419 423 - System shell escape via ! , eg !ls.
420 424 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
421 425 - Keeps track of locally defined variables via %who, %whos.
422 426 - Show object information with a ? eg ?x or x? (use ?? for more info).
423 427 """
424 428 if usage: self.usage = usage
425 429 else: self.usage = self.usage_min
426 430
427 431 # Storage
428 432 self.rc = rc # This will hold all configuration information
429 433 self.pager = 'less'
430 434 # temporary files used for various purposes. Deleted at exit.
431 435 self.tempfiles = []
432 436
433 437 # Keep track of readline usage (later set by init_readline)
434 438 self.has_readline = False
435 439
436 440 # template for logfile headers. It gets resolved at runtime by the
437 441 # logstart method.
438 442 self.loghead_tpl = \
439 443 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
440 444 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
441 445 #log# opts = %s
442 446 #log# args = %s
443 447 #log# It is safe to make manual edits below here.
444 448 #log#-----------------------------------------------------------------------
445 449 """
446 450 # for pushd/popd management
447 451 try:
448 452 self.home_dir = get_home_dir()
449 453 except HomeDirError,msg:
450 454 fatal(msg)
451 455
452 456 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
453 457
454 458 # Functions to call the underlying shell.
455 459
456 460 # utility to expand user variables via Itpl
457 461 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
458 462 self.user_ns))
459 463 # The first is similar to os.system, but it doesn't return a value,
460 464 # and it allows interpolation of variables in the user's namespace.
461 465 self.system = lambda cmd: shell(self.var_expand(cmd),
462 466 header='IPython system call: ',
463 467 verbose=self.rc.system_verbose)
464 468 # These are for getoutput and getoutputerror:
465 469 self.getoutput = lambda cmd: \
466 470 getoutput(self.var_expand(cmd),
467 471 header='IPython system call: ',
468 472 verbose=self.rc.system_verbose)
469 473 self.getoutputerror = lambda cmd: \
470 474 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
471 475 self.user_ns)),
472 476 header='IPython system call: ',
473 477 verbose=self.rc.system_verbose)
474 478
475 479 # RegExp for splitting line contents into pre-char//first
476 480 # word-method//rest. For clarity, each group in on one line.
477 481
478 482 # WARNING: update the regexp if the above escapes are changed, as they
479 483 # are hardwired in.
480 484
481 485 # Don't get carried away with trying to make the autocalling catch too
482 486 # much: it's better to be conservative rather than to trigger hidden
483 487 # evals() somewhere and end up causing side effects.
484 488
485 489 self.line_split = re.compile(r'^([\s*,;/])'
486 490 r'([\?\w\.]+\w*\s*)'
487 491 r'(\(?.*$)')
488 492
489 493 # Original re, keep around for a while in case changes break something
490 494 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
491 495 # r'(\s*[\?\w\.]+\w*\s*)'
492 496 # r'(\(?.*$)')
493 497
494 498 # RegExp to identify potential function names
495 499 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
496 500
497 501 # RegExp to exclude strings with this start from autocalling. In
498 502 # particular, all binary operators should be excluded, so that if foo
499 503 # is callable, foo OP bar doesn't become foo(OP bar), which is
500 504 # invalid. The characters '!=()' don't need to be checked for, as the
501 505 # _prefilter routine explicitely does so, to catch direct calls and
502 506 # rebindings of existing names.
503 507
504 508 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
505 509 # it affects the rest of the group in square brackets.
506 510 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
507 511 '|^is |^not |^in |^and |^or ')
508 512
509 513 # try to catch also methods for stuff in lists/tuples/dicts: off
510 514 # (experimental). For this to work, the line_split regexp would need
511 515 # to be modified so it wouldn't break things at '['. That line is
512 516 # nasty enough that I shouldn't change it until I can test it _well_.
513 517 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
514 518
515 519 # keep track of where we started running (mainly for crash post-mortem)
516 520 self.starting_dir = os.getcwd()
517 521
518 522 # Various switches which can be set
519 523 self.CACHELENGTH = 5000 # this is cheap, it's just text
520 524 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
521 525 self.banner2 = banner2
522 526
523 527 # TraceBack handlers:
524 528
525 529 # Syntax error handler.
526 530 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
527 531
528 532 # The interactive one is initialized with an offset, meaning we always
529 533 # want to remove the topmost item in the traceback, which is our own
530 534 # internal code. Valid modes: ['Plain','Context','Verbose']
531 535 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
532 536 color_scheme='NoColor',
533 537 tb_offset = 1)
534 538
535 539 # IPython itself shouldn't crash. This will produce a detailed
536 540 # post-mortem if it does. But we only install the crash handler for
537 541 # non-threaded shells, the threaded ones use a normal verbose reporter
538 542 # and lose the crash handler. This is because exceptions in the main
539 543 # thread (such as in GUI code) propagate directly to sys.excepthook,
540 544 # and there's no point in printing crash dumps for every user exception.
541 545 if self.isthreaded:
542 546 sys.excepthook = ultraTB.FormattedTB()
543 547 else:
544 548 from IPython import CrashHandler
545 549 sys.excepthook = CrashHandler.CrashHandler(self)
546 550
547 551 # The instance will store a pointer to this, so that runtime code
548 552 # (such as magics) can access it. This is because during the
549 553 # read-eval loop, it gets temporarily overwritten (to deal with GUI
550 554 # frameworks).
551 555 self.sys_excepthook = sys.excepthook
552 556
553 557 # and add any custom exception handlers the user may have specified
554 558 self.set_custom_exc(*custom_exceptions)
555 559
556 560 # Object inspector
557 561 self.inspector = OInspect.Inspector(OInspect.InspectColors,
558 562 PyColorize.ANSICodeColors,
559 563 'NoColor')
560 564 # indentation management
561 565 self.autoindent = False
562 566 self.indent_current_nsp = 0
563 567
564 568 # Make some aliases automatically
565 569 # Prepare list of shell aliases to auto-define
566 570 if os.name == 'posix':
567 571 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
568 572 'mv mv -i','rm rm -i','cp cp -i',
569 573 'cat cat','less less','clear clear',
570 574 # a better ls
571 575 'ls ls -F',
572 576 # long ls
573 577 'll ls -lF',
574 578 # color ls
575 579 'lc ls -F -o --color',
576 580 # ls normal files only
577 581 'lf ls -F -o --color %l | grep ^-',
578 582 # ls symbolic links
579 583 'lk ls -F -o --color %l | grep ^l',
580 584 # directories or links to directories,
581 585 'ldir ls -F -o --color %l | grep /$',
582 586 # things which are executable
583 587 'lx ls -F -o --color %l | grep ^-..x',
584 588 )
585 589 elif os.name in ['nt','dos']:
586 590 auto_alias = ('dir dir /on', 'ls dir /on',
587 591 'ddir dir /ad /on', 'ldir dir /ad /on',
588 592 'mkdir mkdir','rmdir rmdir','echo echo',
589 593 'ren ren','cls cls','copy copy')
590 594 else:
591 595 auto_alias = ()
592 596 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
593 597 # Call the actual (public) initializer
594 598 self.init_auto_alias()
595 599 # end __init__
596 600
597 601 def post_config_initialization(self):
598 602 """Post configuration init method
599 603
600 604 This is called after the configuration files have been processed to
601 605 'finalize' the initialization."""
602 606
603 607 rc = self.rc
604 608
605 609 # Load readline proper
606 610 if rc.readline:
607 611 self.init_readline()
608 612
609 613 # local shortcut, this is used a LOT
610 614 self.log = self.logger.log
611 615
612 616 # Initialize cache, set in/out prompts and printing system
613 617 self.outputcache = CachedOutput(self,
614 618 rc.cache_size,
615 619 rc.pprint,
616 620 input_sep = rc.separate_in,
617 621 output_sep = rc.separate_out,
618 622 output_sep2 = rc.separate_out2,
619 623 ps1 = rc.prompt_in1,
620 624 ps2 = rc.prompt_in2,
621 625 ps_out = rc.prompt_out,
622 626 pad_left = rc.prompts_pad_left)
623 627
624 628 # user may have over-ridden the default print hook:
625 629 try:
626 630 self.outputcache.__class__.display = self.hooks.display
627 631 except AttributeError:
628 632 pass
629 633
630 634 # I don't like assigning globally to sys, because it means when embedding
631 635 # instances, each embedded instance overrides the previous choice. But
632 636 # sys.displayhook seems to be called internally by exec, so I don't see a
633 637 # way around it.
634 638 sys.displayhook = self.outputcache
635 639
636 640 # Set user colors (don't do it in the constructor above so that it
637 641 # doesn't crash if colors option is invalid)
638 642 self.magic_colors(rc.colors)
639 643
640 644 # Set calling of pdb on exceptions
641 645 self.call_pdb = rc.pdb
642 646
643 647 # Load user aliases
644 648 for alias in rc.alias:
645 649 self.magic_alias(alias)
646 650
647 651 # dynamic data that survives through sessions
648 652 # XXX make the filename a config option?
649 653 persist_base = 'persist'
650 654 if rc.profile:
651 655 persist_base += '_%s' % rc.profile
652 656 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
653 657
654 658 try:
655 659 self.persist = pickle.load(file(self.persist_fname))
656 660 except:
657 661 self.persist = {}
658 662
659 663
660 664 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
661 665 try:
662 666 obj = pickle.loads(value)
663 667 except:
664 668
665 669 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
666 670 print "The error was:",sys.exc_info()[0]
667 671 continue
668 672
669 673
670 674 self.user_ns[key] = obj
671 675
672 676 def add_builtins(self):
673 677 """Store ipython references into the builtin namespace.
674 678
675 679 Some parts of ipython operate via builtins injected here, which hold a
676 680 reference to IPython itself."""
677 681
678 682 builtins_new = dict(__IPYTHON__ = self,
679 683 ip_set_hook = self.set_hook,
680 684 jobs = self.jobs,
681 685 ipmagic = self.ipmagic,
682 686 ipalias = self.ipalias,
683 687 ipsystem = self.ipsystem,
684 688 )
685 689 for biname,bival in builtins_new.items():
686 690 try:
687 691 # store the orignal value so we can restore it
688 692 self.builtins_added[biname] = __builtin__.__dict__[biname]
689 693 except KeyError:
690 694 # or mark that it wasn't defined, and we'll just delete it at
691 695 # cleanup
692 696 self.builtins_added[biname] = Undefined
693 697 __builtin__.__dict__[biname] = bival
694 698
695 699 # Keep in the builtins a flag for when IPython is active. We set it
696 700 # with setdefault so that multiple nested IPythons don't clobber one
697 701 # another. Each will increase its value by one upon being activated,
698 702 # which also gives us a way to determine the nesting level.
699 703 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
700 704
701 705 def clean_builtins(self):
702 706 """Remove any builtins which might have been added by add_builtins, or
703 707 restore overwritten ones to their previous values."""
704 708 for biname,bival in self.builtins_added.items():
705 709 if bival is Undefined:
706 710 del __builtin__.__dict__[biname]
707 711 else:
708 712 __builtin__.__dict__[biname] = bival
709 713 self.builtins_added.clear()
710 714
711 715 def set_hook(self,name,hook, priority = 50):
712 716 """set_hook(name,hook) -> sets an internal IPython hook.
713 717
714 718 IPython exposes some of its internal API as user-modifiable hooks. By
715 719 adding your function to one of these hooks, you can modify IPython's
716 720 behavior to call at runtime your own routines."""
717 721
718 722 # At some point in the future, this should validate the hook before it
719 723 # accepts it. Probably at least check that the hook takes the number
720 724 # of args it's supposed to.
721 725 dp = getattr(self.hooks, name, None)
722 726 if not dp:
723 727 dp = IPython.hooks.CommandChainDispatcher()
724 728
725 729 f = new.instancemethod(hook,self,self.__class__)
726 730 try:
727 731 dp.add(f,priority)
728 732 except AttributeError:
729 733 # it was not commandchain, plain old func - replace
730 734 dp = f
731 735
732 736 setattr(self.hooks,name, dp)
733 737
734 738
735 739 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
736 740
737 741 def set_custom_exc(self,exc_tuple,handler):
738 742 """set_custom_exc(exc_tuple,handler)
739 743
740 744 Set a custom exception handler, which will be called if any of the
741 745 exceptions in exc_tuple occur in the mainloop (specifically, in the
742 746 runcode() method.
743 747
744 748 Inputs:
745 749
746 750 - exc_tuple: a *tuple* of valid exceptions to call the defined
747 751 handler for. It is very important that you use a tuple, and NOT A
748 752 LIST here, because of the way Python's except statement works. If
749 753 you only want to trap a single exception, use a singleton tuple:
750 754
751 755 exc_tuple == (MyCustomException,)
752 756
753 757 - handler: this must be defined as a function with the following
754 758 basic interface: def my_handler(self,etype,value,tb).
755 759
756 760 This will be made into an instance method (via new.instancemethod)
757 761 of IPython itself, and it will be called if any of the exceptions
758 762 listed in the exc_tuple are caught. If the handler is None, an
759 763 internal basic one is used, which just prints basic info.
760 764
761 765 WARNING: by putting in your own exception handler into IPython's main
762 766 execution loop, you run a very good chance of nasty crashes. This
763 767 facility should only be used if you really know what you are doing."""
764 768
765 769 assert type(exc_tuple)==type(()) , \
766 770 "The custom exceptions must be given AS A TUPLE."
767 771
768 772 def dummy_handler(self,etype,value,tb):
769 773 print '*** Simple custom exception handler ***'
770 774 print 'Exception type :',etype
771 775 print 'Exception value:',value
772 776 print 'Traceback :',tb
773 777 print 'Source code :','\n'.join(self.buffer)
774 778
775 779 if handler is None: handler = dummy_handler
776 780
777 781 self.CustomTB = new.instancemethod(handler,self,self.__class__)
778 782 self.custom_exceptions = exc_tuple
779 783
780 784 def set_custom_completer(self,completer,pos=0):
781 785 """set_custom_completer(completer,pos=0)
782 786
783 787 Adds a new custom completer function.
784 788
785 789 The position argument (defaults to 0) is the index in the completers
786 790 list where you want the completer to be inserted."""
787 791
788 792 newcomp = new.instancemethod(completer,self.Completer,
789 793 self.Completer.__class__)
790 794 self.Completer.matchers.insert(pos,newcomp)
791 795
792 796 def _get_call_pdb(self):
793 797 return self._call_pdb
794 798
795 799 def _set_call_pdb(self,val):
796 800
797 801 if val not in (0,1,False,True):
798 802 raise ValueError,'new call_pdb value must be boolean'
799 803
800 804 # store value in instance
801 805 self._call_pdb = val
802 806
803 807 # notify the actual exception handlers
804 808 self.InteractiveTB.call_pdb = val
805 809 if self.isthreaded:
806 810 try:
807 811 self.sys_excepthook.call_pdb = val
808 812 except:
809 813 warn('Failed to activate pdb for threaded exception handler')
810 814
811 815 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
812 816 'Control auto-activation of pdb at exceptions')
813 817
814 818
815 819 # These special functions get installed in the builtin namespace, to
816 820 # provide programmatic (pure python) access to magics, aliases and system
817 821 # calls. This is important for logging, user scripting, and more.
818 822
819 823 # We are basically exposing, via normal python functions, the three
820 824 # mechanisms in which ipython offers special call modes (magics for
821 825 # internal control, aliases for direct system access via pre-selected
822 826 # names, and !cmd for calling arbitrary system commands).
823 827
824 828 def ipmagic(self,arg_s):
825 829 """Call a magic function by name.
826 830
827 831 Input: a string containing the name of the magic function to call and any
828 832 additional arguments to be passed to the magic.
829 833
830 834 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
831 835 prompt:
832 836
833 837 In[1]: %name -opt foo bar
834 838
835 839 To call a magic without arguments, simply use ipmagic('name').
836 840
837 841 This provides a proper Python function to call IPython's magics in any
838 842 valid Python code you can type at the interpreter, including loops and
839 843 compound statements. It is added by IPython to the Python builtin
840 844 namespace upon initialization."""
841 845
842 846 args = arg_s.split(' ',1)
843 847 magic_name = args[0]
844 848 magic_name = magic_name.lstrip(self.ESC_MAGIC)
845 849
846 850 try:
847 851 magic_args = args[1]
848 852 except IndexError:
849 853 magic_args = ''
850 854 fn = getattr(self,'magic_'+magic_name,None)
851 855 if fn is None:
852 856 error("Magic function `%s` not found." % magic_name)
853 857 else:
854 858 magic_args = self.var_expand(magic_args)
855 859 return fn(magic_args)
856 860
857 861 def ipalias(self,arg_s):
858 862 """Call an alias by name.
859 863
860 864 Input: a string containing the name of the alias to call and any
861 865 additional arguments to be passed to the magic.
862 866
863 867 ipalias('name -opt foo bar') is equivalent to typing at the ipython
864 868 prompt:
865 869
866 870 In[1]: name -opt foo bar
867 871
868 872 To call an alias without arguments, simply use ipalias('name').
869 873
870 874 This provides a proper Python function to call IPython's aliases in any
871 875 valid Python code you can type at the interpreter, including loops and
872 876 compound statements. It is added by IPython to the Python builtin
873 877 namespace upon initialization."""
874 878
875 879 args = arg_s.split(' ',1)
876 880 alias_name = args[0]
877 881 try:
878 882 alias_args = args[1]
879 883 except IndexError:
880 884 alias_args = ''
881 885 if alias_name in self.alias_table:
882 886 self.call_alias(alias_name,alias_args)
883 887 else:
884 888 error("Alias `%s` not found." % alias_name)
885 889
886 890 def ipsystem(self,arg_s):
887 891 """Make a system call, using IPython."""
888 892
889 893 self.system(arg_s)
890 894
891 895 def complete(self,text):
892 896 """Return a sorted list of all possible completions on text.
893 897
894 898 Inputs:
895 899
896 900 - text: a string of text to be completed on.
897 901
898 902 This is a wrapper around the completion mechanism, similar to what
899 903 readline does at the command line when the TAB key is hit. By
900 904 exposing it as a method, it can be used by other non-readline
901 905 environments (such as GUIs) for text completion.
902 906
903 907 Simple usage example:
904 908
905 909 In [1]: x = 'hello'
906 910
907 911 In [2]: __IP.complete('x.l')
908 912 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
909 913
910 914 complete = self.Completer.complete
911 915 state = 0
912 916 # use a dict so we get unique keys, since ipyhton's multiple
913 917 # completers can return duplicates.
914 918 comps = {}
915 919 while True:
916 920 newcomp = complete(text,state)
917 921 if newcomp is None:
918 922 break
919 923 comps[newcomp] = 1
920 924 state += 1
921 925 outcomps = comps.keys()
922 926 outcomps.sort()
923 927 return outcomps
924 928
925 929 def set_completer_frame(self, frame=None):
926 930 if frame:
927 931 self.Completer.namespace = frame.f_locals
928 932 self.Completer.global_namespace = frame.f_globals
929 933 else:
930 934 self.Completer.namespace = self.user_ns
931 935 self.Completer.global_namespace = self.user_global_ns
932 936
933 937 def init_auto_alias(self):
934 938 """Define some aliases automatically.
935 939
936 940 These are ALL parameter-less aliases"""
937 941
938 942 for alias,cmd in self.auto_alias:
939 943 self.alias_table[alias] = (0,cmd)
940 944
941 945 def alias_table_validate(self,verbose=0):
942 946 """Update information about the alias table.
943 947
944 948 In particular, make sure no Python keywords/builtins are in it."""
945 949
946 950 no_alias = self.no_alias
947 951 for k in self.alias_table.keys():
948 952 if k in no_alias:
949 953 del self.alias_table[k]
950 954 if verbose:
951 955 print ("Deleting alias <%s>, it's a Python "
952 956 "keyword or builtin." % k)
953 957
954 958 def set_autoindent(self,value=None):
955 959 """Set the autoindent flag, checking for readline support.
956 960
957 961 If called with no arguments, it acts as a toggle."""
958 962
959 963 if not self.has_readline:
960 964 if os.name == 'posix':
961 965 warn("The auto-indent feature requires the readline library")
962 966 self.autoindent = 0
963 967 return
964 968 if value is None:
965 969 self.autoindent = not self.autoindent
966 970 else:
967 971 self.autoindent = value
968 972
969 973 def rc_set_toggle(self,rc_field,value=None):
970 974 """Set or toggle a field in IPython's rc config. structure.
971 975
972 976 If called with no arguments, it acts as a toggle.
973 977
974 978 If called with a non-existent field, the resulting AttributeError
975 979 exception will propagate out."""
976 980
977 981 rc_val = getattr(self.rc,rc_field)
978 982 if value is None:
979 983 value = not rc_val
980 984 setattr(self.rc,rc_field,value)
981 985
982 986 def user_setup(self,ipythondir,rc_suffix,mode='install'):
983 987 """Install the user configuration directory.
984 988
985 989 Can be called when running for the first time or to upgrade the user's
986 990 .ipython/ directory with the mode parameter. Valid modes are 'install'
987 991 and 'upgrade'."""
988 992
989 993 def wait():
990 994 try:
991 995 raw_input("Please press <RETURN> to start IPython.")
992 996 except EOFError:
993 997 print >> Term.cout
994 998 print '*'*70
995 999
996 1000 cwd = os.getcwd() # remember where we started
997 1001 glb = glob.glob
998 1002 print '*'*70
999 1003 if mode == 'install':
1000 1004 print \
1001 1005 """Welcome to IPython. I will try to create a personal configuration directory
1002 1006 where you can customize many aspects of IPython's functionality in:\n"""
1003 1007 else:
1004 1008 print 'I am going to upgrade your configuration in:'
1005 1009
1006 1010 print ipythondir
1007 1011
1008 1012 rcdirend = os.path.join('IPython','UserConfig')
1009 1013 cfg = lambda d: os.path.join(d,rcdirend)
1010 1014 try:
1011 1015 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1012 1016 except IOError:
1013 1017 warning = """
1014 1018 Installation error. IPython's directory was not found.
1015 1019
1016 1020 Check the following:
1017 1021
1018 1022 The ipython/IPython directory should be in a directory belonging to your
1019 1023 PYTHONPATH environment variable (that is, it should be in a directory
1020 1024 belonging to sys.path). You can copy it explicitly there or just link to it.
1021 1025
1022 1026 IPython will proceed with builtin defaults.
1023 1027 """
1024 1028 warn(warning)
1025 1029 wait()
1026 1030 return
1027 1031
1028 1032 if mode == 'install':
1029 1033 try:
1030 1034 shutil.copytree(rcdir,ipythondir)
1031 1035 os.chdir(ipythondir)
1032 1036 rc_files = glb("ipythonrc*")
1033 1037 for rc_file in rc_files:
1034 1038 os.rename(rc_file,rc_file+rc_suffix)
1035 1039 except:
1036 1040 warning = """
1037 1041
1038 1042 There was a problem with the installation:
1039 1043 %s
1040 1044 Try to correct it or contact the developers if you think it's a bug.
1041 1045 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1042 1046 warn(warning)
1043 1047 wait()
1044 1048 return
1045 1049
1046 1050 elif mode == 'upgrade':
1047 1051 try:
1048 1052 os.chdir(ipythondir)
1049 1053 except:
1050 1054 print """
1051 1055 Can not upgrade: changing to directory %s failed. Details:
1052 1056 %s
1053 1057 """ % (ipythondir,sys.exc_info()[1])
1054 1058 wait()
1055 1059 return
1056 1060 else:
1057 1061 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1058 1062 for new_full_path in sources:
1059 1063 new_filename = os.path.basename(new_full_path)
1060 1064 if new_filename.startswith('ipythonrc'):
1061 1065 new_filename = new_filename + rc_suffix
1062 1066 # The config directory should only contain files, skip any
1063 1067 # directories which may be there (like CVS)
1064 1068 if os.path.isdir(new_full_path):
1065 1069 continue
1066 1070 if os.path.exists(new_filename):
1067 1071 old_file = new_filename+'.old'
1068 1072 if os.path.exists(old_file):
1069 1073 os.remove(old_file)
1070 1074 os.rename(new_filename,old_file)
1071 1075 shutil.copy(new_full_path,new_filename)
1072 1076 else:
1073 1077 raise ValueError,'unrecognized mode for install:',`mode`
1074 1078
1075 1079 # Fix line-endings to those native to each platform in the config
1076 1080 # directory.
1077 1081 try:
1078 1082 os.chdir(ipythondir)
1079 1083 except:
1080 1084 print """
1081 1085 Problem: changing to directory %s failed.
1082 1086 Details:
1083 1087 %s
1084 1088
1085 1089 Some configuration files may have incorrect line endings. This should not
1086 1090 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1087 1091 wait()
1088 1092 else:
1089 1093 for fname in glb('ipythonrc*'):
1090 1094 try:
1091 1095 native_line_ends(fname,backup=0)
1092 1096 except IOError:
1093 1097 pass
1094 1098
1095 1099 if mode == 'install':
1096 1100 print """
1097 1101 Successful installation!
1098 1102
1099 1103 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1100 1104 IPython manual (there are both HTML and PDF versions supplied with the
1101 1105 distribution) to make sure that your system environment is properly configured
1102 1106 to take advantage of IPython's features.
1103 1107
1104 1108 Important note: the configuration system has changed! The old system is
1105 1109 still in place, but its setting may be partly overridden by the settings in
1106 1110 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1107 1111 if some of the new settings bother you.
1108 1112
1109 1113 """
1110 1114 else:
1111 1115 print """
1112 1116 Successful upgrade!
1113 1117
1114 1118 All files in your directory:
1115 1119 %(ipythondir)s
1116 1120 which would have been overwritten by the upgrade were backed up with a .old
1117 1121 extension. If you had made particular customizations in those files you may
1118 1122 want to merge them back into the new files.""" % locals()
1119 1123 wait()
1120 1124 os.chdir(cwd)
1121 1125 # end user_setup()
1122 1126
1123 1127 def atexit_operations(self):
1124 1128 """This will be executed at the time of exit.
1125 1129
1126 1130 Saving of persistent data should be performed here. """
1127 1131
1128 1132 #print '*** IPython exit cleanup ***' # dbg
1129 1133 # input history
1130 1134 self.savehist()
1131 1135
1132 1136 # Cleanup all tempfiles left around
1133 1137 for tfile in self.tempfiles:
1134 1138 try:
1135 1139 os.unlink(tfile)
1136 1140 except OSError:
1137 1141 pass
1138 1142
1139 1143 # save the "persistent data" catch-all dictionary
1140 1144 try:
1141 1145 pickle.dump(self.persist, open(self.persist_fname,"w"))
1142 1146 except:
1143 1147 print "*** ERROR *** persistent data saving failed."
1144 1148
1145 1149 def savehist(self):
1146 1150 """Save input history to a file (via readline library)."""
1147 1151 try:
1148 1152 self.readline.write_history_file(self.histfile)
1149 1153 except:
1150 1154 print 'Unable to save IPython command history to file: ' + \
1151 1155 `self.histfile`
1152 1156
1153 1157 def pre_readline(self):
1154 1158 """readline hook to be used at the start of each line.
1155 1159
1156 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 1163 self.readline.insert_text(self.indent_current_str())
1160 1164
1161 1165 def init_readline(self):
1162 1166 """Command history completion/saving/reloading."""
1163 1167 try:
1164 1168 import readline
1165 1169 except ImportError:
1166 1170 self.has_readline = 0
1167 1171 self.readline = None
1168 1172 # no point in bugging windows users with this every time:
1169 1173 if os.name == 'posix':
1170 1174 warn('Readline services not available on this platform.')
1171 1175 else:
1172 1176 import atexit
1173 1177 from IPython.completer import IPCompleter
1174 1178 self.Completer = IPCompleter(self,
1175 1179 self.user_ns,
1176 1180 self.user_global_ns,
1177 1181 self.rc.readline_omit__names,
1178 1182 self.alias_table)
1179 1183
1180 1184 # Platform-specific configuration
1181 1185 if os.name == 'nt':
1182 1186 self.readline_startup_hook = readline.set_pre_input_hook
1183 1187 else:
1184 1188 self.readline_startup_hook = readline.set_startup_hook
1185 1189
1186 1190 # Load user's initrc file (readline config)
1187 1191 inputrc_name = os.environ.get('INPUTRC')
1188 1192 if inputrc_name is None:
1189 1193 home_dir = get_home_dir()
1190 1194 if home_dir is not None:
1191 1195 inputrc_name = os.path.join(home_dir,'.inputrc')
1192 1196 if os.path.isfile(inputrc_name):
1193 1197 try:
1194 1198 readline.read_init_file(inputrc_name)
1195 1199 except:
1196 1200 warn('Problems reading readline initialization file <%s>'
1197 1201 % inputrc_name)
1198 1202
1199 1203 self.has_readline = 1
1200 1204 self.readline = readline
1201 1205 # save this in sys so embedded copies can restore it properly
1202 1206 sys.ipcompleter = self.Completer.complete
1203 1207 readline.set_completer(self.Completer.complete)
1204 1208
1205 1209 # Configure readline according to user's prefs
1206 1210 for rlcommand in self.rc.readline_parse_and_bind:
1207 1211 readline.parse_and_bind(rlcommand)
1208 1212
1209 1213 # remove some chars from the delimiters list
1210 1214 delims = readline.get_completer_delims()
1211 1215 delims = delims.translate(string._idmap,
1212 1216 self.rc.readline_remove_delims)
1213 1217 readline.set_completer_delims(delims)
1214 1218 # otherwise we end up with a monster history after a while:
1215 1219 readline.set_history_length(1000)
1216 1220 try:
1217 1221 #print '*** Reading readline history' # dbg
1218 1222 readline.read_history_file(self.histfile)
1219 1223 except IOError:
1220 1224 pass # It doesn't exist yet.
1221 1225
1222 1226 atexit.register(self.atexit_operations)
1223 1227 del atexit
1224 1228
1225 1229 # Configure auto-indent for all platforms
1226 1230 self.set_autoindent(self.rc.autoindent)
1227 1231
1228 1232 def _should_recompile(self,e):
1229 1233 """Utility routine for edit_syntax_error"""
1230 1234
1231 1235 if e.filename in ('<ipython console>','<input>','<string>',
1232 1236 '<console>',None):
1233 1237
1234 1238 return False
1235 1239 try:
1236 1240 if not ask_yes_no('Return to editor to correct syntax error? '
1237 1241 '[Y/n] ','y'):
1238 1242 return False
1239 1243 except EOFError:
1240 1244 return False
1241 1245
1242 1246 def int0(x):
1243 1247 try:
1244 1248 return int(x)
1245 1249 except TypeError:
1246 1250 return 0
1247 1251 # always pass integer line and offset values to editor hook
1248 1252 self.hooks.fix_error_editor(e.filename,
1249 1253 int0(e.lineno),int0(e.offset),e.msg)
1250 1254 return True
1251 1255
1252 1256 def edit_syntax_error(self):
1253 1257 """The bottom half of the syntax error handler called in the main loop.
1254 1258
1255 1259 Loop until syntax error is fixed or user cancels.
1256 1260 """
1257 1261
1258 1262 while self.SyntaxTB.last_syntax_error:
1259 1263 # copy and clear last_syntax_error
1260 1264 err = self.SyntaxTB.clear_err_state()
1261 1265 if not self._should_recompile(err):
1262 1266 return
1263 1267 try:
1264 1268 # may set last_syntax_error again if a SyntaxError is raised
1265 1269 self.safe_execfile(err.filename,self.shell.user_ns)
1266 1270 except:
1267 1271 self.showtraceback()
1268 1272 else:
1269 1273 f = file(err.filename)
1270 1274 try:
1271 1275 sys.displayhook(f.read())
1272 1276 finally:
1273 1277 f.close()
1274 1278
1275 1279 def showsyntaxerror(self, filename=None):
1276 1280 """Display the syntax error that just occurred.
1277 1281
1278 1282 This doesn't display a stack trace because there isn't one.
1279 1283
1280 1284 If a filename is given, it is stuffed in the exception instead
1281 1285 of what was there before (because Python's parser always uses
1282 1286 "<string>" when reading from a string).
1283 1287 """
1284 1288 etype, value, last_traceback = sys.exc_info()
1285 1289 if filename and etype is SyntaxError:
1286 1290 # Work hard to stuff the correct filename in the exception
1287 1291 try:
1288 1292 msg, (dummy_filename, lineno, offset, line) = value
1289 1293 except:
1290 1294 # Not the format we expect; leave it alone
1291 1295 pass
1292 1296 else:
1293 1297 # Stuff in the right filename
1294 1298 try:
1295 1299 # Assume SyntaxError is a class exception
1296 1300 value = SyntaxError(msg, (filename, lineno, offset, line))
1297 1301 except:
1298 1302 # If that failed, assume SyntaxError is a string
1299 1303 value = msg, (filename, lineno, offset, line)
1300 1304 self.SyntaxTB(etype,value,[])
1301 1305
1302 1306 def debugger(self):
1303 1307 """Call the pdb debugger."""
1304 1308
1305 1309 if not self.rc.pdb:
1306 1310 return
1307 1311 pdb.pm()
1308 1312
1309 1313 def showtraceback(self,exc_tuple = None,filename=None):
1310 1314 """Display the exception that just occurred."""
1311 1315
1312 1316 # Though this won't be called by syntax errors in the input line,
1313 1317 # there may be SyntaxError cases whith imported code.
1314 1318 if exc_tuple is None:
1315 1319 type, value, tb = sys.exc_info()
1316 1320 else:
1317 1321 type, value, tb = exc_tuple
1318 1322 if type is SyntaxError:
1319 1323 self.showsyntaxerror(filename)
1320 1324 else:
1321 1325 self.InteractiveTB()
1322 1326 if self.InteractiveTB.call_pdb and self.has_readline:
1323 1327 # pdb mucks up readline, fix it back
1324 1328 self.readline.set_completer(self.Completer.complete)
1325 1329
1326 1330 def mainloop(self,banner=None):
1327 1331 """Creates the local namespace and starts the mainloop.
1328 1332
1329 1333 If an optional banner argument is given, it will override the
1330 1334 internally created default banner."""
1331 1335
1332 1336 if self.rc.c: # Emulate Python's -c option
1333 1337 self.exec_init_cmd()
1334 1338 if banner is None:
1335 1339 if self.rc.banner:
1336 1340 banner = self.BANNER+self.banner2
1337 1341 else:
1338 1342 banner = ''
1339 1343 self.interact(banner)
1340 1344
1341 1345 def exec_init_cmd(self):
1342 1346 """Execute a command given at the command line.
1343 1347
1344 1348 This emulates Python's -c option."""
1345 1349
1346 1350 sys.argv = ['-c']
1347 1351 self.push(self.rc.c)
1348 1352
1349 1353 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1350 1354 """Embeds IPython into a running python program.
1351 1355
1352 1356 Input:
1353 1357
1354 1358 - header: An optional header message can be specified.
1355 1359
1356 1360 - local_ns, global_ns: working namespaces. If given as None, the
1357 1361 IPython-initialized one is updated with __main__.__dict__, so that
1358 1362 program variables become visible but user-specific configuration
1359 1363 remains possible.
1360 1364
1361 1365 - stack_depth: specifies how many levels in the stack to go to
1362 1366 looking for namespaces (when local_ns and global_ns are None). This
1363 1367 allows an intermediate caller to make sure that this function gets
1364 1368 the namespace from the intended level in the stack. By default (0)
1365 1369 it will get its locals and globals from the immediate caller.
1366 1370
1367 1371 Warning: it's possible to use this in a program which is being run by
1368 1372 IPython itself (via %run), but some funny things will happen (a few
1369 1373 globals get overwritten). In the future this will be cleaned up, as
1370 1374 there is no fundamental reason why it can't work perfectly."""
1371 1375
1372 1376 # Get locals and globals from caller
1373 1377 if local_ns is None or global_ns is None:
1374 1378 call_frame = sys._getframe(stack_depth).f_back
1375 1379
1376 1380 if local_ns is None:
1377 1381 local_ns = call_frame.f_locals
1378 1382 if global_ns is None:
1379 1383 global_ns = call_frame.f_globals
1380 1384
1381 1385 # Update namespaces and fire up interpreter
1382 1386
1383 1387 # The global one is easy, we can just throw it in
1384 1388 self.user_global_ns = global_ns
1385 1389
1386 1390 # but the user/local one is tricky: ipython needs it to store internal
1387 1391 # data, but we also need the locals. We'll copy locals in the user
1388 1392 # one, but will track what got copied so we can delete them at exit.
1389 1393 # This is so that a later embedded call doesn't see locals from a
1390 1394 # previous call (which most likely existed in a separate scope).
1391 1395 local_varnames = local_ns.keys()
1392 1396 self.user_ns.update(local_ns)
1393 1397
1394 1398 # Patch for global embedding to make sure that things don't overwrite
1395 1399 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1396 1400 # FIXME. Test this a bit more carefully (the if.. is new)
1397 1401 if local_ns is None and global_ns is None:
1398 1402 self.user_global_ns.update(__main__.__dict__)
1399 1403
1400 1404 # make sure the tab-completer has the correct frame information, so it
1401 1405 # actually completes using the frame's locals/globals
1402 1406 self.set_completer_frame()
1403 1407
1404 1408 # before activating the interactive mode, we need to make sure that
1405 1409 # all names in the builtin namespace needed by ipython point to
1406 1410 # ourselves, and not to other instances.
1407 1411 self.add_builtins()
1408 1412
1409 1413 self.interact(header)
1410 1414
1411 1415 # now, purge out the user namespace from anything we might have added
1412 1416 # from the caller's local namespace
1413 1417 delvar = self.user_ns.pop
1414 1418 for var in local_varnames:
1415 1419 delvar(var,None)
1416 1420 # and clean builtins we may have overridden
1417 1421 self.clean_builtins()
1418 1422
1419 1423 def interact(self, banner=None):
1420 1424 """Closely emulate the interactive Python console.
1421 1425
1422 1426 The optional banner argument specify the banner to print
1423 1427 before the first interaction; by default it prints a banner
1424 1428 similar to the one printed by the real Python interpreter,
1425 1429 followed by the current class name in parentheses (so as not
1426 1430 to confuse this with the real interpreter -- since it's so
1427 1431 close!).
1428 1432
1429 1433 """
1430 1434 cprt = 'Type "copyright", "credits" or "license" for more information.'
1431 1435 if banner is None:
1432 1436 self.write("Python %s on %s\n%s\n(%s)\n" %
1433 1437 (sys.version, sys.platform, cprt,
1434 1438 self.__class__.__name__))
1435 1439 else:
1436 1440 self.write(banner)
1437 1441
1438 1442 more = 0
1439 1443
1440 1444 # Mark activity in the builtins
1441 1445 __builtin__.__dict__['__IPYTHON__active'] += 1
1442 1446
1443 1447 # exit_now is set by a call to %Exit or %Quit
1444 1448 self.exit_now = False
1445 1449 while not self.exit_now:
1446 1450
1447 1451 try:
1448 1452 if more:
1449 1453 prompt = self.outputcache.prompt2
1450 1454 if self.autoindent:
1451 1455 self.readline_startup_hook(self.pre_readline)
1452 1456 else:
1453 1457 prompt = self.outputcache.prompt1
1454 1458 try:
1455 1459 line = self.raw_input(prompt,more)
1456 1460 if self.autoindent:
1457 1461 self.readline_startup_hook(None)
1458 1462 except EOFError:
1459 1463 if self.autoindent:
1460 1464 self.readline_startup_hook(None)
1461 1465 self.write("\n")
1462 1466 self.exit()
1463 1467 except:
1464 1468 # exceptions here are VERY RARE, but they can be triggered
1465 1469 # asynchronously by signal handlers, for example.
1466 1470 self.showtraceback()
1467 1471 else:
1468 1472 more = self.push(line)
1469 1473
1470 1474 if (self.SyntaxTB.last_syntax_error and
1471 1475 self.rc.autoedit_syntax):
1472 1476 self.edit_syntax_error()
1473 1477
1474 1478 except KeyboardInterrupt:
1475 1479 self.write("\nKeyboardInterrupt\n")
1476 1480 self.resetbuffer()
1477 1481 more = 0
1478 1482 # keep cache in sync with the prompt counter:
1479 1483 self.outputcache.prompt_count -= 1
1480 1484
1481 1485 if self.autoindent:
1482 1486 self.indent_current_nsp = 0
1483 1487
1484 1488 except bdb.BdbQuit:
1485 1489 warn("The Python debugger has exited with a BdbQuit exception.\n"
1486 1490 "Because of how pdb handles the stack, it is impossible\n"
1487 1491 "for IPython to properly format this particular exception.\n"
1488 1492 "IPython will resume normal operation.")
1489 1493
1490 1494 # We are off again...
1491 1495 __builtin__.__dict__['__IPYTHON__active'] -= 1
1492 1496
1493 1497 def excepthook(self, type, value, tb):
1494 1498 """One more defense for GUI apps that call sys.excepthook.
1495 1499
1496 1500 GUI frameworks like wxPython trap exceptions and call
1497 1501 sys.excepthook themselves. I guess this is a feature that
1498 1502 enables them to keep running after exceptions that would
1499 1503 otherwise kill their mainloop. This is a bother for IPython
1500 1504 which excepts to catch all of the program exceptions with a try:
1501 1505 except: statement.
1502 1506
1503 1507 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1504 1508 any app directly invokes sys.excepthook, it will look to the user like
1505 1509 IPython crashed. In order to work around this, we can disable the
1506 1510 CrashHandler and replace it with this excepthook instead, which prints a
1507 1511 regular traceback using our InteractiveTB. In this fashion, apps which
1508 1512 call sys.excepthook will generate a regular-looking exception from
1509 1513 IPython, and the CrashHandler will only be triggered by real IPython
1510 1514 crashes.
1511 1515
1512 1516 This hook should be used sparingly, only in places which are not likely
1513 1517 to be true IPython errors.
1514 1518 """
1515 1519
1516 1520 self.InteractiveTB(type, value, tb, tb_offset=0)
1517 1521 if self.InteractiveTB.call_pdb and self.has_readline:
1518 1522 self.readline.set_completer(self.Completer.complete)
1519 1523
1520 1524 def call_alias(self,alias,rest=''):
1521 1525 """Call an alias given its name and the rest of the line.
1522 1526
1523 1527 This function MUST be given a proper alias, because it doesn't make
1524 1528 any checks when looking up into the alias table. The caller is
1525 1529 responsible for invoking it only with a valid alias."""
1526 1530
1527 1531 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1528 1532 nargs,cmd = self.alias_table[alias]
1529 1533 # Expand the %l special to be the user's input line
1530 1534 if cmd.find('%l') >= 0:
1531 1535 cmd = cmd.replace('%l',rest)
1532 1536 rest = ''
1533 1537 if nargs==0:
1534 1538 # Simple, argument-less aliases
1535 1539 cmd = '%s %s' % (cmd,rest)
1536 1540 else:
1537 1541 # Handle aliases with positional arguments
1538 1542 args = rest.split(None,nargs)
1539 1543 if len(args)< nargs:
1540 1544 error('Alias <%s> requires %s arguments, %s given.' %
1541 1545 (alias,nargs,len(args)))
1542 1546 return
1543 1547 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1544 1548 # Now call the macro, evaluating in the user's namespace
1545 1549 try:
1546 1550 self.system(cmd)
1547 1551 except:
1548 1552 self.showtraceback()
1549 1553
1550 1554 def indent_current_str(self):
1551 1555 """return the current level of indentation as a string"""
1552 1556 return self.indent_current_nsp * ' '
1553 1557
1554 1558 def autoindent_update(self,line):
1555 1559 """Keep track of the indent level."""
1556 1560
1557 #import traceback; traceback.print_stack() # dbg
1558 debugp('line')
1559 debugp('self.indent_current_nsp')
1561 #debugx('line')
1562 #debugx('self.indent_current_nsp')
1560 1563 if self.autoindent:
1561 1564 if line:
1562 1565 inisp = num_ini_spaces(line)
1563 1566 if inisp < self.indent_current_nsp:
1564 1567 self.indent_current_nsp = inisp
1565 1568
1566 1569 if line[-1] == ':':
1567 1570 self.indent_current_nsp += 4
1568 1571 elif dedent_re.match(line):
1569 1572 self.indent_current_nsp -= 4
1570 1573 else:
1571 1574 self.indent_current_nsp = 0
1572 1575
1573 1576 def runlines(self,lines):
1574 1577 """Run a string of one or more lines of source.
1575 1578
1576 1579 This method is capable of running a string containing multiple source
1577 1580 lines, as if they had been entered at the IPython prompt. Since it
1578 1581 exposes IPython's processing machinery, the given strings can contain
1579 1582 magic calls (%magic), special shell access (!cmd), etc."""
1580 1583
1581 1584 # We must start with a clean buffer, in case this is run from an
1582 1585 # interactive IPython session (via a magic, for example).
1583 1586 self.resetbuffer()
1584 1587 lines = lines.split('\n')
1585 1588 more = 0
1586 1589 for line in lines:
1587 1590 # skip blank lines so we don't mess up the prompt counter, but do
1588 1591 # NOT skip even a blank line if we are in a code block (more is
1589 1592 # true)
1590 1593 if line or more:
1591 1594 more = self.push(self.prefilter(line,more))
1592 1595 # IPython's runsource returns None if there was an error
1593 1596 # compiling the code. This allows us to stop processing right
1594 1597 # away, so the user gets the error message at the right place.
1595 1598 if more is None:
1596 1599 break
1597 1600 # final newline in case the input didn't have it, so that the code
1598 1601 # actually does get executed
1599 1602 if more:
1600 1603 self.push('\n')
1601 1604
1602 1605 def runsource(self, source, filename='<input>', symbol='single'):
1603 1606 """Compile and run some source in the interpreter.
1604 1607
1605 1608 Arguments are as for compile_command().
1606 1609
1607 1610 One several things can happen:
1608 1611
1609 1612 1) The input is incorrect; compile_command() raised an
1610 1613 exception (SyntaxError or OverflowError). A syntax traceback
1611 1614 will be printed by calling the showsyntaxerror() method.
1612 1615
1613 1616 2) The input is incomplete, and more input is required;
1614 1617 compile_command() returned None. Nothing happens.
1615 1618
1616 1619 3) The input is complete; compile_command() returned a code
1617 1620 object. The code is executed by calling self.runcode() (which
1618 1621 also handles run-time exceptions, except for SystemExit).
1619 1622
1620 1623 The return value is:
1621 1624
1622 1625 - True in case 2
1623 1626
1624 1627 - False in the other cases, unless an exception is raised, where
1625 1628 None is returned instead. This can be used by external callers to
1626 1629 know whether to continue feeding input or not.
1627 1630
1628 1631 The return value can be used to decide whether to use sys.ps1 or
1629 1632 sys.ps2 to prompt the next line."""
1630 1633
1631 1634 try:
1632 1635 code = self.compile(source,filename,symbol)
1633 1636 except (OverflowError, SyntaxError, ValueError):
1634 1637 # Case 1
1635 1638 self.showsyntaxerror(filename)
1636 1639 return None
1637 1640
1638 1641 if code is None:
1639 1642 # Case 2
1640 1643 return True
1641 1644
1642 1645 # Case 3
1643 1646 # We store the code object so that threaded shells and
1644 1647 # custom exception handlers can access all this info if needed.
1645 1648 # The source corresponding to this can be obtained from the
1646 1649 # buffer attribute as '\n'.join(self.buffer).
1647 1650 self.code_to_run = code
1648 1651 # now actually execute the code object
1649 1652 if self.runcode(code) == 0:
1650 1653 return False
1651 1654 else:
1652 1655 return None
1653 1656
1654 1657 def runcode(self,code_obj):
1655 1658 """Execute a code object.
1656 1659
1657 1660 When an exception occurs, self.showtraceback() is called to display a
1658 1661 traceback.
1659 1662
1660 1663 Return value: a flag indicating whether the code to be run completed
1661 1664 successfully:
1662 1665
1663 1666 - 0: successful execution.
1664 1667 - 1: an error occurred.
1665 1668 """
1666 1669
1667 1670 # Set our own excepthook in case the user code tries to call it
1668 1671 # directly, so that the IPython crash handler doesn't get triggered
1669 1672 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1670 1673
1671 1674 # we save the original sys.excepthook in the instance, in case config
1672 1675 # code (such as magics) needs access to it.
1673 1676 self.sys_excepthook = old_excepthook
1674 1677 outflag = 1 # happens in more places, so it's easier as default
1675 1678 try:
1676 1679 try:
1677 1680 # Embedded instances require separate global/local namespaces
1678 1681 # so they can see both the surrounding (local) namespace and
1679 1682 # the module-level globals when called inside another function.
1680 1683 if self.embedded:
1681 1684 exec code_obj in self.user_global_ns, self.user_ns
1682 1685 # Normal (non-embedded) instances should only have a single
1683 1686 # namespace for user code execution, otherwise functions won't
1684 1687 # see interactive top-level globals.
1685 1688 else:
1686 1689 exec code_obj in self.user_ns
1687 1690 finally:
1688 1691 # Reset our crash handler in place
1689 1692 sys.excepthook = old_excepthook
1690 1693 except SystemExit:
1691 1694 self.resetbuffer()
1692 1695 self.showtraceback()
1693 1696 warn("Type exit or quit to exit IPython "
1694 1697 "(%Exit or %Quit do so unconditionally).",level=1)
1695 1698 except self.custom_exceptions:
1696 1699 etype,value,tb = sys.exc_info()
1697 1700 self.CustomTB(etype,value,tb)
1698 1701 except:
1699 1702 self.showtraceback()
1700 1703 else:
1701 1704 outflag = 0
1702 1705 if softspace(sys.stdout, 0):
1703 1706 print
1704 1707 # Flush out code object which has been run (and source)
1705 1708 self.code_to_run = None
1706 1709 return outflag
1707 1710
1708 1711 def push(self, line):
1709 1712 """Push a line to the interpreter.
1710 1713
1711 1714 The line should not have a trailing newline; it may have
1712 1715 internal newlines. The line is appended to a buffer and the
1713 1716 interpreter's runsource() method is called with the
1714 1717 concatenated contents of the buffer as source. If this
1715 1718 indicates that the command was executed or invalid, the buffer
1716 1719 is reset; otherwise, the command is incomplete, and the buffer
1717 1720 is left as it was after the line was appended. The return
1718 1721 value is 1 if more input is required, 0 if the line was dealt
1719 1722 with in some way (this is the same as runsource()).
1720 1723 """
1721 1724
1722 1725 # autoindent management should be done here, and not in the
1723 1726 # interactive loop, since that one is only seen by keyboard input. We
1724 1727 # need this done correctly even for code run via runlines (which uses
1725 1728 # push).
1726 1729
1727 1730 #print 'push line: <%s>' % line # dbg
1728 1731 self.autoindent_update(line)
1729 1732
1730 1733 self.buffer.append(line)
1731 1734 more = self.runsource('\n'.join(self.buffer), self.filename)
1732 1735 if not more:
1733 1736 self.resetbuffer()
1734 1737 return more
1735 1738
1736 1739 def resetbuffer(self):
1737 1740 """Reset the input buffer."""
1738 1741 self.buffer[:] = []
1739 1742
1740 1743 def raw_input(self,prompt='',continue_prompt=False):
1741 1744 """Write a prompt and read a line.
1742 1745
1743 1746 The returned line does not include the trailing newline.
1744 1747 When the user enters the EOF key sequence, EOFError is raised.
1745 1748
1746 1749 Optional inputs:
1747 1750
1748 1751 - prompt(''): a string to be printed to prompt the user.
1749 1752
1750 1753 - continue_prompt(False): whether this line is the first one or a
1751 1754 continuation in a sequence of inputs.
1752 1755 """
1753 1756
1754 1757 line = raw_input_original(prompt)
1755 1758 # Try to be reasonably smart about not re-indenting pasted input more
1756 1759 # than necessary. We do this by trimming out the auto-indent initial
1757 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 1763 if self.autoindent:
1763 1764 if num_ini_spaces(line) > self.indent_current_nsp:
1764 1765 line = line[self.indent_current_nsp:]
1765 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 1776 lineout = self.prefilter(line,continue_prompt)
1770 debugp('lineout')
1771 1777 return lineout
1772 1778
1773 1779 def split_user_input(self,line):
1774 1780 """Split user input into pre-char, function part and rest."""
1775 1781
1776 1782 lsplit = self.line_split.match(line)
1777 1783 if lsplit is None: # no regexp match returns None
1778 1784 try:
1779 1785 iFun,theRest = line.split(None,1)
1780 1786 except ValueError:
1781 1787 iFun,theRest = line,''
1782 1788 pre = re.match('^(\s*)(.*)',line).groups()[0]
1783 1789 else:
1784 1790 pre,iFun,theRest = lsplit.groups()
1785 1791
1786 1792 #print 'line:<%s>' % line # dbg
1787 1793 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1788 1794 return pre,iFun.strip(),theRest
1789 1795
1790 1796 def _prefilter(self, line, continue_prompt):
1791 1797 """Calls different preprocessors, depending on the form of line."""
1792 1798
1793 1799 # All handlers *must* return a value, even if it's blank ('').
1794 1800
1795 1801 # Lines are NOT logged here. Handlers should process the line as
1796 1802 # needed, update the cache AND log it (so that the input cache array
1797 1803 # stays synced).
1798 1804
1799 1805 # This function is _very_ delicate, and since it's also the one which
1800 1806 # determines IPython's response to user input, it must be as efficient
1801 1807 # as possible. For this reason it has _many_ returns in it, trying
1802 1808 # always to exit as quickly as it can figure out what it needs to do.
1803 1809
1804 1810 # This function is the main responsible for maintaining IPython's
1805 1811 # behavior respectful of Python's semantics. So be _very_ careful if
1806 1812 # making changes to anything here.
1807 1813
1808 1814 #.....................................................................
1809 1815 # Code begins
1810 1816
1811 1817 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1812 1818
1813 1819 # save the line away in case we crash, so the post-mortem handler can
1814 1820 # record it
1815 1821 self._last_input_line = line
1816 1822
1817 1823 #print '***line: <%s>' % line # dbg
1818 1824
1819 1825 # the input history needs to track even empty lines
1820 1826 if not line.strip():
1821 1827 if not continue_prompt:
1822 1828 self.outputcache.prompt_count -= 1
1823 1829 return self.handle_normal(line,continue_prompt)
1824 1830 #return self.handle_normal('',continue_prompt)
1825 1831
1826 1832 # print '***cont',continue_prompt # dbg
1827 1833 # special handlers are only allowed for single line statements
1828 1834 if continue_prompt and not self.rc.multi_line_specials:
1829 1835 return self.handle_normal(line,continue_prompt)
1830 1836
1831 1837 # For the rest, we need the structure of the input
1832 1838 pre,iFun,theRest = self.split_user_input(line)
1833 1839 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1834 1840
1835 1841 # First check for explicit escapes in the last/first character
1836 1842 handler = None
1837 1843 if line[-1] == self.ESC_HELP:
1838 1844 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1839 1845 if handler is None:
1840 1846 # look at the first character of iFun, NOT of line, so we skip
1841 1847 # leading whitespace in multiline input
1842 1848 handler = self.esc_handlers.get(iFun[0:1])
1843 1849 if handler is not None:
1844 1850 return handler(line,continue_prompt,pre,iFun,theRest)
1845 1851 # Emacs ipython-mode tags certain input lines
1846 1852 if line.endswith('# PYTHON-MODE'):
1847 1853 return self.handle_emacs(line,continue_prompt)
1848 1854
1849 1855 # Next, check if we can automatically execute this thing
1850 1856
1851 1857 # Allow ! in multi-line statements if multi_line_specials is on:
1852 1858 if continue_prompt and self.rc.multi_line_specials and \
1853 1859 iFun.startswith(self.ESC_SHELL):
1854 1860 return self.handle_shell_escape(line,continue_prompt,
1855 1861 pre=pre,iFun=iFun,
1856 1862 theRest=theRest)
1857 1863
1858 1864 # Let's try to find if the input line is a magic fn
1859 1865 oinfo = None
1860 1866 if hasattr(self,'magic_'+iFun):
1861 1867 # WARNING: _ofind uses getattr(), so it can consume generators and
1862 1868 # cause other side effects.
1863 1869 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1864 1870 if oinfo['ismagic']:
1865 1871 # Be careful not to call magics when a variable assignment is
1866 1872 # being made (ls='hi', for example)
1867 1873 if self.rc.automagic and \
1868 1874 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1869 1875 (self.rc.multi_line_specials or not continue_prompt):
1870 1876 return self.handle_magic(line,continue_prompt,
1871 1877 pre,iFun,theRest)
1872 1878 else:
1873 1879 return self.handle_normal(line,continue_prompt)
1874 1880
1875 1881 # If the rest of the line begins with an (in)equality, assginment or
1876 1882 # function call, we should not call _ofind but simply execute it.
1877 1883 # This avoids spurious geattr() accesses on objects upon assignment.
1878 1884 #
1879 1885 # It also allows users to assign to either alias or magic names true
1880 1886 # python variables (the magic/alias systems always take second seat to
1881 1887 # true python code).
1882 1888 if theRest and theRest[0] in '!=()':
1883 1889 return self.handle_normal(line,continue_prompt)
1884 1890
1885 1891 if oinfo is None:
1886 1892 # let's try to ensure that _oinfo is ONLY called when autocall is
1887 1893 # on. Since it has inevitable potential side effects, at least
1888 1894 # having autocall off should be a guarantee to the user that no
1889 1895 # weird things will happen.
1890 1896
1891 1897 if self.rc.autocall:
1892 1898 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1893 1899 else:
1894 1900 # in this case, all that's left is either an alias or
1895 1901 # processing the line normally.
1896 1902 if iFun in self.alias_table:
1897 1903 return self.handle_alias(line,continue_prompt,
1898 1904 pre,iFun,theRest)
1899 1905
1900 1906 else:
1901 1907 return self.handle_normal(line,continue_prompt)
1902 1908
1903 1909 if not oinfo['found']:
1904 1910 return self.handle_normal(line,continue_prompt)
1905 1911 else:
1906 1912 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1907 1913 if oinfo['isalias']:
1908 1914 return self.handle_alias(line,continue_prompt,
1909 1915 pre,iFun,theRest)
1910 1916
1911 1917 if (self.rc.autocall
1912 1918 and
1913 1919 (
1914 1920 #only consider exclusion re if not "," or ";" autoquoting
1915 1921 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2) or
1916 1922 (not self.re_exclude_auto.match(theRest)))
1917 1923 and
1918 1924 self.re_fun_name.match(iFun) and
1919 1925 callable(oinfo['obj'])) :
1920 1926 #print 'going auto' # dbg
1921 1927 return self.handle_auto(line,continue_prompt,
1922 1928 pre,iFun,theRest,oinfo['obj'])
1923 1929 else:
1924 1930 #print 'was callable?', callable(oinfo['obj']) # dbg
1925 1931 return self.handle_normal(line,continue_prompt)
1926 1932
1927 1933 # If we get here, we have a normal Python line. Log and return.
1928 1934 return self.handle_normal(line,continue_prompt)
1929 1935
1930 1936 def _prefilter_dumb(self, line, continue_prompt):
1931 1937 """simple prefilter function, for debugging"""
1932 1938 return self.handle_normal(line,continue_prompt)
1933 1939
1934 1940 # Set the default prefilter() function (this can be user-overridden)
1935 1941 prefilter = _prefilter
1936 1942
1937 1943 def handle_normal(self,line,continue_prompt=None,
1938 1944 pre=None,iFun=None,theRest=None):
1939 1945 """Handle normal input lines. Use as a template for handlers."""
1940 1946
1941 1947 # With autoindent on, we need some way to exit the input loop, and I
1942 1948 # don't want to force the user to have to backspace all the way to
1943 1949 # clear the line. The rule will be in this case, that either two
1944 1950 # lines of pure whitespace in a row, or a line of pure whitespace but
1945 1951 # of a size different to the indent level, will exit the input loop.
1946 1952
1947 1953 if (continue_prompt and self.autoindent and line.isspace() and
1948 1954 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1949 1955 (self.buffer[-1]).isspace() )):
1950 #print 'reset line' # dbg
1951 1956 line = ''
1952 1957
1953 1958 self.log(line,continue_prompt)
1954 1959 return line
1955 1960
1956 1961 def handle_alias(self,line,continue_prompt=None,
1957 1962 pre=None,iFun=None,theRest=None):
1958 1963 """Handle alias input lines. """
1959 1964
1960 1965 # pre is needed, because it carries the leading whitespace. Otherwise
1961 1966 # aliases won't work in indented sections.
1962 1967 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1963 1968 self.log(line_out,continue_prompt)
1964 1969 return line_out
1965 1970
1966 1971 def handle_shell_escape(self, line, continue_prompt=None,
1967 1972 pre=None,iFun=None,theRest=None):
1968 1973 """Execute the line in a shell, empty return value"""
1969 1974
1970 1975 #print 'line in :', `line` # dbg
1971 1976 # Example of a special handler. Others follow a similar pattern.
1972 1977 if line.lstrip().startswith('!!'):
1973 1978 # rewrite iFun/theRest to properly hold the call to %sx and
1974 1979 # the actual command to be executed, so handle_magic can work
1975 1980 # correctly
1976 1981 theRest = '%s %s' % (iFun[2:],theRest)
1977 1982 iFun = 'sx'
1978 1983 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
1979 1984 line.lstrip()[2:]),
1980 1985 continue_prompt,pre,iFun,theRest)
1981 1986 else:
1982 1987 cmd=line.lstrip().lstrip('!')
1983 1988 line_out = '%sipsystem(%s)' % (pre,make_quoted_expr(cmd))
1984 1989 # update cache/log and return
1985 1990 self.log(line_out,continue_prompt)
1986 1991 return line_out
1987 1992
1988 1993 def handle_magic(self, line, continue_prompt=None,
1989 1994 pre=None,iFun=None,theRest=None):
1990 1995 """Execute magic functions."""
1991 1996
1992 1997
1993 1998 cmd = '%sipmagic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1994 1999 self.log(cmd,continue_prompt)
1995 2000 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1996 2001 return cmd
1997 2002
1998 2003 def handle_auto(self, line, continue_prompt=None,
1999 2004 pre=None,iFun=None,theRest=None,obj=None):
2000 2005 """Hande lines which can be auto-executed, quoting if requested."""
2001 2006
2002 2007 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2003 2008
2004 2009 # This should only be active for single-line input!
2005 2010 if continue_prompt:
2006 2011 self.log(line,continue_prompt)
2007 2012 return line
2008 2013
2009 2014 auto_rewrite = True
2010 2015 if pre == self.ESC_QUOTE:
2011 2016 # Auto-quote splitting on whitespace
2012 2017 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2013 2018 elif pre == self.ESC_QUOTE2:
2014 2019 # Auto-quote whole string
2015 2020 newcmd = '%s("%s")' % (iFun,theRest)
2016 2021 else:
2017 2022 # Auto-paren.
2018 2023 # We only apply it to argument-less calls if the autocall
2019 2024 # parameter is set to 2. We only need to check that autocall is <
2020 2025 # 2, since this function isn't called unless it's at least 1.
2021 2026 if not theRest and (self.rc.autocall < 2):
2022 2027 newcmd = '%s %s' % (iFun,theRest)
2023 2028 auto_rewrite = False
2024 2029 else:
2025 2030 if theRest.startswith('['):
2026 2031 if hasattr(obj,'__getitem__'):
2027 2032 # Don't autocall in this case: item access for an object
2028 2033 # which is BOTH callable and implements __getitem__.
2029 2034 newcmd = '%s %s' % (iFun,theRest)
2030 2035 auto_rewrite = False
2031 2036 else:
2032 2037 # if the object doesn't support [] access, go ahead and
2033 2038 # autocall
2034 2039 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2035 2040 elif theRest.endswith(';'):
2036 2041 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2037 2042 else:
2038 2043 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2039 2044
2040 2045 if auto_rewrite:
2041 2046 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2042 2047 # log what is now valid Python, not the actual user input (without the
2043 2048 # final newline)
2044 2049 self.log(newcmd,continue_prompt)
2045 2050 return newcmd
2046 2051
2047 2052 def handle_help(self, line, continue_prompt=None,
2048 2053 pre=None,iFun=None,theRest=None):
2049 2054 """Try to get some help for the object.
2050 2055
2051 2056 obj? or ?obj -> basic information.
2052 2057 obj?? or ??obj -> more details.
2053 2058 """
2054 2059
2055 2060 # We need to make sure that we don't process lines which would be
2056 2061 # otherwise valid python, such as "x=1 # what?"
2057 2062 try:
2058 2063 codeop.compile_command(line)
2059 2064 except SyntaxError:
2060 2065 # We should only handle as help stuff which is NOT valid syntax
2061 2066 if line[0]==self.ESC_HELP:
2062 2067 line = line[1:]
2063 2068 elif line[-1]==self.ESC_HELP:
2064 2069 line = line[:-1]
2065 2070 self.log('#?'+line)
2066 2071 if line:
2067 2072 self.magic_pinfo(line)
2068 2073 else:
2069 2074 page(self.usage,screen_lines=self.rc.screen_length)
2070 2075 return '' # Empty string is needed here!
2071 2076 except:
2072 2077 # Pass any other exceptions through to the normal handler
2073 2078 return self.handle_normal(line,continue_prompt)
2074 2079 else:
2075 2080 # If the code compiles ok, we should handle it normally
2076 2081 return self.handle_normal(line,continue_prompt)
2077 2082
2078 2083 def handle_emacs(self,line,continue_prompt=None,
2079 2084 pre=None,iFun=None,theRest=None):
2080 2085 """Handle input lines marked by python-mode."""
2081 2086
2082 2087 # Currently, nothing is done. Later more functionality can be added
2083 2088 # here if needed.
2084 2089
2085 2090 # The input cache shouldn't be updated
2086 2091
2087 2092 return line
2088 2093
2089 2094 def mktempfile(self,data=None):
2090 2095 """Make a new tempfile and return its filename.
2091 2096
2092 2097 This makes a call to tempfile.mktemp, but it registers the created
2093 2098 filename internally so ipython cleans it up at exit time.
2094 2099
2095 2100 Optional inputs:
2096 2101
2097 2102 - data(None): if data is given, it gets written out to the temp file
2098 2103 immediately, and the file is closed again."""
2099 2104
2100 2105 filename = tempfile.mktemp('.py','ipython_edit_')
2101 2106 self.tempfiles.append(filename)
2102 2107
2103 2108 if data:
2104 2109 tmp_file = open(filename,'w')
2105 2110 tmp_file.write(data)
2106 2111 tmp_file.close()
2107 2112 return filename
2108 2113
2109 2114 def write(self,data):
2110 2115 """Write a string to the default output"""
2111 2116 Term.cout.write(data)
2112 2117
2113 2118 def write_err(self,data):
2114 2119 """Write a string to the default error output"""
2115 2120 Term.cerr.write(data)
2116 2121
2117 2122 def exit(self):
2118 2123 """Handle interactive exit.
2119 2124
2120 2125 This method sets the exit_now attribute."""
2121 2126
2122 2127 if self.rc.confirm_exit:
2123 2128 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2124 2129 self.exit_now = True
2125 2130 else:
2126 2131 self.exit_now = True
2127 2132 return self.exit_now
2128 2133
2129 2134 def safe_execfile(self,fname,*where,**kw):
2130 2135 fname = os.path.expanduser(fname)
2131 2136
2132 2137 # find things also in current directory
2133 2138 dname = os.path.dirname(fname)
2134 2139 if not sys.path.count(dname):
2135 2140 sys.path.append(dname)
2136 2141
2137 2142 try:
2138 2143 xfile = open(fname)
2139 2144 except:
2140 2145 print >> Term.cerr, \
2141 2146 'Could not open file <%s> for safe execution.' % fname
2142 2147 return None
2143 2148
2144 2149 kw.setdefault('islog',0)
2145 2150 kw.setdefault('quiet',1)
2146 2151 kw.setdefault('exit_ignore',0)
2147 2152 first = xfile.readline()
2148 2153 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2149 2154 xfile.close()
2150 2155 # line by line execution
2151 2156 if first.startswith(loghead) or kw['islog']:
2152 2157 print 'Loading log file <%s> one line at a time...' % fname
2153 2158 if kw['quiet']:
2154 2159 stdout_save = sys.stdout
2155 2160 sys.stdout = StringIO.StringIO()
2156 2161 try:
2157 2162 globs,locs = where[0:2]
2158 2163 except:
2159 2164 try:
2160 2165 globs = locs = where[0]
2161 2166 except:
2162 2167 globs = locs = globals()
2163 2168 badblocks = []
2164 2169
2165 2170 # we also need to identify indented blocks of code when replaying
2166 2171 # logs and put them together before passing them to an exec
2167 2172 # statement. This takes a bit of regexp and look-ahead work in the
2168 2173 # file. It's easiest if we swallow the whole thing in memory
2169 2174 # first, and manually walk through the lines list moving the
2170 2175 # counter ourselves.
2171 2176 indent_re = re.compile('\s+\S')
2172 2177 xfile = open(fname)
2173 2178 filelines = xfile.readlines()
2174 2179 xfile.close()
2175 2180 nlines = len(filelines)
2176 2181 lnum = 0
2177 2182 while lnum < nlines:
2178 2183 line = filelines[lnum]
2179 2184 lnum += 1
2180 2185 # don't re-insert logger status info into cache
2181 2186 if line.startswith('#log#'):
2182 2187 continue
2183 2188 else:
2184 2189 # build a block of code (maybe a single line) for execution
2185 2190 block = line
2186 2191 try:
2187 2192 next = filelines[lnum] # lnum has already incremented
2188 2193 except:
2189 2194 next = None
2190 2195 while next and indent_re.match(next):
2191 2196 block += next
2192 2197 lnum += 1
2193 2198 try:
2194 2199 next = filelines[lnum]
2195 2200 except:
2196 2201 next = None
2197 2202 # now execute the block of one or more lines
2198 2203 try:
2199 2204 exec block in globs,locs
2200 2205 except SystemExit:
2201 2206 pass
2202 2207 except:
2203 2208 badblocks.append(block.rstrip())
2204 2209 if kw['quiet']: # restore stdout
2205 2210 sys.stdout.close()
2206 2211 sys.stdout = stdout_save
2207 2212 print 'Finished replaying log file <%s>' % fname
2208 2213 if badblocks:
2209 2214 print >> sys.stderr, ('\nThe following lines/blocks in file '
2210 2215 '<%s> reported errors:' % fname)
2211 2216
2212 2217 for badline in badblocks:
2213 2218 print >> sys.stderr, badline
2214 2219 else: # regular file execution
2215 2220 try:
2216 2221 execfile(fname,*where)
2217 2222 except SyntaxError:
2218 2223 etype,evalue = sys.exc_info()[:2]
2219 2224 self.SyntaxTB(etype,evalue,[])
2220 2225 warn('Failure executing file: <%s>' % fname)
2221 2226 except SystemExit,status:
2222 2227 if not kw['exit_ignore']:
2223 2228 self.InteractiveTB()
2224 2229 warn('Failure executing file: <%s>' % fname)
2225 2230 except:
2226 2231 self.InteractiveTB()
2227 2232 warn('Failure executing file: <%s>' % fname)
2228 2233
2229 2234 #************************* end of file <iplib.py> *****************************
@@ -1,5041 +1,5066 b''
1 1 2006-01-24 Ville Vainio <vivainio@gmail.com>
2 2
3 3 * iplib.py, hooks.py: 'result_display' hook can return a non-None
4 4 value to manipulate resulting history entry.
5 5
6 6 * ipapi.py: Moved TryNext here from hooks.py, added
7 7 is_ipython_session() to determine whether we are running
8 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 35 2006-01-23 Ville Vainio <vivainio@gmail.com>
11 36
12 37 * Added %cpaste magic for pasting python code
13 38
14 39 2006-01-22 Ville Vainio <vivainio@gmail.com>
15 40
16 41 * Merge from branches/0.7.1 into trunk, revs 1052-1057
17 42
18 43 * Versionstring = 0.7.2.svn
19 44
20 45 * eggsetup.py: A separate script for constructing eggs, creates
21 46 proper launch scripts even on Windows (an .exe file in
22 47 \python24\scripts).
23 48
24 49 * ipapi.py: launch_new_instance, launch entry point needed for the
25 50 egg.
26 51
27 52 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
28 53
29 54 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
30 55 %pfile foo would print the file for foo even if it was a binary.
31 56 Now, extensions '.so' and '.dll' are skipped.
32 57
33 58 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
34 59 bug, where macros would fail in all threaded modes. I'm not 100%
35 60 sure, so I'm going to put out an rc instead of making a release
36 61 today, and wait for feedback for at least a few days.
37 62
38 63 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
39 64 it...) the handling of pasting external code with autoindent on.
40 65 To get out of a multiline input, the rule will appear for most
41 66 users unchanged: two blank lines or change the indent level
42 67 proposed by IPython. But there is a twist now: you can
43 68 add/subtract only *one or two spaces*. If you add/subtract three
44 69 or more (unless you completely delete the line), IPython will
45 70 accept that line, and you'll need to enter a second one of pure
46 71 whitespace. I know it sounds complicated, but I can't find a
47 72 different solution that covers all the cases, with the right
48 73 heuristics. Hopefully in actual use, nobody will really notice
49 74 all these strange rules and things will 'just work'.
50 75
51 76 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
52 77
53 78 * IPython/iplib.py (interact): catch exceptions which can be
54 79 triggered asynchronously by signal handlers. Thanks to an
55 80 automatic crash report, submitted by Colin Kingsley
56 81 <tercel-AT-gentoo.org>.
57 82
58 83 2006-01-20 Ville Vainio <vivainio@gmail.com>
59 84
60 85 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
61 86 (%rehashdir, very useful, try it out) of how to extend ipython
62 87 with new magics. Also added Extensions dir to pythonpath to make
63 88 importing extensions easy.
64 89
65 90 * %store now complains when trying to store interactively declared
66 91 classes / instances of those classes.
67 92
68 93 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
69 94 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
70 95 if they exist, and ipy_user_conf.py with some defaults is created for
71 96 the user.
72 97
73 98 * Startup rehashing done by the config file, not InterpreterExec.
74 99 This means system commands are available even without selecting the
75 100 pysh profile. It's the sensible default after all.
76 101
77 102 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
78 103
79 104 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
80 105 multiline code with autoindent on working. But I am really not
81 106 sure, so this needs more testing. Will commit a debug-enabled
82 107 version for now, while I test it some more, so that Ville and
83 108 others may also catch any problems. Also made
84 109 self.indent_current_str() a method, to ensure that there's no
85 110 chance of the indent space count and the corresponding string
86 111 falling out of sync. All code needing the string should just call
87 112 the method.
88 113
89 114 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
90 115
91 116 * IPython/Magic.py (magic_edit): fix check for when users don't
92 117 save their output files, the try/except was in the wrong section.
93 118
94 119 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
95 120
96 121 * IPython/Magic.py (magic_run): fix __file__ global missing from
97 122 script's namespace when executed via %run. After a report by
98 123 Vivian.
99 124
100 125 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
101 126 when using python 2.4. The parent constructor changed in 2.4, and
102 127 we need to track it directly (we can't call it, as it messes up
103 128 readline and tab-completion inside our pdb would stop working).
104 129 After a bug report by R. Bernstein <rocky-AT-panix.com>.
105 130
106 131 2006-01-16 Ville Vainio <vivainio@gmail.com>
107 132
108 133 * Ipython/magic.py:Reverted back to old %edit functionality
109 134 that returns file contents on exit.
110 135
111 136 * IPython/path.py: Added Jason Orendorff's "path" module to
112 137 IPython tree, http://www.jorendorff.com/articles/python/path/.
113 138 You can get path objects conveniently through %sc, and !!, e.g.:
114 139 sc files=ls
115 140 for p in files.paths: # or files.p
116 141 print p,p.mtime
117 142
118 143 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
119 144 now work again without considering the exclusion regexp -
120 145 hence, things like ',foo my/path' turn to 'foo("my/path")'
121 146 instead of syntax error.
122 147
123 148
124 149 2006-01-14 Ville Vainio <vivainio@gmail.com>
125 150
126 151 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
127 152 ipapi decorators for python 2.4 users, options() provides access to rc
128 153 data.
129 154
130 155 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
131 156 as path separators (even on Linux ;-). Space character after
132 157 backslash (as yielded by tab completer) is still space;
133 158 "%cd long\ name" works as expected.
134 159
135 160 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
136 161 as "chain of command", with priority. API stays the same,
137 162 TryNext exception raised by a hook function signals that
138 163 current hook failed and next hook should try handling it, as
139 164 suggested by Walter Dörwald <walter@livinglogic.de>. Walter also
140 165 requested configurable display hook, which is now implemented.
141 166
142 167 2006-01-13 Ville Vainio <vivainio@gmail.com>
143 168
144 169 * IPython/platutils*.py: platform specific utility functions,
145 170 so far only set_term_title is implemented (change terminal
146 171 label in windowing systems). %cd now changes the title to
147 172 current dir.
148 173
149 174 * IPython/Release.py: Added myself to "authors" list,
150 175 had to create new files.
151 176
152 177 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
153 178 shell escape; not a known bug but had potential to be one in the
154 179 future.
155 180
156 181 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
157 182 extension API for IPython! See the module for usage example. Fix
158 183 OInspect for docstring-less magic functions.
159 184
160 185
161 186 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
162 187
163 188 * IPython/iplib.py (raw_input): temporarily deactivate all
164 189 attempts at allowing pasting of code with autoindent on. It
165 190 introduced bugs (reported by Prabhu) and I can't seem to find a
166 191 robust combination which works in all cases. Will have to revisit
167 192 later.
168 193
169 194 * IPython/genutils.py: remove isspace() function. We've dropped
170 195 2.2 compatibility, so it's OK to use the string method.
171 196
172 197 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
173 198
174 199 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
175 200 matching what NOT to autocall on, to include all python binary
176 201 operators (including things like 'and', 'or', 'is' and 'in').
177 202 Prompted by a bug report on 'foo & bar', but I realized we had
178 203 many more potential bug cases with other operators. The regexp is
179 204 self.re_exclude_auto, it's fairly commented.
180 205
181 206 2006-01-12 Ville Vainio <vivainio@gmail.com>
182 207
183 208 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
184 209 Prettified and hardened string/backslash quoting with ipsystem(),
185 210 ipalias() and ipmagic(). Now even \ characters are passed to
186 211 %magics, !shell escapes and aliases exactly as they are in the
187 212 ipython command line. Should improve backslash experience,
188 213 particularly in Windows (path delimiter for some commands that
189 214 won't understand '/'), but Unix benefits as well (regexps). %cd
190 215 magic still doesn't support backslash path delimiters, though. Also
191 216 deleted all pretense of supporting multiline command strings in
192 217 !system or %magic commands. Thanks to Jerry McRae for suggestions.
193 218
194 219 * doc/build_doc_instructions.txt added. Documentation on how to
195 220 use doc/update_manual.py, added yesterday. Both files contributed
196 221 by Jörgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
197 222 doc/*.sh for deprecation at a later date.
198 223
199 224 * /ipython.py Added ipython.py to root directory for
200 225 zero-installation (tar xzvf ipython.tgz; cd ipython; python
201 226 ipython.py) and development convenience (no need to kee doing
202 227 "setup.py install" between changes).
203 228
204 229 * Made ! and !! shell escapes work (again) in multiline expressions:
205 230 if 1:
206 231 !ls
207 232 !!ls
208 233
209 234 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
210 235
211 236 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
212 237 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
213 238 module in case-insensitive installation. Was causing crashes
214 239 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
215 240
216 241 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
217 242 <marienz-AT-gentoo.org>, closes
218 243 http://www.scipy.net/roundup/ipython/issue51.
219 244
220 245 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
221 246
222 247 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
223 248 problem of excessive CPU usage under *nix and keyboard lag under
224 249 win32.
225 250
226 251 2006-01-10 *** Released version 0.7.0
227 252
228 253 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
229 254
230 255 * IPython/Release.py (revision): tag version number to 0.7.0,
231 256 ready for release.
232 257
233 258 * IPython/Magic.py (magic_edit): Add print statement to %edit so
234 259 it informs the user of the name of the temp. file used. This can
235 260 help if you decide later to reuse that same file, so you know
236 261 where to copy the info from.
237 262
238 263 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
239 264
240 265 * setup_bdist_egg.py: little script to build an egg. Added
241 266 support in the release tools as well.
242 267
243 268 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
244 269
245 270 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
246 271 version selection (new -wxversion command line and ipythonrc
247 272 parameter). Patch contributed by Arnd Baecker
248 273 <arnd.baecker-AT-web.de>.
249 274
250 275 * IPython/iplib.py (embed_mainloop): fix tab-completion in
251 276 embedded instances, for variables defined at the interactive
252 277 prompt of the embedded ipython. Reported by Arnd.
253 278
254 279 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
255 280 it can be used as a (stateful) toggle, or with a direct parameter.
256 281
257 282 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
258 283 could be triggered in certain cases and cause the traceback
259 284 printer not to work.
260 285
261 286 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
262 287
263 288 * IPython/iplib.py (_should_recompile): Small fix, closes
264 289 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
265 290
266 291 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
267 292
268 293 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
269 294 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
270 295 Moad for help with tracking it down.
271 296
272 297 * IPython/iplib.py (handle_auto): fix autocall handling for
273 298 objects which support BOTH __getitem__ and __call__ (so that f [x]
274 299 is left alone, instead of becoming f([x]) automatically).
275 300
276 301 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
277 302 Ville's patch.
278 303
279 304 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
280 305
281 306 * IPython/iplib.py (handle_auto): changed autocall semantics to
282 307 include 'smart' mode, where the autocall transformation is NOT
283 308 applied if there are no arguments on the line. This allows you to
284 309 just type 'foo' if foo is a callable to see its internal form,
285 310 instead of having it called with no arguments (typically a
286 311 mistake). The old 'full' autocall still exists: for that, you
287 312 need to set the 'autocall' parameter to 2 in your ipythonrc file.
288 313
289 314 * IPython/completer.py (Completer.attr_matches): add
290 315 tab-completion support for Enthoughts' traits. After a report by
291 316 Arnd and a patch by Prabhu.
292 317
293 318 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
294 319
295 320 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
296 321 Schmolck's patch to fix inspect.getinnerframes().
297 322
298 323 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
299 324 for embedded instances, regarding handling of namespaces and items
300 325 added to the __builtin__ one. Multiple embedded instances and
301 326 recursive embeddings should work better now (though I'm not sure
302 327 I've got all the corner cases fixed, that code is a bit of a brain
303 328 twister).
304 329
305 330 * IPython/Magic.py (magic_edit): added support to edit in-memory
306 331 macros (automatically creates the necessary temp files). %edit
307 332 also doesn't return the file contents anymore, it's just noise.
308 333
309 334 * IPython/completer.py (Completer.attr_matches): revert change to
310 335 complete only on attributes listed in __all__. I realized it
311 336 cripples the tab-completion system as a tool for exploring the
312 337 internals of unknown libraries (it renders any non-__all__
313 338 attribute off-limits). I got bit by this when trying to see
314 339 something inside the dis module.
315 340
316 341 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
317 342
318 343 * IPython/iplib.py (InteractiveShell.__init__): add .meta
319 344 namespace for users and extension writers to hold data in. This
320 345 follows the discussion in
321 346 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
322 347
323 348 * IPython/completer.py (IPCompleter.complete): small patch to help
324 349 tab-completion under Emacs, after a suggestion by John Barnard
325 350 <barnarj-AT-ccf.org>.
326 351
327 352 * IPython/Magic.py (Magic.extract_input_slices): added support for
328 353 the slice notation in magics to use N-M to represent numbers N...M
329 354 (closed endpoints). This is used by %macro and %save.
330 355
331 356 * IPython/completer.py (Completer.attr_matches): for modules which
332 357 define __all__, complete only on those. After a patch by Jeffrey
333 358 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
334 359 speed up this routine.
335 360
336 361 * IPython/Logger.py (Logger.log): fix a history handling bug. I
337 362 don't know if this is the end of it, but the behavior now is
338 363 certainly much more correct. Note that coupled with macros,
339 364 slightly surprising (at first) behavior may occur: a macro will in
340 365 general expand to multiple lines of input, so upon exiting, the
341 366 in/out counters will both be bumped by the corresponding amount
342 367 (as if the macro's contents had been typed interactively). Typing
343 368 %hist will reveal the intermediate (silently processed) lines.
344 369
345 370 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
346 371 pickle to fail (%run was overwriting __main__ and not restoring
347 372 it, but pickle relies on __main__ to operate).
348 373
349 374 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
350 375 using properties, but forgot to make the main InteractiveShell
351 376 class a new-style class. Properties fail silently, and
352 377 misteriously, with old-style class (getters work, but
353 378 setters don't do anything).
354 379
355 380 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
356 381
357 382 * IPython/Magic.py (magic_history): fix history reporting bug (I
358 383 know some nasties are still there, I just can't seem to find a
359 384 reproducible test case to track them down; the input history is
360 385 falling out of sync...)
361 386
362 387 * IPython/iplib.py (handle_shell_escape): fix bug where both
363 388 aliases and system accesses where broken for indented code (such
364 389 as loops).
365 390
366 391 * IPython/genutils.py (shell): fix small but critical bug for
367 392 win32 system access.
368 393
369 394 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
370 395
371 396 * IPython/iplib.py (showtraceback): remove use of the
372 397 sys.last_{type/value/traceback} structures, which are non
373 398 thread-safe.
374 399 (_prefilter): change control flow to ensure that we NEVER
375 400 introspect objects when autocall is off. This will guarantee that
376 401 having an input line of the form 'x.y', where access to attribute
377 402 'y' has side effects, doesn't trigger the side effect TWICE. It
378 403 is important to note that, with autocall on, these side effects
379 404 can still happen.
380 405 (ipsystem): new builtin, to complete the ip{magic/alias/system}
381 406 trio. IPython offers these three kinds of special calls which are
382 407 not python code, and it's a good thing to have their call method
383 408 be accessible as pure python functions (not just special syntax at
384 409 the command line). It gives us a better internal implementation
385 410 structure, as well as exposing these for user scripting more
386 411 cleanly.
387 412
388 413 * IPython/macro.py (Macro.__init__): moved macros to a standalone
389 414 file. Now that they'll be more likely to be used with the
390 415 persistance system (%store), I want to make sure their module path
391 416 doesn't change in the future, so that we don't break things for
392 417 users' persisted data.
393 418
394 419 * IPython/iplib.py (autoindent_update): move indentation
395 420 management into the _text_ processing loop, not the keyboard
396 421 interactive one. This is necessary to correctly process non-typed
397 422 multiline input (such as macros).
398 423
399 424 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
400 425 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
401 426 which was producing problems in the resulting manual.
402 427 (magic_whos): improve reporting of instances (show their class,
403 428 instead of simply printing 'instance' which isn't terribly
404 429 informative).
405 430
406 431 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
407 432 (minor mods) to support network shares under win32.
408 433
409 434 * IPython/winconsole.py (get_console_size): add new winconsole
410 435 module and fixes to page_dumb() to improve its behavior under
411 436 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
412 437
413 438 * IPython/Magic.py (Macro): simplified Macro class to just
414 439 subclass list. We've had only 2.2 compatibility for a very long
415 440 time, yet I was still avoiding subclassing the builtin types. No
416 441 more (I'm also starting to use properties, though I won't shift to
417 442 2.3-specific features quite yet).
418 443 (magic_store): added Ville's patch for lightweight variable
419 444 persistence, after a request on the user list by Matt Wilkie
420 445 <maphew-AT-gmail.com>. The new %store magic's docstring has full
421 446 details.
422 447
423 448 * IPython/iplib.py (InteractiveShell.post_config_initialization):
424 449 changed the default logfile name from 'ipython.log' to
425 450 'ipython_log.py'. These logs are real python files, and now that
426 451 we have much better multiline support, people are more likely to
427 452 want to use them as such. Might as well name them correctly.
428 453
429 454 * IPython/Magic.py: substantial cleanup. While we can't stop
430 455 using magics as mixins, due to the existing customizations 'out
431 456 there' which rely on the mixin naming conventions, at least I
432 457 cleaned out all cross-class name usage. So once we are OK with
433 458 breaking compatibility, the two systems can be separated.
434 459
435 460 * IPython/Logger.py: major cleanup. This one is NOT a mixin
436 461 anymore, and the class is a fair bit less hideous as well. New
437 462 features were also introduced: timestamping of input, and logging
438 463 of output results. These are user-visible with the -t and -o
439 464 options to %logstart. Closes
440 465 http://www.scipy.net/roundup/ipython/issue11 and a request by
441 466 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
442 467
443 468 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
444 469
445 470 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
446 471 better hadnle backslashes in paths. See the thread 'More Windows
447 472 questions part 2 - \/ characters revisited' on the iypthon user
448 473 list:
449 474 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
450 475
451 476 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
452 477
453 478 (InteractiveShell.__init__): change threaded shells to not use the
454 479 ipython crash handler. This was causing more problems than not,
455 480 as exceptions in the main thread (GUI code, typically) would
456 481 always show up as a 'crash', when they really weren't.
457 482
458 483 The colors and exception mode commands (%colors/%xmode) have been
459 484 synchronized to also take this into account, so users can get
460 485 verbose exceptions for their threaded code as well. I also added
461 486 support for activating pdb inside this exception handler as well,
462 487 so now GUI authors can use IPython's enhanced pdb at runtime.
463 488
464 489 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
465 490 true by default, and add it to the shipped ipythonrc file. Since
466 491 this asks the user before proceeding, I think it's OK to make it
467 492 true by default.
468 493
469 494 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
470 495 of the previous special-casing of input in the eval loop. I think
471 496 this is cleaner, as they really are commands and shouldn't have
472 497 a special role in the middle of the core code.
473 498
474 499 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
475 500
476 501 * IPython/iplib.py (edit_syntax_error): added support for
477 502 automatically reopening the editor if the file had a syntax error
478 503 in it. Thanks to scottt who provided the patch at:
479 504 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
480 505 version committed).
481 506
482 507 * IPython/iplib.py (handle_normal): add suport for multi-line
483 508 input with emtpy lines. This fixes
484 509 http://www.scipy.net/roundup/ipython/issue43 and a similar
485 510 discussion on the user list.
486 511
487 512 WARNING: a behavior change is necessarily introduced to support
488 513 blank lines: now a single blank line with whitespace does NOT
489 514 break the input loop, which means that when autoindent is on, by
490 515 default hitting return on the next (indented) line does NOT exit.
491 516
492 517 Instead, to exit a multiline input you can either have:
493 518
494 519 - TWO whitespace lines (just hit return again), or
495 520 - a single whitespace line of a different length than provided
496 521 by the autoindent (add or remove a space).
497 522
498 523 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
499 524 module to better organize all readline-related functionality.
500 525 I've deleted FlexCompleter and put all completion clases here.
501 526
502 527 * IPython/iplib.py (raw_input): improve indentation management.
503 528 It is now possible to paste indented code with autoindent on, and
504 529 the code is interpreted correctly (though it still looks bad on
505 530 screen, due to the line-oriented nature of ipython).
506 531 (MagicCompleter.complete): change behavior so that a TAB key on an
507 532 otherwise empty line actually inserts a tab, instead of completing
508 533 on the entire global namespace. This makes it easier to use the
509 534 TAB key for indentation. After a request by Hans Meine
510 535 <hans_meine-AT-gmx.net>
511 536 (_prefilter): add support so that typing plain 'exit' or 'quit'
512 537 does a sensible thing. Originally I tried to deviate as little as
513 538 possible from the default python behavior, but even that one may
514 539 change in this direction (thread on python-dev to that effect).
515 540 Regardless, ipython should do the right thing even if CPython's
516 541 '>>>' prompt doesn't.
517 542 (InteractiveShell): removed subclassing code.InteractiveConsole
518 543 class. By now we'd overridden just about all of its methods: I've
519 544 copied the remaining two over, and now ipython is a standalone
520 545 class. This will provide a clearer picture for the chainsaw
521 546 branch refactoring.
522 547
523 548 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
524 549
525 550 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
526 551 failures for objects which break when dir() is called on them.
527 552
528 553 * IPython/FlexCompleter.py (Completer.__init__): Added support for
529 554 distinct local and global namespaces in the completer API. This
530 555 change allows us top properly handle completion with distinct
531 556 scopes, including in embedded instances (this had never really
532 557 worked correctly).
533 558
534 559 Note: this introduces a change in the constructor for
535 560 MagicCompleter, as a new global_namespace parameter is now the
536 561 second argument (the others were bumped one position).
537 562
538 563 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
539 564
540 565 * IPython/iplib.py (embed_mainloop): fix tab-completion in
541 566 embedded instances (which can be done now thanks to Vivian's
542 567 frame-handling fixes for pdb).
543 568 (InteractiveShell.__init__): Fix namespace handling problem in
544 569 embedded instances. We were overwriting __main__ unconditionally,
545 570 and this should only be done for 'full' (non-embedded) IPython;
546 571 embedded instances must respect the caller's __main__. Thanks to
547 572 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
548 573
549 574 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
550 575
551 576 * setup.py: added download_url to setup(). This registers the
552 577 download address at PyPI, which is not only useful to humans
553 578 browsing the site, but is also picked up by setuptools (the Eggs
554 579 machinery). Thanks to Ville and R. Kern for the info/discussion
555 580 on this.
556 581
557 582 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
558 583
559 584 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
560 585 This brings a lot of nice functionality to the pdb mode, which now
561 586 has tab-completion, syntax highlighting, and better stack handling
562 587 than before. Many thanks to Vivian De Smedt
563 588 <vivian-AT-vdesmedt.com> for the original patches.
564 589
565 590 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
566 591
567 592 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
568 593 sequence to consistently accept the banner argument. The
569 594 inconsistency was tripping SAGE, thanks to Gary Zablackis
570 595 <gzabl-AT-yahoo.com> for the report.
571 596
572 597 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
573 598
574 599 * IPython/iplib.py (InteractiveShell.post_config_initialization):
575 600 Fix bug where a naked 'alias' call in the ipythonrc file would
576 601 cause a crash. Bug reported by Jorgen Stenarson.
577 602
578 603 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
579 604
580 605 * IPython/ipmaker.py (make_IPython): cleanups which should improve
581 606 startup time.
582 607
583 608 * IPython/iplib.py (runcode): my globals 'fix' for embedded
584 609 instances had introduced a bug with globals in normal code. Now
585 610 it's working in all cases.
586 611
587 612 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
588 613 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
589 614 has been introduced to set the default case sensitivity of the
590 615 searches. Users can still select either mode at runtime on a
591 616 per-search basis.
592 617
593 618 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
594 619
595 620 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
596 621 attributes in wildcard searches for subclasses. Modified version
597 622 of a patch by Jorgen.
598 623
599 624 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
600 625
601 626 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
602 627 embedded instances. I added a user_global_ns attribute to the
603 628 InteractiveShell class to handle this.
604 629
605 630 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
606 631
607 632 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
608 633 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
609 634 (reported under win32, but may happen also in other platforms).
610 635 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
611 636
612 637 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
613 638
614 639 * IPython/Magic.py (magic_psearch): new support for wildcard
615 640 patterns. Now, typing ?a*b will list all names which begin with a
616 641 and end in b, for example. The %psearch magic has full
617 642 docstrings. Many thanks to Jörgen Stenarson
618 643 <jorgen.stenarson-AT-bostream.nu>, author of the patches
619 644 implementing this functionality.
620 645
621 646 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
622 647
623 648 * Manual: fixed long-standing annoyance of double-dashes (as in
624 649 --prefix=~, for example) being stripped in the HTML version. This
625 650 is a latex2html bug, but a workaround was provided. Many thanks
626 651 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
627 652 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
628 653 rolling. This seemingly small issue had tripped a number of users
629 654 when first installing, so I'm glad to see it gone.
630 655
631 656 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
632 657
633 658 * IPython/Extensions/numeric_formats.py: fix missing import,
634 659 reported by Stephen Walton.
635 660
636 661 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
637 662
638 663 * IPython/demo.py: finish demo module, fully documented now.
639 664
640 665 * IPython/genutils.py (file_read): simple little utility to read a
641 666 file and ensure it's closed afterwards.
642 667
643 668 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
644 669
645 670 * IPython/demo.py (Demo.__init__): added support for individually
646 671 tagging blocks for automatic execution.
647 672
648 673 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
649 674 syntax-highlighted python sources, requested by John.
650 675
651 676 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
652 677
653 678 * IPython/demo.py (Demo.again): fix bug where again() blocks after
654 679 finishing.
655 680
656 681 * IPython/genutils.py (shlex_split): moved from Magic to here,
657 682 where all 2.2 compatibility stuff lives. I needed it for demo.py.
658 683
659 684 * IPython/demo.py (Demo.__init__): added support for silent
660 685 blocks, improved marks as regexps, docstrings written.
661 686 (Demo.__init__): better docstring, added support for sys.argv.
662 687
663 688 * IPython/genutils.py (marquee): little utility used by the demo
664 689 code, handy in general.
665 690
666 691 * IPython/demo.py (Demo.__init__): new class for interactive
667 692 demos. Not documented yet, I just wrote it in a hurry for
668 693 scipy'05. Will docstring later.
669 694
670 695 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
671 696
672 697 * IPython/Shell.py (sigint_handler): Drastic simplification which
673 698 also seems to make Ctrl-C work correctly across threads! This is
674 699 so simple, that I can't beleive I'd missed it before. Needs more
675 700 testing, though.
676 701 (KBINT): Never mind, revert changes. I'm sure I'd tried something
677 702 like this before...
678 703
679 704 * IPython/genutils.py (get_home_dir): add protection against
680 705 non-dirs in win32 registry.
681 706
682 707 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
683 708 bug where dict was mutated while iterating (pysh crash).
684 709
685 710 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
686 711
687 712 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
688 713 spurious newlines added by this routine. After a report by
689 714 F. Mantegazza.
690 715
691 716 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
692 717
693 718 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
694 719 calls. These were a leftover from the GTK 1.x days, and can cause
695 720 problems in certain cases (after a report by John Hunter).
696 721
697 722 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
698 723 os.getcwd() fails at init time. Thanks to patch from David Remahl
699 724 <chmod007-AT-mac.com>.
700 725 (InteractiveShell.__init__): prevent certain special magics from
701 726 being shadowed by aliases. Closes
702 727 http://www.scipy.net/roundup/ipython/issue41.
703 728
704 729 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
705 730
706 731 * IPython/iplib.py (InteractiveShell.complete): Added new
707 732 top-level completion method to expose the completion mechanism
708 733 beyond readline-based environments.
709 734
710 735 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
711 736
712 737 * tools/ipsvnc (svnversion): fix svnversion capture.
713 738
714 739 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
715 740 attribute to self, which was missing. Before, it was set by a
716 741 routine which in certain cases wasn't being called, so the
717 742 instance could end up missing the attribute. This caused a crash.
718 743 Closes http://www.scipy.net/roundup/ipython/issue40.
719 744
720 745 2005-08-16 Fernando Perez <fperez@colorado.edu>
721 746
722 747 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
723 748 contains non-string attribute. Closes
724 749 http://www.scipy.net/roundup/ipython/issue38.
725 750
726 751 2005-08-14 Fernando Perez <fperez@colorado.edu>
727 752
728 753 * tools/ipsvnc: Minor improvements, to add changeset info.
729 754
730 755 2005-08-12 Fernando Perez <fperez@colorado.edu>
731 756
732 757 * IPython/iplib.py (runsource): remove self.code_to_run_src
733 758 attribute. I realized this is nothing more than
734 759 '\n'.join(self.buffer), and having the same data in two different
735 760 places is just asking for synchronization bugs. This may impact
736 761 people who have custom exception handlers, so I need to warn
737 762 ipython-dev about it (F. Mantegazza may use them).
738 763
739 764 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
740 765
741 766 * IPython/genutils.py: fix 2.2 compatibility (generators)
742 767
743 768 2005-07-18 Fernando Perez <fperez@colorado.edu>
744 769
745 770 * IPython/genutils.py (get_home_dir): fix to help users with
746 771 invalid $HOME under win32.
747 772
748 773 2005-07-17 Fernando Perez <fperez@colorado.edu>
749 774
750 775 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
751 776 some old hacks and clean up a bit other routines; code should be
752 777 simpler and a bit faster.
753 778
754 779 * IPython/iplib.py (interact): removed some last-resort attempts
755 780 to survive broken stdout/stderr. That code was only making it
756 781 harder to abstract out the i/o (necessary for gui integration),
757 782 and the crashes it could prevent were extremely rare in practice
758 783 (besides being fully user-induced in a pretty violent manner).
759 784
760 785 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
761 786 Nothing major yet, but the code is simpler to read; this should
762 787 make it easier to do more serious modifications in the future.
763 788
764 789 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
765 790 which broke in .15 (thanks to a report by Ville).
766 791
767 792 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
768 793 be quite correct, I know next to nothing about unicode). This
769 794 will allow unicode strings to be used in prompts, amongst other
770 795 cases. It also will prevent ipython from crashing when unicode
771 796 shows up unexpectedly in many places. If ascii encoding fails, we
772 797 assume utf_8. Currently the encoding is not a user-visible
773 798 setting, though it could be made so if there is demand for it.
774 799
775 800 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
776 801
777 802 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
778 803
779 804 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
780 805
781 806 * IPython/genutils.py: Add 2.2 compatibility here, so all other
782 807 code can work transparently for 2.2/2.3.
783 808
784 809 2005-07-16 Fernando Perez <fperez@colorado.edu>
785 810
786 811 * IPython/ultraTB.py (ExceptionColors): Make a global variable
787 812 out of the color scheme table used for coloring exception
788 813 tracebacks. This allows user code to add new schemes at runtime.
789 814 This is a minimally modified version of the patch at
790 815 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
791 816 for the contribution.
792 817
793 818 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
794 819 slightly modified version of the patch in
795 820 http://www.scipy.net/roundup/ipython/issue34, which also allows me
796 821 to remove the previous try/except solution (which was costlier).
797 822 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
798 823
799 824 2005-06-08 Fernando Perez <fperez@colorado.edu>
800 825
801 826 * IPython/iplib.py (write/write_err): Add methods to abstract all
802 827 I/O a bit more.
803 828
804 829 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
805 830 warning, reported by Aric Hagberg, fix by JD Hunter.
806 831
807 832 2005-06-02 *** Released version 0.6.15
808 833
809 834 2005-06-01 Fernando Perez <fperez@colorado.edu>
810 835
811 836 * IPython/iplib.py (MagicCompleter.file_matches): Fix
812 837 tab-completion of filenames within open-quoted strings. Note that
813 838 this requires that in ~/.ipython/ipythonrc, users change the
814 839 readline delimiters configuration to read:
815 840
816 841 readline_remove_delims -/~
817 842
818 843
819 844 2005-05-31 *** Released version 0.6.14
820 845
821 846 2005-05-29 Fernando Perez <fperez@colorado.edu>
822 847
823 848 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
824 849 with files not on the filesystem. Reported by Eliyahu Sandler
825 850 <eli@gondolin.net>
826 851
827 852 2005-05-22 Fernando Perez <fperez@colorado.edu>
828 853
829 854 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
830 855 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
831 856
832 857 2005-05-19 Fernando Perez <fperez@colorado.edu>
833 858
834 859 * IPython/iplib.py (safe_execfile): close a file which could be
835 860 left open (causing problems in win32, which locks open files).
836 861 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
837 862
838 863 2005-05-18 Fernando Perez <fperez@colorado.edu>
839 864
840 865 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
841 866 keyword arguments correctly to safe_execfile().
842 867
843 868 2005-05-13 Fernando Perez <fperez@colorado.edu>
844 869
845 870 * ipython.1: Added info about Qt to manpage, and threads warning
846 871 to usage page (invoked with --help).
847 872
848 873 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
849 874 new matcher (it goes at the end of the priority list) to do
850 875 tab-completion on named function arguments. Submitted by George
851 876 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
852 877 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
853 878 for more details.
854 879
855 880 * IPython/Magic.py (magic_run): Added new -e flag to ignore
856 881 SystemExit exceptions in the script being run. Thanks to a report
857 882 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
858 883 producing very annoying behavior when running unit tests.
859 884
860 885 2005-05-12 Fernando Perez <fperez@colorado.edu>
861 886
862 887 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
863 888 which I'd broken (again) due to a changed regexp. In the process,
864 889 added ';' as an escape to auto-quote the whole line without
865 890 splitting its arguments. Thanks to a report by Jerry McRae
866 891 <qrs0xyc02-AT-sneakemail.com>.
867 892
868 893 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
869 894 possible crashes caused by a TokenError. Reported by Ed Schofield
870 895 <schofield-AT-ftw.at>.
871 896
872 897 2005-05-06 Fernando Perez <fperez@colorado.edu>
873 898
874 899 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
875 900
876 901 2005-04-29 Fernando Perez <fperez@colorado.edu>
877 902
878 903 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
879 904 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
880 905 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
881 906 which provides support for Qt interactive usage (similar to the
882 907 existing one for WX and GTK). This had been often requested.
883 908
884 909 2005-04-14 *** Released version 0.6.13
885 910
886 911 2005-04-08 Fernando Perez <fperez@colorado.edu>
887 912
888 913 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
889 914 from _ofind, which gets called on almost every input line. Now,
890 915 we only try to get docstrings if they are actually going to be
891 916 used (the overhead of fetching unnecessary docstrings can be
892 917 noticeable for certain objects, such as Pyro proxies).
893 918
894 919 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
895 920 for completers. For some reason I had been passing them the state
896 921 variable, which completers never actually need, and was in
897 922 conflict with the rlcompleter API. Custom completers ONLY need to
898 923 take the text parameter.
899 924
900 925 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
901 926 work correctly in pysh. I've also moved all the logic which used
902 927 to be in pysh.py here, which will prevent problems with future
903 928 upgrades. However, this time I must warn users to update their
904 929 pysh profile to include the line
905 930
906 931 import_all IPython.Extensions.InterpreterExec
907 932
908 933 because otherwise things won't work for them. They MUST also
909 934 delete pysh.py and the line
910 935
911 936 execfile pysh.py
912 937
913 938 from their ipythonrc-pysh.
914 939
915 940 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
916 941 robust in the face of objects whose dir() returns non-strings
917 942 (which it shouldn't, but some broken libs like ITK do). Thanks to
918 943 a patch by John Hunter (implemented differently, though). Also
919 944 minor improvements by using .extend instead of + on lists.
920 945
921 946 * pysh.py:
922 947
923 948 2005-04-06 Fernando Perez <fperez@colorado.edu>
924 949
925 950 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
926 951 by default, so that all users benefit from it. Those who don't
927 952 want it can still turn it off.
928 953
929 954 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
930 955 config file, I'd forgotten about this, so users were getting it
931 956 off by default.
932 957
933 958 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
934 959 consistency. Now magics can be called in multiline statements,
935 960 and python variables can be expanded in magic calls via $var.
936 961 This makes the magic system behave just like aliases or !system
937 962 calls.
938 963
939 964 2005-03-28 Fernando Perez <fperez@colorado.edu>
940 965
941 966 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
942 967 expensive string additions for building command. Add support for
943 968 trailing ';' when autocall is used.
944 969
945 970 2005-03-26 Fernando Perez <fperez@colorado.edu>
946 971
947 972 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
948 973 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
949 974 ipython.el robust against prompts with any number of spaces
950 975 (including 0) after the ':' character.
951 976
952 977 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
953 978 continuation prompt, which misled users to think the line was
954 979 already indented. Closes debian Bug#300847, reported to me by
955 980 Norbert Tretkowski <tretkowski-AT-inittab.de>.
956 981
957 982 2005-03-23 Fernando Perez <fperez@colorado.edu>
958 983
959 984 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
960 985 properly aligned if they have embedded newlines.
961 986
962 987 * IPython/iplib.py (runlines): Add a public method to expose
963 988 IPython's code execution machinery, so that users can run strings
964 989 as if they had been typed at the prompt interactively.
965 990 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
966 991 methods which can call the system shell, but with python variable
967 992 expansion. The three such methods are: __IPYTHON__.system,
968 993 .getoutput and .getoutputerror. These need to be documented in a
969 994 'public API' section (to be written) of the manual.
970 995
971 996 2005-03-20 Fernando Perez <fperez@colorado.edu>
972 997
973 998 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
974 999 for custom exception handling. This is quite powerful, and it
975 1000 allows for user-installable exception handlers which can trap
976 1001 custom exceptions at runtime and treat them separately from
977 1002 IPython's default mechanisms. At the request of Frédéric
978 1003 Mantegazza <mantegazza-AT-ill.fr>.
979 1004 (InteractiveShell.set_custom_completer): public API function to
980 1005 add new completers at runtime.
981 1006
982 1007 2005-03-19 Fernando Perez <fperez@colorado.edu>
983 1008
984 1009 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
985 1010 allow objects which provide their docstrings via non-standard
986 1011 mechanisms (like Pyro proxies) to still be inspected by ipython's
987 1012 ? system.
988 1013
989 1014 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
990 1015 automatic capture system. I tried quite hard to make it work
991 1016 reliably, and simply failed. I tried many combinations with the
992 1017 subprocess module, but eventually nothing worked in all needed
993 1018 cases (not blocking stdin for the child, duplicating stdout
994 1019 without blocking, etc). The new %sc/%sx still do capture to these
995 1020 magical list/string objects which make shell use much more
996 1021 conveninent, so not all is lost.
997 1022
998 1023 XXX - FIX MANUAL for the change above!
999 1024
1000 1025 (runsource): I copied code.py's runsource() into ipython to modify
1001 1026 it a bit. Now the code object and source to be executed are
1002 1027 stored in ipython. This makes this info accessible to third-party
1003 1028 tools, like custom exception handlers. After a request by Frédéric
1004 1029 Mantegazza <mantegazza-AT-ill.fr>.
1005 1030
1006 1031 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1007 1032 history-search via readline (like C-p/C-n). I'd wanted this for a
1008 1033 long time, but only recently found out how to do it. For users
1009 1034 who already have their ipythonrc files made and want this, just
1010 1035 add:
1011 1036
1012 1037 readline_parse_and_bind "\e[A": history-search-backward
1013 1038 readline_parse_and_bind "\e[B": history-search-forward
1014 1039
1015 1040 2005-03-18 Fernando Perez <fperez@colorado.edu>
1016 1041
1017 1042 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1018 1043 LSString and SList classes which allow transparent conversions
1019 1044 between list mode and whitespace-separated string.
1020 1045 (magic_r): Fix recursion problem in %r.
1021 1046
1022 1047 * IPython/genutils.py (LSString): New class to be used for
1023 1048 automatic storage of the results of all alias/system calls in _o
1024 1049 and _e (stdout/err). These provide a .l/.list attribute which
1025 1050 does automatic splitting on newlines. This means that for most
1026 1051 uses, you'll never need to do capturing of output with %sc/%sx
1027 1052 anymore, since ipython keeps this always done for you. Note that
1028 1053 only the LAST results are stored, the _o/e variables are
1029 1054 overwritten on each call. If you need to save their contents
1030 1055 further, simply bind them to any other name.
1031 1056
1032 1057 2005-03-17 Fernando Perez <fperez@colorado.edu>
1033 1058
1034 1059 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1035 1060 prompt namespace handling.
1036 1061
1037 1062 2005-03-16 Fernando Perez <fperez@colorado.edu>
1038 1063
1039 1064 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1040 1065 classic prompts to be '>>> ' (final space was missing, and it
1041 1066 trips the emacs python mode).
1042 1067 (BasePrompt.__str__): Added safe support for dynamic prompt
1043 1068 strings. Now you can set your prompt string to be '$x', and the
1044 1069 value of x will be printed from your interactive namespace. The
1045 1070 interpolation syntax includes the full Itpl support, so
1046 1071 ${foo()+x+bar()} is a valid prompt string now, and the function
1047 1072 calls will be made at runtime.
1048 1073
1049 1074 2005-03-15 Fernando Perez <fperez@colorado.edu>
1050 1075
1051 1076 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1052 1077 avoid name clashes in pylab. %hist still works, it just forwards
1053 1078 the call to %history.
1054 1079
1055 1080 2005-03-02 *** Released version 0.6.12
1056 1081
1057 1082 2005-03-02 Fernando Perez <fperez@colorado.edu>
1058 1083
1059 1084 * IPython/iplib.py (handle_magic): log magic calls properly as
1060 1085 ipmagic() function calls.
1061 1086
1062 1087 * IPython/Magic.py (magic_time): Improved %time to support
1063 1088 statements and provide wall-clock as well as CPU time.
1064 1089
1065 1090 2005-02-27 Fernando Perez <fperez@colorado.edu>
1066 1091
1067 1092 * IPython/hooks.py: New hooks module, to expose user-modifiable
1068 1093 IPython functionality in a clean manner. For now only the editor
1069 1094 hook is actually written, and other thigns which I intend to turn
1070 1095 into proper hooks aren't yet there. The display and prefilter
1071 1096 stuff, for example, should be hooks. But at least now the
1072 1097 framework is in place, and the rest can be moved here with more
1073 1098 time later. IPython had had a .hooks variable for a long time for
1074 1099 this purpose, but I'd never actually used it for anything.
1075 1100
1076 1101 2005-02-26 Fernando Perez <fperez@colorado.edu>
1077 1102
1078 1103 * IPython/ipmaker.py (make_IPython): make the default ipython
1079 1104 directory be called _ipython under win32, to follow more the
1080 1105 naming peculiarities of that platform (where buggy software like
1081 1106 Visual Sourcesafe breaks with .named directories). Reported by
1082 1107 Ville Vainio.
1083 1108
1084 1109 2005-02-23 Fernando Perez <fperez@colorado.edu>
1085 1110
1086 1111 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1087 1112 auto_aliases for win32 which were causing problems. Users can
1088 1113 define the ones they personally like.
1089 1114
1090 1115 2005-02-21 Fernando Perez <fperez@colorado.edu>
1091 1116
1092 1117 * IPython/Magic.py (magic_time): new magic to time execution of
1093 1118 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1094 1119
1095 1120 2005-02-19 Fernando Perez <fperez@colorado.edu>
1096 1121
1097 1122 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1098 1123 into keys (for prompts, for example).
1099 1124
1100 1125 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1101 1126 prompts in case users want them. This introduces a small behavior
1102 1127 change: ipython does not automatically add a space to all prompts
1103 1128 anymore. To get the old prompts with a space, users should add it
1104 1129 manually to their ipythonrc file, so for example prompt_in1 should
1105 1130 now read 'In [\#]: ' instead of 'In [\#]:'.
1106 1131 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1107 1132 file) to control left-padding of secondary prompts.
1108 1133
1109 1134 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1110 1135 the profiler can't be imported. Fix for Debian, which removed
1111 1136 profile.py because of License issues. I applied a slightly
1112 1137 modified version of the original Debian patch at
1113 1138 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1114 1139
1115 1140 2005-02-17 Fernando Perez <fperez@colorado.edu>
1116 1141
1117 1142 * IPython/genutils.py (native_line_ends): Fix bug which would
1118 1143 cause improper line-ends under win32 b/c I was not opening files
1119 1144 in binary mode. Bug report and fix thanks to Ville.
1120 1145
1121 1146 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1122 1147 trying to catch spurious foo[1] autocalls. My fix actually broke
1123 1148 ',/' autoquote/call with explicit escape (bad regexp).
1124 1149
1125 1150 2005-02-15 *** Released version 0.6.11
1126 1151
1127 1152 2005-02-14 Fernando Perez <fperez@colorado.edu>
1128 1153
1129 1154 * IPython/background_jobs.py: New background job management
1130 1155 subsystem. This is implemented via a new set of classes, and
1131 1156 IPython now provides a builtin 'jobs' object for background job
1132 1157 execution. A convenience %bg magic serves as a lightweight
1133 1158 frontend for starting the more common type of calls. This was
1134 1159 inspired by discussions with B. Granger and the BackgroundCommand
1135 1160 class described in the book Python Scripting for Computational
1136 1161 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1137 1162 (although ultimately no code from this text was used, as IPython's
1138 1163 system is a separate implementation).
1139 1164
1140 1165 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1141 1166 to control the completion of single/double underscore names
1142 1167 separately. As documented in the example ipytonrc file, the
1143 1168 readline_omit__names variable can now be set to 2, to omit even
1144 1169 single underscore names. Thanks to a patch by Brian Wong
1145 1170 <BrianWong-AT-AirgoNetworks.Com>.
1146 1171 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1147 1172 be autocalled as foo([1]) if foo were callable. A problem for
1148 1173 things which are both callable and implement __getitem__.
1149 1174 (init_readline): Fix autoindentation for win32. Thanks to a patch
1150 1175 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1151 1176
1152 1177 2005-02-12 Fernando Perez <fperez@colorado.edu>
1153 1178
1154 1179 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1155 1180 which I had written long ago to sort out user error messages which
1156 1181 may occur during startup. This seemed like a good idea initially,
1157 1182 but it has proven a disaster in retrospect. I don't want to
1158 1183 change much code for now, so my fix is to set the internal 'debug'
1159 1184 flag to true everywhere, whose only job was precisely to control
1160 1185 this subsystem. This closes issue 28 (as well as avoiding all
1161 1186 sorts of strange hangups which occur from time to time).
1162 1187
1163 1188 2005-02-07 Fernando Perez <fperez@colorado.edu>
1164 1189
1165 1190 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1166 1191 previous call produced a syntax error.
1167 1192
1168 1193 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1169 1194 classes without constructor.
1170 1195
1171 1196 2005-02-06 Fernando Perez <fperez@colorado.edu>
1172 1197
1173 1198 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1174 1199 completions with the results of each matcher, so we return results
1175 1200 to the user from all namespaces. This breaks with ipython
1176 1201 tradition, but I think it's a nicer behavior. Now you get all
1177 1202 possible completions listed, from all possible namespaces (python,
1178 1203 filesystem, magics...) After a request by John Hunter
1179 1204 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1180 1205
1181 1206 2005-02-05 Fernando Perez <fperez@colorado.edu>
1182 1207
1183 1208 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1184 1209 the call had quote characters in it (the quotes were stripped).
1185 1210
1186 1211 2005-01-31 Fernando Perez <fperez@colorado.edu>
1187 1212
1188 1213 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1189 1214 Itpl.itpl() to make the code more robust against psyco
1190 1215 optimizations.
1191 1216
1192 1217 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1193 1218 of causing an exception. Quicker, cleaner.
1194 1219
1195 1220 2005-01-28 Fernando Perez <fperez@colorado.edu>
1196 1221
1197 1222 * scripts/ipython_win_post_install.py (install): hardcode
1198 1223 sys.prefix+'python.exe' as the executable path. It turns out that
1199 1224 during the post-installation run, sys.executable resolves to the
1200 1225 name of the binary installer! I should report this as a distutils
1201 1226 bug, I think. I updated the .10 release with this tiny fix, to
1202 1227 avoid annoying the lists further.
1203 1228
1204 1229 2005-01-27 *** Released version 0.6.10
1205 1230
1206 1231 2005-01-27 Fernando Perez <fperez@colorado.edu>
1207 1232
1208 1233 * IPython/numutils.py (norm): Added 'inf' as optional name for
1209 1234 L-infinity norm, included references to mathworld.com for vector
1210 1235 norm definitions.
1211 1236 (amin/amax): added amin/amax for array min/max. Similar to what
1212 1237 pylab ships with after the recent reorganization of names.
1213 1238 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1214 1239
1215 1240 * ipython.el: committed Alex's recent fixes and improvements.
1216 1241 Tested with python-mode from CVS, and it looks excellent. Since
1217 1242 python-mode hasn't released anything in a while, I'm temporarily
1218 1243 putting a copy of today's CVS (v 4.70) of python-mode in:
1219 1244 http://ipython.scipy.org/tmp/python-mode.el
1220 1245
1221 1246 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1222 1247 sys.executable for the executable name, instead of assuming it's
1223 1248 called 'python.exe' (the post-installer would have produced broken
1224 1249 setups on systems with a differently named python binary).
1225 1250
1226 1251 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1227 1252 references to os.linesep, to make the code more
1228 1253 platform-independent. This is also part of the win32 coloring
1229 1254 fixes.
1230 1255
1231 1256 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1232 1257 lines, which actually cause coloring bugs because the length of
1233 1258 the line is very difficult to correctly compute with embedded
1234 1259 escapes. This was the source of all the coloring problems under
1235 1260 Win32. I think that _finally_, Win32 users have a properly
1236 1261 working ipython in all respects. This would never have happened
1237 1262 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1238 1263
1239 1264 2005-01-26 *** Released version 0.6.9
1240 1265
1241 1266 2005-01-25 Fernando Perez <fperez@colorado.edu>
1242 1267
1243 1268 * setup.py: finally, we have a true Windows installer, thanks to
1244 1269 the excellent work of Viktor Ransmayr
1245 1270 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1246 1271 Windows users. The setup routine is quite a bit cleaner thanks to
1247 1272 this, and the post-install script uses the proper functions to
1248 1273 allow a clean de-installation using the standard Windows Control
1249 1274 Panel.
1250 1275
1251 1276 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1252 1277 environment variable under all OSes (including win32) if
1253 1278 available. This will give consistency to win32 users who have set
1254 1279 this variable for any reason. If os.environ['HOME'] fails, the
1255 1280 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1256 1281
1257 1282 2005-01-24 Fernando Perez <fperez@colorado.edu>
1258 1283
1259 1284 * IPython/numutils.py (empty_like): add empty_like(), similar to
1260 1285 zeros_like() but taking advantage of the new empty() Numeric routine.
1261 1286
1262 1287 2005-01-23 *** Released version 0.6.8
1263 1288
1264 1289 2005-01-22 Fernando Perez <fperez@colorado.edu>
1265 1290
1266 1291 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1267 1292 automatic show() calls. After discussing things with JDH, it
1268 1293 turns out there are too many corner cases where this can go wrong.
1269 1294 It's best not to try to be 'too smart', and simply have ipython
1270 1295 reproduce as much as possible the default behavior of a normal
1271 1296 python shell.
1272 1297
1273 1298 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1274 1299 line-splitting regexp and _prefilter() to avoid calling getattr()
1275 1300 on assignments. This closes
1276 1301 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1277 1302 readline uses getattr(), so a simple <TAB> keypress is still
1278 1303 enough to trigger getattr() calls on an object.
1279 1304
1280 1305 2005-01-21 Fernando Perez <fperez@colorado.edu>
1281 1306
1282 1307 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1283 1308 docstring under pylab so it doesn't mask the original.
1284 1309
1285 1310 2005-01-21 *** Released version 0.6.7
1286 1311
1287 1312 2005-01-21 Fernando Perez <fperez@colorado.edu>
1288 1313
1289 1314 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1290 1315 signal handling for win32 users in multithreaded mode.
1291 1316
1292 1317 2005-01-17 Fernando Perez <fperez@colorado.edu>
1293 1318
1294 1319 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1295 1320 instances with no __init__. After a crash report by Norbert Nemec
1296 1321 <Norbert-AT-nemec-online.de>.
1297 1322
1298 1323 2005-01-14 Fernando Perez <fperez@colorado.edu>
1299 1324
1300 1325 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1301 1326 names for verbose exceptions, when multiple dotted names and the
1302 1327 'parent' object were present on the same line.
1303 1328
1304 1329 2005-01-11 Fernando Perez <fperez@colorado.edu>
1305 1330
1306 1331 * IPython/genutils.py (flag_calls): new utility to trap and flag
1307 1332 calls in functions. I need it to clean up matplotlib support.
1308 1333 Also removed some deprecated code in genutils.
1309 1334
1310 1335 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1311 1336 that matplotlib scripts called with %run, which don't call show()
1312 1337 themselves, still have their plotting windows open.
1313 1338
1314 1339 2005-01-05 Fernando Perez <fperez@colorado.edu>
1315 1340
1316 1341 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1317 1342 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1318 1343
1319 1344 2004-12-19 Fernando Perez <fperez@colorado.edu>
1320 1345
1321 1346 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1322 1347 parent_runcode, which was an eyesore. The same result can be
1323 1348 obtained with Python's regular superclass mechanisms.
1324 1349
1325 1350 2004-12-17 Fernando Perez <fperez@colorado.edu>
1326 1351
1327 1352 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1328 1353 reported by Prabhu.
1329 1354 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1330 1355 sys.stderr) instead of explicitly calling sys.stderr. This helps
1331 1356 maintain our I/O abstractions clean, for future GUI embeddings.
1332 1357
1333 1358 * IPython/genutils.py (info): added new utility for sys.stderr
1334 1359 unified info message handling (thin wrapper around warn()).
1335 1360
1336 1361 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1337 1362 composite (dotted) names on verbose exceptions.
1338 1363 (VerboseTB.nullrepr): harden against another kind of errors which
1339 1364 Python's inspect module can trigger, and which were crashing
1340 1365 IPython. Thanks to a report by Marco Lombardi
1341 1366 <mlombard-AT-ma010192.hq.eso.org>.
1342 1367
1343 1368 2004-12-13 *** Released version 0.6.6
1344 1369
1345 1370 2004-12-12 Fernando Perez <fperez@colorado.edu>
1346 1371
1347 1372 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1348 1373 generated by pygtk upon initialization if it was built without
1349 1374 threads (for matplotlib users). After a crash reported by
1350 1375 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1351 1376
1352 1377 * IPython/ipmaker.py (make_IPython): fix small bug in the
1353 1378 import_some parameter for multiple imports.
1354 1379
1355 1380 * IPython/iplib.py (ipmagic): simplified the interface of
1356 1381 ipmagic() to take a single string argument, just as it would be
1357 1382 typed at the IPython cmd line.
1358 1383 (ipalias): Added new ipalias() with an interface identical to
1359 1384 ipmagic(). This completes exposing a pure python interface to the
1360 1385 alias and magic system, which can be used in loops or more complex
1361 1386 code where IPython's automatic line mangling is not active.
1362 1387
1363 1388 * IPython/genutils.py (timing): changed interface of timing to
1364 1389 simply run code once, which is the most common case. timings()
1365 1390 remains unchanged, for the cases where you want multiple runs.
1366 1391
1367 1392 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1368 1393 bug where Python2.2 crashes with exec'ing code which does not end
1369 1394 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1370 1395 before.
1371 1396
1372 1397 2004-12-10 Fernando Perez <fperez@colorado.edu>
1373 1398
1374 1399 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1375 1400 -t to -T, to accomodate the new -t flag in %run (the %run and
1376 1401 %prun options are kind of intermixed, and it's not easy to change
1377 1402 this with the limitations of python's getopt).
1378 1403
1379 1404 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1380 1405 the execution of scripts. It's not as fine-tuned as timeit.py,
1381 1406 but it works from inside ipython (and under 2.2, which lacks
1382 1407 timeit.py). Optionally a number of runs > 1 can be given for
1383 1408 timing very short-running code.
1384 1409
1385 1410 * IPython/genutils.py (uniq_stable): new routine which returns a
1386 1411 list of unique elements in any iterable, but in stable order of
1387 1412 appearance. I needed this for the ultraTB fixes, and it's a handy
1388 1413 utility.
1389 1414
1390 1415 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1391 1416 dotted names in Verbose exceptions. This had been broken since
1392 1417 the very start, now x.y will properly be printed in a Verbose
1393 1418 traceback, instead of x being shown and y appearing always as an
1394 1419 'undefined global'. Getting this to work was a bit tricky,
1395 1420 because by default python tokenizers are stateless. Saved by
1396 1421 python's ability to easily add a bit of state to an arbitrary
1397 1422 function (without needing to build a full-blown callable object).
1398 1423
1399 1424 Also big cleanup of this code, which had horrendous runtime
1400 1425 lookups of zillions of attributes for colorization. Moved all
1401 1426 this code into a few templates, which make it cleaner and quicker.
1402 1427
1403 1428 Printout quality was also improved for Verbose exceptions: one
1404 1429 variable per line, and memory addresses are printed (this can be
1405 1430 quite handy in nasty debugging situations, which is what Verbose
1406 1431 is for).
1407 1432
1408 1433 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1409 1434 the command line as scripts to be loaded by embedded instances.
1410 1435 Doing so has the potential for an infinite recursion if there are
1411 1436 exceptions thrown in the process. This fixes a strange crash
1412 1437 reported by Philippe MULLER <muller-AT-irit.fr>.
1413 1438
1414 1439 2004-12-09 Fernando Perez <fperez@colorado.edu>
1415 1440
1416 1441 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1417 1442 to reflect new names in matplotlib, which now expose the
1418 1443 matlab-compatible interface via a pylab module instead of the
1419 1444 'matlab' name. The new code is backwards compatible, so users of
1420 1445 all matplotlib versions are OK. Patch by J. Hunter.
1421 1446
1422 1447 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1423 1448 of __init__ docstrings for instances (class docstrings are already
1424 1449 automatically printed). Instances with customized docstrings
1425 1450 (indep. of the class) are also recognized and all 3 separate
1426 1451 docstrings are printed (instance, class, constructor). After some
1427 1452 comments/suggestions by J. Hunter.
1428 1453
1429 1454 2004-12-05 Fernando Perez <fperez@colorado.edu>
1430 1455
1431 1456 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1432 1457 warnings when tab-completion fails and triggers an exception.
1433 1458
1434 1459 2004-12-03 Fernando Perez <fperez@colorado.edu>
1435 1460
1436 1461 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1437 1462 be triggered when using 'run -p'. An incorrect option flag was
1438 1463 being set ('d' instead of 'D').
1439 1464 (manpage): fix missing escaped \- sign.
1440 1465
1441 1466 2004-11-30 *** Released version 0.6.5
1442 1467
1443 1468 2004-11-30 Fernando Perez <fperez@colorado.edu>
1444 1469
1445 1470 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1446 1471 setting with -d option.
1447 1472
1448 1473 * setup.py (docfiles): Fix problem where the doc glob I was using
1449 1474 was COMPLETELY BROKEN. It was giving the right files by pure
1450 1475 accident, but failed once I tried to include ipython.el. Note:
1451 1476 glob() does NOT allow you to do exclusion on multiple endings!
1452 1477
1453 1478 2004-11-29 Fernando Perez <fperez@colorado.edu>
1454 1479
1455 1480 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1456 1481 the manpage as the source. Better formatting & consistency.
1457 1482
1458 1483 * IPython/Magic.py (magic_run): Added new -d option, to run
1459 1484 scripts under the control of the python pdb debugger. Note that
1460 1485 this required changing the %prun option -d to -D, to avoid a clash
1461 1486 (since %run must pass options to %prun, and getopt is too dumb to
1462 1487 handle options with string values with embedded spaces). Thanks
1463 1488 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1464 1489 (magic_who_ls): added type matching to %who and %whos, so that one
1465 1490 can filter their output to only include variables of certain
1466 1491 types. Another suggestion by Matthew.
1467 1492 (magic_whos): Added memory summaries in kb and Mb for arrays.
1468 1493 (magic_who): Improve formatting (break lines every 9 vars).
1469 1494
1470 1495 2004-11-28 Fernando Perez <fperez@colorado.edu>
1471 1496
1472 1497 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1473 1498 cache when empty lines were present.
1474 1499
1475 1500 2004-11-24 Fernando Perez <fperez@colorado.edu>
1476 1501
1477 1502 * IPython/usage.py (__doc__): document the re-activated threading
1478 1503 options for WX and GTK.
1479 1504
1480 1505 2004-11-23 Fernando Perez <fperez@colorado.edu>
1481 1506
1482 1507 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1483 1508 the -wthread and -gthread options, along with a new -tk one to try
1484 1509 and coordinate Tk threading with wx/gtk. The tk support is very
1485 1510 platform dependent, since it seems to require Tcl and Tk to be
1486 1511 built with threads (Fedora1/2 appears NOT to have it, but in
1487 1512 Prabhu's Debian boxes it works OK). But even with some Tk
1488 1513 limitations, this is a great improvement.
1489 1514
1490 1515 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1491 1516 info in user prompts. Patch by Prabhu.
1492 1517
1493 1518 2004-11-18 Fernando Perez <fperez@colorado.edu>
1494 1519
1495 1520 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1496 1521 EOFErrors and bail, to avoid infinite loops if a non-terminating
1497 1522 file is fed into ipython. Patch submitted in issue 19 by user,
1498 1523 many thanks.
1499 1524
1500 1525 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1501 1526 autoquote/parens in continuation prompts, which can cause lots of
1502 1527 problems. Closes roundup issue 20.
1503 1528
1504 1529 2004-11-17 Fernando Perez <fperez@colorado.edu>
1505 1530
1506 1531 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1507 1532 reported as debian bug #280505. I'm not sure my local changelog
1508 1533 entry has the proper debian format (Jack?).
1509 1534
1510 1535 2004-11-08 *** Released version 0.6.4
1511 1536
1512 1537 2004-11-08 Fernando Perez <fperez@colorado.edu>
1513 1538
1514 1539 * IPython/iplib.py (init_readline): Fix exit message for Windows
1515 1540 when readline is active. Thanks to a report by Eric Jones
1516 1541 <eric-AT-enthought.com>.
1517 1542
1518 1543 2004-11-07 Fernando Perez <fperez@colorado.edu>
1519 1544
1520 1545 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1521 1546 sometimes seen by win2k/cygwin users.
1522 1547
1523 1548 2004-11-06 Fernando Perez <fperez@colorado.edu>
1524 1549
1525 1550 * IPython/iplib.py (interact): Change the handling of %Exit from
1526 1551 trying to propagate a SystemExit to an internal ipython flag.
1527 1552 This is less elegant than using Python's exception mechanism, but
1528 1553 I can't get that to work reliably with threads, so under -pylab
1529 1554 %Exit was hanging IPython. Cross-thread exception handling is
1530 1555 really a bitch. Thaks to a bug report by Stephen Walton
1531 1556 <stephen.walton-AT-csun.edu>.
1532 1557
1533 1558 2004-11-04 Fernando Perez <fperez@colorado.edu>
1534 1559
1535 1560 * IPython/iplib.py (raw_input_original): store a pointer to the
1536 1561 true raw_input to harden against code which can modify it
1537 1562 (wx.py.PyShell does this and would otherwise crash ipython).
1538 1563 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1539 1564
1540 1565 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1541 1566 Ctrl-C problem, which does not mess up the input line.
1542 1567
1543 1568 2004-11-03 Fernando Perez <fperez@colorado.edu>
1544 1569
1545 1570 * IPython/Release.py: Changed licensing to BSD, in all files.
1546 1571 (name): lowercase name for tarball/RPM release.
1547 1572
1548 1573 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1549 1574 use throughout ipython.
1550 1575
1551 1576 * IPython/Magic.py (Magic._ofind): Switch to using the new
1552 1577 OInspect.getdoc() function.
1553 1578
1554 1579 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1555 1580 of the line currently being canceled via Ctrl-C. It's extremely
1556 1581 ugly, but I don't know how to do it better (the problem is one of
1557 1582 handling cross-thread exceptions).
1558 1583
1559 1584 2004-10-28 Fernando Perez <fperez@colorado.edu>
1560 1585
1561 1586 * IPython/Shell.py (signal_handler): add signal handlers to trap
1562 1587 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1563 1588 report by Francesc Alted.
1564 1589
1565 1590 2004-10-21 Fernando Perez <fperez@colorado.edu>
1566 1591
1567 1592 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1568 1593 to % for pysh syntax extensions.
1569 1594
1570 1595 2004-10-09 Fernando Perez <fperez@colorado.edu>
1571 1596
1572 1597 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1573 1598 arrays to print a more useful summary, without calling str(arr).
1574 1599 This avoids the problem of extremely lengthy computations which
1575 1600 occur if arr is large, and appear to the user as a system lockup
1576 1601 with 100% cpu activity. After a suggestion by Kristian Sandberg
1577 1602 <Kristian.Sandberg@colorado.edu>.
1578 1603 (Magic.__init__): fix bug in global magic escapes not being
1579 1604 correctly set.
1580 1605
1581 1606 2004-10-08 Fernando Perez <fperez@colorado.edu>
1582 1607
1583 1608 * IPython/Magic.py (__license__): change to absolute imports of
1584 1609 ipython's own internal packages, to start adapting to the absolute
1585 1610 import requirement of PEP-328.
1586 1611
1587 1612 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1588 1613 files, and standardize author/license marks through the Release
1589 1614 module instead of having per/file stuff (except for files with
1590 1615 particular licenses, like the MIT/PSF-licensed codes).
1591 1616
1592 1617 * IPython/Debugger.py: remove dead code for python 2.1
1593 1618
1594 1619 2004-10-04 Fernando Perez <fperez@colorado.edu>
1595 1620
1596 1621 * IPython/iplib.py (ipmagic): New function for accessing magics
1597 1622 via a normal python function call.
1598 1623
1599 1624 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1600 1625 from '@' to '%', to accomodate the new @decorator syntax of python
1601 1626 2.4.
1602 1627
1603 1628 2004-09-29 Fernando Perez <fperez@colorado.edu>
1604 1629
1605 1630 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1606 1631 matplotlib.use to prevent running scripts which try to switch
1607 1632 interactive backends from within ipython. This will just crash
1608 1633 the python interpreter, so we can't allow it (but a detailed error
1609 1634 is given to the user).
1610 1635
1611 1636 2004-09-28 Fernando Perez <fperez@colorado.edu>
1612 1637
1613 1638 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1614 1639 matplotlib-related fixes so that using @run with non-matplotlib
1615 1640 scripts doesn't pop up spurious plot windows. This requires
1616 1641 matplotlib >= 0.63, where I had to make some changes as well.
1617 1642
1618 1643 * IPython/ipmaker.py (make_IPython): update version requirement to
1619 1644 python 2.2.
1620 1645
1621 1646 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1622 1647 banner arg for embedded customization.
1623 1648
1624 1649 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1625 1650 explicit uses of __IP as the IPython's instance name. Now things
1626 1651 are properly handled via the shell.name value. The actual code
1627 1652 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1628 1653 is much better than before. I'll clean things completely when the
1629 1654 magic stuff gets a real overhaul.
1630 1655
1631 1656 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1632 1657 minor changes to debian dir.
1633 1658
1634 1659 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1635 1660 pointer to the shell itself in the interactive namespace even when
1636 1661 a user-supplied dict is provided. This is needed for embedding
1637 1662 purposes (found by tests with Michel Sanner).
1638 1663
1639 1664 2004-09-27 Fernando Perez <fperez@colorado.edu>
1640 1665
1641 1666 * IPython/UserConfig/ipythonrc: remove []{} from
1642 1667 readline_remove_delims, so that things like [modname.<TAB> do
1643 1668 proper completion. This disables [].TAB, but that's a less common
1644 1669 case than module names in list comprehensions, for example.
1645 1670 Thanks to a report by Andrea Riciputi.
1646 1671
1647 1672 2004-09-09 Fernando Perez <fperez@colorado.edu>
1648 1673
1649 1674 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1650 1675 blocking problems in win32 and osx. Fix by John.
1651 1676
1652 1677 2004-09-08 Fernando Perez <fperez@colorado.edu>
1653 1678
1654 1679 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1655 1680 for Win32 and OSX. Fix by John Hunter.
1656 1681
1657 1682 2004-08-30 *** Released version 0.6.3
1658 1683
1659 1684 2004-08-30 Fernando Perez <fperez@colorado.edu>
1660 1685
1661 1686 * setup.py (isfile): Add manpages to list of dependent files to be
1662 1687 updated.
1663 1688
1664 1689 2004-08-27 Fernando Perez <fperez@colorado.edu>
1665 1690
1666 1691 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1667 1692 for now. They don't really work with standalone WX/GTK code
1668 1693 (though matplotlib IS working fine with both of those backends).
1669 1694 This will neeed much more testing. I disabled most things with
1670 1695 comments, so turning it back on later should be pretty easy.
1671 1696
1672 1697 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1673 1698 autocalling of expressions like r'foo', by modifying the line
1674 1699 split regexp. Closes
1675 1700 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1676 1701 Riley <ipythonbugs-AT-sabi.net>.
1677 1702 (InteractiveShell.mainloop): honor --nobanner with banner
1678 1703 extensions.
1679 1704
1680 1705 * IPython/Shell.py: Significant refactoring of all classes, so
1681 1706 that we can really support ALL matplotlib backends and threading
1682 1707 models (John spotted a bug with Tk which required this). Now we
1683 1708 should support single-threaded, WX-threads and GTK-threads, both
1684 1709 for generic code and for matplotlib.
1685 1710
1686 1711 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1687 1712 -pylab, to simplify things for users. Will also remove the pylab
1688 1713 profile, since now all of matplotlib configuration is directly
1689 1714 handled here. This also reduces startup time.
1690 1715
1691 1716 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1692 1717 shell wasn't being correctly called. Also in IPShellWX.
1693 1718
1694 1719 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1695 1720 fine-tune banner.
1696 1721
1697 1722 * IPython/numutils.py (spike): Deprecate these spike functions,
1698 1723 delete (long deprecated) gnuplot_exec handler.
1699 1724
1700 1725 2004-08-26 Fernando Perez <fperez@colorado.edu>
1701 1726
1702 1727 * ipython.1: Update for threading options, plus some others which
1703 1728 were missing.
1704 1729
1705 1730 * IPython/ipmaker.py (__call__): Added -wthread option for
1706 1731 wxpython thread handling. Make sure threading options are only
1707 1732 valid at the command line.
1708 1733
1709 1734 * scripts/ipython: moved shell selection into a factory function
1710 1735 in Shell.py, to keep the starter script to a minimum.
1711 1736
1712 1737 2004-08-25 Fernando Perez <fperez@colorado.edu>
1713 1738
1714 1739 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1715 1740 John. Along with some recent changes he made to matplotlib, the
1716 1741 next versions of both systems should work very well together.
1717 1742
1718 1743 2004-08-24 Fernando Perez <fperez@colorado.edu>
1719 1744
1720 1745 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1721 1746 tried to switch the profiling to using hotshot, but I'm getting
1722 1747 strange errors from prof.runctx() there. I may be misreading the
1723 1748 docs, but it looks weird. For now the profiling code will
1724 1749 continue to use the standard profiler.
1725 1750
1726 1751 2004-08-23 Fernando Perez <fperez@colorado.edu>
1727 1752
1728 1753 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1729 1754 threaded shell, by John Hunter. It's not quite ready yet, but
1730 1755 close.
1731 1756
1732 1757 2004-08-22 Fernando Perez <fperez@colorado.edu>
1733 1758
1734 1759 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1735 1760 in Magic and ultraTB.
1736 1761
1737 1762 * ipython.1: document threading options in manpage.
1738 1763
1739 1764 * scripts/ipython: Changed name of -thread option to -gthread,
1740 1765 since this is GTK specific. I want to leave the door open for a
1741 1766 -wthread option for WX, which will most likely be necessary. This
1742 1767 change affects usage and ipmaker as well.
1743 1768
1744 1769 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1745 1770 handle the matplotlib shell issues. Code by John Hunter
1746 1771 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1747 1772 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1748 1773 broken (and disabled for end users) for now, but it puts the
1749 1774 infrastructure in place.
1750 1775
1751 1776 2004-08-21 Fernando Perez <fperez@colorado.edu>
1752 1777
1753 1778 * ipythonrc-pylab: Add matplotlib support.
1754 1779
1755 1780 * matplotlib_config.py: new files for matplotlib support, part of
1756 1781 the pylab profile.
1757 1782
1758 1783 * IPython/usage.py (__doc__): documented the threading options.
1759 1784
1760 1785 2004-08-20 Fernando Perez <fperez@colorado.edu>
1761 1786
1762 1787 * ipython: Modified the main calling routine to handle the -thread
1763 1788 and -mpthread options. This needs to be done as a top-level hack,
1764 1789 because it determines which class to instantiate for IPython
1765 1790 itself.
1766 1791
1767 1792 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1768 1793 classes to support multithreaded GTK operation without blocking,
1769 1794 and matplotlib with all backends. This is a lot of still very
1770 1795 experimental code, and threads are tricky. So it may still have a
1771 1796 few rough edges... This code owes a lot to
1772 1797 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1773 1798 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1774 1799 to John Hunter for all the matplotlib work.
1775 1800
1776 1801 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1777 1802 options for gtk thread and matplotlib support.
1778 1803
1779 1804 2004-08-16 Fernando Perez <fperez@colorado.edu>
1780 1805
1781 1806 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1782 1807 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1783 1808 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1784 1809
1785 1810 2004-08-11 Fernando Perez <fperez@colorado.edu>
1786 1811
1787 1812 * setup.py (isfile): Fix build so documentation gets updated for
1788 1813 rpms (it was only done for .tgz builds).
1789 1814
1790 1815 2004-08-10 Fernando Perez <fperez@colorado.edu>
1791 1816
1792 1817 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1793 1818
1794 1819 * iplib.py : Silence syntax error exceptions in tab-completion.
1795 1820
1796 1821 2004-08-05 Fernando Perez <fperez@colorado.edu>
1797 1822
1798 1823 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1799 1824 'color off' mark for continuation prompts. This was causing long
1800 1825 continuation lines to mis-wrap.
1801 1826
1802 1827 2004-08-01 Fernando Perez <fperez@colorado.edu>
1803 1828
1804 1829 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1805 1830 for building ipython to be a parameter. All this is necessary
1806 1831 right now to have a multithreaded version, but this insane
1807 1832 non-design will be cleaned up soon. For now, it's a hack that
1808 1833 works.
1809 1834
1810 1835 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1811 1836 args in various places. No bugs so far, but it's a dangerous
1812 1837 practice.
1813 1838
1814 1839 2004-07-31 Fernando Perez <fperez@colorado.edu>
1815 1840
1816 1841 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1817 1842 fix completion of files with dots in their names under most
1818 1843 profiles (pysh was OK because the completion order is different).
1819 1844
1820 1845 2004-07-27 Fernando Perez <fperez@colorado.edu>
1821 1846
1822 1847 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1823 1848 keywords manually, b/c the one in keyword.py was removed in python
1824 1849 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1825 1850 This is NOT a bug under python 2.3 and earlier.
1826 1851
1827 1852 2004-07-26 Fernando Perez <fperez@colorado.edu>
1828 1853
1829 1854 * IPython/ultraTB.py (VerboseTB.text): Add another
1830 1855 linecache.checkcache() call to try to prevent inspect.py from
1831 1856 crashing under python 2.3. I think this fixes
1832 1857 http://www.scipy.net/roundup/ipython/issue17.
1833 1858
1834 1859 2004-07-26 *** Released version 0.6.2
1835 1860
1836 1861 2004-07-26 Fernando Perez <fperez@colorado.edu>
1837 1862
1838 1863 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1839 1864 fail for any number.
1840 1865 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1841 1866 empty bookmarks.
1842 1867
1843 1868 2004-07-26 *** Released version 0.6.1
1844 1869
1845 1870 2004-07-26 Fernando Perez <fperez@colorado.edu>
1846 1871
1847 1872 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1848 1873
1849 1874 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1850 1875 escaping '()[]{}' in filenames.
1851 1876
1852 1877 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1853 1878 Python 2.2 users who lack a proper shlex.split.
1854 1879
1855 1880 2004-07-19 Fernando Perez <fperez@colorado.edu>
1856 1881
1857 1882 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1858 1883 for reading readline's init file. I follow the normal chain:
1859 1884 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1860 1885 report by Mike Heeter. This closes
1861 1886 http://www.scipy.net/roundup/ipython/issue16.
1862 1887
1863 1888 2004-07-18 Fernando Perez <fperez@colorado.edu>
1864 1889
1865 1890 * IPython/iplib.py (__init__): Add better handling of '\' under
1866 1891 Win32 for filenames. After a patch by Ville.
1867 1892
1868 1893 2004-07-17 Fernando Perez <fperez@colorado.edu>
1869 1894
1870 1895 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1871 1896 autocalling would be triggered for 'foo is bar' if foo is
1872 1897 callable. I also cleaned up the autocall detection code to use a
1873 1898 regexp, which is faster. Bug reported by Alexander Schmolck.
1874 1899
1875 1900 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1876 1901 '?' in them would confuse the help system. Reported by Alex
1877 1902 Schmolck.
1878 1903
1879 1904 2004-07-16 Fernando Perez <fperez@colorado.edu>
1880 1905
1881 1906 * IPython/GnuplotInteractive.py (__all__): added plot2.
1882 1907
1883 1908 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1884 1909 plotting dictionaries, lists or tuples of 1d arrays.
1885 1910
1886 1911 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1887 1912 optimizations.
1888 1913
1889 1914 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1890 1915 the information which was there from Janko's original IPP code:
1891 1916
1892 1917 03.05.99 20:53 porto.ifm.uni-kiel.de
1893 1918 --Started changelog.
1894 1919 --make clear do what it say it does
1895 1920 --added pretty output of lines from inputcache
1896 1921 --Made Logger a mixin class, simplifies handling of switches
1897 1922 --Added own completer class. .string<TAB> expands to last history
1898 1923 line which starts with string. The new expansion is also present
1899 1924 with Ctrl-r from the readline library. But this shows, who this
1900 1925 can be done for other cases.
1901 1926 --Added convention that all shell functions should accept a
1902 1927 parameter_string This opens the door for different behaviour for
1903 1928 each function. @cd is a good example of this.
1904 1929
1905 1930 04.05.99 12:12 porto.ifm.uni-kiel.de
1906 1931 --added logfile rotation
1907 1932 --added new mainloop method which freezes first the namespace
1908 1933
1909 1934 07.05.99 21:24 porto.ifm.uni-kiel.de
1910 1935 --added the docreader classes. Now there is a help system.
1911 1936 -This is only a first try. Currently it's not easy to put new
1912 1937 stuff in the indices. But this is the way to go. Info would be
1913 1938 better, but HTML is every where and not everybody has an info
1914 1939 system installed and it's not so easy to change html-docs to info.
1915 1940 --added global logfile option
1916 1941 --there is now a hook for object inspection method pinfo needs to
1917 1942 be provided for this. Can be reached by two '??'.
1918 1943
1919 1944 08.05.99 20:51 porto.ifm.uni-kiel.de
1920 1945 --added a README
1921 1946 --bug in rc file. Something has changed so functions in the rc
1922 1947 file need to reference the shell and not self. Not clear if it's a
1923 1948 bug or feature.
1924 1949 --changed rc file for new behavior
1925 1950
1926 1951 2004-07-15 Fernando Perez <fperez@colorado.edu>
1927 1952
1928 1953 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1929 1954 cache was falling out of sync in bizarre manners when multi-line
1930 1955 input was present. Minor optimizations and cleanup.
1931 1956
1932 1957 (Logger): Remove old Changelog info for cleanup. This is the
1933 1958 information which was there from Janko's original code:
1934 1959
1935 1960 Changes to Logger: - made the default log filename a parameter
1936 1961
1937 1962 - put a check for lines beginning with !@? in log(). Needed
1938 1963 (even if the handlers properly log their lines) for mid-session
1939 1964 logging activation to work properly. Without this, lines logged
1940 1965 in mid session, which get read from the cache, would end up
1941 1966 'bare' (with !@? in the open) in the log. Now they are caught
1942 1967 and prepended with a #.
1943 1968
1944 1969 * IPython/iplib.py (InteractiveShell.init_readline): added check
1945 1970 in case MagicCompleter fails to be defined, so we don't crash.
1946 1971
1947 1972 2004-07-13 Fernando Perez <fperez@colorado.edu>
1948 1973
1949 1974 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1950 1975 of EPS if the requested filename ends in '.eps'.
1951 1976
1952 1977 2004-07-04 Fernando Perez <fperez@colorado.edu>
1953 1978
1954 1979 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1955 1980 escaping of quotes when calling the shell.
1956 1981
1957 1982 2004-07-02 Fernando Perez <fperez@colorado.edu>
1958 1983
1959 1984 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1960 1985 gettext not working because we were clobbering '_'. Fixes
1961 1986 http://www.scipy.net/roundup/ipython/issue6.
1962 1987
1963 1988 2004-07-01 Fernando Perez <fperez@colorado.edu>
1964 1989
1965 1990 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1966 1991 into @cd. Patch by Ville.
1967 1992
1968 1993 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1969 1994 new function to store things after ipmaker runs. Patch by Ville.
1970 1995 Eventually this will go away once ipmaker is removed and the class
1971 1996 gets cleaned up, but for now it's ok. Key functionality here is
1972 1997 the addition of the persistent storage mechanism, a dict for
1973 1998 keeping data across sessions (for now just bookmarks, but more can
1974 1999 be implemented later).
1975 2000
1976 2001 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1977 2002 persistent across sections. Patch by Ville, I modified it
1978 2003 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1979 2004 added a '-l' option to list all bookmarks.
1980 2005
1981 2006 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1982 2007 center for cleanup. Registered with atexit.register(). I moved
1983 2008 here the old exit_cleanup(). After a patch by Ville.
1984 2009
1985 2010 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1986 2011 characters in the hacked shlex_split for python 2.2.
1987 2012
1988 2013 * IPython/iplib.py (file_matches): more fixes to filenames with
1989 2014 whitespace in them. It's not perfect, but limitations in python's
1990 2015 readline make it impossible to go further.
1991 2016
1992 2017 2004-06-29 Fernando Perez <fperez@colorado.edu>
1993 2018
1994 2019 * IPython/iplib.py (file_matches): escape whitespace correctly in
1995 2020 filename completions. Bug reported by Ville.
1996 2021
1997 2022 2004-06-28 Fernando Perez <fperez@colorado.edu>
1998 2023
1999 2024 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2000 2025 the history file will be called 'history-PROFNAME' (or just
2001 2026 'history' if no profile is loaded). I was getting annoyed at
2002 2027 getting my Numerical work history clobbered by pysh sessions.
2003 2028
2004 2029 * IPython/iplib.py (InteractiveShell.__init__): Internal
2005 2030 getoutputerror() function so that we can honor the system_verbose
2006 2031 flag for _all_ system calls. I also added escaping of #
2007 2032 characters here to avoid confusing Itpl.
2008 2033
2009 2034 * IPython/Magic.py (shlex_split): removed call to shell in
2010 2035 parse_options and replaced it with shlex.split(). The annoying
2011 2036 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2012 2037 to backport it from 2.3, with several frail hacks (the shlex
2013 2038 module is rather limited in 2.2). Thanks to a suggestion by Ville
2014 2039 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2015 2040 problem.
2016 2041
2017 2042 (Magic.magic_system_verbose): new toggle to print the actual
2018 2043 system calls made by ipython. Mainly for debugging purposes.
2019 2044
2020 2045 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2021 2046 doesn't support persistence. Reported (and fix suggested) by
2022 2047 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2023 2048
2024 2049 2004-06-26 Fernando Perez <fperez@colorado.edu>
2025 2050
2026 2051 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2027 2052 continue prompts.
2028 2053
2029 2054 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2030 2055 function (basically a big docstring) and a few more things here to
2031 2056 speedup startup. pysh.py is now very lightweight. We want because
2032 2057 it gets execfile'd, while InterpreterExec gets imported, so
2033 2058 byte-compilation saves time.
2034 2059
2035 2060 2004-06-25 Fernando Perez <fperez@colorado.edu>
2036 2061
2037 2062 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2038 2063 -NUM', which was recently broken.
2039 2064
2040 2065 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2041 2066 in multi-line input (but not !!, which doesn't make sense there).
2042 2067
2043 2068 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2044 2069 It's just too useful, and people can turn it off in the less
2045 2070 common cases where it's a problem.
2046 2071
2047 2072 2004-06-24 Fernando Perez <fperez@colorado.edu>
2048 2073
2049 2074 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2050 2075 special syntaxes (like alias calling) is now allied in multi-line
2051 2076 input. This is still _very_ experimental, but it's necessary for
2052 2077 efficient shell usage combining python looping syntax with system
2053 2078 calls. For now it's restricted to aliases, I don't think it
2054 2079 really even makes sense to have this for magics.
2055 2080
2056 2081 2004-06-23 Fernando Perez <fperez@colorado.edu>
2057 2082
2058 2083 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2059 2084 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2060 2085
2061 2086 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2062 2087 extensions under Windows (after code sent by Gary Bishop). The
2063 2088 extensions considered 'executable' are stored in IPython's rc
2064 2089 structure as win_exec_ext.
2065 2090
2066 2091 * IPython/genutils.py (shell): new function, like system() but
2067 2092 without return value. Very useful for interactive shell work.
2068 2093
2069 2094 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2070 2095 delete aliases.
2071 2096
2072 2097 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2073 2098 sure that the alias table doesn't contain python keywords.
2074 2099
2075 2100 2004-06-21 Fernando Perez <fperez@colorado.edu>
2076 2101
2077 2102 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2078 2103 non-existent items are found in $PATH. Reported by Thorsten.
2079 2104
2080 2105 2004-06-20 Fernando Perez <fperez@colorado.edu>
2081 2106
2082 2107 * IPython/iplib.py (complete): modified the completer so that the
2083 2108 order of priorities can be easily changed at runtime.
2084 2109
2085 2110 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2086 2111 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2087 2112
2088 2113 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2089 2114 expand Python variables prepended with $ in all system calls. The
2090 2115 same was done to InteractiveShell.handle_shell_escape. Now all
2091 2116 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2092 2117 expansion of python variables and expressions according to the
2093 2118 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2094 2119
2095 2120 Though PEP-215 has been rejected, a similar (but simpler) one
2096 2121 seems like it will go into Python 2.4, PEP-292 -
2097 2122 http://www.python.org/peps/pep-0292.html.
2098 2123
2099 2124 I'll keep the full syntax of PEP-215, since IPython has since the
2100 2125 start used Ka-Ping Yee's reference implementation discussed there
2101 2126 (Itpl), and I actually like the powerful semantics it offers.
2102 2127
2103 2128 In order to access normal shell variables, the $ has to be escaped
2104 2129 via an extra $. For example:
2105 2130
2106 2131 In [7]: PATH='a python variable'
2107 2132
2108 2133 In [8]: !echo $PATH
2109 2134 a python variable
2110 2135
2111 2136 In [9]: !echo $$PATH
2112 2137 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2113 2138
2114 2139 (Magic.parse_options): escape $ so the shell doesn't evaluate
2115 2140 things prematurely.
2116 2141
2117 2142 * IPython/iplib.py (InteractiveShell.call_alias): added the
2118 2143 ability for aliases to expand python variables via $.
2119 2144
2120 2145 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2121 2146 system, now there's a @rehash/@rehashx pair of magics. These work
2122 2147 like the csh rehash command, and can be invoked at any time. They
2123 2148 build a table of aliases to everything in the user's $PATH
2124 2149 (@rehash uses everything, @rehashx is slower but only adds
2125 2150 executable files). With this, the pysh.py-based shell profile can
2126 2151 now simply call rehash upon startup, and full access to all
2127 2152 programs in the user's path is obtained.
2128 2153
2129 2154 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2130 2155 functionality is now fully in place. I removed the old dynamic
2131 2156 code generation based approach, in favor of a much lighter one
2132 2157 based on a simple dict. The advantage is that this allows me to
2133 2158 now have thousands of aliases with negligible cost (unthinkable
2134 2159 with the old system).
2135 2160
2136 2161 2004-06-19 Fernando Perez <fperez@colorado.edu>
2137 2162
2138 2163 * IPython/iplib.py (__init__): extended MagicCompleter class to
2139 2164 also complete (last in priority) on user aliases.
2140 2165
2141 2166 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2142 2167 call to eval.
2143 2168 (ItplNS.__init__): Added a new class which functions like Itpl,
2144 2169 but allows configuring the namespace for the evaluation to occur
2145 2170 in.
2146 2171
2147 2172 2004-06-18 Fernando Perez <fperez@colorado.edu>
2148 2173
2149 2174 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2150 2175 better message when 'exit' or 'quit' are typed (a common newbie
2151 2176 confusion).
2152 2177
2153 2178 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2154 2179 check for Windows users.
2155 2180
2156 2181 * IPython/iplib.py (InteractiveShell.user_setup): removed
2157 2182 disabling of colors for Windows. I'll test at runtime and issue a
2158 2183 warning if Gary's readline isn't found, as to nudge users to
2159 2184 download it.
2160 2185
2161 2186 2004-06-16 Fernando Perez <fperez@colorado.edu>
2162 2187
2163 2188 * IPython/genutils.py (Stream.__init__): changed to print errors
2164 2189 to sys.stderr. I had a circular dependency here. Now it's
2165 2190 possible to run ipython as IDLE's shell (consider this pre-alpha,
2166 2191 since true stdout things end up in the starting terminal instead
2167 2192 of IDLE's out).
2168 2193
2169 2194 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2170 2195 users who haven't # updated their prompt_in2 definitions. Remove
2171 2196 eventually.
2172 2197 (multiple_replace): added credit to original ASPN recipe.
2173 2198
2174 2199 2004-06-15 Fernando Perez <fperez@colorado.edu>
2175 2200
2176 2201 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2177 2202 list of auto-defined aliases.
2178 2203
2179 2204 2004-06-13 Fernando Perez <fperez@colorado.edu>
2180 2205
2181 2206 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2182 2207 install was really requested (so setup.py can be used for other
2183 2208 things under Windows).
2184 2209
2185 2210 2004-06-10 Fernando Perez <fperez@colorado.edu>
2186 2211
2187 2212 * IPython/Logger.py (Logger.create_log): Manually remove any old
2188 2213 backup, since os.remove may fail under Windows. Fixes bug
2189 2214 reported by Thorsten.
2190 2215
2191 2216 2004-06-09 Fernando Perez <fperez@colorado.edu>
2192 2217
2193 2218 * examples/example-embed.py: fixed all references to %n (replaced
2194 2219 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2195 2220 for all examples and the manual as well.
2196 2221
2197 2222 2004-06-08 Fernando Perez <fperez@colorado.edu>
2198 2223
2199 2224 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2200 2225 alignment and color management. All 3 prompt subsystems now
2201 2226 inherit from BasePrompt.
2202 2227
2203 2228 * tools/release: updates for windows installer build and tag rpms
2204 2229 with python version (since paths are fixed).
2205 2230
2206 2231 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2207 2232 which will become eventually obsolete. Also fixed the default
2208 2233 prompt_in2 to use \D, so at least new users start with the correct
2209 2234 defaults.
2210 2235 WARNING: Users with existing ipythonrc files will need to apply
2211 2236 this fix manually!
2212 2237
2213 2238 * setup.py: make windows installer (.exe). This is finally the
2214 2239 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2215 2240 which I hadn't included because it required Python 2.3 (or recent
2216 2241 distutils).
2217 2242
2218 2243 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2219 2244 usage of new '\D' escape.
2220 2245
2221 2246 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2222 2247 lacks os.getuid())
2223 2248 (CachedOutput.set_colors): Added the ability to turn coloring
2224 2249 on/off with @colors even for manually defined prompt colors. It
2225 2250 uses a nasty global, but it works safely and via the generic color
2226 2251 handling mechanism.
2227 2252 (Prompt2.__init__): Introduced new escape '\D' for continuation
2228 2253 prompts. It represents the counter ('\#') as dots.
2229 2254 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2230 2255 need to update their ipythonrc files and replace '%n' with '\D' in
2231 2256 their prompt_in2 settings everywhere. Sorry, but there's
2232 2257 otherwise no clean way to get all prompts to properly align. The
2233 2258 ipythonrc shipped with IPython has been updated.
2234 2259
2235 2260 2004-06-07 Fernando Perez <fperez@colorado.edu>
2236 2261
2237 2262 * setup.py (isfile): Pass local_icons option to latex2html, so the
2238 2263 resulting HTML file is self-contained. Thanks to
2239 2264 dryice-AT-liu.com.cn for the tip.
2240 2265
2241 2266 * pysh.py: I created a new profile 'shell', which implements a
2242 2267 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2243 2268 system shell, nor will it become one anytime soon. It's mainly
2244 2269 meant to illustrate the use of the new flexible bash-like prompts.
2245 2270 I guess it could be used by hardy souls for true shell management,
2246 2271 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2247 2272 profile. This uses the InterpreterExec extension provided by
2248 2273 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2249 2274
2250 2275 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2251 2276 auto-align itself with the length of the previous input prompt
2252 2277 (taking into account the invisible color escapes).
2253 2278 (CachedOutput.__init__): Large restructuring of this class. Now
2254 2279 all three prompts (primary1, primary2, output) are proper objects,
2255 2280 managed by the 'parent' CachedOutput class. The code is still a
2256 2281 bit hackish (all prompts share state via a pointer to the cache),
2257 2282 but it's overall far cleaner than before.
2258 2283
2259 2284 * IPython/genutils.py (getoutputerror): modified to add verbose,
2260 2285 debug and header options. This makes the interface of all getout*
2261 2286 functions uniform.
2262 2287 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2263 2288
2264 2289 * IPython/Magic.py (Magic.default_option): added a function to
2265 2290 allow registering default options for any magic command. This
2266 2291 makes it easy to have profiles which customize the magics globally
2267 2292 for a certain use. The values set through this function are
2268 2293 picked up by the parse_options() method, which all magics should
2269 2294 use to parse their options.
2270 2295
2271 2296 * IPython/genutils.py (warn): modified the warnings framework to
2272 2297 use the Term I/O class. I'm trying to slowly unify all of
2273 2298 IPython's I/O operations to pass through Term.
2274 2299
2275 2300 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2276 2301 the secondary prompt to correctly match the length of the primary
2277 2302 one for any prompt. Now multi-line code will properly line up
2278 2303 even for path dependent prompts, such as the new ones available
2279 2304 via the prompt_specials.
2280 2305
2281 2306 2004-06-06 Fernando Perez <fperez@colorado.edu>
2282 2307
2283 2308 * IPython/Prompts.py (prompt_specials): Added the ability to have
2284 2309 bash-like special sequences in the prompts, which get
2285 2310 automatically expanded. Things like hostname, current working
2286 2311 directory and username are implemented already, but it's easy to
2287 2312 add more in the future. Thanks to a patch by W.J. van der Laan
2288 2313 <gnufnork-AT-hetdigitalegat.nl>
2289 2314 (prompt_specials): Added color support for prompt strings, so
2290 2315 users can define arbitrary color setups for their prompts.
2291 2316
2292 2317 2004-06-05 Fernando Perez <fperez@colorado.edu>
2293 2318
2294 2319 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2295 2320 code to load Gary Bishop's readline and configure it
2296 2321 automatically. Thanks to Gary for help on this.
2297 2322
2298 2323 2004-06-01 Fernando Perez <fperez@colorado.edu>
2299 2324
2300 2325 * IPython/Logger.py (Logger.create_log): fix bug for logging
2301 2326 with no filename (previous fix was incomplete).
2302 2327
2303 2328 2004-05-25 Fernando Perez <fperez@colorado.edu>
2304 2329
2305 2330 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2306 2331 parens would get passed to the shell.
2307 2332
2308 2333 2004-05-20 Fernando Perez <fperez@colorado.edu>
2309 2334
2310 2335 * IPython/Magic.py (Magic.magic_prun): changed default profile
2311 2336 sort order to 'time' (the more common profiling need).
2312 2337
2313 2338 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2314 2339 so that source code shown is guaranteed in sync with the file on
2315 2340 disk (also changed in psource). Similar fix to the one for
2316 2341 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2317 2342 <yann.ledu-AT-noos.fr>.
2318 2343
2319 2344 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2320 2345 with a single option would not be correctly parsed. Closes
2321 2346 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2322 2347 introduced in 0.6.0 (on 2004-05-06).
2323 2348
2324 2349 2004-05-13 *** Released version 0.6.0
2325 2350
2326 2351 2004-05-13 Fernando Perez <fperez@colorado.edu>
2327 2352
2328 2353 * debian/: Added debian/ directory to CVS, so that debian support
2329 2354 is publicly accessible. The debian package is maintained by Jack
2330 2355 Moffit <jack-AT-xiph.org>.
2331 2356
2332 2357 * Documentation: included the notes about an ipython-based system
2333 2358 shell (the hypothetical 'pysh') into the new_design.pdf document,
2334 2359 so that these ideas get distributed to users along with the
2335 2360 official documentation.
2336 2361
2337 2362 2004-05-10 Fernando Perez <fperez@colorado.edu>
2338 2363
2339 2364 * IPython/Logger.py (Logger.create_log): fix recently introduced
2340 2365 bug (misindented line) where logstart would fail when not given an
2341 2366 explicit filename.
2342 2367
2343 2368 2004-05-09 Fernando Perez <fperez@colorado.edu>
2344 2369
2345 2370 * IPython/Magic.py (Magic.parse_options): skip system call when
2346 2371 there are no options to look for. Faster, cleaner for the common
2347 2372 case.
2348 2373
2349 2374 * Documentation: many updates to the manual: describing Windows
2350 2375 support better, Gnuplot updates, credits, misc small stuff. Also
2351 2376 updated the new_design doc a bit.
2352 2377
2353 2378 2004-05-06 *** Released version 0.6.0.rc1
2354 2379
2355 2380 2004-05-06 Fernando Perez <fperez@colorado.edu>
2356 2381
2357 2382 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2358 2383 operations to use the vastly more efficient list/''.join() method.
2359 2384 (FormattedTB.text): Fix
2360 2385 http://www.scipy.net/roundup/ipython/issue12 - exception source
2361 2386 extract not updated after reload. Thanks to Mike Salib
2362 2387 <msalib-AT-mit.edu> for pinning the source of the problem.
2363 2388 Fortunately, the solution works inside ipython and doesn't require
2364 2389 any changes to python proper.
2365 2390
2366 2391 * IPython/Magic.py (Magic.parse_options): Improved to process the
2367 2392 argument list as a true shell would (by actually using the
2368 2393 underlying system shell). This way, all @magics automatically get
2369 2394 shell expansion for variables. Thanks to a comment by Alex
2370 2395 Schmolck.
2371 2396
2372 2397 2004-04-04 Fernando Perez <fperez@colorado.edu>
2373 2398
2374 2399 * IPython/iplib.py (InteractiveShell.interact): Added a special
2375 2400 trap for a debugger quit exception, which is basically impossible
2376 2401 to handle by normal mechanisms, given what pdb does to the stack.
2377 2402 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2378 2403
2379 2404 2004-04-03 Fernando Perez <fperez@colorado.edu>
2380 2405
2381 2406 * IPython/genutils.py (Term): Standardized the names of the Term
2382 2407 class streams to cin/cout/cerr, following C++ naming conventions
2383 2408 (I can't use in/out/err because 'in' is not a valid attribute
2384 2409 name).
2385 2410
2386 2411 * IPython/iplib.py (InteractiveShell.interact): don't increment
2387 2412 the prompt if there's no user input. By Daniel 'Dang' Griffith
2388 2413 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2389 2414 Francois Pinard.
2390 2415
2391 2416 2004-04-02 Fernando Perez <fperez@colorado.edu>
2392 2417
2393 2418 * IPython/genutils.py (Stream.__init__): Modified to survive at
2394 2419 least importing in contexts where stdin/out/err aren't true file
2395 2420 objects, such as PyCrust (they lack fileno() and mode). However,
2396 2421 the recovery facilities which rely on these things existing will
2397 2422 not work.
2398 2423
2399 2424 2004-04-01 Fernando Perez <fperez@colorado.edu>
2400 2425
2401 2426 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2402 2427 use the new getoutputerror() function, so it properly
2403 2428 distinguishes stdout/err.
2404 2429
2405 2430 * IPython/genutils.py (getoutputerror): added a function to
2406 2431 capture separately the standard output and error of a command.
2407 2432 After a comment from dang on the mailing lists. This code is
2408 2433 basically a modified version of commands.getstatusoutput(), from
2409 2434 the standard library.
2410 2435
2411 2436 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2412 2437 '!!' as a special syntax (shorthand) to access @sx.
2413 2438
2414 2439 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2415 2440 command and return its output as a list split on '\n'.
2416 2441
2417 2442 2004-03-31 Fernando Perez <fperez@colorado.edu>
2418 2443
2419 2444 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2420 2445 method to dictionaries used as FakeModule instances if they lack
2421 2446 it. At least pydoc in python2.3 breaks for runtime-defined
2422 2447 functions without this hack. At some point I need to _really_
2423 2448 understand what FakeModule is doing, because it's a gross hack.
2424 2449 But it solves Arnd's problem for now...
2425 2450
2426 2451 2004-02-27 Fernando Perez <fperez@colorado.edu>
2427 2452
2428 2453 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2429 2454 mode would behave erratically. Also increased the number of
2430 2455 possible logs in rotate mod to 999. Thanks to Rod Holland
2431 2456 <rhh@StructureLABS.com> for the report and fixes.
2432 2457
2433 2458 2004-02-26 Fernando Perez <fperez@colorado.edu>
2434 2459
2435 2460 * IPython/genutils.py (page): Check that the curses module really
2436 2461 has the initscr attribute before trying to use it. For some
2437 2462 reason, the Solaris curses module is missing this. I think this
2438 2463 should be considered a Solaris python bug, but I'm not sure.
2439 2464
2440 2465 2004-01-17 Fernando Perez <fperez@colorado.edu>
2441 2466
2442 2467 * IPython/genutils.py (Stream.__init__): Changes to try to make
2443 2468 ipython robust against stdin/out/err being closed by the user.
2444 2469 This is 'user error' (and blocks a normal python session, at least
2445 2470 the stdout case). However, Ipython should be able to survive such
2446 2471 instances of abuse as gracefully as possible. To simplify the
2447 2472 coding and maintain compatibility with Gary Bishop's Term
2448 2473 contributions, I've made use of classmethods for this. I think
2449 2474 this introduces a dependency on python 2.2.
2450 2475
2451 2476 2004-01-13 Fernando Perez <fperez@colorado.edu>
2452 2477
2453 2478 * IPython/numutils.py (exp_safe): simplified the code a bit and
2454 2479 removed the need for importing the kinds module altogether.
2455 2480
2456 2481 2004-01-06 Fernando Perez <fperez@colorado.edu>
2457 2482
2458 2483 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2459 2484 a magic function instead, after some community feedback. No
2460 2485 special syntax will exist for it, but its name is deliberately
2461 2486 very short.
2462 2487
2463 2488 2003-12-20 Fernando Perez <fperez@colorado.edu>
2464 2489
2465 2490 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2466 2491 new functionality, to automagically assign the result of a shell
2467 2492 command to a variable. I'll solicit some community feedback on
2468 2493 this before making it permanent.
2469 2494
2470 2495 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2471 2496 requested about callables for which inspect couldn't obtain a
2472 2497 proper argspec. Thanks to a crash report sent by Etienne
2473 2498 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2474 2499
2475 2500 2003-12-09 Fernando Perez <fperez@colorado.edu>
2476 2501
2477 2502 * IPython/genutils.py (page): patch for the pager to work across
2478 2503 various versions of Windows. By Gary Bishop.
2479 2504
2480 2505 2003-12-04 Fernando Perez <fperez@colorado.edu>
2481 2506
2482 2507 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2483 2508 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2484 2509 While I tested this and it looks ok, there may still be corner
2485 2510 cases I've missed.
2486 2511
2487 2512 2003-12-01 Fernando Perez <fperez@colorado.edu>
2488 2513
2489 2514 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2490 2515 where a line like 'p,q=1,2' would fail because the automagic
2491 2516 system would be triggered for @p.
2492 2517
2493 2518 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2494 2519 cleanups, code unmodified.
2495 2520
2496 2521 * IPython/genutils.py (Term): added a class for IPython to handle
2497 2522 output. In most cases it will just be a proxy for stdout/err, but
2498 2523 having this allows modifications to be made for some platforms,
2499 2524 such as handling color escapes under Windows. All of this code
2500 2525 was contributed by Gary Bishop, with minor modifications by me.
2501 2526 The actual changes affect many files.
2502 2527
2503 2528 2003-11-30 Fernando Perez <fperez@colorado.edu>
2504 2529
2505 2530 * IPython/iplib.py (file_matches): new completion code, courtesy
2506 2531 of Jeff Collins. This enables filename completion again under
2507 2532 python 2.3, which disabled it at the C level.
2508 2533
2509 2534 2003-11-11 Fernando Perez <fperez@colorado.edu>
2510 2535
2511 2536 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2512 2537 for Numeric.array(map(...)), but often convenient.
2513 2538
2514 2539 2003-11-05 Fernando Perez <fperez@colorado.edu>
2515 2540
2516 2541 * IPython/numutils.py (frange): Changed a call from int() to
2517 2542 int(round()) to prevent a problem reported with arange() in the
2518 2543 numpy list.
2519 2544
2520 2545 2003-10-06 Fernando Perez <fperez@colorado.edu>
2521 2546
2522 2547 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2523 2548 prevent crashes if sys lacks an argv attribute (it happens with
2524 2549 embedded interpreters which build a bare-bones sys module).
2525 2550 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2526 2551
2527 2552 2003-09-24 Fernando Perez <fperez@colorado.edu>
2528 2553
2529 2554 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2530 2555 to protect against poorly written user objects where __getattr__
2531 2556 raises exceptions other than AttributeError. Thanks to a bug
2532 2557 report by Oliver Sander <osander-AT-gmx.de>.
2533 2558
2534 2559 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2535 2560 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2536 2561
2537 2562 2003-09-09 Fernando Perez <fperez@colorado.edu>
2538 2563
2539 2564 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2540 2565 unpacking a list whith a callable as first element would
2541 2566 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2542 2567 Collins.
2543 2568
2544 2569 2003-08-25 *** Released version 0.5.0
2545 2570
2546 2571 2003-08-22 Fernando Perez <fperez@colorado.edu>
2547 2572
2548 2573 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2549 2574 improperly defined user exceptions. Thanks to feedback from Mark
2550 2575 Russell <mrussell-AT-verio.net>.
2551 2576
2552 2577 2003-08-20 Fernando Perez <fperez@colorado.edu>
2553 2578
2554 2579 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2555 2580 printing so that it would print multi-line string forms starting
2556 2581 with a new line. This way the formatting is better respected for
2557 2582 objects which work hard to make nice string forms.
2558 2583
2559 2584 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2560 2585 autocall would overtake data access for objects with both
2561 2586 __getitem__ and __call__.
2562 2587
2563 2588 2003-08-19 *** Released version 0.5.0-rc1
2564 2589
2565 2590 2003-08-19 Fernando Perez <fperez@colorado.edu>
2566 2591
2567 2592 * IPython/deep_reload.py (load_tail): single tiny change here
2568 2593 seems to fix the long-standing bug of dreload() failing to work
2569 2594 for dotted names. But this module is pretty tricky, so I may have
2570 2595 missed some subtlety. Needs more testing!.
2571 2596
2572 2597 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2573 2598 exceptions which have badly implemented __str__ methods.
2574 2599 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2575 2600 which I've been getting reports about from Python 2.3 users. I
2576 2601 wish I had a simple test case to reproduce the problem, so I could
2577 2602 either write a cleaner workaround or file a bug report if
2578 2603 necessary.
2579 2604
2580 2605 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2581 2606 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2582 2607 a bug report by Tjabo Kloppenburg.
2583 2608
2584 2609 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2585 2610 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2586 2611 seems rather unstable. Thanks to a bug report by Tjabo
2587 2612 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2588 2613
2589 2614 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2590 2615 this out soon because of the critical fixes in the inner loop for
2591 2616 generators.
2592 2617
2593 2618 * IPython/Magic.py (Magic.getargspec): removed. This (and
2594 2619 _get_def) have been obsoleted by OInspect for a long time, I
2595 2620 hadn't noticed that they were dead code.
2596 2621 (Magic._ofind): restored _ofind functionality for a few literals
2597 2622 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2598 2623 for things like "hello".capitalize?, since that would require a
2599 2624 potentially dangerous eval() again.
2600 2625
2601 2626 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2602 2627 logic a bit more to clean up the escapes handling and minimize the
2603 2628 use of _ofind to only necessary cases. The interactive 'feel' of
2604 2629 IPython should have improved quite a bit with the changes in
2605 2630 _prefilter and _ofind (besides being far safer than before).
2606 2631
2607 2632 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2608 2633 obscure, never reported). Edit would fail to find the object to
2609 2634 edit under some circumstances.
2610 2635 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2611 2636 which were causing double-calling of generators. Those eval calls
2612 2637 were _very_ dangerous, since code with side effects could be
2613 2638 triggered. As they say, 'eval is evil'... These were the
2614 2639 nastiest evals in IPython. Besides, _ofind is now far simpler,
2615 2640 and it should also be quite a bit faster. Its use of inspect is
2616 2641 also safer, so perhaps some of the inspect-related crashes I've
2617 2642 seen lately with Python 2.3 might be taken care of. That will
2618 2643 need more testing.
2619 2644
2620 2645 2003-08-17 Fernando Perez <fperez@colorado.edu>
2621 2646
2622 2647 * IPython/iplib.py (InteractiveShell._prefilter): significant
2623 2648 simplifications to the logic for handling user escapes. Faster
2624 2649 and simpler code.
2625 2650
2626 2651 2003-08-14 Fernando Perez <fperez@colorado.edu>
2627 2652
2628 2653 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2629 2654 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2630 2655 but it should be quite a bit faster. And the recursive version
2631 2656 generated O(log N) intermediate storage for all rank>1 arrays,
2632 2657 even if they were contiguous.
2633 2658 (l1norm): Added this function.
2634 2659 (norm): Added this function for arbitrary norms (including
2635 2660 l-infinity). l1 and l2 are still special cases for convenience
2636 2661 and speed.
2637 2662
2638 2663 2003-08-03 Fernando Perez <fperez@colorado.edu>
2639 2664
2640 2665 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2641 2666 exceptions, which now raise PendingDeprecationWarnings in Python
2642 2667 2.3. There were some in Magic and some in Gnuplot2.
2643 2668
2644 2669 2003-06-30 Fernando Perez <fperez@colorado.edu>
2645 2670
2646 2671 * IPython/genutils.py (page): modified to call curses only for
2647 2672 terminals where TERM=='xterm'. After problems under many other
2648 2673 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2649 2674
2650 2675 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2651 2676 would be triggered when readline was absent. This was just an old
2652 2677 debugging statement I'd forgotten to take out.
2653 2678
2654 2679 2003-06-20 Fernando Perez <fperez@colorado.edu>
2655 2680
2656 2681 * IPython/genutils.py (clock): modified to return only user time
2657 2682 (not counting system time), after a discussion on scipy. While
2658 2683 system time may be a useful quantity occasionally, it may much
2659 2684 more easily be skewed by occasional swapping or other similar
2660 2685 activity.
2661 2686
2662 2687 2003-06-05 Fernando Perez <fperez@colorado.edu>
2663 2688
2664 2689 * IPython/numutils.py (identity): new function, for building
2665 2690 arbitrary rank Kronecker deltas (mostly backwards compatible with
2666 2691 Numeric.identity)
2667 2692
2668 2693 2003-06-03 Fernando Perez <fperez@colorado.edu>
2669 2694
2670 2695 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2671 2696 arguments passed to magics with spaces, to allow trailing '\' to
2672 2697 work normally (mainly for Windows users).
2673 2698
2674 2699 2003-05-29 Fernando Perez <fperez@colorado.edu>
2675 2700
2676 2701 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2677 2702 instead of pydoc.help. This fixes a bizarre behavior where
2678 2703 printing '%s' % locals() would trigger the help system. Now
2679 2704 ipython behaves like normal python does.
2680 2705
2681 2706 Note that if one does 'from pydoc import help', the bizarre
2682 2707 behavior returns, but this will also happen in normal python, so
2683 2708 it's not an ipython bug anymore (it has to do with how pydoc.help
2684 2709 is implemented).
2685 2710
2686 2711 2003-05-22 Fernando Perez <fperez@colorado.edu>
2687 2712
2688 2713 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2689 2714 return [] instead of None when nothing matches, also match to end
2690 2715 of line. Patch by Gary Bishop.
2691 2716
2692 2717 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2693 2718 protection as before, for files passed on the command line. This
2694 2719 prevents the CrashHandler from kicking in if user files call into
2695 2720 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2696 2721 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2697 2722
2698 2723 2003-05-20 *** Released version 0.4.0
2699 2724
2700 2725 2003-05-20 Fernando Perez <fperez@colorado.edu>
2701 2726
2702 2727 * setup.py: added support for manpages. It's a bit hackish b/c of
2703 2728 a bug in the way the bdist_rpm distutils target handles gzipped
2704 2729 manpages, but it works. After a patch by Jack.
2705 2730
2706 2731 2003-05-19 Fernando Perez <fperez@colorado.edu>
2707 2732
2708 2733 * IPython/numutils.py: added a mockup of the kinds module, since
2709 2734 it was recently removed from Numeric. This way, numutils will
2710 2735 work for all users even if they are missing kinds.
2711 2736
2712 2737 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2713 2738 failure, which can occur with SWIG-wrapped extensions. After a
2714 2739 crash report from Prabhu.
2715 2740
2716 2741 2003-05-16 Fernando Perez <fperez@colorado.edu>
2717 2742
2718 2743 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2719 2744 protect ipython from user code which may call directly
2720 2745 sys.excepthook (this looks like an ipython crash to the user, even
2721 2746 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2722 2747 This is especially important to help users of WxWindows, but may
2723 2748 also be useful in other cases.
2724 2749
2725 2750 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2726 2751 an optional tb_offset to be specified, and to preserve exception
2727 2752 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2728 2753
2729 2754 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2730 2755
2731 2756 2003-05-15 Fernando Perez <fperez@colorado.edu>
2732 2757
2733 2758 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2734 2759 installing for a new user under Windows.
2735 2760
2736 2761 2003-05-12 Fernando Perez <fperez@colorado.edu>
2737 2762
2738 2763 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2739 2764 handler for Emacs comint-based lines. Currently it doesn't do
2740 2765 much (but importantly, it doesn't update the history cache). In
2741 2766 the future it may be expanded if Alex needs more functionality
2742 2767 there.
2743 2768
2744 2769 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2745 2770 info to crash reports.
2746 2771
2747 2772 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2748 2773 just like Python's -c. Also fixed crash with invalid -color
2749 2774 option value at startup. Thanks to Will French
2750 2775 <wfrench-AT-bestweb.net> for the bug report.
2751 2776
2752 2777 2003-05-09 Fernando Perez <fperez@colorado.edu>
2753 2778
2754 2779 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2755 2780 to EvalDict (it's a mapping, after all) and simplified its code
2756 2781 quite a bit, after a nice discussion on c.l.py where Gustavo
2757 2782 Córdova <gcordova-AT-sismex.com> suggested the new version.
2758 2783
2759 2784 2003-04-30 Fernando Perez <fperez@colorado.edu>
2760 2785
2761 2786 * IPython/genutils.py (timings_out): modified it to reduce its
2762 2787 overhead in the common reps==1 case.
2763 2788
2764 2789 2003-04-29 Fernando Perez <fperez@colorado.edu>
2765 2790
2766 2791 * IPython/genutils.py (timings_out): Modified to use the resource
2767 2792 module, which avoids the wraparound problems of time.clock().
2768 2793
2769 2794 2003-04-17 *** Released version 0.2.15pre4
2770 2795
2771 2796 2003-04-17 Fernando Perez <fperez@colorado.edu>
2772 2797
2773 2798 * setup.py (scriptfiles): Split windows-specific stuff over to a
2774 2799 separate file, in an attempt to have a Windows GUI installer.
2775 2800 That didn't work, but part of the groundwork is done.
2776 2801
2777 2802 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2778 2803 indent/unindent with 4 spaces. Particularly useful in combination
2779 2804 with the new auto-indent option.
2780 2805
2781 2806 2003-04-16 Fernando Perez <fperez@colorado.edu>
2782 2807
2783 2808 * IPython/Magic.py: various replacements of self.rc for
2784 2809 self.shell.rc. A lot more remains to be done to fully disentangle
2785 2810 this class from the main Shell class.
2786 2811
2787 2812 * IPython/GnuplotRuntime.py: added checks for mouse support so
2788 2813 that we don't try to enable it if the current gnuplot doesn't
2789 2814 really support it. Also added checks so that we don't try to
2790 2815 enable persist under Windows (where Gnuplot doesn't recognize the
2791 2816 option).
2792 2817
2793 2818 * IPython/iplib.py (InteractiveShell.interact): Added optional
2794 2819 auto-indenting code, after a patch by King C. Shu
2795 2820 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2796 2821 get along well with pasting indented code. If I ever figure out
2797 2822 how to make that part go well, it will become on by default.
2798 2823
2799 2824 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2800 2825 crash ipython if there was an unmatched '%' in the user's prompt
2801 2826 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2802 2827
2803 2828 * IPython/iplib.py (InteractiveShell.interact): removed the
2804 2829 ability to ask the user whether he wants to crash or not at the
2805 2830 'last line' exception handler. Calling functions at that point
2806 2831 changes the stack, and the error reports would have incorrect
2807 2832 tracebacks.
2808 2833
2809 2834 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2810 2835 pass through a peger a pretty-printed form of any object. After a
2811 2836 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2812 2837
2813 2838 2003-04-14 Fernando Perez <fperez@colorado.edu>
2814 2839
2815 2840 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2816 2841 all files in ~ would be modified at first install (instead of
2817 2842 ~/.ipython). This could be potentially disastrous, as the
2818 2843 modification (make line-endings native) could damage binary files.
2819 2844
2820 2845 2003-04-10 Fernando Perez <fperez@colorado.edu>
2821 2846
2822 2847 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2823 2848 handle only lines which are invalid python. This now means that
2824 2849 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2825 2850 for the bug report.
2826 2851
2827 2852 2003-04-01 Fernando Perez <fperez@colorado.edu>
2828 2853
2829 2854 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2830 2855 where failing to set sys.last_traceback would crash pdb.pm().
2831 2856 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2832 2857 report.
2833 2858
2834 2859 2003-03-25 Fernando Perez <fperez@colorado.edu>
2835 2860
2836 2861 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2837 2862 before printing it (it had a lot of spurious blank lines at the
2838 2863 end).
2839 2864
2840 2865 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2841 2866 output would be sent 21 times! Obviously people don't use this
2842 2867 too often, or I would have heard about it.
2843 2868
2844 2869 2003-03-24 Fernando Perez <fperez@colorado.edu>
2845 2870
2846 2871 * setup.py (scriptfiles): renamed the data_files parameter from
2847 2872 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2848 2873 for the patch.
2849 2874
2850 2875 2003-03-20 Fernando Perez <fperez@colorado.edu>
2851 2876
2852 2877 * IPython/genutils.py (error): added error() and fatal()
2853 2878 functions.
2854 2879
2855 2880 2003-03-18 *** Released version 0.2.15pre3
2856 2881
2857 2882 2003-03-18 Fernando Perez <fperez@colorado.edu>
2858 2883
2859 2884 * setupext/install_data_ext.py
2860 2885 (install_data_ext.initialize_options): Class contributed by Jack
2861 2886 Moffit for fixing the old distutils hack. He is sending this to
2862 2887 the distutils folks so in the future we may not need it as a
2863 2888 private fix.
2864 2889
2865 2890 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2866 2891 changes for Debian packaging. See his patch for full details.
2867 2892 The old distutils hack of making the ipythonrc* files carry a
2868 2893 bogus .py extension is gone, at last. Examples were moved to a
2869 2894 separate subdir under doc/, and the separate executable scripts
2870 2895 now live in their own directory. Overall a great cleanup. The
2871 2896 manual was updated to use the new files, and setup.py has been
2872 2897 fixed for this setup.
2873 2898
2874 2899 * IPython/PyColorize.py (Parser.usage): made non-executable and
2875 2900 created a pycolor wrapper around it to be included as a script.
2876 2901
2877 2902 2003-03-12 *** Released version 0.2.15pre2
2878 2903
2879 2904 2003-03-12 Fernando Perez <fperez@colorado.edu>
2880 2905
2881 2906 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2882 2907 long-standing problem with garbage characters in some terminals.
2883 2908 The issue was really that the \001 and \002 escapes must _only_ be
2884 2909 passed to input prompts (which call readline), but _never_ to
2885 2910 normal text to be printed on screen. I changed ColorANSI to have
2886 2911 two classes: TermColors and InputTermColors, each with the
2887 2912 appropriate escapes for input prompts or normal text. The code in
2888 2913 Prompts.py got slightly more complicated, but this very old and
2889 2914 annoying bug is finally fixed.
2890 2915
2891 2916 All the credit for nailing down the real origin of this problem
2892 2917 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2893 2918 *Many* thanks to him for spending quite a bit of effort on this.
2894 2919
2895 2920 2003-03-05 *** Released version 0.2.15pre1
2896 2921
2897 2922 2003-03-03 Fernando Perez <fperez@colorado.edu>
2898 2923
2899 2924 * IPython/FakeModule.py: Moved the former _FakeModule to a
2900 2925 separate file, because it's also needed by Magic (to fix a similar
2901 2926 pickle-related issue in @run).
2902 2927
2903 2928 2003-03-02 Fernando Perez <fperez@colorado.edu>
2904 2929
2905 2930 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2906 2931 the autocall option at runtime.
2907 2932 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2908 2933 across Magic.py to start separating Magic from InteractiveShell.
2909 2934 (Magic._ofind): Fixed to return proper namespace for dotted
2910 2935 names. Before, a dotted name would always return 'not currently
2911 2936 defined', because it would find the 'parent'. s.x would be found,
2912 2937 but since 'x' isn't defined by itself, it would get confused.
2913 2938 (Magic.magic_run): Fixed pickling problems reported by Ralf
2914 2939 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2915 2940 that I'd used when Mike Heeter reported similar issues at the
2916 2941 top-level, but now for @run. It boils down to injecting the
2917 2942 namespace where code is being executed with something that looks
2918 2943 enough like a module to fool pickle.dump(). Since a pickle stores
2919 2944 a named reference to the importing module, we need this for
2920 2945 pickles to save something sensible.
2921 2946
2922 2947 * IPython/ipmaker.py (make_IPython): added an autocall option.
2923 2948
2924 2949 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2925 2950 the auto-eval code. Now autocalling is an option, and the code is
2926 2951 also vastly safer. There is no more eval() involved at all.
2927 2952
2928 2953 2003-03-01 Fernando Perez <fperez@colorado.edu>
2929 2954
2930 2955 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2931 2956 dict with named keys instead of a tuple.
2932 2957
2933 2958 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2934 2959
2935 2960 * setup.py (make_shortcut): Fixed message about directories
2936 2961 created during Windows installation (the directories were ok, just
2937 2962 the printed message was misleading). Thanks to Chris Liechti
2938 2963 <cliechti-AT-gmx.net> for the heads up.
2939 2964
2940 2965 2003-02-21 Fernando Perez <fperez@colorado.edu>
2941 2966
2942 2967 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2943 2968 of ValueError exception when checking for auto-execution. This
2944 2969 one is raised by things like Numeric arrays arr.flat when the
2945 2970 array is non-contiguous.
2946 2971
2947 2972 2003-01-31 Fernando Perez <fperez@colorado.edu>
2948 2973
2949 2974 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2950 2975 not return any value at all (even though the command would get
2951 2976 executed).
2952 2977 (xsys): Flush stdout right after printing the command to ensure
2953 2978 proper ordering of commands and command output in the total
2954 2979 output.
2955 2980 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2956 2981 system/getoutput as defaults. The old ones are kept for
2957 2982 compatibility reasons, so no code which uses this library needs
2958 2983 changing.
2959 2984
2960 2985 2003-01-27 *** Released version 0.2.14
2961 2986
2962 2987 2003-01-25 Fernando Perez <fperez@colorado.edu>
2963 2988
2964 2989 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2965 2990 functions defined in previous edit sessions could not be re-edited
2966 2991 (because the temp files were immediately removed). Now temp files
2967 2992 are removed only at IPython's exit.
2968 2993 (Magic.magic_run): Improved @run to perform shell-like expansions
2969 2994 on its arguments (~users and $VARS). With this, @run becomes more
2970 2995 like a normal command-line.
2971 2996
2972 2997 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2973 2998 bugs related to embedding and cleaned up that code. A fairly
2974 2999 important one was the impossibility to access the global namespace
2975 3000 through the embedded IPython (only local variables were visible).
2976 3001
2977 3002 2003-01-14 Fernando Perez <fperez@colorado.edu>
2978 3003
2979 3004 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2980 3005 auto-calling to be a bit more conservative. Now it doesn't get
2981 3006 triggered if any of '!=()<>' are in the rest of the input line, to
2982 3007 allow comparing callables. Thanks to Alex for the heads up.
2983 3008
2984 3009 2003-01-07 Fernando Perez <fperez@colorado.edu>
2985 3010
2986 3011 * IPython/genutils.py (page): fixed estimation of the number of
2987 3012 lines in a string to be paged to simply count newlines. This
2988 3013 prevents over-guessing due to embedded escape sequences. A better
2989 3014 long-term solution would involve stripping out the control chars
2990 3015 for the count, but it's potentially so expensive I just don't
2991 3016 think it's worth doing.
2992 3017
2993 3018 2002-12-19 *** Released version 0.2.14pre50
2994 3019
2995 3020 2002-12-19 Fernando Perez <fperez@colorado.edu>
2996 3021
2997 3022 * tools/release (version): Changed release scripts to inform
2998 3023 Andrea and build a NEWS file with a list of recent changes.
2999 3024
3000 3025 * IPython/ColorANSI.py (__all__): changed terminal detection
3001 3026 code. Seems to work better for xterms without breaking
3002 3027 konsole. Will need more testing to determine if WinXP and Mac OSX
3003 3028 also work ok.
3004 3029
3005 3030 2002-12-18 *** Released version 0.2.14pre49
3006 3031
3007 3032 2002-12-18 Fernando Perez <fperez@colorado.edu>
3008 3033
3009 3034 * Docs: added new info about Mac OSX, from Andrea.
3010 3035
3011 3036 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3012 3037 allow direct plotting of python strings whose format is the same
3013 3038 of gnuplot data files.
3014 3039
3015 3040 2002-12-16 Fernando Perez <fperez@colorado.edu>
3016 3041
3017 3042 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3018 3043 value of exit question to be acknowledged.
3019 3044
3020 3045 2002-12-03 Fernando Perez <fperez@colorado.edu>
3021 3046
3022 3047 * IPython/ipmaker.py: removed generators, which had been added
3023 3048 by mistake in an earlier debugging run. This was causing trouble
3024 3049 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3025 3050 for pointing this out.
3026 3051
3027 3052 2002-11-17 Fernando Perez <fperez@colorado.edu>
3028 3053
3029 3054 * Manual: updated the Gnuplot section.
3030 3055
3031 3056 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3032 3057 a much better split of what goes in Runtime and what goes in
3033 3058 Interactive.
3034 3059
3035 3060 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3036 3061 being imported from iplib.
3037 3062
3038 3063 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3039 3064 for command-passing. Now the global Gnuplot instance is called
3040 3065 'gp' instead of 'g', which was really a far too fragile and
3041 3066 common name.
3042 3067
3043 3068 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3044 3069 bounding boxes generated by Gnuplot for square plots.
3045 3070
3046 3071 * IPython/genutils.py (popkey): new function added. I should
3047 3072 suggest this on c.l.py as a dict method, it seems useful.
3048 3073
3049 3074 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3050 3075 to transparently handle PostScript generation. MUCH better than
3051 3076 the previous plot_eps/replot_eps (which I removed now). The code
3052 3077 is also fairly clean and well documented now (including
3053 3078 docstrings).
3054 3079
3055 3080 2002-11-13 Fernando Perez <fperez@colorado.edu>
3056 3081
3057 3082 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3058 3083 (inconsistent with options).
3059 3084
3060 3085 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3061 3086 manually disabled, I don't know why. Fixed it.
3062 3087 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3063 3088 eps output.
3064 3089
3065 3090 2002-11-12 Fernando Perez <fperez@colorado.edu>
3066 3091
3067 3092 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3068 3093 don't propagate up to caller. Fixes crash reported by François
3069 3094 Pinard.
3070 3095
3071 3096 2002-11-09 Fernando Perez <fperez@colorado.edu>
3072 3097
3073 3098 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3074 3099 history file for new users.
3075 3100 (make_IPython): fixed bug where initial install would leave the
3076 3101 user running in the .ipython dir.
3077 3102 (make_IPython): fixed bug where config dir .ipython would be
3078 3103 created regardless of the given -ipythondir option. Thanks to Cory
3079 3104 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3080 3105
3081 3106 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3082 3107 type confirmations. Will need to use it in all of IPython's code
3083 3108 consistently.
3084 3109
3085 3110 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3086 3111 context to print 31 lines instead of the default 5. This will make
3087 3112 the crash reports extremely detailed in case the problem is in
3088 3113 libraries I don't have access to.
3089 3114
3090 3115 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3091 3116 line of defense' code to still crash, but giving users fair
3092 3117 warning. I don't want internal errors to go unreported: if there's
3093 3118 an internal problem, IPython should crash and generate a full
3094 3119 report.
3095 3120
3096 3121 2002-11-08 Fernando Perez <fperez@colorado.edu>
3097 3122
3098 3123 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3099 3124 otherwise uncaught exceptions which can appear if people set
3100 3125 sys.stdout to something badly broken. Thanks to a crash report
3101 3126 from henni-AT-mail.brainbot.com.
3102 3127
3103 3128 2002-11-04 Fernando Perez <fperez@colorado.edu>
3104 3129
3105 3130 * IPython/iplib.py (InteractiveShell.interact): added
3106 3131 __IPYTHON__active to the builtins. It's a flag which goes on when
3107 3132 the interaction starts and goes off again when it stops. This
3108 3133 allows embedding code to detect being inside IPython. Before this
3109 3134 was done via __IPYTHON__, but that only shows that an IPython
3110 3135 instance has been created.
3111 3136
3112 3137 * IPython/Magic.py (Magic.magic_env): I realized that in a
3113 3138 UserDict, instance.data holds the data as a normal dict. So I
3114 3139 modified @env to return os.environ.data instead of rebuilding a
3115 3140 dict by hand.
3116 3141
3117 3142 2002-11-02 Fernando Perez <fperez@colorado.edu>
3118 3143
3119 3144 * IPython/genutils.py (warn): changed so that level 1 prints no
3120 3145 header. Level 2 is now the default (with 'WARNING' header, as
3121 3146 before). I think I tracked all places where changes were needed in
3122 3147 IPython, but outside code using the old level numbering may have
3123 3148 broken.
3124 3149
3125 3150 * IPython/iplib.py (InteractiveShell.runcode): added this to
3126 3151 handle the tracebacks in SystemExit traps correctly. The previous
3127 3152 code (through interact) was printing more of the stack than
3128 3153 necessary, showing IPython internal code to the user.
3129 3154
3130 3155 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3131 3156 default. Now that the default at the confirmation prompt is yes,
3132 3157 it's not so intrusive. François' argument that ipython sessions
3133 3158 tend to be complex enough not to lose them from an accidental C-d,
3134 3159 is a valid one.
3135 3160
3136 3161 * IPython/iplib.py (InteractiveShell.interact): added a
3137 3162 showtraceback() call to the SystemExit trap, and modified the exit
3138 3163 confirmation to have yes as the default.
3139 3164
3140 3165 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3141 3166 this file. It's been gone from the code for a long time, this was
3142 3167 simply leftover junk.
3143 3168
3144 3169 2002-11-01 Fernando Perez <fperez@colorado.edu>
3145 3170
3146 3171 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3147 3172 added. If set, IPython now traps EOF and asks for
3148 3173 confirmation. After a request by François Pinard.
3149 3174
3150 3175 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3151 3176 of @abort, and with a new (better) mechanism for handling the
3152 3177 exceptions.
3153 3178
3154 3179 2002-10-27 Fernando Perez <fperez@colorado.edu>
3155 3180
3156 3181 * IPython/usage.py (__doc__): updated the --help information and
3157 3182 the ipythonrc file to indicate that -log generates
3158 3183 ./ipython.log. Also fixed the corresponding info in @logstart.
3159 3184 This and several other fixes in the manuals thanks to reports by
3160 3185 François Pinard <pinard-AT-iro.umontreal.ca>.
3161 3186
3162 3187 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3163 3188 refer to @logstart (instead of @log, which doesn't exist).
3164 3189
3165 3190 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3166 3191 AttributeError crash. Thanks to Christopher Armstrong
3167 3192 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3168 3193 introduced recently (in 0.2.14pre37) with the fix to the eval
3169 3194 problem mentioned below.
3170 3195
3171 3196 2002-10-17 Fernando Perez <fperez@colorado.edu>
3172 3197
3173 3198 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3174 3199 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3175 3200
3176 3201 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3177 3202 this function to fix a problem reported by Alex Schmolck. He saw
3178 3203 it with list comprehensions and generators, which were getting
3179 3204 called twice. The real problem was an 'eval' call in testing for
3180 3205 automagic which was evaluating the input line silently.
3181 3206
3182 3207 This is a potentially very nasty bug, if the input has side
3183 3208 effects which must not be repeated. The code is much cleaner now,
3184 3209 without any blanket 'except' left and with a regexp test for
3185 3210 actual function names.
3186 3211
3187 3212 But an eval remains, which I'm not fully comfortable with. I just
3188 3213 don't know how to find out if an expression could be a callable in
3189 3214 the user's namespace without doing an eval on the string. However
3190 3215 that string is now much more strictly checked so that no code
3191 3216 slips by, so the eval should only happen for things that can
3192 3217 really be only function/method names.
3193 3218
3194 3219 2002-10-15 Fernando Perez <fperez@colorado.edu>
3195 3220
3196 3221 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3197 3222 OSX information to main manual, removed README_Mac_OSX file from
3198 3223 distribution. Also updated credits for recent additions.
3199 3224
3200 3225 2002-10-10 Fernando Perez <fperez@colorado.edu>
3201 3226
3202 3227 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3203 3228 terminal-related issues. Many thanks to Andrea Riciputi
3204 3229 <andrea.riciputi-AT-libero.it> for writing it.
3205 3230
3206 3231 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3207 3232 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3208 3233
3209 3234 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3210 3235 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3211 3236 <syver-en-AT-online.no> who both submitted patches for this problem.
3212 3237
3213 3238 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3214 3239 global embedding to make sure that things don't overwrite user
3215 3240 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3216 3241
3217 3242 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3218 3243 compatibility. Thanks to Hayden Callow
3219 3244 <h.callow-AT-elec.canterbury.ac.nz>
3220 3245
3221 3246 2002-10-04 Fernando Perez <fperez@colorado.edu>
3222 3247
3223 3248 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3224 3249 Gnuplot.File objects.
3225 3250
3226 3251 2002-07-23 Fernando Perez <fperez@colorado.edu>
3227 3252
3228 3253 * IPython/genutils.py (timing): Added timings() and timing() for
3229 3254 quick access to the most commonly needed data, the execution
3230 3255 times. Old timing() renamed to timings_out().
3231 3256
3232 3257 2002-07-18 Fernando Perez <fperez@colorado.edu>
3233 3258
3234 3259 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3235 3260 bug with nested instances disrupting the parent's tab completion.
3236 3261
3237 3262 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3238 3263 all_completions code to begin the emacs integration.
3239 3264
3240 3265 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3241 3266 argument to allow titling individual arrays when plotting.
3242 3267
3243 3268 2002-07-15 Fernando Perez <fperez@colorado.edu>
3244 3269
3245 3270 * setup.py (make_shortcut): changed to retrieve the value of
3246 3271 'Program Files' directory from the registry (this value changes in
3247 3272 non-english versions of Windows). Thanks to Thomas Fanslau
3248 3273 <tfanslau-AT-gmx.de> for the report.
3249 3274
3250 3275 2002-07-10 Fernando Perez <fperez@colorado.edu>
3251 3276
3252 3277 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3253 3278 a bug in pdb, which crashes if a line with only whitespace is
3254 3279 entered. Bug report submitted to sourceforge.
3255 3280
3256 3281 2002-07-09 Fernando Perez <fperez@colorado.edu>
3257 3282
3258 3283 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3259 3284 reporting exceptions (it's a bug in inspect.py, I just set a
3260 3285 workaround).
3261 3286
3262 3287 2002-07-08 Fernando Perez <fperez@colorado.edu>
3263 3288
3264 3289 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3265 3290 __IPYTHON__ in __builtins__ to show up in user_ns.
3266 3291
3267 3292 2002-07-03 Fernando Perez <fperez@colorado.edu>
3268 3293
3269 3294 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3270 3295 name from @gp_set_instance to @gp_set_default.
3271 3296
3272 3297 * IPython/ipmaker.py (make_IPython): default editor value set to
3273 3298 '0' (a string), to match the rc file. Otherwise will crash when
3274 3299 .strip() is called on it.
3275 3300
3276 3301
3277 3302 2002-06-28 Fernando Perez <fperez@colorado.edu>
3278 3303
3279 3304 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3280 3305 of files in current directory when a file is executed via
3281 3306 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3282 3307
3283 3308 * setup.py (manfiles): fix for rpm builds, submitted by RA
3284 3309 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3285 3310
3286 3311 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3287 3312 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3288 3313 string!). A. Schmolck caught this one.
3289 3314
3290 3315 2002-06-27 Fernando Perez <fperez@colorado.edu>
3291 3316
3292 3317 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3293 3318 defined files at the cmd line. __name__ wasn't being set to
3294 3319 __main__.
3295 3320
3296 3321 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3297 3322 regular lists and tuples besides Numeric arrays.
3298 3323
3299 3324 * IPython/Prompts.py (CachedOutput.__call__): Added output
3300 3325 supression for input ending with ';'. Similar to Mathematica and
3301 3326 Matlab. The _* vars and Out[] list are still updated, just like
3302 3327 Mathematica behaves.
3303 3328
3304 3329 2002-06-25 Fernando Perez <fperez@colorado.edu>
3305 3330
3306 3331 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3307 3332 .ini extensions for profiels under Windows.
3308 3333
3309 3334 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3310 3335 string form. Fix contributed by Alexander Schmolck
3311 3336 <a.schmolck-AT-gmx.net>
3312 3337
3313 3338 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3314 3339 pre-configured Gnuplot instance.
3315 3340
3316 3341 2002-06-21 Fernando Perez <fperez@colorado.edu>
3317 3342
3318 3343 * IPython/numutils.py (exp_safe): new function, works around the
3319 3344 underflow problems in Numeric.
3320 3345 (log2): New fn. Safe log in base 2: returns exact integer answer
3321 3346 for exact integer powers of 2.
3322 3347
3323 3348 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3324 3349 properly.
3325 3350
3326 3351 2002-06-20 Fernando Perez <fperez@colorado.edu>
3327 3352
3328 3353 * IPython/genutils.py (timing): new function like
3329 3354 Mathematica's. Similar to time_test, but returns more info.
3330 3355
3331 3356 2002-06-18 Fernando Perez <fperez@colorado.edu>
3332 3357
3333 3358 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3334 3359 according to Mike Heeter's suggestions.
3335 3360
3336 3361 2002-06-16 Fernando Perez <fperez@colorado.edu>
3337 3362
3338 3363 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3339 3364 system. GnuplotMagic is gone as a user-directory option. New files
3340 3365 make it easier to use all the gnuplot stuff both from external
3341 3366 programs as well as from IPython. Had to rewrite part of
3342 3367 hardcopy() b/c of a strange bug: often the ps files simply don't
3343 3368 get created, and require a repeat of the command (often several
3344 3369 times).
3345 3370
3346 3371 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3347 3372 resolve output channel at call time, so that if sys.stderr has
3348 3373 been redirected by user this gets honored.
3349 3374
3350 3375 2002-06-13 Fernando Perez <fperez@colorado.edu>
3351 3376
3352 3377 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3353 3378 IPShell. Kept a copy with the old names to avoid breaking people's
3354 3379 embedded code.
3355 3380
3356 3381 * IPython/ipython: simplified it to the bare minimum after
3357 3382 Holger's suggestions. Added info about how to use it in
3358 3383 PYTHONSTARTUP.
3359 3384
3360 3385 * IPython/Shell.py (IPythonShell): changed the options passing
3361 3386 from a string with funky %s replacements to a straight list. Maybe
3362 3387 a bit more typing, but it follows sys.argv conventions, so there's
3363 3388 less special-casing to remember.
3364 3389
3365 3390 2002-06-12 Fernando Perez <fperez@colorado.edu>
3366 3391
3367 3392 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3368 3393 command. Thanks to a suggestion by Mike Heeter.
3369 3394 (Magic.magic_pfile): added behavior to look at filenames if given
3370 3395 arg is not a defined object.
3371 3396 (Magic.magic_save): New @save function to save code snippets. Also
3372 3397 a Mike Heeter idea.
3373 3398
3374 3399 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3375 3400 plot() and replot(). Much more convenient now, especially for
3376 3401 interactive use.
3377 3402
3378 3403 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3379 3404 filenames.
3380 3405
3381 3406 2002-06-02 Fernando Perez <fperez@colorado.edu>
3382 3407
3383 3408 * IPython/Struct.py (Struct.__init__): modified to admit
3384 3409 initialization via another struct.
3385 3410
3386 3411 * IPython/genutils.py (SystemExec.__init__): New stateful
3387 3412 interface to xsys and bq. Useful for writing system scripts.
3388 3413
3389 3414 2002-05-30 Fernando Perez <fperez@colorado.edu>
3390 3415
3391 3416 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3392 3417 documents. This will make the user download smaller (it's getting
3393 3418 too big).
3394 3419
3395 3420 2002-05-29 Fernando Perez <fperez@colorado.edu>
3396 3421
3397 3422 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3398 3423 fix problems with shelve and pickle. Seems to work, but I don't
3399 3424 know if corner cases break it. Thanks to Mike Heeter
3400 3425 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3401 3426
3402 3427 2002-05-24 Fernando Perez <fperez@colorado.edu>
3403 3428
3404 3429 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3405 3430 macros having broken.
3406 3431
3407 3432 2002-05-21 Fernando Perez <fperez@colorado.edu>
3408 3433
3409 3434 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3410 3435 introduced logging bug: all history before logging started was
3411 3436 being written one character per line! This came from the redesign
3412 3437 of the input history as a special list which slices to strings,
3413 3438 not to lists.
3414 3439
3415 3440 2002-05-20 Fernando Perez <fperez@colorado.edu>
3416 3441
3417 3442 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3418 3443 be an attribute of all classes in this module. The design of these
3419 3444 classes needs some serious overhauling.
3420 3445
3421 3446 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3422 3447 which was ignoring '_' in option names.
3423 3448
3424 3449 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3425 3450 'Verbose_novars' to 'Context' and made it the new default. It's a
3426 3451 bit more readable and also safer than verbose.
3427 3452
3428 3453 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3429 3454 triple-quoted strings.
3430 3455
3431 3456 * IPython/OInspect.py (__all__): new module exposing the object
3432 3457 introspection facilities. Now the corresponding magics are dummy
3433 3458 wrappers around this. Having this module will make it much easier
3434 3459 to put these functions into our modified pdb.
3435 3460 This new object inspector system uses the new colorizing module,
3436 3461 so source code and other things are nicely syntax highlighted.
3437 3462
3438 3463 2002-05-18 Fernando Perez <fperez@colorado.edu>
3439 3464
3440 3465 * IPython/ColorANSI.py: Split the coloring tools into a separate
3441 3466 module so I can use them in other code easier (they were part of
3442 3467 ultraTB).
3443 3468
3444 3469 2002-05-17 Fernando Perez <fperez@colorado.edu>
3445 3470
3446 3471 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3447 3472 fixed it to set the global 'g' also to the called instance, as
3448 3473 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3449 3474 user's 'g' variables).
3450 3475
3451 3476 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3452 3477 global variables (aliases to _ih,_oh) so that users which expect
3453 3478 In[5] or Out[7] to work aren't unpleasantly surprised.
3454 3479 (InputList.__getslice__): new class to allow executing slices of
3455 3480 input history directly. Very simple class, complements the use of
3456 3481 macros.
3457 3482
3458 3483 2002-05-16 Fernando Perez <fperez@colorado.edu>
3459 3484
3460 3485 * setup.py (docdirbase): make doc directory be just doc/IPython
3461 3486 without version numbers, it will reduce clutter for users.
3462 3487
3463 3488 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3464 3489 execfile call to prevent possible memory leak. See for details:
3465 3490 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3466 3491
3467 3492 2002-05-15 Fernando Perez <fperez@colorado.edu>
3468 3493
3469 3494 * IPython/Magic.py (Magic.magic_psource): made the object
3470 3495 introspection names be more standard: pdoc, pdef, pfile and
3471 3496 psource. They all print/page their output, and it makes
3472 3497 remembering them easier. Kept old names for compatibility as
3473 3498 aliases.
3474 3499
3475 3500 2002-05-14 Fernando Perez <fperez@colorado.edu>
3476 3501
3477 3502 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3478 3503 what the mouse problem was. The trick is to use gnuplot with temp
3479 3504 files and NOT with pipes (for data communication), because having
3480 3505 both pipes and the mouse on is bad news.
3481 3506
3482 3507 2002-05-13 Fernando Perez <fperez@colorado.edu>
3483 3508
3484 3509 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3485 3510 bug. Information would be reported about builtins even when
3486 3511 user-defined functions overrode them.
3487 3512
3488 3513 2002-05-11 Fernando Perez <fperez@colorado.edu>
3489 3514
3490 3515 * IPython/__init__.py (__all__): removed FlexCompleter from
3491 3516 __all__ so that things don't fail in platforms without readline.
3492 3517
3493 3518 2002-05-10 Fernando Perez <fperez@colorado.edu>
3494 3519
3495 3520 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3496 3521 it requires Numeric, effectively making Numeric a dependency for
3497 3522 IPython.
3498 3523
3499 3524 * Released 0.2.13
3500 3525
3501 3526 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3502 3527 profiler interface. Now all the major options from the profiler
3503 3528 module are directly supported in IPython, both for single
3504 3529 expressions (@prun) and for full programs (@run -p).
3505 3530
3506 3531 2002-05-09 Fernando Perez <fperez@colorado.edu>
3507 3532
3508 3533 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3509 3534 magic properly formatted for screen.
3510 3535
3511 3536 * setup.py (make_shortcut): Changed things to put pdf version in
3512 3537 doc/ instead of doc/manual (had to change lyxport a bit).
3513 3538
3514 3539 * IPython/Magic.py (Profile.string_stats): made profile runs go
3515 3540 through pager (they are long and a pager allows searching, saving,
3516 3541 etc.)
3517 3542
3518 3543 2002-05-08 Fernando Perez <fperez@colorado.edu>
3519 3544
3520 3545 * Released 0.2.12
3521 3546
3522 3547 2002-05-06 Fernando Perez <fperez@colorado.edu>
3523 3548
3524 3549 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3525 3550 introduced); 'hist n1 n2' was broken.
3526 3551 (Magic.magic_pdb): added optional on/off arguments to @pdb
3527 3552 (Magic.magic_run): added option -i to @run, which executes code in
3528 3553 the IPython namespace instead of a clean one. Also added @irun as
3529 3554 an alias to @run -i.
3530 3555
3531 3556 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3532 3557 fixed (it didn't really do anything, the namespaces were wrong).
3533 3558
3534 3559 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3535 3560
3536 3561 * IPython/__init__.py (__all__): Fixed package namespace, now
3537 3562 'import IPython' does give access to IPython.<all> as
3538 3563 expected. Also renamed __release__ to Release.
3539 3564
3540 3565 * IPython/Debugger.py (__license__): created new Pdb class which
3541 3566 functions like a drop-in for the normal pdb.Pdb but does NOT
3542 3567 import readline by default. This way it doesn't muck up IPython's
3543 3568 readline handling, and now tab-completion finally works in the
3544 3569 debugger -- sort of. It completes things globally visible, but the
3545 3570 completer doesn't track the stack as pdb walks it. That's a bit
3546 3571 tricky, and I'll have to implement it later.
3547 3572
3548 3573 2002-05-05 Fernando Perez <fperez@colorado.edu>
3549 3574
3550 3575 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3551 3576 magic docstrings when printed via ? (explicit \'s were being
3552 3577 printed).
3553 3578
3554 3579 * IPython/ipmaker.py (make_IPython): fixed namespace
3555 3580 identification bug. Now variables loaded via logs or command-line
3556 3581 files are recognized in the interactive namespace by @who.
3557 3582
3558 3583 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3559 3584 log replay system stemming from the string form of Structs.
3560 3585
3561 3586 * IPython/Magic.py (Macro.__init__): improved macros to properly
3562 3587 handle magic commands in them.
3563 3588 (Magic.magic_logstart): usernames are now expanded so 'logstart
3564 3589 ~/mylog' now works.
3565 3590
3566 3591 * IPython/iplib.py (complete): fixed bug where paths starting with
3567 3592 '/' would be completed as magic names.
3568 3593
3569 3594 2002-05-04 Fernando Perez <fperez@colorado.edu>
3570 3595
3571 3596 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3572 3597 allow running full programs under the profiler's control.
3573 3598
3574 3599 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3575 3600 mode to report exceptions verbosely but without formatting
3576 3601 variables. This addresses the issue of ipython 'freezing' (it's
3577 3602 not frozen, but caught in an expensive formatting loop) when huge
3578 3603 variables are in the context of an exception.
3579 3604 (VerboseTB.text): Added '--->' markers at line where exception was
3580 3605 triggered. Much clearer to read, especially in NoColor modes.
3581 3606
3582 3607 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3583 3608 implemented in reverse when changing to the new parse_options().
3584 3609
3585 3610 2002-05-03 Fernando Perez <fperez@colorado.edu>
3586 3611
3587 3612 * IPython/Magic.py (Magic.parse_options): new function so that
3588 3613 magics can parse options easier.
3589 3614 (Magic.magic_prun): new function similar to profile.run(),
3590 3615 suggested by Chris Hart.
3591 3616 (Magic.magic_cd): fixed behavior so that it only changes if
3592 3617 directory actually is in history.
3593 3618
3594 3619 * IPython/usage.py (__doc__): added information about potential
3595 3620 slowness of Verbose exception mode when there are huge data
3596 3621 structures to be formatted (thanks to Archie Paulson).
3597 3622
3598 3623 * IPython/ipmaker.py (make_IPython): Changed default logging
3599 3624 (when simply called with -log) to use curr_dir/ipython.log in
3600 3625 rotate mode. Fixed crash which was occuring with -log before
3601 3626 (thanks to Jim Boyle).
3602 3627
3603 3628 2002-05-01 Fernando Perez <fperez@colorado.edu>
3604 3629
3605 3630 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3606 3631 was nasty -- though somewhat of a corner case).
3607 3632
3608 3633 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3609 3634 text (was a bug).
3610 3635
3611 3636 2002-04-30 Fernando Perez <fperez@colorado.edu>
3612 3637
3613 3638 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3614 3639 a print after ^D or ^C from the user so that the In[] prompt
3615 3640 doesn't over-run the gnuplot one.
3616 3641
3617 3642 2002-04-29 Fernando Perez <fperez@colorado.edu>
3618 3643
3619 3644 * Released 0.2.10
3620 3645
3621 3646 * IPython/__release__.py (version): get date dynamically.
3622 3647
3623 3648 * Misc. documentation updates thanks to Arnd's comments. Also ran
3624 3649 a full spellcheck on the manual (hadn't been done in a while).
3625 3650
3626 3651 2002-04-27 Fernando Perez <fperez@colorado.edu>
3627 3652
3628 3653 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3629 3654 starting a log in mid-session would reset the input history list.
3630 3655
3631 3656 2002-04-26 Fernando Perez <fperez@colorado.edu>
3632 3657
3633 3658 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3634 3659 all files were being included in an update. Now anything in
3635 3660 UserConfig that matches [A-Za-z]*.py will go (this excludes
3636 3661 __init__.py)
3637 3662
3638 3663 2002-04-25 Fernando Perez <fperez@colorado.edu>
3639 3664
3640 3665 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3641 3666 to __builtins__ so that any form of embedded or imported code can
3642 3667 test for being inside IPython.
3643 3668
3644 3669 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3645 3670 changed to GnuplotMagic because it's now an importable module,
3646 3671 this makes the name follow that of the standard Gnuplot module.
3647 3672 GnuplotMagic can now be loaded at any time in mid-session.
3648 3673
3649 3674 2002-04-24 Fernando Perez <fperez@colorado.edu>
3650 3675
3651 3676 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3652 3677 the globals (IPython has its own namespace) and the
3653 3678 PhysicalQuantity stuff is much better anyway.
3654 3679
3655 3680 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3656 3681 embedding example to standard user directory for
3657 3682 distribution. Also put it in the manual.
3658 3683
3659 3684 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3660 3685 instance as first argument (so it doesn't rely on some obscure
3661 3686 hidden global).
3662 3687
3663 3688 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3664 3689 delimiters. While it prevents ().TAB from working, it allows
3665 3690 completions in open (... expressions. This is by far a more common
3666 3691 case.
3667 3692
3668 3693 2002-04-23 Fernando Perez <fperez@colorado.edu>
3669 3694
3670 3695 * IPython/Extensions/InterpreterPasteInput.py: new
3671 3696 syntax-processing module for pasting lines with >>> or ... at the
3672 3697 start.
3673 3698
3674 3699 * IPython/Extensions/PhysicalQ_Interactive.py
3675 3700 (PhysicalQuantityInteractive.__int__): fixed to work with either
3676 3701 Numeric or math.
3677 3702
3678 3703 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3679 3704 provided profiles. Now we have:
3680 3705 -math -> math module as * and cmath with its own namespace.
3681 3706 -numeric -> Numeric as *, plus gnuplot & grace
3682 3707 -physics -> same as before
3683 3708
3684 3709 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3685 3710 user-defined magics wouldn't be found by @magic if they were
3686 3711 defined as class methods. Also cleaned up the namespace search
3687 3712 logic and the string building (to use %s instead of many repeated
3688 3713 string adds).
3689 3714
3690 3715 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3691 3716 of user-defined magics to operate with class methods (cleaner, in
3692 3717 line with the gnuplot code).
3693 3718
3694 3719 2002-04-22 Fernando Perez <fperez@colorado.edu>
3695 3720
3696 3721 * setup.py: updated dependency list so that manual is updated when
3697 3722 all included files change.
3698 3723
3699 3724 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3700 3725 the delimiter removal option (the fix is ugly right now).
3701 3726
3702 3727 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3703 3728 all of the math profile (quicker loading, no conflict between
3704 3729 g-9.8 and g-gnuplot).
3705 3730
3706 3731 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3707 3732 name of post-mortem files to IPython_crash_report.txt.
3708 3733
3709 3734 * Cleanup/update of the docs. Added all the new readline info and
3710 3735 formatted all lists as 'real lists'.
3711 3736
3712 3737 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3713 3738 tab-completion options, since the full readline parse_and_bind is
3714 3739 now accessible.
3715 3740
3716 3741 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3717 3742 handling of readline options. Now users can specify any string to
3718 3743 be passed to parse_and_bind(), as well as the delimiters to be
3719 3744 removed.
3720 3745 (InteractiveShell.__init__): Added __name__ to the global
3721 3746 namespace so that things like Itpl which rely on its existence
3722 3747 don't crash.
3723 3748 (InteractiveShell._prefilter): Defined the default with a _ so
3724 3749 that prefilter() is easier to override, while the default one
3725 3750 remains available.
3726 3751
3727 3752 2002-04-18 Fernando Perez <fperez@colorado.edu>
3728 3753
3729 3754 * Added information about pdb in the docs.
3730 3755
3731 3756 2002-04-17 Fernando Perez <fperez@colorado.edu>
3732 3757
3733 3758 * IPython/ipmaker.py (make_IPython): added rc_override option to
3734 3759 allow passing config options at creation time which may override
3735 3760 anything set in the config files or command line. This is
3736 3761 particularly useful for configuring embedded instances.
3737 3762
3738 3763 2002-04-15 Fernando Perez <fperez@colorado.edu>
3739 3764
3740 3765 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3741 3766 crash embedded instances because of the input cache falling out of
3742 3767 sync with the output counter.
3743 3768
3744 3769 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3745 3770 mode which calls pdb after an uncaught exception in IPython itself.
3746 3771
3747 3772 2002-04-14 Fernando Perez <fperez@colorado.edu>
3748 3773
3749 3774 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3750 3775 readline, fix it back after each call.
3751 3776
3752 3777 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3753 3778 method to force all access via __call__(), which guarantees that
3754 3779 traceback references are properly deleted.
3755 3780
3756 3781 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3757 3782 improve printing when pprint is in use.
3758 3783
3759 3784 2002-04-13 Fernando Perez <fperez@colorado.edu>
3760 3785
3761 3786 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3762 3787 exceptions aren't caught anymore. If the user triggers one, he
3763 3788 should know why he's doing it and it should go all the way up,
3764 3789 just like any other exception. So now @abort will fully kill the
3765 3790 embedded interpreter and the embedding code (unless that happens
3766 3791 to catch SystemExit).
3767 3792
3768 3793 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3769 3794 and a debugger() method to invoke the interactive pdb debugger
3770 3795 after printing exception information. Also added the corresponding
3771 3796 -pdb option and @pdb magic to control this feature, and updated
3772 3797 the docs. After a suggestion from Christopher Hart
3773 3798 (hart-AT-caltech.edu).
3774 3799
3775 3800 2002-04-12 Fernando Perez <fperez@colorado.edu>
3776 3801
3777 3802 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3778 3803 the exception handlers defined by the user (not the CrashHandler)
3779 3804 so that user exceptions don't trigger an ipython bug report.
3780 3805
3781 3806 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3782 3807 configurable (it should have always been so).
3783 3808
3784 3809 2002-03-26 Fernando Perez <fperez@colorado.edu>
3785 3810
3786 3811 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3787 3812 and there to fix embedding namespace issues. This should all be
3788 3813 done in a more elegant way.
3789 3814
3790 3815 2002-03-25 Fernando Perez <fperez@colorado.edu>
3791 3816
3792 3817 * IPython/genutils.py (get_home_dir): Try to make it work under
3793 3818 win9x also.
3794 3819
3795 3820 2002-03-20 Fernando Perez <fperez@colorado.edu>
3796 3821
3797 3822 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3798 3823 sys.displayhook untouched upon __init__.
3799 3824
3800 3825 2002-03-19 Fernando Perez <fperez@colorado.edu>
3801 3826
3802 3827 * Released 0.2.9 (for embedding bug, basically).
3803 3828
3804 3829 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3805 3830 exceptions so that enclosing shell's state can be restored.
3806 3831
3807 3832 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3808 3833 naming conventions in the .ipython/ dir.
3809 3834
3810 3835 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3811 3836 from delimiters list so filenames with - in them get expanded.
3812 3837
3813 3838 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3814 3839 sys.displayhook not being properly restored after an embedded call.
3815 3840
3816 3841 2002-03-18 Fernando Perez <fperez@colorado.edu>
3817 3842
3818 3843 * Released 0.2.8
3819 3844
3820 3845 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3821 3846 some files weren't being included in a -upgrade.
3822 3847 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3823 3848 on' so that the first tab completes.
3824 3849 (InteractiveShell.handle_magic): fixed bug with spaces around
3825 3850 quotes breaking many magic commands.
3826 3851
3827 3852 * setup.py: added note about ignoring the syntax error messages at
3828 3853 installation.
3829 3854
3830 3855 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3831 3856 streamlining the gnuplot interface, now there's only one magic @gp.
3832 3857
3833 3858 2002-03-17 Fernando Perez <fperez@colorado.edu>
3834 3859
3835 3860 * IPython/UserConfig/magic_gnuplot.py: new name for the
3836 3861 example-magic_pm.py file. Much enhanced system, now with a shell
3837 3862 for communicating directly with gnuplot, one command at a time.
3838 3863
3839 3864 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3840 3865 setting __name__=='__main__'.
3841 3866
3842 3867 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3843 3868 mini-shell for accessing gnuplot from inside ipython. Should
3844 3869 extend it later for grace access too. Inspired by Arnd's
3845 3870 suggestion.
3846 3871
3847 3872 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3848 3873 calling magic functions with () in their arguments. Thanks to Arnd
3849 3874 Baecker for pointing this to me.
3850 3875
3851 3876 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3852 3877 infinitely for integer or complex arrays (only worked with floats).
3853 3878
3854 3879 2002-03-16 Fernando Perez <fperez@colorado.edu>
3855 3880
3856 3881 * setup.py: Merged setup and setup_windows into a single script
3857 3882 which properly handles things for windows users.
3858 3883
3859 3884 2002-03-15 Fernando Perez <fperez@colorado.edu>
3860 3885
3861 3886 * Big change to the manual: now the magics are all automatically
3862 3887 documented. This information is generated from their docstrings
3863 3888 and put in a latex file included by the manual lyx file. This way
3864 3889 we get always up to date information for the magics. The manual
3865 3890 now also has proper version information, also auto-synced.
3866 3891
3867 3892 For this to work, an undocumented --magic_docstrings option was added.
3868 3893
3869 3894 2002-03-13 Fernando Perez <fperez@colorado.edu>
3870 3895
3871 3896 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3872 3897 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3873 3898
3874 3899 2002-03-12 Fernando Perez <fperez@colorado.edu>
3875 3900
3876 3901 * IPython/ultraTB.py (TermColors): changed color escapes again to
3877 3902 fix the (old, reintroduced) line-wrapping bug. Basically, if
3878 3903 \001..\002 aren't given in the color escapes, lines get wrapped
3879 3904 weirdly. But giving those screws up old xterms and emacs terms. So
3880 3905 I added some logic for emacs terms to be ok, but I can't identify old
3881 3906 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3882 3907
3883 3908 2002-03-10 Fernando Perez <fperez@colorado.edu>
3884 3909
3885 3910 * IPython/usage.py (__doc__): Various documentation cleanups and
3886 3911 updates, both in usage docstrings and in the manual.
3887 3912
3888 3913 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3889 3914 handling of caching. Set minimum acceptabe value for having a
3890 3915 cache at 20 values.
3891 3916
3892 3917 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3893 3918 install_first_time function to a method, renamed it and added an
3894 3919 'upgrade' mode. Now people can update their config directory with
3895 3920 a simple command line switch (-upgrade, also new).
3896 3921
3897 3922 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3898 3923 @file (convenient for automagic users under Python >= 2.2).
3899 3924 Removed @files (it seemed more like a plural than an abbrev. of
3900 3925 'file show').
3901 3926
3902 3927 * IPython/iplib.py (install_first_time): Fixed crash if there were
3903 3928 backup files ('~') in .ipython/ install directory.
3904 3929
3905 3930 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3906 3931 system. Things look fine, but these changes are fairly
3907 3932 intrusive. Test them for a few days.
3908 3933
3909 3934 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3910 3935 the prompts system. Now all in/out prompt strings are user
3911 3936 controllable. This is particularly useful for embedding, as one
3912 3937 can tag embedded instances with particular prompts.
3913 3938
3914 3939 Also removed global use of sys.ps1/2, which now allows nested
3915 3940 embeddings without any problems. Added command-line options for
3916 3941 the prompt strings.
3917 3942
3918 3943 2002-03-08 Fernando Perez <fperez@colorado.edu>
3919 3944
3920 3945 * IPython/UserConfig/example-embed-short.py (ipshell): added
3921 3946 example file with the bare minimum code for embedding.
3922 3947
3923 3948 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3924 3949 functionality for the embeddable shell to be activated/deactivated
3925 3950 either globally or at each call.
3926 3951
3927 3952 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3928 3953 rewriting the prompt with '--->' for auto-inputs with proper
3929 3954 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3930 3955 this is handled by the prompts class itself, as it should.
3931 3956
3932 3957 2002-03-05 Fernando Perez <fperez@colorado.edu>
3933 3958
3934 3959 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3935 3960 @logstart to avoid name clashes with the math log function.
3936 3961
3937 3962 * Big updates to X/Emacs section of the manual.
3938 3963
3939 3964 * Removed ipython_emacs. Milan explained to me how to pass
3940 3965 arguments to ipython through Emacs. Some day I'm going to end up
3941 3966 learning some lisp...
3942 3967
3943 3968 2002-03-04 Fernando Perez <fperez@colorado.edu>
3944 3969
3945 3970 * IPython/ipython_emacs: Created script to be used as the
3946 3971 py-python-command Emacs variable so we can pass IPython
3947 3972 parameters. I can't figure out how to tell Emacs directly to pass
3948 3973 parameters to IPython, so a dummy shell script will do it.
3949 3974
3950 3975 Other enhancements made for things to work better under Emacs'
3951 3976 various types of terminals. Many thanks to Milan Zamazal
3952 3977 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3953 3978
3954 3979 2002-03-01 Fernando Perez <fperez@colorado.edu>
3955 3980
3956 3981 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3957 3982 that loading of readline is now optional. This gives better
3958 3983 control to emacs users.
3959 3984
3960 3985 * IPython/ultraTB.py (__date__): Modified color escape sequences
3961 3986 and now things work fine under xterm and in Emacs' term buffers
3962 3987 (though not shell ones). Well, in emacs you get colors, but all
3963 3988 seem to be 'light' colors (no difference between dark and light
3964 3989 ones). But the garbage chars are gone, and also in xterms. It
3965 3990 seems that now I'm using 'cleaner' ansi sequences.
3966 3991
3967 3992 2002-02-21 Fernando Perez <fperez@colorado.edu>
3968 3993
3969 3994 * Released 0.2.7 (mainly to publish the scoping fix).
3970 3995
3971 3996 * IPython/Logger.py (Logger.logstate): added. A corresponding
3972 3997 @logstate magic was created.
3973 3998
3974 3999 * IPython/Magic.py: fixed nested scoping problem under Python
3975 4000 2.1.x (automagic wasn't working).
3976 4001
3977 4002 2002-02-20 Fernando Perez <fperez@colorado.edu>
3978 4003
3979 4004 * Released 0.2.6.
3980 4005
3981 4006 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3982 4007 option so that logs can come out without any headers at all.
3983 4008
3984 4009 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3985 4010 SciPy.
3986 4011
3987 4012 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3988 4013 that embedded IPython calls don't require vars() to be explicitly
3989 4014 passed. Now they are extracted from the caller's frame (code
3990 4015 snatched from Eric Jones' weave). Added better documentation to
3991 4016 the section on embedding and the example file.
3992 4017
3993 4018 * IPython/genutils.py (page): Changed so that under emacs, it just
3994 4019 prints the string. You can then page up and down in the emacs
3995 4020 buffer itself. This is how the builtin help() works.
3996 4021
3997 4022 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3998 4023 macro scoping: macros need to be executed in the user's namespace
3999 4024 to work as if they had been typed by the user.
4000 4025
4001 4026 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4002 4027 execute automatically (no need to type 'exec...'). They then
4003 4028 behave like 'true macros'. The printing system was also modified
4004 4029 for this to work.
4005 4030
4006 4031 2002-02-19 Fernando Perez <fperez@colorado.edu>
4007 4032
4008 4033 * IPython/genutils.py (page_file): new function for paging files
4009 4034 in an OS-independent way. Also necessary for file viewing to work
4010 4035 well inside Emacs buffers.
4011 4036 (page): Added checks for being in an emacs buffer.
4012 4037 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4013 4038 same bug in iplib.
4014 4039
4015 4040 2002-02-18 Fernando Perez <fperez@colorado.edu>
4016 4041
4017 4042 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4018 4043 of readline so that IPython can work inside an Emacs buffer.
4019 4044
4020 4045 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4021 4046 method signatures (they weren't really bugs, but it looks cleaner
4022 4047 and keeps PyChecker happy).
4023 4048
4024 4049 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4025 4050 for implementing various user-defined hooks. Currently only
4026 4051 display is done.
4027 4052
4028 4053 * IPython/Prompts.py (CachedOutput._display): changed display
4029 4054 functions so that they can be dynamically changed by users easily.
4030 4055
4031 4056 * IPython/Extensions/numeric_formats.py (num_display): added an
4032 4057 extension for printing NumPy arrays in flexible manners. It
4033 4058 doesn't do anything yet, but all the structure is in
4034 4059 place. Ultimately the plan is to implement output format control
4035 4060 like in Octave.
4036 4061
4037 4062 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4038 4063 methods are found at run-time by all the automatic machinery.
4039 4064
4040 4065 2002-02-17 Fernando Perez <fperez@colorado.edu>
4041 4066
4042 4067 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4043 4068 whole file a little.
4044 4069
4045 4070 * ToDo: closed this document. Now there's a new_design.lyx
4046 4071 document for all new ideas. Added making a pdf of it for the
4047 4072 end-user distro.
4048 4073
4049 4074 * IPython/Logger.py (Logger.switch_log): Created this to replace
4050 4075 logon() and logoff(). It also fixes a nasty crash reported by
4051 4076 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4052 4077
4053 4078 * IPython/iplib.py (complete): got auto-completion to work with
4054 4079 automagic (I had wanted this for a long time).
4055 4080
4056 4081 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4057 4082 to @file, since file() is now a builtin and clashes with automagic
4058 4083 for @file.
4059 4084
4060 4085 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4061 4086 of this was previously in iplib, which had grown to more than 2000
4062 4087 lines, way too long. No new functionality, but it makes managing
4063 4088 the code a bit easier.
4064 4089
4065 4090 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4066 4091 information to crash reports.
4067 4092
4068 4093 2002-02-12 Fernando Perez <fperez@colorado.edu>
4069 4094
4070 4095 * Released 0.2.5.
4071 4096
4072 4097 2002-02-11 Fernando Perez <fperez@colorado.edu>
4073 4098
4074 4099 * Wrote a relatively complete Windows installer. It puts
4075 4100 everything in place, creates Start Menu entries and fixes the
4076 4101 color issues. Nothing fancy, but it works.
4077 4102
4078 4103 2002-02-10 Fernando Perez <fperez@colorado.edu>
4079 4104
4080 4105 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4081 4106 os.path.expanduser() call so that we can type @run ~/myfile.py and
4082 4107 have thigs work as expected.
4083 4108
4084 4109 * IPython/genutils.py (page): fixed exception handling so things
4085 4110 work both in Unix and Windows correctly. Quitting a pager triggers
4086 4111 an IOError/broken pipe in Unix, and in windows not finding a pager
4087 4112 is also an IOError, so I had to actually look at the return value
4088 4113 of the exception, not just the exception itself. Should be ok now.
4089 4114
4090 4115 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4091 4116 modified to allow case-insensitive color scheme changes.
4092 4117
4093 4118 2002-02-09 Fernando Perez <fperez@colorado.edu>
4094 4119
4095 4120 * IPython/genutils.py (native_line_ends): new function to leave
4096 4121 user config files with os-native line-endings.
4097 4122
4098 4123 * README and manual updates.
4099 4124
4100 4125 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4101 4126 instead of StringType to catch Unicode strings.
4102 4127
4103 4128 * IPython/genutils.py (filefind): fixed bug for paths with
4104 4129 embedded spaces (very common in Windows).
4105 4130
4106 4131 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4107 4132 files under Windows, so that they get automatically associated
4108 4133 with a text editor. Windows makes it a pain to handle
4109 4134 extension-less files.
4110 4135
4111 4136 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4112 4137 warning about readline only occur for Posix. In Windows there's no
4113 4138 way to get readline, so why bother with the warning.
4114 4139
4115 4140 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4116 4141 for __str__ instead of dir(self), since dir() changed in 2.2.
4117 4142
4118 4143 * Ported to Windows! Tested on XP, I suspect it should work fine
4119 4144 on NT/2000, but I don't think it will work on 98 et al. That
4120 4145 series of Windows is such a piece of junk anyway that I won't try
4121 4146 porting it there. The XP port was straightforward, showed a few
4122 4147 bugs here and there (fixed all), in particular some string
4123 4148 handling stuff which required considering Unicode strings (which
4124 4149 Windows uses). This is good, but hasn't been too tested :) No
4125 4150 fancy installer yet, I'll put a note in the manual so people at
4126 4151 least make manually a shortcut.
4127 4152
4128 4153 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4129 4154 into a single one, "colors". This now controls both prompt and
4130 4155 exception color schemes, and can be changed both at startup
4131 4156 (either via command-line switches or via ipythonrc files) and at
4132 4157 runtime, with @colors.
4133 4158 (Magic.magic_run): renamed @prun to @run and removed the old
4134 4159 @run. The two were too similar to warrant keeping both.
4135 4160
4136 4161 2002-02-03 Fernando Perez <fperez@colorado.edu>
4137 4162
4138 4163 * IPython/iplib.py (install_first_time): Added comment on how to
4139 4164 configure the color options for first-time users. Put a <return>
4140 4165 request at the end so that small-terminal users get a chance to
4141 4166 read the startup info.
4142 4167
4143 4168 2002-01-23 Fernando Perez <fperez@colorado.edu>
4144 4169
4145 4170 * IPython/iplib.py (CachedOutput.update): Changed output memory
4146 4171 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4147 4172 input history we still use _i. Did this b/c these variable are
4148 4173 very commonly used in interactive work, so the less we need to
4149 4174 type the better off we are.
4150 4175 (Magic.magic_prun): updated @prun to better handle the namespaces
4151 4176 the file will run in, including a fix for __name__ not being set
4152 4177 before.
4153 4178
4154 4179 2002-01-20 Fernando Perez <fperez@colorado.edu>
4155 4180
4156 4181 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4157 4182 extra garbage for Python 2.2. Need to look more carefully into
4158 4183 this later.
4159 4184
4160 4185 2002-01-19 Fernando Perez <fperez@colorado.edu>
4161 4186
4162 4187 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4163 4188 display SyntaxError exceptions properly formatted when they occur
4164 4189 (they can be triggered by imported code).
4165 4190
4166 4191 2002-01-18 Fernando Perez <fperez@colorado.edu>
4167 4192
4168 4193 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4169 4194 SyntaxError exceptions are reported nicely formatted, instead of
4170 4195 spitting out only offset information as before.
4171 4196 (Magic.magic_prun): Added the @prun function for executing
4172 4197 programs with command line args inside IPython.
4173 4198
4174 4199 2002-01-16 Fernando Perez <fperez@colorado.edu>
4175 4200
4176 4201 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4177 4202 to *not* include the last item given in a range. This brings their
4178 4203 behavior in line with Python's slicing:
4179 4204 a[n1:n2] -> a[n1]...a[n2-1]
4180 4205 It may be a bit less convenient, but I prefer to stick to Python's
4181 4206 conventions *everywhere*, so users never have to wonder.
4182 4207 (Magic.magic_macro): Added @macro function to ease the creation of
4183 4208 macros.
4184 4209
4185 4210 2002-01-05 Fernando Perez <fperez@colorado.edu>
4186 4211
4187 4212 * Released 0.2.4.
4188 4213
4189 4214 * IPython/iplib.py (Magic.magic_pdef):
4190 4215 (InteractiveShell.safe_execfile): report magic lines and error
4191 4216 lines without line numbers so one can easily copy/paste them for
4192 4217 re-execution.
4193 4218
4194 4219 * Updated manual with recent changes.
4195 4220
4196 4221 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4197 4222 docstring printing when class? is called. Very handy for knowing
4198 4223 how to create class instances (as long as __init__ is well
4199 4224 documented, of course :)
4200 4225 (Magic.magic_doc): print both class and constructor docstrings.
4201 4226 (Magic.magic_pdef): give constructor info if passed a class and
4202 4227 __call__ info for callable object instances.
4203 4228
4204 4229 2002-01-04 Fernando Perez <fperez@colorado.edu>
4205 4230
4206 4231 * Made deep_reload() off by default. It doesn't always work
4207 4232 exactly as intended, so it's probably safer to have it off. It's
4208 4233 still available as dreload() anyway, so nothing is lost.
4209 4234
4210 4235 2002-01-02 Fernando Perez <fperez@colorado.edu>
4211 4236
4212 4237 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4213 4238 so I wanted an updated release).
4214 4239
4215 4240 2001-12-27 Fernando Perez <fperez@colorado.edu>
4216 4241
4217 4242 * IPython/iplib.py (InteractiveShell.interact): Added the original
4218 4243 code from 'code.py' for this module in order to change the
4219 4244 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4220 4245 the history cache would break when the user hit Ctrl-C, and
4221 4246 interact() offers no way to add any hooks to it.
4222 4247
4223 4248 2001-12-23 Fernando Perez <fperez@colorado.edu>
4224 4249
4225 4250 * setup.py: added check for 'MANIFEST' before trying to remove
4226 4251 it. Thanks to Sean Reifschneider.
4227 4252
4228 4253 2001-12-22 Fernando Perez <fperez@colorado.edu>
4229 4254
4230 4255 * Released 0.2.2.
4231 4256
4232 4257 * Finished (reasonably) writing the manual. Later will add the
4233 4258 python-standard navigation stylesheets, but for the time being
4234 4259 it's fairly complete. Distribution will include html and pdf
4235 4260 versions.
4236 4261
4237 4262 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4238 4263 (MayaVi author).
4239 4264
4240 4265 2001-12-21 Fernando Perez <fperez@colorado.edu>
4241 4266
4242 4267 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4243 4268 good public release, I think (with the manual and the distutils
4244 4269 installer). The manual can use some work, but that can go
4245 4270 slowly. Otherwise I think it's quite nice for end users. Next
4246 4271 summer, rewrite the guts of it...
4247 4272
4248 4273 * Changed format of ipythonrc files to use whitespace as the
4249 4274 separator instead of an explicit '='. Cleaner.
4250 4275
4251 4276 2001-12-20 Fernando Perez <fperez@colorado.edu>
4252 4277
4253 4278 * Started a manual in LyX. For now it's just a quick merge of the
4254 4279 various internal docstrings and READMEs. Later it may grow into a
4255 4280 nice, full-blown manual.
4256 4281
4257 4282 * Set up a distutils based installer. Installation should now be
4258 4283 trivially simple for end-users.
4259 4284
4260 4285 2001-12-11 Fernando Perez <fperez@colorado.edu>
4261 4286
4262 4287 * Released 0.2.0. First public release, announced it at
4263 4288 comp.lang.python. From now on, just bugfixes...
4264 4289
4265 4290 * Went through all the files, set copyright/license notices and
4266 4291 cleaned up things. Ready for release.
4267 4292
4268 4293 2001-12-10 Fernando Perez <fperez@colorado.edu>
4269 4294
4270 4295 * Changed the first-time installer not to use tarfiles. It's more
4271 4296 robust now and less unix-dependent. Also makes it easier for
4272 4297 people to later upgrade versions.
4273 4298
4274 4299 * Changed @exit to @abort to reflect the fact that it's pretty
4275 4300 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4276 4301 becomes significant only when IPyhton is embedded: in that case,
4277 4302 C-D closes IPython only, but @abort kills the enclosing program
4278 4303 too (unless it had called IPython inside a try catching
4279 4304 SystemExit).
4280 4305
4281 4306 * Created Shell module which exposes the actuall IPython Shell
4282 4307 classes, currently the normal and the embeddable one. This at
4283 4308 least offers a stable interface we won't need to change when
4284 4309 (later) the internals are rewritten. That rewrite will be confined
4285 4310 to iplib and ipmaker, but the Shell interface should remain as is.
4286 4311
4287 4312 * Added embed module which offers an embeddable IPShell object,
4288 4313 useful to fire up IPython *inside* a running program. Great for
4289 4314 debugging or dynamical data analysis.
4290 4315
4291 4316 2001-12-08 Fernando Perez <fperez@colorado.edu>
4292 4317
4293 4318 * Fixed small bug preventing seeing info from methods of defined
4294 4319 objects (incorrect namespace in _ofind()).
4295 4320
4296 4321 * Documentation cleanup. Moved the main usage docstrings to a
4297 4322 separate file, usage.py (cleaner to maintain, and hopefully in the
4298 4323 future some perlpod-like way of producing interactive, man and
4299 4324 html docs out of it will be found).
4300 4325
4301 4326 * Added @profile to see your profile at any time.
4302 4327
4303 4328 * Added @p as an alias for 'print'. It's especially convenient if
4304 4329 using automagic ('p x' prints x).
4305 4330
4306 4331 * Small cleanups and fixes after a pychecker run.
4307 4332
4308 4333 * Changed the @cd command to handle @cd - and @cd -<n> for
4309 4334 visiting any directory in _dh.
4310 4335
4311 4336 * Introduced _dh, a history of visited directories. @dhist prints
4312 4337 it out with numbers.
4313 4338
4314 4339 2001-12-07 Fernando Perez <fperez@colorado.edu>
4315 4340
4316 4341 * Released 0.1.22
4317 4342
4318 4343 * Made initialization a bit more robust against invalid color
4319 4344 options in user input (exit, not traceback-crash).
4320 4345
4321 4346 * Changed the bug crash reporter to write the report only in the
4322 4347 user's .ipython directory. That way IPython won't litter people's
4323 4348 hard disks with crash files all over the place. Also print on
4324 4349 screen the necessary mail command.
4325 4350
4326 4351 * With the new ultraTB, implemented LightBG color scheme for light
4327 4352 background terminals. A lot of people like white backgrounds, so I
4328 4353 guess we should at least give them something readable.
4329 4354
4330 4355 2001-12-06 Fernando Perez <fperez@colorado.edu>
4331 4356
4332 4357 * Modified the structure of ultraTB. Now there's a proper class
4333 4358 for tables of color schemes which allow adding schemes easily and
4334 4359 switching the active scheme without creating a new instance every
4335 4360 time (which was ridiculous). The syntax for creating new schemes
4336 4361 is also cleaner. I think ultraTB is finally done, with a clean
4337 4362 class structure. Names are also much cleaner (now there's proper
4338 4363 color tables, no need for every variable to also have 'color' in
4339 4364 its name).
4340 4365
4341 4366 * Broke down genutils into separate files. Now genutils only
4342 4367 contains utility functions, and classes have been moved to their
4343 4368 own files (they had enough independent functionality to warrant
4344 4369 it): ConfigLoader, OutputTrap, Struct.
4345 4370
4346 4371 2001-12-05 Fernando Perez <fperez@colorado.edu>
4347 4372
4348 4373 * IPython turns 21! Released version 0.1.21, as a candidate for
4349 4374 public consumption. If all goes well, release in a few days.
4350 4375
4351 4376 * Fixed path bug (files in Extensions/ directory wouldn't be found
4352 4377 unless IPython/ was explicitly in sys.path).
4353 4378
4354 4379 * Extended the FlexCompleter class as MagicCompleter to allow
4355 4380 completion of @-starting lines.
4356 4381
4357 4382 * Created __release__.py file as a central repository for release
4358 4383 info that other files can read from.
4359 4384
4360 4385 * Fixed small bug in logging: when logging was turned on in
4361 4386 mid-session, old lines with special meanings (!@?) were being
4362 4387 logged without the prepended comment, which is necessary since
4363 4388 they are not truly valid python syntax. This should make session
4364 4389 restores produce less errors.
4365 4390
4366 4391 * The namespace cleanup forced me to make a FlexCompleter class
4367 4392 which is nothing but a ripoff of rlcompleter, but with selectable
4368 4393 namespace (rlcompleter only works in __main__.__dict__). I'll try
4369 4394 to submit a note to the authors to see if this change can be
4370 4395 incorporated in future rlcompleter releases (Dec.6: done)
4371 4396
4372 4397 * More fixes to namespace handling. It was a mess! Now all
4373 4398 explicit references to __main__.__dict__ are gone (except when
4374 4399 really needed) and everything is handled through the namespace
4375 4400 dicts in the IPython instance. We seem to be getting somewhere
4376 4401 with this, finally...
4377 4402
4378 4403 * Small documentation updates.
4379 4404
4380 4405 * Created the Extensions directory under IPython (with an
4381 4406 __init__.py). Put the PhysicalQ stuff there. This directory should
4382 4407 be used for all special-purpose extensions.
4383 4408
4384 4409 * File renaming:
4385 4410 ipythonlib --> ipmaker
4386 4411 ipplib --> iplib
4387 4412 This makes a bit more sense in terms of what these files actually do.
4388 4413
4389 4414 * Moved all the classes and functions in ipythonlib to ipplib, so
4390 4415 now ipythonlib only has make_IPython(). This will ease up its
4391 4416 splitting in smaller functional chunks later.
4392 4417
4393 4418 * Cleaned up (done, I think) output of @whos. Better column
4394 4419 formatting, and now shows str(var) for as much as it can, which is
4395 4420 typically what one gets with a 'print var'.
4396 4421
4397 4422 2001-12-04 Fernando Perez <fperez@colorado.edu>
4398 4423
4399 4424 * Fixed namespace problems. Now builtin/IPyhton/user names get
4400 4425 properly reported in their namespace. Internal namespace handling
4401 4426 is finally getting decent (not perfect yet, but much better than
4402 4427 the ad-hoc mess we had).
4403 4428
4404 4429 * Removed -exit option. If people just want to run a python
4405 4430 script, that's what the normal interpreter is for. Less
4406 4431 unnecessary options, less chances for bugs.
4407 4432
4408 4433 * Added a crash handler which generates a complete post-mortem if
4409 4434 IPython crashes. This will help a lot in tracking bugs down the
4410 4435 road.
4411 4436
4412 4437 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4413 4438 which were boud to functions being reassigned would bypass the
4414 4439 logger, breaking the sync of _il with the prompt counter. This
4415 4440 would then crash IPython later when a new line was logged.
4416 4441
4417 4442 2001-12-02 Fernando Perez <fperez@colorado.edu>
4418 4443
4419 4444 * Made IPython a package. This means people don't have to clutter
4420 4445 their sys.path with yet another directory. Changed the INSTALL
4421 4446 file accordingly.
4422 4447
4423 4448 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4424 4449 sorts its output (so @who shows it sorted) and @whos formats the
4425 4450 table according to the width of the first column. Nicer, easier to
4426 4451 read. Todo: write a generic table_format() which takes a list of
4427 4452 lists and prints it nicely formatted, with optional row/column
4428 4453 separators and proper padding and justification.
4429 4454
4430 4455 * Released 0.1.20
4431 4456
4432 4457 * Fixed bug in @log which would reverse the inputcache list (a
4433 4458 copy operation was missing).
4434 4459
4435 4460 * Code cleanup. @config was changed to use page(). Better, since
4436 4461 its output is always quite long.
4437 4462
4438 4463 * Itpl is back as a dependency. I was having too many problems
4439 4464 getting the parametric aliases to work reliably, and it's just
4440 4465 easier to code weird string operations with it than playing %()s
4441 4466 games. It's only ~6k, so I don't think it's too big a deal.
4442 4467
4443 4468 * Found (and fixed) a very nasty bug with history. !lines weren't
4444 4469 getting cached, and the out of sync caches would crash
4445 4470 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4446 4471 division of labor a bit better. Bug fixed, cleaner structure.
4447 4472
4448 4473 2001-12-01 Fernando Perez <fperez@colorado.edu>
4449 4474
4450 4475 * Released 0.1.19
4451 4476
4452 4477 * Added option -n to @hist to prevent line number printing. Much
4453 4478 easier to copy/paste code this way.
4454 4479
4455 4480 * Created global _il to hold the input list. Allows easy
4456 4481 re-execution of blocks of code by slicing it (inspired by Janko's
4457 4482 comment on 'macros').
4458 4483
4459 4484 * Small fixes and doc updates.
4460 4485
4461 4486 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4462 4487 much too fragile with automagic. Handles properly multi-line
4463 4488 statements and takes parameters.
4464 4489
4465 4490 2001-11-30 Fernando Perez <fperez@colorado.edu>
4466 4491
4467 4492 * Version 0.1.18 released.
4468 4493
4469 4494 * Fixed nasty namespace bug in initial module imports.
4470 4495
4471 4496 * Added copyright/license notes to all code files (except
4472 4497 DPyGetOpt). For the time being, LGPL. That could change.
4473 4498
4474 4499 * Rewrote a much nicer README, updated INSTALL, cleaned up
4475 4500 ipythonrc-* samples.
4476 4501
4477 4502 * Overall code/documentation cleanup. Basically ready for
4478 4503 release. Only remaining thing: licence decision (LGPL?).
4479 4504
4480 4505 * Converted load_config to a class, ConfigLoader. Now recursion
4481 4506 control is better organized. Doesn't include the same file twice.
4482 4507
4483 4508 2001-11-29 Fernando Perez <fperez@colorado.edu>
4484 4509
4485 4510 * Got input history working. Changed output history variables from
4486 4511 _p to _o so that _i is for input and _o for output. Just cleaner
4487 4512 convention.
4488 4513
4489 4514 * Implemented parametric aliases. This pretty much allows the
4490 4515 alias system to offer full-blown shell convenience, I think.
4491 4516
4492 4517 * Version 0.1.17 released, 0.1.18 opened.
4493 4518
4494 4519 * dot_ipython/ipythonrc (alias): added documentation.
4495 4520 (xcolor): Fixed small bug (xcolors -> xcolor)
4496 4521
4497 4522 * Changed the alias system. Now alias is a magic command to define
4498 4523 aliases just like the shell. Rationale: the builtin magics should
4499 4524 be there for things deeply connected to IPython's
4500 4525 architecture. And this is a much lighter system for what I think
4501 4526 is the really important feature: allowing users to define quickly
4502 4527 magics that will do shell things for them, so they can customize
4503 4528 IPython easily to match their work habits. If someone is really
4504 4529 desperate to have another name for a builtin alias, they can
4505 4530 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4506 4531 works.
4507 4532
4508 4533 2001-11-28 Fernando Perez <fperez@colorado.edu>
4509 4534
4510 4535 * Changed @file so that it opens the source file at the proper
4511 4536 line. Since it uses less, if your EDITOR environment is
4512 4537 configured, typing v will immediately open your editor of choice
4513 4538 right at the line where the object is defined. Not as quick as
4514 4539 having a direct @edit command, but for all intents and purposes it
4515 4540 works. And I don't have to worry about writing @edit to deal with
4516 4541 all the editors, less does that.
4517 4542
4518 4543 * Version 0.1.16 released, 0.1.17 opened.
4519 4544
4520 4545 * Fixed some nasty bugs in the page/page_dumb combo that could
4521 4546 crash IPython.
4522 4547
4523 4548 2001-11-27 Fernando Perez <fperez@colorado.edu>
4524 4549
4525 4550 * Version 0.1.15 released, 0.1.16 opened.
4526 4551
4527 4552 * Finally got ? and ?? to work for undefined things: now it's
4528 4553 possible to type {}.get? and get information about the get method
4529 4554 of dicts, or os.path? even if only os is defined (so technically
4530 4555 os.path isn't). Works at any level. For example, after import os,
4531 4556 os?, os.path?, os.path.abspath? all work. This is great, took some
4532 4557 work in _ofind.
4533 4558
4534 4559 * Fixed more bugs with logging. The sanest way to do it was to add
4535 4560 to @log a 'mode' parameter. Killed two in one shot (this mode
4536 4561 option was a request of Janko's). I think it's finally clean
4537 4562 (famous last words).
4538 4563
4539 4564 * Added a page_dumb() pager which does a decent job of paging on
4540 4565 screen, if better things (like less) aren't available. One less
4541 4566 unix dependency (someday maybe somebody will port this to
4542 4567 windows).
4543 4568
4544 4569 * Fixed problem in magic_log: would lock of logging out if log
4545 4570 creation failed (because it would still think it had succeeded).
4546 4571
4547 4572 * Improved the page() function using curses to auto-detect screen
4548 4573 size. Now it can make a much better decision on whether to print
4549 4574 or page a string. Option screen_length was modified: a value 0
4550 4575 means auto-detect, and that's the default now.
4551 4576
4552 4577 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4553 4578 go out. I'll test it for a few days, then talk to Janko about
4554 4579 licences and announce it.
4555 4580
4556 4581 * Fixed the length of the auto-generated ---> prompt which appears
4557 4582 for auto-parens and auto-quotes. Getting this right isn't trivial,
4558 4583 with all the color escapes, different prompt types and optional
4559 4584 separators. But it seems to be working in all the combinations.
4560 4585
4561 4586 2001-11-26 Fernando Perez <fperez@colorado.edu>
4562 4587
4563 4588 * Wrote a regexp filter to get option types from the option names
4564 4589 string. This eliminates the need to manually keep two duplicate
4565 4590 lists.
4566 4591
4567 4592 * Removed the unneeded check_option_names. Now options are handled
4568 4593 in a much saner manner and it's easy to visually check that things
4569 4594 are ok.
4570 4595
4571 4596 * Updated version numbers on all files I modified to carry a
4572 4597 notice so Janko and Nathan have clear version markers.
4573 4598
4574 4599 * Updated docstring for ultraTB with my changes. I should send
4575 4600 this to Nathan.
4576 4601
4577 4602 * Lots of small fixes. Ran everything through pychecker again.
4578 4603
4579 4604 * Made loading of deep_reload an cmd line option. If it's not too
4580 4605 kosher, now people can just disable it. With -nodeep_reload it's
4581 4606 still available as dreload(), it just won't overwrite reload().
4582 4607
4583 4608 * Moved many options to the no| form (-opt and -noopt
4584 4609 accepted). Cleaner.
4585 4610
4586 4611 * Changed magic_log so that if called with no parameters, it uses
4587 4612 'rotate' mode. That way auto-generated logs aren't automatically
4588 4613 over-written. For normal logs, now a backup is made if it exists
4589 4614 (only 1 level of backups). A new 'backup' mode was added to the
4590 4615 Logger class to support this. This was a request by Janko.
4591 4616
4592 4617 * Added @logoff/@logon to stop/restart an active log.
4593 4618
4594 4619 * Fixed a lot of bugs in log saving/replay. It was pretty
4595 4620 broken. Now special lines (!@,/) appear properly in the command
4596 4621 history after a log replay.
4597 4622
4598 4623 * Tried and failed to implement full session saving via pickle. My
4599 4624 idea was to pickle __main__.__dict__, but modules can't be
4600 4625 pickled. This would be a better alternative to replaying logs, but
4601 4626 seems quite tricky to get to work. Changed -session to be called
4602 4627 -logplay, which more accurately reflects what it does. And if we
4603 4628 ever get real session saving working, -session is now available.
4604 4629
4605 4630 * Implemented color schemes for prompts also. As for tracebacks,
4606 4631 currently only NoColor and Linux are supported. But now the
4607 4632 infrastructure is in place, based on a generic ColorScheme
4608 4633 class. So writing and activating new schemes both for the prompts
4609 4634 and the tracebacks should be straightforward.
4610 4635
4611 4636 * Version 0.1.13 released, 0.1.14 opened.
4612 4637
4613 4638 * Changed handling of options for output cache. Now counter is
4614 4639 hardwired starting at 1 and one specifies the maximum number of
4615 4640 entries *in the outcache* (not the max prompt counter). This is
4616 4641 much better, since many statements won't increase the cache
4617 4642 count. It also eliminated some confusing options, now there's only
4618 4643 one: cache_size.
4619 4644
4620 4645 * Added 'alias' magic function and magic_alias option in the
4621 4646 ipythonrc file. Now the user can easily define whatever names he
4622 4647 wants for the magic functions without having to play weird
4623 4648 namespace games. This gives IPython a real shell-like feel.
4624 4649
4625 4650 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4626 4651 @ or not).
4627 4652
4628 4653 This was one of the last remaining 'visible' bugs (that I know
4629 4654 of). I think if I can clean up the session loading so it works
4630 4655 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4631 4656 about licensing).
4632 4657
4633 4658 2001-11-25 Fernando Perez <fperez@colorado.edu>
4634 4659
4635 4660 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4636 4661 there's a cleaner distinction between what ? and ?? show.
4637 4662
4638 4663 * Added screen_length option. Now the user can define his own
4639 4664 screen size for page() operations.
4640 4665
4641 4666 * Implemented magic shell-like functions with automatic code
4642 4667 generation. Now adding another function is just a matter of adding
4643 4668 an entry to a dict, and the function is dynamically generated at
4644 4669 run-time. Python has some really cool features!
4645 4670
4646 4671 * Renamed many options to cleanup conventions a little. Now all
4647 4672 are lowercase, and only underscores where needed. Also in the code
4648 4673 option name tables are clearer.
4649 4674
4650 4675 * Changed prompts a little. Now input is 'In [n]:' instead of
4651 4676 'In[n]:='. This allows it the numbers to be aligned with the
4652 4677 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4653 4678 Python (it was a Mathematica thing). The '...' continuation prompt
4654 4679 was also changed a little to align better.
4655 4680
4656 4681 * Fixed bug when flushing output cache. Not all _p<n> variables
4657 4682 exist, so their deletion needs to be wrapped in a try:
4658 4683
4659 4684 * Figured out how to properly use inspect.formatargspec() (it
4660 4685 requires the args preceded by *). So I removed all the code from
4661 4686 _get_pdef in Magic, which was just replicating that.
4662 4687
4663 4688 * Added test to prefilter to allow redefining magic function names
4664 4689 as variables. This is ok, since the @ form is always available,
4665 4690 but whe should allow the user to define a variable called 'ls' if
4666 4691 he needs it.
4667 4692
4668 4693 * Moved the ToDo information from README into a separate ToDo.
4669 4694
4670 4695 * General code cleanup and small bugfixes. I think it's close to a
4671 4696 state where it can be released, obviously with a big 'beta'
4672 4697 warning on it.
4673 4698
4674 4699 * Got the magic function split to work. Now all magics are defined
4675 4700 in a separate class. It just organizes things a bit, and now
4676 4701 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4677 4702 was too long).
4678 4703
4679 4704 * Changed @clear to @reset to avoid potential confusions with
4680 4705 the shell command clear. Also renamed @cl to @clear, which does
4681 4706 exactly what people expect it to from their shell experience.
4682 4707
4683 4708 Added a check to the @reset command (since it's so
4684 4709 destructive, it's probably a good idea to ask for confirmation).
4685 4710 But now reset only works for full namespace resetting. Since the
4686 4711 del keyword is already there for deleting a few specific
4687 4712 variables, I don't see the point of having a redundant magic
4688 4713 function for the same task.
4689 4714
4690 4715 2001-11-24 Fernando Perez <fperez@colorado.edu>
4691 4716
4692 4717 * Updated the builtin docs (esp. the ? ones).
4693 4718
4694 4719 * Ran all the code through pychecker. Not terribly impressed with
4695 4720 it: lots of spurious warnings and didn't really find anything of
4696 4721 substance (just a few modules being imported and not used).
4697 4722
4698 4723 * Implemented the new ultraTB functionality into IPython. New
4699 4724 option: xcolors. This chooses color scheme. xmode now only selects
4700 4725 between Plain and Verbose. Better orthogonality.
4701 4726
4702 4727 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4703 4728 mode and color scheme for the exception handlers. Now it's
4704 4729 possible to have the verbose traceback with no coloring.
4705 4730
4706 4731 2001-11-23 Fernando Perez <fperez@colorado.edu>
4707 4732
4708 4733 * Version 0.1.12 released, 0.1.13 opened.
4709 4734
4710 4735 * Removed option to set auto-quote and auto-paren escapes by
4711 4736 user. The chances of breaking valid syntax are just too high. If
4712 4737 someone *really* wants, they can always dig into the code.
4713 4738
4714 4739 * Made prompt separators configurable.
4715 4740
4716 4741 2001-11-22 Fernando Perez <fperez@colorado.edu>
4717 4742
4718 4743 * Small bugfixes in many places.
4719 4744
4720 4745 * Removed the MyCompleter class from ipplib. It seemed redundant
4721 4746 with the C-p,C-n history search functionality. Less code to
4722 4747 maintain.
4723 4748
4724 4749 * Moved all the original ipython.py code into ipythonlib.py. Right
4725 4750 now it's just one big dump into a function called make_IPython, so
4726 4751 no real modularity has been gained. But at least it makes the
4727 4752 wrapper script tiny, and since ipythonlib is a module, it gets
4728 4753 compiled and startup is much faster.
4729 4754
4730 4755 This is a reasobably 'deep' change, so we should test it for a
4731 4756 while without messing too much more with the code.
4732 4757
4733 4758 2001-11-21 Fernando Perez <fperez@colorado.edu>
4734 4759
4735 4760 * Version 0.1.11 released, 0.1.12 opened for further work.
4736 4761
4737 4762 * Removed dependency on Itpl. It was only needed in one place. It
4738 4763 would be nice if this became part of python, though. It makes life
4739 4764 *a lot* easier in some cases.
4740 4765
4741 4766 * Simplified the prefilter code a bit. Now all handlers are
4742 4767 expected to explicitly return a value (at least a blank string).
4743 4768
4744 4769 * Heavy edits in ipplib. Removed the help system altogether. Now
4745 4770 obj?/?? is used for inspecting objects, a magic @doc prints
4746 4771 docstrings, and full-blown Python help is accessed via the 'help'
4747 4772 keyword. This cleans up a lot of code (less to maintain) and does
4748 4773 the job. Since 'help' is now a standard Python component, might as
4749 4774 well use it and remove duplicate functionality.
4750 4775
4751 4776 Also removed the option to use ipplib as a standalone program. By
4752 4777 now it's too dependent on other parts of IPython to function alone.
4753 4778
4754 4779 * Fixed bug in genutils.pager. It would crash if the pager was
4755 4780 exited immediately after opening (broken pipe).
4756 4781
4757 4782 * Trimmed down the VerboseTB reporting a little. The header is
4758 4783 much shorter now and the repeated exception arguments at the end
4759 4784 have been removed. For interactive use the old header seemed a bit
4760 4785 excessive.
4761 4786
4762 4787 * Fixed small bug in output of @whos for variables with multi-word
4763 4788 types (only first word was displayed).
4764 4789
4765 4790 2001-11-17 Fernando Perez <fperez@colorado.edu>
4766 4791
4767 4792 * Version 0.1.10 released, 0.1.11 opened for further work.
4768 4793
4769 4794 * Modified dirs and friends. dirs now *returns* the stack (not
4770 4795 prints), so one can manipulate it as a variable. Convenient to
4771 4796 travel along many directories.
4772 4797
4773 4798 * Fixed bug in magic_pdef: would only work with functions with
4774 4799 arguments with default values.
4775 4800
4776 4801 2001-11-14 Fernando Perez <fperez@colorado.edu>
4777 4802
4778 4803 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4779 4804 example with IPython. Various other minor fixes and cleanups.
4780 4805
4781 4806 * Version 0.1.9 released, 0.1.10 opened for further work.
4782 4807
4783 4808 * Added sys.path to the list of directories searched in the
4784 4809 execfile= option. It used to be the current directory and the
4785 4810 user's IPYTHONDIR only.
4786 4811
4787 4812 2001-11-13 Fernando Perez <fperez@colorado.edu>
4788 4813
4789 4814 * Reinstated the raw_input/prefilter separation that Janko had
4790 4815 initially. This gives a more convenient setup for extending the
4791 4816 pre-processor from the outside: raw_input always gets a string,
4792 4817 and prefilter has to process it. We can then redefine prefilter
4793 4818 from the outside and implement extensions for special
4794 4819 purposes.
4795 4820
4796 4821 Today I got one for inputting PhysicalQuantity objects
4797 4822 (from Scientific) without needing any function calls at
4798 4823 all. Extremely convenient, and it's all done as a user-level
4799 4824 extension (no IPython code was touched). Now instead of:
4800 4825 a = PhysicalQuantity(4.2,'m/s**2')
4801 4826 one can simply say
4802 4827 a = 4.2 m/s**2
4803 4828 or even
4804 4829 a = 4.2 m/s^2
4805 4830
4806 4831 I use this, but it's also a proof of concept: IPython really is
4807 4832 fully user-extensible, even at the level of the parsing of the
4808 4833 command line. It's not trivial, but it's perfectly doable.
4809 4834
4810 4835 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4811 4836 the problem of modules being loaded in the inverse order in which
4812 4837 they were defined in
4813 4838
4814 4839 * Version 0.1.8 released, 0.1.9 opened for further work.
4815 4840
4816 4841 * Added magics pdef, source and file. They respectively show the
4817 4842 definition line ('prototype' in C), source code and full python
4818 4843 file for any callable object. The object inspector oinfo uses
4819 4844 these to show the same information.
4820 4845
4821 4846 * Version 0.1.7 released, 0.1.8 opened for further work.
4822 4847
4823 4848 * Separated all the magic functions into a class called Magic. The
4824 4849 InteractiveShell class was becoming too big for Xemacs to handle
4825 4850 (de-indenting a line would lock it up for 10 seconds while it
4826 4851 backtracked on the whole class!)
4827 4852
4828 4853 FIXME: didn't work. It can be done, but right now namespaces are
4829 4854 all messed up. Do it later (reverted it for now, so at least
4830 4855 everything works as before).
4831 4856
4832 4857 * Got the object introspection system (magic_oinfo) working! I
4833 4858 think this is pretty much ready for release to Janko, so he can
4834 4859 test it for a while and then announce it. Pretty much 100% of what
4835 4860 I wanted for the 'phase 1' release is ready. Happy, tired.
4836 4861
4837 4862 2001-11-12 Fernando Perez <fperez@colorado.edu>
4838 4863
4839 4864 * Version 0.1.6 released, 0.1.7 opened for further work.
4840 4865
4841 4866 * Fixed bug in printing: it used to test for truth before
4842 4867 printing, so 0 wouldn't print. Now checks for None.
4843 4868
4844 4869 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4845 4870 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4846 4871 reaches by hand into the outputcache. Think of a better way to do
4847 4872 this later.
4848 4873
4849 4874 * Various small fixes thanks to Nathan's comments.
4850 4875
4851 4876 * Changed magic_pprint to magic_Pprint. This way it doesn't
4852 4877 collide with pprint() and the name is consistent with the command
4853 4878 line option.
4854 4879
4855 4880 * Changed prompt counter behavior to be fully like
4856 4881 Mathematica's. That is, even input that doesn't return a result
4857 4882 raises the prompt counter. The old behavior was kind of confusing
4858 4883 (getting the same prompt number several times if the operation
4859 4884 didn't return a result).
4860 4885
4861 4886 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4862 4887
4863 4888 * Fixed -Classic mode (wasn't working anymore).
4864 4889
4865 4890 * Added colored prompts using Nathan's new code. Colors are
4866 4891 currently hardwired, they can be user-configurable. For
4867 4892 developers, they can be chosen in file ipythonlib.py, at the
4868 4893 beginning of the CachedOutput class def.
4869 4894
4870 4895 2001-11-11 Fernando Perez <fperez@colorado.edu>
4871 4896
4872 4897 * Version 0.1.5 released, 0.1.6 opened for further work.
4873 4898
4874 4899 * Changed magic_env to *return* the environment as a dict (not to
4875 4900 print it). This way it prints, but it can also be processed.
4876 4901
4877 4902 * Added Verbose exception reporting to interactive
4878 4903 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4879 4904 traceback. Had to make some changes to the ultraTB file. This is
4880 4905 probably the last 'big' thing in my mental todo list. This ties
4881 4906 in with the next entry:
4882 4907
4883 4908 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4884 4909 has to specify is Plain, Color or Verbose for all exception
4885 4910 handling.
4886 4911
4887 4912 * Removed ShellServices option. All this can really be done via
4888 4913 the magic system. It's easier to extend, cleaner and has automatic
4889 4914 namespace protection and documentation.
4890 4915
4891 4916 2001-11-09 Fernando Perez <fperez@colorado.edu>
4892 4917
4893 4918 * Fixed bug in output cache flushing (missing parameter to
4894 4919 __init__). Other small bugs fixed (found using pychecker).
4895 4920
4896 4921 * Version 0.1.4 opened for bugfixing.
4897 4922
4898 4923 2001-11-07 Fernando Perez <fperez@colorado.edu>
4899 4924
4900 4925 * Version 0.1.3 released, mainly because of the raw_input bug.
4901 4926
4902 4927 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4903 4928 and when testing for whether things were callable, a call could
4904 4929 actually be made to certain functions. They would get called again
4905 4930 once 'really' executed, with a resulting double call. A disaster
4906 4931 in many cases (list.reverse() would never work!).
4907 4932
4908 4933 * Removed prefilter() function, moved its code to raw_input (which
4909 4934 after all was just a near-empty caller for prefilter). This saves
4910 4935 a function call on every prompt, and simplifies the class a tiny bit.
4911 4936
4912 4937 * Fix _ip to __ip name in magic example file.
4913 4938
4914 4939 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4915 4940 work with non-gnu versions of tar.
4916 4941
4917 4942 2001-11-06 Fernando Perez <fperez@colorado.edu>
4918 4943
4919 4944 * Version 0.1.2. Just to keep track of the recent changes.
4920 4945
4921 4946 * Fixed nasty bug in output prompt routine. It used to check 'if
4922 4947 arg != None...'. Problem is, this fails if arg implements a
4923 4948 special comparison (__cmp__) which disallows comparing to
4924 4949 None. Found it when trying to use the PhysicalQuantity module from
4925 4950 ScientificPython.
4926 4951
4927 4952 2001-11-05 Fernando Perez <fperez@colorado.edu>
4928 4953
4929 4954 * Also added dirs. Now the pushd/popd/dirs family functions
4930 4955 basically like the shell, with the added convenience of going home
4931 4956 when called with no args.
4932 4957
4933 4958 * pushd/popd slightly modified to mimic shell behavior more
4934 4959 closely.
4935 4960
4936 4961 * Added env,pushd,popd from ShellServices as magic functions. I
4937 4962 think the cleanest will be to port all desired functions from
4938 4963 ShellServices as magics and remove ShellServices altogether. This
4939 4964 will provide a single, clean way of adding functionality
4940 4965 (shell-type or otherwise) to IP.
4941 4966
4942 4967 2001-11-04 Fernando Perez <fperez@colorado.edu>
4943 4968
4944 4969 * Added .ipython/ directory to sys.path. This way users can keep
4945 4970 customizations there and access them via import.
4946 4971
4947 4972 2001-11-03 Fernando Perez <fperez@colorado.edu>
4948 4973
4949 4974 * Opened version 0.1.1 for new changes.
4950 4975
4951 4976 * Changed version number to 0.1.0: first 'public' release, sent to
4952 4977 Nathan and Janko.
4953 4978
4954 4979 * Lots of small fixes and tweaks.
4955 4980
4956 4981 * Minor changes to whos format. Now strings are shown, snipped if
4957 4982 too long.
4958 4983
4959 4984 * Changed ShellServices to work on __main__ so they show up in @who
4960 4985
4961 4986 * Help also works with ? at the end of a line:
4962 4987 ?sin and sin?
4963 4988 both produce the same effect. This is nice, as often I use the
4964 4989 tab-complete to find the name of a method, but I used to then have
4965 4990 to go to the beginning of the line to put a ? if I wanted more
4966 4991 info. Now I can just add the ? and hit return. Convenient.
4967 4992
4968 4993 2001-11-02 Fernando Perez <fperez@colorado.edu>
4969 4994
4970 4995 * Python version check (>=2.1) added.
4971 4996
4972 4997 * Added LazyPython documentation. At this point the docs are quite
4973 4998 a mess. A cleanup is in order.
4974 4999
4975 5000 * Auto-installer created. For some bizarre reason, the zipfiles
4976 5001 module isn't working on my system. So I made a tar version
4977 5002 (hopefully the command line options in various systems won't kill
4978 5003 me).
4979 5004
4980 5005 * Fixes to Struct in genutils. Now all dictionary-like methods are
4981 5006 protected (reasonably).
4982 5007
4983 5008 * Added pager function to genutils and changed ? to print usage
4984 5009 note through it (it was too long).
4985 5010
4986 5011 * Added the LazyPython functionality. Works great! I changed the
4987 5012 auto-quote escape to ';', it's on home row and next to '. But
4988 5013 both auto-quote and auto-paren (still /) escapes are command-line
4989 5014 parameters.
4990 5015
4991 5016
4992 5017 2001-11-01 Fernando Perez <fperez@colorado.edu>
4993 5018
4994 5019 * Version changed to 0.0.7. Fairly large change: configuration now
4995 5020 is all stored in a directory, by default .ipython. There, all
4996 5021 config files have normal looking names (not .names)
4997 5022
4998 5023 * Version 0.0.6 Released first to Lucas and Archie as a test
4999 5024 run. Since it's the first 'semi-public' release, change version to
5000 5025 > 0.0.6 for any changes now.
5001 5026
5002 5027 * Stuff I had put in the ipplib.py changelog:
5003 5028
5004 5029 Changes to InteractiveShell:
5005 5030
5006 5031 - Made the usage message a parameter.
5007 5032
5008 5033 - Require the name of the shell variable to be given. It's a bit
5009 5034 of a hack, but allows the name 'shell' not to be hardwire in the
5010 5035 magic (@) handler, which is problematic b/c it requires
5011 5036 polluting the global namespace with 'shell'. This in turn is
5012 5037 fragile: if a user redefines a variable called shell, things
5013 5038 break.
5014 5039
5015 5040 - magic @: all functions available through @ need to be defined
5016 5041 as magic_<name>, even though they can be called simply as
5017 5042 @<name>. This allows the special command @magic to gather
5018 5043 information automatically about all existing magic functions,
5019 5044 even if they are run-time user extensions, by parsing the shell
5020 5045 instance __dict__ looking for special magic_ names.
5021 5046
5022 5047 - mainloop: added *two* local namespace parameters. This allows
5023 5048 the class to differentiate between parameters which were there
5024 5049 before and after command line initialization was processed. This
5025 5050 way, later @who can show things loaded at startup by the
5026 5051 user. This trick was necessary to make session saving/reloading
5027 5052 really work: ideally after saving/exiting/reloading a session,
5028 5053 *everythin* should look the same, including the output of @who. I
5029 5054 was only able to make this work with this double namespace
5030 5055 trick.
5031 5056
5032 5057 - added a header to the logfile which allows (almost) full
5033 5058 session restoring.
5034 5059
5035 5060 - prepend lines beginning with @ or !, with a and log
5036 5061 them. Why? !lines: may be useful to know what you did @lines:
5037 5062 they may affect session state. So when restoring a session, at
5038 5063 least inform the user of their presence. I couldn't quite get
5039 5064 them to properly re-execute, but at least the user is warned.
5040 5065
5041 5066 * Started ChangeLog.
@@ -1,9491 +1,9505 b''
1 1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
2 2 \lyxformat 221
3 3 \textclass article
4 4 \begin_preamble
5 5 %\usepackage{ae,aecompl}
6 6 \usepackage{color}
7 7
8 8 % A few colors to replace the defaults for certain link types
9 9 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
10 10 \definecolor{darkorange}{rgb}{.71,0.21,0.01}
11 11 \definecolor{darkred}{rgb}{.52,0.08,0.01}
12 12 \definecolor{darkgreen}{rgb}{.12,.54,.11}
13 13
14 14 % Use and configure listings package for nicely formatted code
15 15 \usepackage{listings}
16 16 \lstset{
17 17 language=Python,
18 18 basicstyle=\small\ttfamily,
19 19 commentstyle=\ttfamily\color{blue},
20 20 stringstyle=\ttfamily\color{darkorange},
21 21 showstringspaces=false,
22 22 breaklines=true,
23 23 postbreak = \space\dots
24 24 }
25 25
26 26 \usepackage[%pdftex, % needed for pdflatex
27 27 breaklinks=true, % so long urls are correctly broken across lines
28 28 colorlinks=true,
29 29 urlcolor=blue,
30 30 linkcolor=darkred,
31 31 citecolor=darkgreen,
32 32 ]{hyperref}
33 33
34 34 \usepackage{html}
35 35
36 36 % This helps prevent overly long lines that stretch beyond the margins
37 37 \sloppy
38 38
39 39 % Define a \codelist command which either uses listings for latex, or
40 40 % plain verbatim for html (since latex2html doesn't understand the
41 41 % listings package).
42 42 \usepackage{verbatim}
43 43 \newcommand{\codelist}[1] {
44 44 \latex{\lstinputlisting{#1}}
45 45 \html{\verbatiminput{#1}}
46 46 }
47 47 \end_preamble
48 48 \language english
49 49 \inputencoding latin1
50 50 \fontscheme palatino
51 51 \graphics default
52 52 \paperfontsize 11
53 53 \spacing single
54 54 \papersize Default
55 55 \paperpackage a4
56 56 \use_geometry 1
57 57 \use_amsmath 0
58 58 \use_natbib 0
59 59 \use_numerical_citations 0
60 60 \paperorientation portrait
61 61 \leftmargin 1in
62 62 \topmargin 1in
63 63 \rightmargin 1in
64 64 \bottommargin 1in
65 65 \secnumdepth 3
66 66 \tocdepth 3
67 67 \paragraph_separation skip
68 68 \defskip medskip
69 69 \quotes_language english
70 70 \quotes_times 2
71 71 \papercolumns 1
72 \papersides 1
72 \papersides 2
73 73 \paperpagestyle fancy
74 74
75 75 \layout Title
76 76
77 77 IPython
78 78 \newline
79 79
80 80 \size larger
81 81 An enhanced Interactive Python
82 82 \size large
83 83
84 84 \newline
85 85 User Manual, v.
86 86 __version__
87 87 \layout Author
88 88
89 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 104 \layout Standard
91 105
92 106
93 107 \begin_inset ERT
94 108 status Collapsed
95 109
96 110 \layout Standard
97 111
98 112 \backslash
99 113 latex{
100 114 \end_inset
101 115
102 116
103 117 \begin_inset LatexCommand \tableofcontents{}
104 118
105 119 \end_inset
106 120
107 121
108 122 \begin_inset ERT
109 123 status Collapsed
110 124
111 125 \layout Standard
112 126 }
113 127 \end_inset
114 128
115 129
116 130 \layout Standard
117 131
118 132
119 133 \begin_inset ERT
120 134 status Open
121 135
122 136 \layout Standard
123 137
124 138 \backslash
125 139 html{
126 140 \backslash
127 141 bodytext{bgcolor=#ffffff}}
128 142 \end_inset
129 143
130 144
131 145 \layout Section
132 146 \pagebreak_top
133 147 Overview
134 148 \layout Standard
135 149
136 150 One of Python's most useful features is its interactive interpreter.
137 151 This system allows very fast testing of ideas without the overhead of creating
138 152 test files as is typical in most programming languages.
139 153 However, the interpreter supplied with the standard Python distribution
140 154 is somewhat limited for extended interactive use.
141 155 \layout Standard
142 156
143 157 IPython is a free software project (released under the BSD license) which
144 158 tries to:
145 159 \layout Enumerate
146 160
147 161 Provide an interactive shell superior to Python's default.
148 162 IPython has many features for object introspection, system shell access,
149 163 and its own special command system for adding functionality when working
150 164 interactively.
151 165 It tries to be a very efficient environment both for Python code development
152 166 and for exploration of problems using Python objects (in situations like
153 167 data analysis).
154 168 \layout Enumerate
155 169
156 170 Serve as an embeddable, ready to use interpreter for your own programs.
157 171 IPython can be started with a single call from inside another program,
158 172 providing access to the current namespace.
159 173 This can be very useful both for debugging purposes and for situations
160 174 where a blend of batch-processing and interactive exploration are needed.
161 175 \layout Enumerate
162 176
163 177 Offer a flexible framework which can be used as the base environment for
164 178 other systems with Python as the underlying language.
165 179 Specifically scientific environments like Mathematica, IDL and Matlab inspired
166 180 its design, but similar ideas can be useful in many fields.
167 181 \layout Enumerate
168 182
169 183 Allow interactive testing of threaded graphical toolkits.
170 184 IPython has support for interactive, non-blocking control of GTK, Qt and
171 185 WX applications via special threading flags.
172 186 The normal Python shell can only do this for Tkinter applications.
173 187 \layout Subsection
174 188
175 189 Main features
176 190 \layout Itemize
177 191
178 192 Dynamic object introspection.
179 193 One can access docstrings, function definition prototypes, source code,
180 194 source files and other details of any object accessible to the interpreter
181 195 with a single keystroke (`
182 196 \family typewriter
183 197 ?
184 198 \family default
185 199 ', and using `
186 200 \family typewriter
187 201 ??
188 202 \family default
189 203 ' provides additional detail).
190 204 \layout Itemize
191 205
192 206 Searching through modules and namespaces with `
193 207 \family typewriter
194 208 *
195 209 \family default
196 210 ' wildcards, both when using the `
197 211 \family typewriter
198 212 ?
199 213 \family default
200 214 ' system and via the
201 215 \family typewriter
202 216 %psearch
203 217 \family default
204 218 command.
205 219 \layout Itemize
206 220
207 221 Completion in the local namespace, by typing TAB at the prompt.
208 222 This works for keywords, methods, variables and files in the current directory.
209 223 This is supported via the readline library, and full access to configuring
210 224 readline's behavior is provided.
211 225 \layout Itemize
212 226
213 227 Numbered input/output prompts with command history (persistent across sessions
214 228 and tied to each profile), full searching in this history and caching of
215 229 all input and output.
216 230 \layout Itemize
217 231
218 232 User-extensible `magic' commands.
219 233 A set of commands prefixed with
220 234 \family typewriter
221 235 %
222 236 \family default
223 237 is available for controlling IPython itself and provides directory control,
224 238 namespace information and many aliases to common system shell commands.
225 239 \layout Itemize
226 240
227 241 Alias facility for defining your own system aliases.
228 242 \layout Itemize
229 243
230 244 Complete system shell access.
231 245 Lines starting with ! are passed directly to the system shell, and using
232 246 !! captures shell output into python variables for further use.
233 247 \layout Itemize
234 248
235 249 Background execution of Python commands in a separate thread.
236 250 IPython has an internal job manager called
237 251 \family typewriter
238 252 jobs
239 253 \family default
240 254 , and a conveninence backgrounding magic function called
241 255 \family typewriter
242 256 %bg
243 257 \family default
244 258 .
245 259 \layout Itemize
246 260
247 261 The ability to expand python variables when calling the system shell.
248 262 In a shell command, any python variable prefixed with
249 263 \family typewriter
250 264 $
251 265 \family default
252 266 is expanded.
253 267 A double
254 268 \family typewriter
255 269 $$
256 270 \family default
257 271 allows passing a literal
258 272 \family typewriter
259 273 $
260 274 \family default
261 275 to the shell (for access to shell and environment variables like
262 276 \family typewriter
263 277 $PATH
264 278 \family default
265 279 ).
266 280 \layout Itemize
267 281
268 282 Filesystem navigation, via a magic
269 283 \family typewriter
270 284 %cd
271 285 \family default
272 286 command, along with a persistent bookmark system (using
273 287 \family typewriter
274 288 %bookmark
275 289 \family default
276 290 ) for fast access to frequently visited directories.
277 291 \layout Itemize
278 292
279 293 A lightweight persistence framework via the
280 294 \family typewriter
281 295 %store
282 296 \family default
283 297 command, which allows you to save arbitrary Python variables.
284 298 These get restored automatically when your session restarts.
285 299 \layout Itemize
286 300
287 301 Automatic indentation (optional) of code as you type (through the readline
288 302 library).
289 303 \layout Itemize
290 304
291 305 Macro system for quickly re-executing multiple lines of previous input with
292 306 a single name.
293 307 Macros can be stored persistently via
294 308 \family typewriter
295 309 %store
296 310 \family default
297 311 and edited via
298 312 \family typewriter
299 313 %edit
300 314 \family default
301 315 .
302 316
303 317 \layout Itemize
304 318
305 319 Session logging (you can then later use these logs as code in your programs).
306 320 Logs can optionally timestamp all input, and also store session output
307 321 (marked as comments, so the log remains valid Python source code).
308 322 \layout Itemize
309 323
310 324 Session restoring: logs can be replayed to restore a previous session to
311 325 the state where you left it.
312 326 \layout Itemize
313 327
314 328 Verbose and colored exception traceback printouts.
315 329 Easier to parse visually, and in verbose mode they produce a lot of useful
316 330 debugging information (basically a terminal version of the cgitb module).
317 331 \layout Itemize
318 332
319 333 Auto-parentheses: callable objects can be executed without parentheses:
320 334
321 335 \family typewriter
322 336 `sin 3'
323 337 \family default
324 338 is automatically converted to
325 339 \family typewriter
326 340 `sin(3)
327 341 \family default
328 342 '.
329 343 \layout Itemize
330 344
331 345 Auto-quoting: using `
332 346 \family typewriter
333 347 ,
334 348 \family default
335 349 ' or `
336 350 \family typewriter
337 351 ;
338 352 \family default
339 353 ' as the first character forces auto-quoting of the rest of the line:
340 354 \family typewriter
341 355 `,my_function a\SpecialChar ~
342 356 b'
343 357 \family default
344 358 becomes automatically
345 359 \family typewriter
346 360 `my_function("a","b")'
347 361 \family default
348 362 , while
349 363 \family typewriter
350 364 `;my_function a\SpecialChar ~
351 365 b'
352 366 \family default
353 367 becomes
354 368 \family typewriter
355 369 `my_function("a b")'
356 370 \family default
357 371 .
358 372 \layout Itemize
359 373
360 374 Extensible input syntax.
361 375 You can define filters that pre-process user input to simplify input in
362 376 special situations.
363 377 This allows for example pasting multi-line code fragments which start with
364 378
365 379 \family typewriter
366 380 `>>>'
367 381 \family default
368 382 or
369 383 \family typewriter
370 384 `...'
371 385 \family default
372 386 such as those from other python sessions or the standard Python documentation.
373 387 \layout Itemize
374 388
375 389 Flexible configuration system.
376 390 It uses a configuration file which allows permanent setting of all command-line
377 391 options, module loading, code and file execution.
378 392 The system allows recursive file inclusion, so you can have a base file
379 393 with defaults and layers which load other customizations for particular
380 394 projects.
381 395 \layout Itemize
382 396
383 397 Embeddable.
384 398 You can call IPython as a python shell inside your own python programs.
385 399 This can be used both for debugging code or for providing interactive abilities
386 400 to your programs with knowledge about the local namespaces (very useful
387 401 in debugging and data analysis situations).
388 402 \layout Itemize
389 403
390 404 Easy debugger access.
391 405 You can set IPython to call up an enhanced version of the Python debugger
392 406 (
393 407 \family typewriter
394 408 pdb
395 409 \family default
396 410 ) every time there is an uncaught exception.
397 411 This drops you inside the code which triggered the exception with all the
398 412 data live and it is possible to navigate the stack to rapidly isolate the
399 413 source of a bug.
400 414 The
401 415 \family typewriter
402 416 %run
403 417 \family default
404 418 magic command --with the
405 419 \family typewriter
406 420 -d
407 421 \family default
408 422 option-- can run any script under
409 423 \family typewriter
410 424 pdb
411 425 \family default
412 426 's control, automatically setting initial breakpoints for you.
413 427 This version of
414 428 \family typewriter
415 429 pdb
416 430 \family default
417 431 has IPython-specific improvements, including tab-completion and traceback
418 432 coloring support.
419 433 \layout Itemize
420 434
421 435 Profiler support.
422 436 You can run single statements (similar to
423 437 \family typewriter
424 438 profile.run()
425 439 \family default
426 440 ) or complete programs under the profiler's control.
427 441 While this is possible with the standard
428 442 \family typewriter
429 443 profile
430 444 \family default
431 445 module, IPython wraps this functionality with magic commands (see
432 446 \family typewriter
433 447 `%prun'
434 448 \family default
435 449 and
436 450 \family typewriter
437 451 `%run -p
438 452 \family default
439 453 ') convenient for rapid interactive work.
440 454 \layout Subsection
441 455
442 456 Portability and Python requirements
443 457 \layout Standard
444 458
445 459
446 460 \series bold
447 461 Python requirements:
448 462 \series default
449 463 IPython requires with Python version 2.3 or newer.
450 464 If you are still using Python 2.2 and can not upgrade, the last version
451 465 of IPython which worked with Python 2.2 was 0.6.15, so you will have to use
452 466 that.
453 467 \layout Standard
454 468
455 469 IPython is developed under
456 470 \series bold
457 471 Linux
458 472 \series default
459 473 , but it should work in any reasonable Unix-type system (tested OK under
460 474 Solaris and the *BSD family, for which a port exists thanks to Dryice Liu).
461 475 \layout Standard
462 476
463 477
464 478 \series bold
465 479 Mac OS X
466 480 \series default
467 481 : it works, apparently without any problems (thanks to Jim Boyle at Lawrence
468 482 Livermore for the information).
469 483 Thanks to Andrea Riciputi, Fink support is available.
470 484 \layout Standard
471 485
472 486
473 487 \series bold
474 488 CygWin
475 489 \series default
476 490 : it works mostly OK, though some users have reported problems with prompt
477 491 coloring.
478 492 No satisfactory solution to this has been found so far, you may want to
479 493 disable colors permanently in the
480 494 \family typewriter
481 495 ipythonrc
482 496 \family default
483 497 configuration file if you experience problems.
484 498 If you have proper color support under cygwin, please post to the IPython
485 499 mailing list so this issue can be resolved for all users.
486 500 \layout Standard
487 501
488 502
489 503 \series bold
490 504 Windows
491 505 \series default
492 506 : it works well under Windows XP/2k, and I suspect NT should behave similarly.
493 507 Section\SpecialChar ~
494 508
495 509 \begin_inset LatexCommand \ref{sub:Under-Windows}
496 510
497 511 \end_inset
498 512
499 513 describes installation details for Windows, including some additional tools
500 514 needed on this platform.
501 515 \layout Standard
502 516
503 517 Windows 9x support is present, and has been reported to work fine (at least
504 518 on WinME).
505 519 \layout Standard
506 520
507 521 Note, that I have very little access to and experience with Windows development.
508 522 However, an excellent group of Win32 users (led by Ville Vainio), consistenly
509 523 contribute bugfixes and platform-specific enhancements, so they more than
510 524 make up for my deficiencies on that front.
511 525 In fact, Win32 users report using IPython as a system shell (see Sec.\SpecialChar ~
512 526
513 527 \begin_inset LatexCommand \ref{sec:IPython-as-shell}
514 528
515 529 \end_inset
516 530
517 531 for details), as it offers a level of control and features which the default
518 532
519 533 \family typewriter
520 534 cmd.exe
521 535 \family default
522 536 doesn't provide.
523 537 \layout Subsection
524 538
525 539 Location
526 540 \layout Standard
527 541
528 542 IPython is generously hosted at
529 543 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
530 544
531 545 \end_inset
532 546
533 547 by the Enthought, Inc and the SciPy project.
534 548 This site offers downloads, subversion access, mailing lists and a bug
535 549 tracking system.
536 550 I am very grateful to Enthought (
537 551 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
538 552
539 553 \end_inset
540 554
541 555 ) and all of the SciPy team for their contribution.
542 556 \layout Section
543 557
544 558
545 559 \begin_inset LatexCommand \label{sec:install}
546 560
547 561 \end_inset
548 562
549 563 Installation
550 564 \layout Subsection
551 565
552 566 Instant instructions
553 567 \layout Standard
554 568
555 569 If you are of the impatient kind, under Linux/Unix simply untar/unzip the
556 570 download, then install with
557 571 \family typewriter
558 572 `python setup.py install'
559 573 \family default
560 574 .
561 575 Under Windows, double-click on the provided
562 576 \family typewriter
563 577 .exe
564 578 \family default
565 579 binary installer.
566 580 \layout Standard
567 581
568 582 Then, take a look at Sections
569 583 \begin_inset LatexCommand \ref{sec:good_config}
570 584
571 585 \end_inset
572 586
573 587 for configuring things optimally and
574 588 \begin_inset LatexCommand \ref{sec:quick_tips}
575 589
576 590 \end_inset
577 591
578 592 for quick tips on efficient use of IPython.
579 593 You can later refer to the rest of the manual for all the gory details.
580 594 \layout Standard
581 595
582 596 See the notes in sec.
583 597
584 598 \begin_inset LatexCommand \ref{sec:upgrade}
585 599
586 600 \end_inset
587 601
588 602 for upgrading IPython versions.
589 603 \layout Subsection
590 604
591 605 Detailed Unix instructions (Linux, Mac OS X, etc.)
592 606 \layout Standard
593 607
594 608 For RPM based systems, simply install the supplied package in the usual
595 609 manner.
596 610 If you download the tar archive, the process is:
597 611 \layout Enumerate
598 612
599 613 Unzip/untar the
600 614 \family typewriter
601 615 ipython-XXX.tar.gz
602 616 \family default
603 617 file wherever you want (
604 618 \family typewriter
605 619 XXX
606 620 \family default
607 621 is the version number).
608 622 It will make a directory called
609 623 \family typewriter
610 624 ipython-XXX.
611 625
612 626 \family default
613 627 Change into that directory where you will find the files
614 628 \family typewriter
615 629 README
616 630 \family default
617 631 and
618 632 \family typewriter
619 633 setup.py
620 634 \family default
621 635 .
622 636
623 637 \family typewriter
624 638 O
625 639 \family default
626 640 nce you've completed the installation, you can safely remove this directory.
627 641
628 642 \layout Enumerate
629 643
630 644 If you are installing over a previous installation of version 0.2.0 or earlier,
631 645 first remove your
632 646 \family typewriter
633 647 $HOME/.ipython
634 648 \family default
635 649 directory, since the configuration file format has changed somewhat (the
636 650 '=' were removed from all option specifications).
637 651 Or you can call ipython with the
638 652 \family typewriter
639 653 -upgrade
640 654 \family default
641 655 option and it will do this automatically for you.
642 656 \layout Enumerate
643 657
644 658 IPython uses distutils, so you can install it by simply typing at the system
645 659 prompt (don't type the
646 660 \family typewriter
647 661 $
648 662 \family default
649 663 )
650 664 \newline
651 665
652 666 \family typewriter
653 667 $ python setup.py install
654 668 \family default
655 669
656 670 \newline
657 671 Note that this assumes you have root access to your machine.
658 672 If you don't have root access or don't want IPython to go in the default
659 673 python directories, you'll need to use the
660 674 \begin_inset ERT
661 675 status Collapsed
662 676
663 677 \layout Standard
664 678
665 679 \backslash
666 680 verb|--home|
667 681 \end_inset
668 682
669 683 option (or
670 684 \begin_inset ERT
671 685 status Collapsed
672 686
673 687 \layout Standard
674 688
675 689 \backslash
676 690 verb|--prefix|
677 691 \end_inset
678 692
679 693 ).
680 694 For example:
681 695 \newline
682 696
683 697 \begin_inset ERT
684 698 status Collapsed
685 699
686 700 \layout Standard
687 701
688 702 \backslash
689 703 verb|$ python setup.py install --home $HOME/local|
690 704 \end_inset
691 705
692 706
693 707 \newline
694 708 will install IPython into
695 709 \family typewriter
696 710 $HOME/local
697 711 \family default
698 712 and its subdirectories (creating them if necessary).
699 713 \newline
700 714 You can type
701 715 \newline
702 716
703 717 \begin_inset ERT
704 718 status Collapsed
705 719
706 720 \layout Standard
707 721
708 722 \backslash
709 723 verb|$ python setup.py --help|
710 724 \end_inset
711 725
712 726
713 727 \newline
714 728 for more details.
715 729 \newline
716 730 Note that if you change the default location for
717 731 \begin_inset ERT
718 732 status Collapsed
719 733
720 734 \layout Standard
721 735
722 736 \backslash
723 737 verb|--home|
724 738 \end_inset
725 739
726 740 at installation, IPython may end up installed at a location which is not
727 741 part of your
728 742 \family typewriter
729 743 $PYTHONPATH
730 744 \family default
731 745 environment variable.
732 746 In this case, you'll need to configure this variable to include the actual
733 747 directory where the
734 748 \family typewriter
735 749 IPython/
736 750 \family default
737 751 directory ended (typically the value you give to
738 752 \begin_inset ERT
739 753 status Collapsed
740 754
741 755 \layout Standard
742 756
743 757 \backslash
744 758 verb|--home|
745 759 \end_inset
746 760
747 761 plus
748 762 \family typewriter
749 763 /lib/python
750 764 \family default
751 765 ).
752 766 \layout Subsubsection
753 767
754 768 Mac OSX information
755 769 \layout Standard
756 770
757 771 Under OSX, there is a choice you need to make.
758 772 Apple ships its own build of Python, which lives in the core OSX filesystem
759 773 hierarchy.
760 774 You can also manually install a separate Python, either purely by hand
761 775 (typically in
762 776 \family typewriter
763 777 /usr/local
764 778 \family default
765 779 ) or by using Fink, which puts everything under
766 780 \family typewriter
767 781 /sw
768 782 \family default
769 783 .
770 784 Which route to follow is a matter of personal preference, as I've seen
771 785 users who favor each of the approaches.
772 786 Here I will simply list the known installation issues under OSX, along
773 787 with their solutions.
774 788 \layout Standard
775 789
776 790 This page:
777 791 \begin_inset LatexCommand \htmlurl{http://geosci.uchicago.edu/~tobis/pylab.html}
778 792
779 793 \end_inset
780 794
781 795 contains information on this topic, with additional details on how to make
782 796 IPython and matplotlib play nicely under OSX.
783 797 \layout Subsubsection*
784 798
785 799 GUI problems
786 800 \layout Standard
787 801
788 802 The following instructions apply to an install of IPython under OSX from
789 803 unpacking the
790 804 \family typewriter
791 805 .tar.gz
792 806 \family default
793 807 distribution and installing it for the default Python interpreter shipped
794 808 by Apple.
795 809 If you are using a fink install, fink will take care of these details for
796 810 you, by installing IPython against fink's Python.
797 811 \layout Standard
798 812
799 813 IPython offers various forms of support for interacting with graphical applicati
800 814 ons from the command line, from simple Tk apps (which are in principle always
801 815 supported by Python) to interactive control of WX, Qt and GTK apps.
802 816 Under OSX, however, this requires that ipython is installed by calling
803 817 the special
804 818 \family typewriter
805 819 pythonw
806 820 \family default
807 821 script at installation time, which takes care of coordinating things with
808 822 Apple's graphical environment.
809 823 \layout Standard
810 824
811 825 So when installing under OSX, it is best to use the following command:
812 826 \family typewriter
813 827
814 828 \newline
815 829
816 830 \family default
817 831
818 832 \begin_inset ERT
819 833 status Collapsed
820 834
821 835 \layout Standard
822 836
823 837 \backslash
824 838 verb| $ sudo pythonw setup.py install --install-scripts=/usr/local/bin|
825 839 \end_inset
826 840
827 841
828 842 \newline
829 843 or
830 844 \newline
831 845
832 846 \begin_inset ERT
833 847 status Collapsed
834 848
835 849 \layout Standard
836 850
837 851 \backslash
838 852 verb| $ sudo pythonw setup.py install --install-scripts=/usr/bin|
839 853 \end_inset
840 854
841 855
842 856 \newline
843 857 depending on where you like to keep hand-installed executables.
844 858 \layout Standard
845 859
846 860 The resulting script will have an appropriate shebang line (the first line
847 861 in the script whic begins with
848 862 \family typewriter
849 863 #!...
850 864 \family default
851 865 ) such that the ipython interpreter can interact with the OS X GUI.
852 866 If the installed version does not work and has a shebang line that points
853 867 to, for example, just
854 868 \family typewriter
855 869 /usr/bin/python
856 870 \family default
857 871 , then you might have a stale, cached version in your
858 872 \family typewriter
859 873 build/scripts-<python-version>
860 874 \family default
861 875 directory.
862 876 Delete that directory and rerun the
863 877 \family typewriter
864 878 setup.py
865 879 \family default
866 880 .
867 881
868 882 \layout Standard
869 883
870 884 It is also a good idea to use the special flag
871 885 \begin_inset ERT
872 886 status Collapsed
873 887
874 888 \layout Standard
875 889
876 890 \backslash
877 891 verb|--install-scripts|
878 892 \end_inset
879 893
880 894 as indicated above, to ensure that the ipython scripts end up in a location
881 895 which is part of your
882 896 \family typewriter
883 897 $PATH
884 898 \family default
885 899 .
886 900 Otherwise Apple's Python will put the scripts in an internal directory
887 901 not available by default at the command line (if you use
888 902 \family typewriter
889 903 /usr/local/bin
890 904 \family default
891 905 , you need to make sure this is in your
892 906 \family typewriter
893 907 $PATH
894 908 \family default
895 909 , which may not be true by default).
896 910 \layout Subsubsection*
897 911
898 912 Readline problems
899 913 \layout Standard
900 914
901 915 By default, the Python version shipped by Apple does
902 916 \emph on
903 917 not
904 918 \emph default
905 919 include the readline library, so central to IPython's behavior.
906 920 If you install IPython against Apple's Python, you will not have arrow
907 921 keys, tab completion, etc.
908 922 For Mac OSX 10.3 (Panther), you can find a prebuilt readline library here:
909 923 \newline
910 924
911 925 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip}
912 926
913 927 \end_inset
914 928
915 929
916 930 \layout Standard
917 931
918 932 If you are using OSX 10.4 (Tiger), after installing this package you need
919 933 to either:
920 934 \layout Enumerate
921 935
922 936 move
923 937 \family typewriter
924 938 readline.so
925 939 \family default
926 940 from
927 941 \family typewriter
928 942 /Library/Python/2.3
929 943 \family default
930 944 to
931 945 \family typewriter
932 946 /Library/Python/2.3/site-packages
933 947 \family default
934 948 , or
935 949 \layout Enumerate
936 950
937 951 install
938 952 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/TigerPython23Compat.pkg.zip}
939 953
940 954 \end_inset
941 955
942 956
943 957 \layout Standard
944 958
945 959 Users installing against Fink's Python or a properly hand-built one should
946 960 not have this problem.
947 961 \layout Subsubsection*
948 962
949 963 DarwinPorts
950 964 \layout Standard
951 965
952 966 I report here a message from an OSX user, who suggests an alternative means
953 967 of using IPython under this operating system with good results.
954 968 Please let me know of any updates that may be useful for this section.
955 969 His message is reproduced verbatim below:
956 970 \layout Quote
957 971
958 972 From: Markus Banfi
959 973 \family typewriter
960 974 <markus.banfi-AT-mospheira.net>
961 975 \layout Quote
962 976
963 977 As a MacOS X (10.4.2) user I prefer to install software using DawinPorts instead
964 978 of Fink.
965 979 I had no problems installing ipython with DarwinPorts.
966 980 It's just:
967 981 \layout Quote
968 982
969 983
970 984 \family typewriter
971 985 sudo port install py-ipython
972 986 \layout Quote
973 987
974 988 It automatically resolved all dependencies (python24, readline, py-readline).
975 989 So far I did not encounter any problems with the DarwinPorts port of ipython.
976 990
977 991 \layout Subsection
978 992
979 993
980 994 \begin_inset LatexCommand \label{sub:Under-Windows}
981 995
982 996 \end_inset
983 997
984 998 Windows instructions
985 999 \layout Standard
986 1000
987 1001 Some of IPython's very useful features are:
988 1002 \layout Itemize
989 1003
990 1004 Integrated readline support (Tab-based file, object and attribute completion,
991 1005 input history across sessions, editable command line, etc.)
992 1006 \layout Itemize
993 1007
994 1008 Coloring of prompts, code and tracebacks.
995 1009 \layout Standard
996 1010
997 1011 These, by default, are only available under Unix-like operating systems.
998 1012 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
999 1013 from them.
1000 1014 His readline library implements both GNU readline functionality and color
1001 1015 support, so that IPython under Windows XP/2k can be as friendly and powerful
1002 1016 as under Unix-like environments.
1003 1017 \layout Standard
1004 1018
1005 1019 The
1006 1020 \family typewriter
1007 1021 readline
1008 1022 \family default
1009 1023 extension needs two other libraries to work, so in all you need:
1010 1024 \layout Enumerate
1011 1025
1012 1026
1013 1027 \family typewriter
1014 1028 PyWin32
1015 1029 \family default
1016 1030 from
1017 1031 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
1018 1032
1019 1033 \end_inset
1020 1034
1021 1035 .
1022 1036 \layout Enumerate
1023 1037
1024 1038
1025 1039 \family typewriter
1026 1040 CTypes
1027 1041 \family default
1028 1042 from
1029 1043 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
1030 1044
1031 1045 \end_inset
1032 1046
1033 1047 (you
1034 1048 \emph on
1035 1049 must
1036 1050 \emph default
1037 1051 use version 0.9.1 or newer).
1038 1052 \layout Enumerate
1039 1053
1040 1054
1041 1055 \family typewriter
1042 1056 Readline
1043 1057 \family default
1044 1058 for Windows from
1045 1059 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
1046 1060
1047 1061 \end_inset
1048 1062
1049 1063 .
1050 1064 \layout Standard
1051 1065
1052 1066
1053 1067 \series bold
1054 1068 Warning about a broken readline-like library:
1055 1069 \series default
1056 1070 several users have reported problems stemming from using the pseudo-readline
1057 1071 library at
1058 1072 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1059 1073
1060 1074 \end_inset
1061 1075
1062 1076 .
1063 1077 This is a broken library which, while called readline, only implements
1064 1078 an incomplete subset of the readline API.
1065 1079 Since it is still called readline, it fools IPython's detection mechanisms
1066 1080 and causes unpredictable crashes later.
1067 1081 If you wish to use IPython under Windows, you must NOT use this library,
1068 1082 which for all purposes is (at least as of version 1.6) terminally broken.
1069 1083 \layout Subsubsection
1070 1084
1071 1085 Installation procedure
1072 1086 \layout Standard
1073 1087
1074 1088 Once you have the above installed, from the IPython download directory grab
1075 1089 the
1076 1090 \family typewriter
1077 1091 ipython-XXX.win32.exe
1078 1092 \family default
1079 1093 file, where
1080 1094 \family typewriter
1081 1095 XXX
1082 1096 \family default
1083 1097 represents the version number.
1084 1098 This is a regular windows executable installer, which you can simply double-cli
1085 1099 ck to install.
1086 1100 It will add an entry for IPython to your Start Menu, as well as registering
1087 1101 IPython in the Windows list of applications, so you can later uninstall
1088 1102 it from the Control Panel.
1089 1103
1090 1104 \layout Standard
1091 1105
1092 1106 IPython tries to install the configuration information in a directory named
1093 1107
1094 1108 \family typewriter
1095 1109 .ipython
1096 1110 \family default
1097 1111 (
1098 1112 \family typewriter
1099 1113 _ipython
1100 1114 \family default
1101 1115 under Windows) located in your `home' directory.
1102 1116 IPython sets this directory by looking for a
1103 1117 \family typewriter
1104 1118 HOME
1105 1119 \family default
1106 1120 environment variable; if such a variable does not exist, it uses
1107 1121 \family typewriter
1108 1122 HOMEDRIVE
1109 1123 \backslash
1110 1124 HOMEPATH
1111 1125 \family default
1112 1126 (these are always defined by Windows).
1113 1127 This typically gives something like
1114 1128 \family typewriter
1115 1129 C:
1116 1130 \backslash
1117 1131 Documents and Settings
1118 1132 \backslash
1119 1133 YourUserName
1120 1134 \family default
1121 1135 , but your local details may vary.
1122 1136 In this directory you will find all the files that configure IPython's
1123 1137 defaults, and you can put there your profiles and extensions.
1124 1138 This directory is automatically added by IPython to
1125 1139 \family typewriter
1126 1140 sys.path
1127 1141 \family default
1128 1142 , so anything you place there can be found by
1129 1143 \family typewriter
1130 1144 import
1131 1145 \family default
1132 1146 statements.
1133 1147 \layout Paragraph
1134 1148
1135 1149 Upgrading
1136 1150 \layout Standard
1137 1151
1138 1152 For an IPython upgrade, you should first uninstall the previous version.
1139 1153 This will ensure that all files and directories (such as the documentation)
1140 1154 which carry embedded version strings in their names are properly removed.
1141 1155 \layout Paragraph
1142 1156
1143 1157 Manual installation under Win32
1144 1158 \layout Standard
1145 1159
1146 1160 In case the automatic installer does not work for some reason, you can download
1147 1161 the
1148 1162 \family typewriter
1149 1163 ipython-XXX.tar.gz
1150 1164 \family default
1151 1165 file, which contains the full IPython source distribution (the popular
1152 1166 WinZip can read
1153 1167 \family typewriter
1154 1168 .tar.gz
1155 1169 \family default
1156 1170 files).
1157 1171 After uncompressing the archive, you can install it at a command terminal
1158 1172 just like any other Python module, by using
1159 1173 \family typewriter
1160 1174 `python setup.py install'
1161 1175 \family default
1162 1176 .
1163 1177
1164 1178 \layout Standard
1165 1179
1166 1180 After the installation, run the supplied
1167 1181 \family typewriter
1168 1182 win32_manual_post_install.py
1169 1183 \family default
1170 1184 script, which creates the necessary Start Menu shortcuts for you.
1171 1185 \layout Subsection
1172 1186
1173 1187
1174 1188 \begin_inset LatexCommand \label{sec:upgrade}
1175 1189
1176 1190 \end_inset
1177 1191
1178 1192 Upgrading from a previous version
1179 1193 \layout Standard
1180 1194
1181 1195 If you are upgrading from a previous version of IPython, after doing the
1182 1196 routine installation described above, you should call IPython with the
1183 1197
1184 1198 \family typewriter
1185 1199 -upgrade
1186 1200 \family default
1187 1201 option the first time you run your new copy.
1188 1202 This will automatically update your configuration directory while preserving
1189 1203 copies of your old files.
1190 1204 You can then later merge back any personal customizations you may have
1191 1205 made into the new files.
1192 1206 It is a good idea to do this as there may be new options available in the
1193 1207 new configuration files which you will not have.
1194 1208 \layout Standard
1195 1209
1196 1210 Under Windows, if you don't know how to call python scripts with arguments
1197 1211 from a command line, simply delete the old config directory and IPython
1198 1212 will make a new one.
1199 1213 Win2k and WinXP users will find it in
1200 1214 \family typewriter
1201 1215 C:
1202 1216 \backslash
1203 1217 Documents and Settings
1204 1218 \backslash
1205 1219 YourUserName
1206 1220 \backslash
1207 1221 _ipython
1208 1222 \family default
1209 1223 , and Win 9x users under
1210 1224 \family typewriter
1211 1225 C:
1212 1226 \backslash
1213 1227 Program Files
1214 1228 \backslash
1215 1229 IPython
1216 1230 \backslash
1217 1231 _ipython.
1218 1232 \layout Section
1219 1233
1220 1234
1221 1235 \begin_inset LatexCommand \label{sec:good_config}
1222 1236
1223 1237 \end_inset
1224 1238
1225 1239
1226 1240 \begin_inset OptArg
1227 1241 collapsed true
1228 1242
1229 1243 \layout Standard
1230 1244
1231 1245 Initial configuration
1232 1246 \begin_inset ERT
1233 1247 status Collapsed
1234 1248
1235 1249 \layout Standard
1236 1250
1237 1251 \backslash
1238 1252 ldots
1239 1253 \end_inset
1240 1254
1241 1255
1242 1256 \end_inset
1243 1257
1244 1258 Initial configuration of your environment
1245 1259 \layout Standard
1246 1260
1247 1261 This section will help you set various things in your environment for your
1248 1262 IPython sessions to be as efficient as possible.
1249 1263 All of IPython's configuration information, along with several example
1250 1264 files, is stored in a directory named by default
1251 1265 \family typewriter
1252 1266 $HOME/.ipython
1253 1267 \family default
1254 1268 .
1255 1269 You can change this by defining the environment variable
1256 1270 \family typewriter
1257 1271 IPYTHONDIR
1258 1272 \family default
1259 1273 , or at runtime with the command line option
1260 1274 \family typewriter
1261 1275 -ipythondir
1262 1276 \family default
1263 1277 .
1264 1278 \layout Standard
1265 1279
1266 1280 If all goes well, the first time you run IPython it should automatically
1267 1281 create a user copy of the config directory for you, based on its builtin
1268 1282 defaults.
1269 1283 You can look at the files it creates to learn more about configuring the
1270 1284 system.
1271 1285 The main file you will modify to configure IPython's behavior is called
1272 1286
1273 1287 \family typewriter
1274 1288 ipythonrc
1275 1289 \family default
1276 1290 (with a
1277 1291 \family typewriter
1278 1292 .ini
1279 1293 \family default
1280 1294 extension under Windows), included for reference in Sec.
1281 1295
1282 1296 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1283 1297
1284 1298 \end_inset
1285 1299
1286 1300 .
1287 1301 This file is very commented and has many variables you can change to suit
1288 1302 your taste, you can find more details in Sec.
1289 1303
1290 1304 \begin_inset LatexCommand \ref{sec:customization}
1291 1305
1292 1306 \end_inset
1293 1307
1294 1308 .
1295 1309 Here we discuss the basic things you will want to make sure things are
1296 1310 working properly from the beginning.
1297 1311 \layout Subsection
1298 1312
1299 1313
1300 1314 \begin_inset LatexCommand \label{sec:help-access}
1301 1315
1302 1316 \end_inset
1303 1317
1304 1318 Access to the Python help system
1305 1319 \layout Standard
1306 1320
1307 1321 This is true for Python in general (not just for IPython): you should have
1308 1322 an environment variable called
1309 1323 \family typewriter
1310 1324 PYTHONDOCS
1311 1325 \family default
1312 1326 pointing to the directory where your HTML Python documentation lives.
1313 1327 In my system it's
1314 1328 \family typewriter
1315 1329 /usr/share/doc/python-docs-2.3.4/html
1316 1330 \family default
1317 1331 , check your local details or ask your systems administrator.
1318 1332
1319 1333 \layout Standard
1320 1334
1321 1335 This is the directory which holds the HTML version of the Python manuals.
1322 1336 Unfortunately it seems that different Linux distributions package these
1323 1337 files differently, so you may have to look around a bit.
1324 1338 Below I show the contents of this directory on my system for reference:
1325 1339 \layout Standard
1326 1340
1327 1341
1328 1342 \family typewriter
1329 1343 [html]> ls
1330 1344 \newline
1331 1345 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1332 1346 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1333 1347 \layout Standard
1334 1348
1335 1349 You should really make sure this variable is correctly set so that Python's
1336 1350 pydoc-based help system works.
1337 1351 It is a powerful and convenient system with full access to the Python manuals
1338 1352 and all modules accessible to you.
1339 1353 \layout Standard
1340 1354
1341 1355 Under Windows it seems that pydoc finds the documentation automatically,
1342 1356 so no extra setup appears necessary.
1343 1357 \layout Subsection
1344 1358
1345 1359 Editor
1346 1360 \layout Standard
1347 1361
1348 1362 The
1349 1363 \family typewriter
1350 1364 %edit
1351 1365 \family default
1352 1366 command (and its alias
1353 1367 \family typewriter
1354 1368 %ed
1355 1369 \family default
1356 1370 ) will invoke the editor set in your environment as
1357 1371 \family typewriter
1358 1372 EDITOR
1359 1373 \family default
1360 1374 .
1361 1375 If this variable is not set, it will default to
1362 1376 \family typewriter
1363 1377 vi
1364 1378 \family default
1365 1379 under Linux/Unix and to
1366 1380 \family typewriter
1367 1381 notepad
1368 1382 \family default
1369 1383 under Windows.
1370 1384 You may want to set this variable properly and to a lightweight editor
1371 1385 which doesn't take too long to start (that is, something other than a new
1372 1386 instance of
1373 1387 \family typewriter
1374 1388 Emacs
1375 1389 \family default
1376 1390 ).
1377 1391 This way you can edit multi-line code quickly and with the power of a real
1378 1392 editor right inside IPython.
1379 1393
1380 1394 \layout Standard
1381 1395
1382 1396 If you are a dedicated
1383 1397 \family typewriter
1384 1398 Emacs
1385 1399 \family default
1386 1400 user, you should set up the
1387 1401 \family typewriter
1388 1402 Emacs
1389 1403 \family default
1390 1404 server so that new requests are handled by the original process.
1391 1405 This means that almost no time is spent in handling the request (assuming
1392 1406 an
1393 1407 \family typewriter
1394 1408 Emacs
1395 1409 \family default
1396 1410 process is already running).
1397 1411 For this to work, you need to set your
1398 1412 \family typewriter
1399 1413 EDITOR
1400 1414 \family default
1401 1415 environment variable to
1402 1416 \family typewriter
1403 1417 'emacsclient'
1404 1418 \family default
1405 1419 .
1406 1420
1407 1421 \family typewriter
1408 1422
1409 1423 \family default
1410 1424 The code below, supplied by Francois Pinard, can then be used in your
1411 1425 \family typewriter
1412 1426 .emacs
1413 1427 \family default
1414 1428 file to enable the server:
1415 1429 \layout Standard
1416 1430
1417 1431
1418 1432 \family typewriter
1419 1433 (defvar server-buffer-clients)
1420 1434 \newline
1421 1435 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1422 1436 \newline
1423 1437
1424 1438 \begin_inset ERT
1425 1439 status Collapsed
1426 1440
1427 1441 \layout Standard
1428 1442
1429 1443 \backslash
1430 1444 hspace*{0mm}
1431 1445 \end_inset
1432 1446
1433 1447 \SpecialChar ~
1434 1448 \SpecialChar ~
1435 1449 (server-start)
1436 1450 \newline
1437 1451
1438 1452 \begin_inset ERT
1439 1453 status Collapsed
1440 1454
1441 1455 \layout Standard
1442 1456
1443 1457 \backslash
1444 1458 hspace*{0mm}
1445 1459 \end_inset
1446 1460
1447 1461 \SpecialChar ~
1448 1462 \SpecialChar ~
1449 1463 (defun fp-kill-server-with-buffer-routine ()
1450 1464 \newline
1451 1465
1452 1466 \begin_inset ERT
1453 1467 status Collapsed
1454 1468
1455 1469 \layout Standard
1456 1470
1457 1471 \backslash
1458 1472 hspace*{0mm}
1459 1473 \end_inset
1460 1474
1461 1475 \SpecialChar ~
1462 1476 \SpecialChar ~
1463 1477 \SpecialChar ~
1464 1478 \SpecialChar ~
1465 1479 (and server-buffer-clients (server-done)))
1466 1480 \newline
1467 1481
1468 1482 \begin_inset ERT
1469 1483 status Collapsed
1470 1484
1471 1485 \layout Standard
1472 1486
1473 1487 \backslash
1474 1488 hspace*{0mm}
1475 1489 \end_inset
1476 1490
1477 1491 \SpecialChar ~
1478 1492 \SpecialChar ~
1479 1493 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1480 1494 \layout Standard
1481 1495
1482 1496 You can also set the value of this editor via the commmand-line option '-
1483 1497 \family typewriter
1484 1498 editor'
1485 1499 \family default
1486 1500 or in your
1487 1501 \family typewriter
1488 1502 ipythonrc
1489 1503 \family default
1490 1504 file.
1491 1505 This is useful if you wish to use specifically for IPython an editor different
1492 1506 from your typical default (and for Windows users who tend to use fewer
1493 1507 environment variables).
1494 1508 \layout Subsection
1495 1509
1496 1510 Color
1497 1511 \layout Standard
1498 1512
1499 1513 The default IPython configuration has most bells and whistles turned on
1500 1514 (they're pretty safe).
1501 1515 But there's one that
1502 1516 \emph on
1503 1517 may
1504 1518 \emph default
1505 1519 cause problems on some systems: the use of color on screen for displaying
1506 1520 information.
1507 1521 This is very useful, since IPython can show prompts and exception tracebacks
1508 1522 with various colors, display syntax-highlighted source code, and in general
1509 1523 make it easier to visually parse information.
1510 1524 \layout Standard
1511 1525
1512 1526 The following terminals seem to handle the color sequences fine:
1513 1527 \layout Itemize
1514 1528
1515 1529 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1516 1530 \layout Itemize
1517 1531
1518 1532 CDE terminal (tested under Solaris).
1519 1533 This one boldfaces light colors.
1520 1534 \layout Itemize
1521 1535
1522 1536 (X)Emacs buffers.
1523 1537 See sec.
1524 1538 \begin_inset LatexCommand \ref{sec:emacs}
1525 1539
1526 1540 \end_inset
1527 1541
1528 1542 for more details on using IPython with (X)Emacs.
1529 1543 \layout Itemize
1530 1544
1531 1545 A Windows (XP/2k) command prompt
1532 1546 \emph on
1533 1547 with Gary Bishop's support extensions
1534 1548 \emph default
1535 1549 .
1536 1550 Gary's extensions are discussed in Sec.\SpecialChar ~
1537 1551
1538 1552 \begin_inset LatexCommand \ref{sub:Under-Windows}
1539 1553
1540 1554 \end_inset
1541 1555
1542 1556 .
1543 1557 \layout Itemize
1544 1558
1545 1559 A Windows (XP/2k) CygWin shell.
1546 1560 Although some users have reported problems; it is not clear whether there
1547 1561 is an issue for everyone or only under specific configurations.
1548 1562 If you have full color support under cygwin, please post to the IPython
1549 1563 mailing list so this issue can be resolved for all users.
1550 1564 \layout Standard
1551 1565
1552 1566 These have shown problems:
1553 1567 \layout Itemize
1554 1568
1555 1569 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1556 1570 or ssh.
1557 1571 \layout Itemize
1558 1572
1559 1573 Windows native command prompt in WinXP/2k,
1560 1574 \emph on
1561 1575 without
1562 1576 \emph default
1563 1577 Gary Bishop's extensions.
1564 1578 Once Gary's readline library is installed, the normal WinXP/2k command
1565 1579 prompt works perfectly.
1566 1580 \layout Standard
1567 1581
1568 1582 Currently the following color schemes are available:
1569 1583 \layout Itemize
1570 1584
1571 1585
1572 1586 \family typewriter
1573 1587 NoColor
1574 1588 \family default
1575 1589 : uses no color escapes at all (all escapes are empty
1576 1590 \begin_inset Quotes eld
1577 1591 \end_inset
1578 1592
1579 1593
1580 1594 \begin_inset Quotes eld
1581 1595 \end_inset
1582 1596
1583 1597 strings).
1584 1598 This 'scheme' is thus fully safe to use in any terminal.
1585 1599 \layout Itemize
1586 1600
1587 1601
1588 1602 \family typewriter
1589 1603 Linux
1590 1604 \family default
1591 1605 : works well in Linux console type environments: dark background with light
1592 1606 fonts.
1593 1607 It uses bright colors for information, so it is difficult to read if you
1594 1608 have a light colored background.
1595 1609 \layout Itemize
1596 1610
1597 1611
1598 1612 \family typewriter
1599 1613 LightBG
1600 1614 \family default
1601 1615 : the basic colors are similar to those in the
1602 1616 \family typewriter
1603 1617 Linux
1604 1618 \family default
1605 1619 scheme but darker.
1606 1620 It is easy to read in terminals with light backgrounds.
1607 1621 \layout Standard
1608 1622
1609 1623 IPython uses colors for two main groups of things: prompts and tracebacks
1610 1624 which are directly printed to the terminal, and the object introspection
1611 1625 system which passes large sets of data through a pager.
1612 1626 \layout Subsubsection
1613 1627
1614 1628 Input/Output prompts and exception tracebacks
1615 1629 \layout Standard
1616 1630
1617 1631 You can test whether the colored prompts and tracebacks work on your system
1618 1632 interactively by typing
1619 1633 \family typewriter
1620 1634 '%colors Linux'
1621 1635 \family default
1622 1636 at the prompt (use '
1623 1637 \family typewriter
1624 1638 %colors LightBG'
1625 1639 \family default
1626 1640 if your terminal has a light background).
1627 1641 If the input prompt shows garbage like:
1628 1642 \newline
1629 1643
1630 1644 \family typewriter
1631 1645 [0;32mIn [[1;32m1[0;32m]: [0;00m
1632 1646 \family default
1633 1647
1634 1648 \newline
1635 1649 instead of (in color) something like:
1636 1650 \newline
1637 1651
1638 1652 \family typewriter
1639 1653 In [1]:
1640 1654 \family default
1641 1655
1642 1656 \newline
1643 1657 this means that your terminal doesn't properly handle color escape sequences.
1644 1658 You can go to a 'no color' mode by typing '
1645 1659 \family typewriter
1646 1660 %colors NoColor
1647 1661 \family default
1648 1662 '.
1649 1663
1650 1664 \layout Standard
1651 1665
1652 1666 You can try using a different terminal emulator program.
1653 1667 To permanently set your color preferences, edit the file
1654 1668 \family typewriter
1655 1669 $HOME/.ipython/ipythonrc
1656 1670 \family default
1657 1671 and set the
1658 1672 \family typewriter
1659 1673 colors
1660 1674 \family default
1661 1675 option to the desired value.
1662 1676 \layout Subsubsection
1663 1677
1664 1678 Object details (types, docstrings, source code, etc.)
1665 1679 \layout Standard
1666 1680
1667 1681 IPython has a set of special functions for studying the objects you are
1668 1682 working with, discussed in detail in Sec.
1669 1683
1670 1684 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1671 1685
1672 1686 \end_inset
1673 1687
1674 1688 .
1675 1689 But this system relies on passing information which is longer than your
1676 1690 screen through a data pager, such as the common Unix
1677 1691 \family typewriter
1678 1692 less
1679 1693 \family default
1680 1694 and
1681 1695 \family typewriter
1682 1696 more
1683 1697 \family default
1684 1698 programs.
1685 1699 In order to be able to see this information in color, your pager needs
1686 1700 to be properly configured.
1687 1701 I strongly recommend using
1688 1702 \family typewriter
1689 1703 less
1690 1704 \family default
1691 1705 instead of
1692 1706 \family typewriter
1693 1707 more
1694 1708 \family default
1695 1709 , as it seems that
1696 1710 \family typewriter
1697 1711 more
1698 1712 \family default
1699 1713 simply can not understand colored text correctly.
1700 1714 \layout Standard
1701 1715
1702 1716 In order to configure
1703 1717 \family typewriter
1704 1718 less
1705 1719 \family default
1706 1720 as your default pager, do the following:
1707 1721 \layout Enumerate
1708 1722
1709 1723 Set the environment
1710 1724 \family typewriter
1711 1725 PAGER
1712 1726 \family default
1713 1727 variable to
1714 1728 \family typewriter
1715 1729 less
1716 1730 \family default
1717 1731 .
1718 1732 \layout Enumerate
1719 1733
1720 1734 Set the environment
1721 1735 \family typewriter
1722 1736 LESS
1723 1737 \family default
1724 1738 variable to
1725 1739 \family typewriter
1726 1740 -r
1727 1741 \family default
1728 1742 (plus any other options you always want to pass to
1729 1743 \family typewriter
1730 1744 less
1731 1745 \family default
1732 1746 by default).
1733 1747 This tells
1734 1748 \family typewriter
1735 1749 less
1736 1750 \family default
1737 1751 to properly interpret control sequences, which is how color information
1738 1752 is given to your terminal.
1739 1753 \layout Standard
1740 1754
1741 1755 For the
1742 1756 \family typewriter
1743 1757 csh
1744 1758 \family default
1745 1759 or
1746 1760 \family typewriter
1747 1761 tcsh
1748 1762 \family default
1749 1763 shells, add to your
1750 1764 \family typewriter
1751 1765 ~/.cshrc
1752 1766 \family default
1753 1767 file the lines:
1754 1768 \layout Standard
1755 1769
1756 1770
1757 1771 \family typewriter
1758 1772 setenv PAGER less
1759 1773 \newline
1760 1774 setenv LESS -r
1761 1775 \layout Standard
1762 1776
1763 1777 There is similar syntax for other Unix shells, look at your system documentation
1764 1778 for details.
1765 1779 \layout Standard
1766 1780
1767 1781 If you are on a system which lacks proper data pagers (such as Windows),
1768 1782 IPython will use a very limited builtin pager.
1769 1783 \layout Subsection
1770 1784
1771 1785
1772 1786 \begin_inset LatexCommand \label{sec:emacs}
1773 1787
1774 1788 \end_inset
1775 1789
1776 1790 (X)Emacs configuration
1777 1791 \layout Standard
1778 1792
1779 1793 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1780 1794 (X)Emacs and IPython get along very well.
1781 1795
1782 1796 \layout Standard
1783 1797
1784 1798
1785 1799 \series bold
1786 1800 Important note:
1787 1801 \series default
1788 1802 You will need to use a recent enough version of
1789 1803 \family typewriter
1790 1804 python-mode.el
1791 1805 \family default
1792 1806 , along with the file
1793 1807 \family typewriter
1794 1808 ipython.el
1795 1809 \family default
1796 1810 .
1797 1811 You can check that the version you have of
1798 1812 \family typewriter
1799 1813 python-mode.el
1800 1814 \family default
1801 1815 is new enough by either looking at the revision number in the file itself,
1802 1816 or asking for it in (X)Emacs via
1803 1817 \family typewriter
1804 1818 M-x py-version
1805 1819 \family default
1806 1820 .
1807 1821 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1808 1822 \layout Standard
1809 1823
1810 1824 The file
1811 1825 \family typewriter
1812 1826 ipython.el
1813 1827 \family default
1814 1828 is included with the IPython distribution, in the documentation directory
1815 1829 (where this manual resides in PDF and HTML formats).
1816 1830 \layout Standard
1817 1831
1818 1832 Once you put these files in your Emacs path, all you need in your
1819 1833 \family typewriter
1820 1834 .emacs
1821 1835 \family default
1822 1836 file is:
1823 1837 \layout Standard
1824 1838
1825 1839
1826 1840 \family typewriter
1827 1841 (require 'ipython)
1828 1842 \layout Standard
1829 1843
1830 1844 This should give you full support for executing code snippets via IPython,
1831 1845 opening IPython as your Python shell via
1832 1846 \family typewriter
1833 1847 C-c\SpecialChar ~
1834 1848 !
1835 1849 \family default
1836 1850 , etc.
1837 1851
1838 1852 \layout Subsubsection*
1839 1853
1840 1854 Notes
1841 1855 \layout Itemize
1842 1856
1843 1857 There is one caveat you should be aware of: you must start the IPython shell
1844 1858
1845 1859 \emph on
1846 1860 before
1847 1861 \emph default
1848 1862 attempting to execute any code regions via
1849 1863 \family typewriter
1850 1864 C-c\SpecialChar ~
1851 1865 |
1852 1866 \family default
1853 1867 .
1854 1868 Simply type
1855 1869 \family typewriter
1856 1870 C-c\SpecialChar ~
1857 1871 !
1858 1872 \family default
1859 1873 to start IPython before passing any code regions to the interpreter, and
1860 1874 you shouldn't experience any problems.
1861 1875 \newline
1862 1876 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1863 1877 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1864 1878 \layout Itemize
1865 1879
1866 1880 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1867 1881 ts should be directed to him through the IPython mailing lists.
1868 1882
1869 1883 \layout Itemize
1870 1884
1871 1885 This code is still somewhat experimental so it's a bit rough around the
1872 1886 edges (although in practice, it works quite well).
1873 1887 \layout Itemize
1874 1888
1875 1889 Be aware that if you customize
1876 1890 \family typewriter
1877 1891 py-python-command
1878 1892 \family default
1879 1893 previously, this value will override what
1880 1894 \family typewriter
1881 1895 ipython.el
1882 1896 \family default
1883 1897 does (because loading the customization variables comes later).
1884 1898 \layout Section
1885 1899
1886 1900
1887 1901 \begin_inset LatexCommand \label{sec:quick_tips}
1888 1902
1889 1903 \end_inset
1890 1904
1891 1905 Quick tips
1892 1906 \layout Standard
1893 1907
1894 1908 IPython can be used as an improved replacement for the Python prompt, and
1895 1909 for that you don't really need to read any more of this manual.
1896 1910 But in this section we'll try to summarize a few tips on how to make the
1897 1911 most effective use of it for everyday Python development, highlighting
1898 1912 things you might miss in the rest of the manual (which is getting long).
1899 1913 We'll give references to parts in the manual which provide more detail
1900 1914 when appropriate.
1901 1915 \layout Standard
1902 1916
1903 1917 The following article by Jeremy Jones provides an introductory tutorial
1904 1918 about IPython:
1905 1919 \newline
1906 1920
1907 1921 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1908 1922
1909 1923 \end_inset
1910 1924
1911 1925
1912 1926 \layout Itemize
1913 1927
1914 1928 The TAB key.
1915 1929 TAB-completion, especially for attributes, is a convenient way to explore
1916 1930 the structure of any object you're dealing with.
1917 1931 Simply type
1918 1932 \family typewriter
1919 1933 object_name.<TAB>
1920 1934 \family default
1921 1935 and a list of the object's attributes will be printed (see sec.
1922 1936
1923 1937 \begin_inset LatexCommand \ref{sec:readline}
1924 1938
1925 1939 \end_inset
1926 1940
1927 1941 for more).
1928 1942 Tab completion also works on file and directory names, which combined with
1929 1943 IPython's alias system allows you to do from within IPython many of the
1930 1944 things you normally would need the system shell for.
1931 1945
1932 1946 \layout Itemize
1933 1947
1934 1948 Explore your objects.
1935 1949 Typing
1936 1950 \family typewriter
1937 1951 object_name?
1938 1952 \family default
1939 1953 will print all sorts of details about any object, including docstrings,
1940 1954 function definition lines (for call arguments) and constructor details
1941 1955 for classes.
1942 1956 The magic commands
1943 1957 \family typewriter
1944 1958 %pdoc
1945 1959 \family default
1946 1960 ,
1947 1961 \family typewriter
1948 1962 %pdef
1949 1963 \family default
1950 1964 ,
1951 1965 \family typewriter
1952 1966 %psource
1953 1967 \family default
1954 1968 and
1955 1969 \family typewriter
1956 1970 %pfile
1957 1971 \family default
1958 1972 will respectively print the docstring, function definition line, full source
1959 1973 code and the complete file for any object (when they can be found).
1960 1974 If automagic is on (it is by default), you don't need to type the '
1961 1975 \family typewriter
1962 1976 %
1963 1977 \family default
1964 1978 ' explicitly.
1965 1979 See sec.
1966 1980
1967 1981 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1968 1982
1969 1983 \end_inset
1970 1984
1971 1985 for more.
1972 1986 \layout Itemize
1973 1987
1974 1988 The
1975 1989 \family typewriter
1976 1990 %run
1977 1991 \family default
1978 1992 magic command allows you to run any python script and load all of its data
1979 1993 directly into the interactive namespace.
1980 1994 Since the file is re-read from disk each time, changes you make to it are
1981 1995 reflected immediately (in contrast to the behavior of
1982 1996 \family typewriter
1983 1997 import
1984 1998 \family default
1985 1999 ).
1986 2000 I rarely use
1987 2001 \family typewriter
1988 2002 import
1989 2003 \family default
1990 2004 for code I am testing, relying on
1991 2005 \family typewriter
1992 2006 %run
1993 2007 \family default
1994 2008 instead.
1995 2009 See sec.
1996 2010
1997 2011 \begin_inset LatexCommand \ref{sec:magic}
1998 2012
1999 2013 \end_inset
2000 2014
2001 2015 for more on this and other magic commands, or type the name of any magic
2002 2016 command and ? to get details on it.
2003 2017 See also sec.
2004 2018
2005 2019 \begin_inset LatexCommand \ref{sec:dreload}
2006 2020
2007 2021 \end_inset
2008 2022
2009 2023 for a recursive reload command.
2010 2024 \newline
2011 2025
2012 2026 \family typewriter
2013 2027 %run
2014 2028 \family default
2015 2029 also has special flags for timing the execution of your scripts (
2016 2030 \family typewriter
2017 2031 -t
2018 2032 \family default
2019 2033 ) and for executing them under the control of either Python's
2020 2034 \family typewriter
2021 2035 pdb
2022 2036 \family default
2023 2037 debugger (
2024 2038 \family typewriter
2025 2039 -d
2026 2040 \family default
2027 2041 ) or profiler (
2028 2042 \family typewriter
2029 2043 -p
2030 2044 \family default
2031 2045 ).
2032 2046 With all of these,
2033 2047 \family typewriter
2034 2048 %run
2035 2049 \family default
2036 2050 can be used as the main tool for efficient interactive development of code
2037 2051 which you write in your editor of choice.
2038 2052 \layout Itemize
2039 2053
2040 2054 Use the Python debugger,
2041 2055 \family typewriter
2042 2056 pdb
2043 2057 \family default
2044 2058
2045 2059 \begin_inset Foot
2046 2060 collapsed true
2047 2061
2048 2062 \layout Standard
2049 2063
2050 2064 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2051 2065 to IPython's improved debugger and profiler support.
2052 2066 \end_inset
2053 2067
2054 2068 .
2055 2069 The
2056 2070 \family typewriter
2057 2071 %pdb
2058 2072 \family default
2059 2073 command allows you to toggle on and off the automatic invocation of an
2060 2074 IPython-enhanced
2061 2075 \family typewriter
2062 2076 pdb
2063 2077 \family default
2064 2078 debugger (with coloring, tab completion and more) at any uncaught exception.
2065 2079 The advantage of this is that
2066 2080 \family typewriter
2067 2081 pdb
2068 2082 \family default
2069 2083 starts
2070 2084 \emph on
2071 2085 inside
2072 2086 \emph default
2073 2087 the function where the exception occurred, with all data still available.
2074 2088 You can print variables, see code, execute statements and even walk up
2075 2089 and down the call stack to track down the true source of the problem (which
2076 2090 often is many layers in the stack above where the exception gets triggered).
2077 2091 \newline
2078 2092 Running programs with
2079 2093 \family typewriter
2080 2094 %run
2081 2095 \family default
2082 2096 and pdb active can be an efficient to develop and debug code, in many cases
2083 2097 eliminating the need for
2084 2098 \family typewriter
2085 2099 print
2086 2100 \family default
2087 2101 statements or external debugging tools.
2088 2102 I often simply put a
2089 2103 \family typewriter
2090 2104 1/0
2091 2105 \family default
2092 2106 in a place where I want to take a look so that pdb gets called, quickly
2093 2107 view whatever variables I need to or test various pieces of code and then
2094 2108 remove the
2095 2109 \family typewriter
2096 2110 1/0
2097 2111 \family default
2098 2112 .
2099 2113 \newline
2100 2114 Note also that `
2101 2115 \family typewriter
2102 2116 %run -d
2103 2117 \family default
2104 2118 ' activates
2105 2119 \family typewriter
2106 2120 pdb
2107 2121 \family default
2108 2122 and automatically sets initial breakpoints for you to step through your
2109 2123 code, watch variables, etc.
2110 2124 See Sec.\SpecialChar ~
2111 2125
2112 2126 \begin_inset LatexCommand \ref{sec:cache_output}
2113 2127
2114 2128 \end_inset
2115 2129
2116 2130 for details.
2117 2131 \layout Itemize
2118 2132
2119 2133 Use the output cache.
2120 2134 All output results are automatically stored in a global dictionary named
2121 2135
2122 2136 \family typewriter
2123 2137 Out
2124 2138 \family default
2125 2139 and variables named
2126 2140 \family typewriter
2127 2141 _1
2128 2142 \family default
2129 2143 ,
2130 2144 \family typewriter
2131 2145 _2
2132 2146 \family default
2133 2147 , etc.
2134 2148 alias them.
2135 2149 For example, the result of input line 4 is available either as
2136 2150 \family typewriter
2137 2151 Out[4]
2138 2152 \family default
2139 2153 or as
2140 2154 \family typewriter
2141 2155 _4
2142 2156 \family default
2143 2157 .
2144 2158 Additionally, three variables named
2145 2159 \family typewriter
2146 2160 _
2147 2161 \family default
2148 2162 ,
2149 2163 \family typewriter
2150 2164 __
2151 2165 \family default
2152 2166 and
2153 2167 \family typewriter
2154 2168 ___
2155 2169 \family default
2156 2170 are always kept updated with the for the last three results.
2157 2171 This allows you to recall any previous result and further use it for new
2158 2172 calculations.
2159 2173 See Sec.\SpecialChar ~
2160 2174
2161 2175 \begin_inset LatexCommand \ref{sec:cache_output}
2162 2176
2163 2177 \end_inset
2164 2178
2165 2179 for more.
2166 2180 \layout Itemize
2167 2181
2168 2182 Put a '
2169 2183 \family typewriter
2170 2184 ;
2171 2185 \family default
2172 2186 ' at the end of a line to supress the printing of output.
2173 2187 This is useful when doing calculations which generate long output you are
2174 2188 not interested in seeing.
2175 2189 The
2176 2190 \family typewriter
2177 2191 _*
2178 2192 \family default
2179 2193 variables and the
2180 2194 \family typewriter
2181 2195 Out[]
2182 2196 \family default
2183 2197 list do get updated with the contents of the output, even if it is not
2184 2198 printed.
2185 2199 You can thus still access the generated results this way for further processing.
2186 2200 \layout Itemize
2187 2201
2188 2202 A similar system exists for caching input.
2189 2203 All input is stored in a global list called
2190 2204 \family typewriter
2191 2205 In
2192 2206 \family default
2193 2207 , so you can re-execute lines 22 through 28 plus line 34 by typing
2194 2208 \family typewriter
2195 2209 'exec In[22:29]+In[34]'
2196 2210 \family default
2197 2211 (using Python slicing notation).
2198 2212 If you need to execute the same set of lines often, you can assign them
2199 2213 to a macro with the
2200 2214 \family typewriter
2201 2215 %macro
2202 2216 \family default
2203 2217
2204 2218 \family typewriter
2205 2219 function.
2206 2220
2207 2221 \family default
2208 2222 See sec.
2209 2223
2210 2224 \begin_inset LatexCommand \ref{sec:cache_input}
2211 2225
2212 2226 \end_inset
2213 2227
2214 2228 for more.
2215 2229 \layout Itemize
2216 2230
2217 2231 Use your input history.
2218 2232 The
2219 2233 \family typewriter
2220 2234 %hist
2221 2235 \family default
2222 2236 command can show you all previous input, without line numbers if desired
2223 2237 (option
2224 2238 \family typewriter
2225 2239 -n
2226 2240 \family default
2227 2241 ) so you can directly copy and paste code either back in IPython or in a
2228 2242 text editor.
2229 2243 You can also save all your history by turning on logging via
2230 2244 \family typewriter
2231 2245 %logstart
2232 2246 \family default
2233 2247 ; these logs can later be either reloaded as IPython sessions or used as
2234 2248 code for your programs.
2235 2249 \layout Itemize
2236 2250
2237 2251 Define your own system aliases.
2238 2252 Even though IPython gives you access to your system shell via the
2239 2253 \family typewriter
2240 2254 !
2241 2255 \family default
2242 2256 prefix, it is convenient to have aliases to the system commands you use
2243 2257 most often.
2244 2258 This allows you to work seamlessly from inside IPython with the same commands
2245 2259 you are used to in your system shell.
2246 2260 \newline
2247 2261 IPython comes with some pre-defined aliases and a complete system for changing
2248 2262 directories, both via a stack (see
2249 2263 \family typewriter
2250 2264 %pushd
2251 2265 \family default
2252 2266 ,
2253 2267 \family typewriter
2254 2268 %popd
2255 2269 \family default
2256 2270 and
2257 2271 \family typewriter
2258 2272 %ds
2259 2273 \family default
2260 2274 ) and via direct
2261 2275 \family typewriter
2262 2276 %cd
2263 2277 \family default
2264 2278 .
2265 2279 The latter keeps a history of visited directories and allows you to go
2266 2280 to any previously visited one.
2267 2281 \layout Itemize
2268 2282
2269 2283 Use Python to manipulate the results of system commands.
2270 2284 The `
2271 2285 \family typewriter
2272 2286 !!
2273 2287 \family default
2274 2288 ' special syntax, and the
2275 2289 \family typewriter
2276 2290 %sc
2277 2291 \family default
2278 2292 and
2279 2293 \family typewriter
2280 2294 %sx
2281 2295 \family default
2282 2296 magic commands allow you to capture system output into Python variables.
2283 2297 \layout Itemize
2284 2298
2285 2299 Expand python variables when calling the shell (either via
2286 2300 \family typewriter
2287 2301 `!'
2288 2302 \family default
2289 2303 and
2290 2304 \family typewriter
2291 2305 `!!'
2292 2306 \family default
2293 2307 or via aliases) by prepending a
2294 2308 \family typewriter
2295 2309 $
2296 2310 \family default
2297 2311 in front of them.
2298 2312 You can also expand complete python expressions.
2299 2313 See sec.\SpecialChar ~
2300 2314
2301 2315 \begin_inset LatexCommand \ref{sub:System-shell-access}
2302 2316
2303 2317 \end_inset
2304 2318
2305 2319 for more.
2306 2320 \layout Itemize
2307 2321
2308 2322 Use profiles to maintain different configurations (modules to load, function
2309 2323 definitions, option settings) for particular tasks.
2310 2324 You can then have customized versions of IPython for specific purposes.
2311 2325 See sec.\SpecialChar ~
2312 2326
2313 2327 \begin_inset LatexCommand \ref{sec:profiles}
2314 2328
2315 2329 \end_inset
2316 2330
2317 2331 for more.
2318 2332 \layout Itemize
2319 2333
2320 2334 Embed IPython in your programs.
2321 2335 A few lines of code are enough to load a complete IPython inside your own
2322 2336 programs, giving you the ability to work with your data interactively after
2323 2337 automatic processing has been completed.
2324 2338 See sec.\SpecialChar ~
2325 2339
2326 2340 \begin_inset LatexCommand \ref{sec:embed}
2327 2341
2328 2342 \end_inset
2329 2343
2330 2344 for more.
2331 2345 \layout Itemize
2332 2346
2333 2347 Use the Python profiler.
2334 2348 When dealing with performance issues, the
2335 2349 \family typewriter
2336 2350 %run
2337 2351 \family default
2338 2352 command with a
2339 2353 \family typewriter
2340 2354 -p
2341 2355 \family default
2342 2356 option allows you to run complete programs under the control of the Python
2343 2357 profiler.
2344 2358 The
2345 2359 \family typewriter
2346 2360 %prun
2347 2361 \family default
2348 2362 command does a similar job for single Python expressions (like function
2349 2363 calls).
2350 2364 \layout Itemize
2351 2365
2352 2366 Use the IPython.demo.Demo class to load any Python script as an interactive
2353 2367 demo.
2354 2368 With a minimal amount of simple markup, you can control the execution of
2355 2369 the script, stopping as needed.
2356 2370 See sec.\SpecialChar ~
2357 2371
2358 2372 \begin_inset LatexCommand \ref{sec:interactive-demos}
2359 2373
2360 2374 \end_inset
2361 2375
2362 2376 for more.
2363 2377 \layout Subsection
2364 2378
2365 2379 Source code handling tips
2366 2380 \layout Standard
2367 2381
2368 2382 IPython is a line-oriented program, without full control of the terminal.
2369 2383 Therefore, it doesn't support true multiline editing.
2370 2384 However, it has a number of useful tools to help you in dealing effectively
2371 2385 with more complex editing.
2372 2386 \layout Standard
2373 2387
2374 2388 The
2375 2389 \family typewriter
2376 2390 %edit
2377 2391 \family default
2378 2392 command gives a reasonable approximation of multiline editing, by invoking
2379 2393 your favorite editor on the spot.
2380 2394 IPython will execute the code you type in there as if it were typed interactive
2381 2395 ly.
2382 2396 Type
2383 2397 \family typewriter
2384 2398 %edit?
2385 2399 \family default
2386 2400 for the full details on the edit command.
2387 2401 \layout Standard
2388 2402
2389 2403 If you have typed various commands during a session, which you'd like to
2390 2404 reuse, IPython provides you with a number of tools.
2391 2405 Start by using
2392 2406 \family typewriter
2393 2407 %hist
2394 2408 \family default
2395 2409 to see your input history, so you can see the line numbers of all input.
2396 2410 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
2397 2411 and 28.
2398 2412 All the commands below can operate on these with the syntax
2399 2413 \layout LyX-Code
2400 2414
2401 2415 %command 10-20 24 28
2402 2416 \layout Standard
2403 2417
2404 2418 where the command given can be:
2405 2419 \layout Itemize
2406 2420
2407 2421
2408 2422 \family typewriter
2409 2423 %macro <macroname>
2410 2424 \family default
2411 2425 : this stores the lines into a variable which, when called at the prompt,
2412 2426 re-executes the input.
2413 2427 Macros can be edited later using
2414 2428 \family typewriter
2415 2429 `%edit macroname
2416 2430 \family default
2417 2431 ', and they can be stored persistently across sessions with `
2418 2432 \family typewriter
2419 2433 %store macroname
2420 2434 \family default
2421 2435 ' (the storage system is per-profile).
2422 2436 The combination of quick macros, persistent storage and editing, allows
2423 2437 you to easily refine quick-and-dirty interactive input into permanent utilities
2424 2438 , always available both in IPython and as files for general reuse.
2425 2439 \layout Itemize
2426 2440
2427 2441
2428 2442 \family typewriter
2429 2443 %edit
2430 2444 \family default
2431 2445 : this will open a text editor with those lines pre-loaded for further modificat
2432 2446 ion.
2433 2447 It will then execute the resulting file's contents as if you had typed
2434 2448 it at the prompt.
2435 2449 \layout Itemize
2436 2450
2437 2451
2438 2452 \family typewriter
2439 2453 %save <filename>
2440 2454 \family default
2441 2455 : this saves the lines directly to a named file on disk.
2442 2456 \layout Standard
2443 2457
2444 2458 While
2445 2459 \family typewriter
2446 2460 %macro
2447 2461 \family default
2448 2462 saves input lines into memory for interactive re-execution, sometimes you'd
2449 2463 like to save your input directly to a file.
2450 2464 The
2451 2465 \family typewriter
2452 2466 %save
2453 2467 \family default
2454 2468 magic does this: its input sytnax is the same as
2455 2469 \family typewriter
2456 2470 %macro
2457 2471 \family default
2458 2472 , but it saves your input directly to a Python file.
2459 2473 Note that the
2460 2474 \family typewriter
2461 2475 %logstart
2462 2476 \family default
2463 2477 command also saves input, but it logs
2464 2478 \emph on
2465 2479 all
2466 2480 \emph default
2467 2481 input to disk (though you can temporarily suspend it and reactivate it
2468 2482 with
2469 2483 \family typewriter
2470 2484 %logoff/%logon
2471 2485 \family default
2472 2486 );
2473 2487 \family typewriter
2474 2488 %save
2475 2489 \family default
2476 2490 allows you to select which lines of input you need to save.
2477 2491 \layout Subsubsection*
2478 2492
2479 2493 Lightweight 'version control'
2480 2494 \layout Standard
2481 2495
2482 2496 When you call
2483 2497 \family typewriter
2484 2498 %edit
2485 2499 \family default
2486 2500 with no arguments, IPython opens an empty editor with a temporary file,
2487 2501 and it returns the contents of your editing session as a string variable.
2488 2502 Thanks to IPython's output caching mechanism, this is automatically stored:
2489 2503 \layout LyX-Code
2490 2504
2491 2505 In [1]: %edit
2492 2506 \layout LyX-Code
2493 2507
2494 2508 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
2495 2509 \layout LyX-Code
2496 2510
2497 2511 Editing...
2498 2512 done.
2499 2513 Executing edited code...
2500 2514 \layout LyX-Code
2501 2515
2502 2516 hello - this is a temporary file
2503 2517 \layout LyX-Code
2504 2518
2505 2519 Out[1]: "print 'hello - this is a temporary file'
2506 2520 \backslash
2507 2521 n"
2508 2522 \layout Standard
2509 2523
2510 2524 Now, if you call
2511 2525 \family typewriter
2512 2526 `%edit -p'
2513 2527 \family default
2514 2528 , IPython tries to open an editor with the same data as the last time you
2515 2529 used
2516 2530 \family typewriter
2517 2531 %edit
2518 2532 \family default
2519 2533 .
2520 2534 So if you haven't used
2521 2535 \family typewriter
2522 2536 %edit
2523 2537 \family default
2524 2538 in the meantime, this same contents will reopen; however, it will be done
2525 2539 in a
2526 2540 \emph on
2527 2541 new file
2528 2542 \emph default
2529 2543 .
2530 2544 This means that if you make changes and you later want to find an old version,
2531 2545 you can always retrieve it by using its output number, via
2532 2546 \family typewriter
2533 2547 `%edit _NN'
2534 2548 \family default
2535 2549 , where
2536 2550 \family typewriter
2537 2551 NN
2538 2552 \family default
2539 2553 is the number of the output prompt.
2540 2554 \layout Standard
2541 2555
2542 2556 Continuing with the example above, this should illustrate this idea:
2543 2557 \layout LyX-Code
2544 2558
2545 2559 In [2]: edit -p
2546 2560 \layout LyX-Code
2547 2561
2548 2562 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
2549 2563 \layout LyX-Code
2550 2564
2551 2565 Editing...
2552 2566 done.
2553 2567 Executing edited code...
2554 2568 \layout LyX-Code
2555 2569
2556 2570 hello - now I made some changes
2557 2571 \layout LyX-Code
2558 2572
2559 2573 Out[2]: "print 'hello - now I made some changes'
2560 2574 \backslash
2561 2575 n"
2562 2576 \layout LyX-Code
2563 2577
2564 2578 In [3]: edit _1
2565 2579 \layout LyX-Code
2566 2580
2567 2581 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
2568 2582 \layout LyX-Code
2569 2583
2570 2584 Editing...
2571 2585 done.
2572 2586 Executing edited code...
2573 2587 \layout LyX-Code
2574 2588
2575 2589 hello - this is a temporary file
2576 2590 \layout LyX-Code
2577 2591
2578 2592 IPython version control at work :)
2579 2593 \layout LyX-Code
2580 2594
2581 2595 Out[3]: "print 'hello - this is a temporary file'
2582 2596 \backslash
2583 2597 nprint 'IPython version control at work :)'
2584 2598 \backslash
2585 2599 n"
2586 2600 \layout Standard
2587 2601
2588 2602 This section was written after a contribution by Alexander Belchenko on
2589 2603 the IPython user list.
2590 2604 \layout LyX-Code
2591 2605
2592 2606 \layout Subsection
2593 2607
2594 2608 Effective logging
2595 2609 \layout Standard
2596 2610
2597 2611 A very useful suggestion sent in by Robert Kern follows:
2598 2612 \layout Standard
2599 2613
2600 2614 I recently happened on a nifty way to keep tidy per-project log files.
2601 2615 I made a profile for my project (which is called "parkfield").
2602 2616 \layout LyX-Code
2603 2617
2604 2618 include ipythonrc
2605 2619 \layout LyX-Code
2606 2620
2607 2621 # cancel earlier logfile invocation:
2608 2622 \layout LyX-Code
2609 2623
2610 2624 logfile ''
2611 2625 \layout LyX-Code
2612 2626
2613 2627 execute import time
2614 2628 \layout LyX-Code
2615 2629
2616 2630 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
2617 2631 \layout LyX-Code
2618 2632
2619 2633 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
2620 2634 \layout Standard
2621 2635
2622 2636 I also added a shell alias for convenience:
2623 2637 \layout LyX-Code
2624 2638
2625 2639 alias parkfield="ipython -pylab -profile parkfield"
2626 2640 \layout Standard
2627 2641
2628 2642 Now I have a nice little directory with everything I ever type in, organized
2629 2643 by project and date.
2630 2644 \layout Standard
2631 2645
2632 2646
2633 2647 \series bold
2634 2648 Contribute your own:
2635 2649 \series default
2636 2650 If you have your own favorite tip on using IPython efficiently for a certain
2637 2651 task (especially things which can't be done in the normal Python interpreter),
2638 2652 don't hesitate to send it!
2639 2653 \layout Section
2640 2654
2641 2655 Command-line use
2642 2656 \layout Standard
2643 2657
2644 2658 You start IPython with the command:
2645 2659 \layout Standard
2646 2660
2647 2661
2648 2662 \family typewriter
2649 2663 $ ipython [options] files
2650 2664 \layout Standard
2651 2665
2652 2666 If invoked with no options, it executes all the files listed in sequence
2653 2667 and drops you into the interpreter while still acknowledging any options
2654 2668 you may have set in your ipythonrc file.
2655 2669 This behavior is different from standard Python, which when called as
2656 2670 \family typewriter
2657 2671 python -i
2658 2672 \family default
2659 2673 will only execute one file and ignore your configuration setup.
2660 2674 \layout Standard
2661 2675
2662 2676 Please note that some of the configuration options are not available at
2663 2677 the command line, simply because they are not practical here.
2664 2678 Look into your ipythonrc configuration file for details on those.
2665 2679 This file typically installed in the
2666 2680 \family typewriter
2667 2681 $HOME/.ipython
2668 2682 \family default
2669 2683 directory.
2670 2684 For Windows users,
2671 2685 \family typewriter
2672 2686 $HOME
2673 2687 \family default
2674 2688 resolves to
2675 2689 \family typewriter
2676 2690 C:
2677 2691 \backslash
2678 2692
2679 2693 \backslash
2680 2694 Documents and Settings
2681 2695 \backslash
2682 2696
2683 2697 \backslash
2684 2698 YourUserName
2685 2699 \family default
2686 2700 in most instances.
2687 2701 In the rest of this text, we will refer to this directory as
2688 2702 \family typewriter
2689 2703 IPYTHONDIR
2690 2704 \family default
2691 2705 .
2692 2706 \layout Subsection
2693 2707
2694 2708
2695 2709 \begin_inset LatexCommand \label{sec:threading-opts}
2696 2710
2697 2711 \end_inset
2698 2712
2699 2713 Special Threading Options
2700 2714 \layout Standard
2701 2715
2702 2716 The following special options are ONLY valid at the beginning of the command
2703 2717 line, and not later.
2704 2718 This is because they control the initial- ization of ipython itself, before
2705 2719 the normal option-handling mechanism is active.
2706 2720 \layout List
2707 2721 \labelwidthstring 00.00.0000
2708 2722
2709 2723
2710 2724 \family typewriter
2711 2725 \series bold
2712 2726 -gthread,\SpecialChar ~
2713 2727 -qthread,\SpecialChar ~
2714 2728 -wthread,\SpecialChar ~
2715 2729 -pylab:
2716 2730 \family default
2717 2731 \series default
2718 2732 Only
2719 2733 \emph on
2720 2734 one
2721 2735 \emph default
2722 2736 of these can be given, and it can only be given as the first option passed
2723 2737 to IPython (it will have no effect in any other position).
2724 2738 They provide threading support for the GTK Qt and WXPython toolkits, and
2725 2739 for the matplotlib library.
2726 2740 \layout List
2727 2741 \labelwidthstring 00.00.0000
2728 2742
2729 2743 \SpecialChar ~
2730 2744 With any of the first three options, IPython starts running a separate
2731 2745 thread for the graphical toolkit's operation, so that you can open and
2732 2746 control graphical elements from within an IPython command line, without
2733 2747 blocking.
2734 2748 All three provide essentially the same functionality, respectively for
2735 2749 GTK, QT and WXWidgets (via their Python interfaces).
2736 2750 \layout List
2737 2751 \labelwidthstring 00.00.0000
2738 2752
2739 2753 \SpecialChar ~
2740 2754 Note that with
2741 2755 \family typewriter
2742 2756 -wthread
2743 2757 \family default
2744 2758 , you can additionally use the -wxversion option to request a specific version
2745 2759 of wx to be used.
2746 2760 This requires that you have the
2747 2761 \family typewriter
2748 2762 wxversion
2749 2763 \family default
2750 2764 Python module installed, which is part of recent wxPython distributions.
2751 2765 \layout List
2752 2766 \labelwidthstring 00.00.0000
2753 2767
2754 2768 \SpecialChar ~
2755 2769 If
2756 2770 \family typewriter
2757 2771 -pylab
2758 2772 \family default
2759 2773 is given, IPython loads special support for the mat plotlib library (
2760 2774 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2761 2775
2762 2776 \end_inset
2763 2777
2764 2778 ), allowing interactive usage of any of its backends as defined in the user's
2765 2779
2766 2780 \family typewriter
2767 2781 ~/.matplotlib/matplotlibrc
2768 2782 \family default
2769 2783 file.
2770 2784 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2771 2785 of matplotlib backend requires it.
2772 2786 It also modifies the
2773 2787 \family typewriter
2774 2788 %run
2775 2789 \family default
2776 2790 command to correctly execute (without blocking) any matplotlib-based script
2777 2791 which calls
2778 2792 \family typewriter
2779 2793 show()
2780 2794 \family default
2781 2795 at the end.
2782 2796
2783 2797 \layout List
2784 2798 \labelwidthstring 00.00.0000
2785 2799
2786 2800
2787 2801 \family typewriter
2788 2802 \series bold
2789 2803 -tk
2790 2804 \family default
2791 2805 \series default
2792 2806 The
2793 2807 \family typewriter
2794 2808 -g/q/wthread
2795 2809 \family default
2796 2810 options, and
2797 2811 \family typewriter
2798 2812 -pylab
2799 2813 \family default
2800 2814 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2801 2815 Tk graphical interfaces.
2802 2816 This means that when either GTK, Qt or WX threading is active, any attempt
2803 2817 to open a Tk GUI will result in a dead window, and possibly cause the Python
2804 2818 interpreter to crash.
2805 2819 An extra option,
2806 2820 \family typewriter
2807 2821 -tk
2808 2822 \family default
2809 2823 , is available to address this issue.
2810 2824 It can
2811 2825 \emph on
2812 2826 only
2813 2827 \emph default
2814 2828 be given as a
2815 2829 \emph on
2816 2830 second
2817 2831 \emph default
2818 2832 option after any of the above (
2819 2833 \family typewriter
2820 2834 -gthread
2821 2835 \family default
2822 2836 ,
2823 2837 \family typewriter
2824 2838 -wthread
2825 2839 \family default
2826 2840 or
2827 2841 \family typewriter
2828 2842 -pylab
2829 2843 \family default
2830 2844 ).
2831 2845 \layout List
2832 2846 \labelwidthstring 00.00.0000
2833 2847
2834 2848 \SpecialChar ~
2835 2849 If
2836 2850 \family typewriter
2837 2851 -tk
2838 2852 \family default
2839 2853 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2840 2854 This is however potentially unreliable, and you will have to test on your
2841 2855 platform and Python configuration to determine whether it works for you.
2842 2856 Debian users have reported success, apparently due to the fact that Debian
2843 2857 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2844 2858 Under other Linux environments (such as Fedora Core 2/3), this option has
2845 2859 caused random crashes and lockups of the Python interpreter.
2846 2860 Under other operating systems (Mac OSX and Windows), you'll need to try
2847 2861 it to find out, since currently no user reports are available.
2848 2862 \layout List
2849 2863 \labelwidthstring 00.00.0000
2850 2864
2851 2865 \SpecialChar ~
2852 2866 There is unfortunately no way for IPython to determine at run time whether
2853 2867
2854 2868 \family typewriter
2855 2869 -tk
2856 2870 \family default
2857 2871 will work reliably or not, so you will need to do some experiments before
2858 2872 relying on it for regular work.
2859 2873
2860 2874 \layout Subsection
2861 2875
2862 2876
2863 2877 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2864 2878
2865 2879 \end_inset
2866 2880
2867 2881 Regular Options
2868 2882 \layout Standard
2869 2883
2870 2884 After the above threading options have been given, regular options can follow
2871 2885 in any order.
2872 2886 All options can be abbreviated to their shortest non-ambiguous form and
2873 2887 are case-sensitive.
2874 2888 One or two dashes can be used.
2875 2889 Some options have an alternate short form, indicated after a
2876 2890 \family typewriter
2877 2891 |
2878 2892 \family default
2879 2893 .
2880 2894 \layout Standard
2881 2895
2882 2896 Most options can also be set from your ipythonrc configuration file.
2883 2897 See the provided example for more details on what the options do.
2884 2898 Options given at the command line override the values set in the ipythonrc
2885 2899 file.
2886 2900 \layout Standard
2887 2901
2888 2902 All options with a
2889 2903 \family typewriter
2890 2904 [no]
2891 2905 \family default
2892 2906 prepended can be specified in negated form (
2893 2907 \family typewriter
2894 2908 -nooption
2895 2909 \family default
2896 2910 instead of
2897 2911 \family typewriter
2898 2912 -option
2899 2913 \family default
2900 2914 ) to turn the feature off.
2901 2915 \layout List
2902 2916 \labelwidthstring 00.00.0000
2903 2917
2904 2918
2905 2919 \family typewriter
2906 2920 \series bold
2907 2921 -help
2908 2922 \family default
2909 2923 \series default
2910 2924 : print a help message and exit.
2911 2925 \layout List
2912 2926 \labelwidthstring 00.00.0000
2913 2927
2914 2928
2915 2929 \family typewriter
2916 2930 \series bold
2917 2931 -pylab:
2918 2932 \family default
2919 2933 \series default
2920 2934 this can
2921 2935 \emph on
2922 2936 only
2923 2937 \emph default
2924 2938 be given as the
2925 2939 \emph on
2926 2940 first
2927 2941 \emph default
2928 2942 option passed to IPython (it will have no effect in any other position).
2929 2943 It adds special support for the matplotlib library (
2930 2944 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2931 2945
2932 2946 \end_inset
2933 2947
2934 2948 ), allowing interactive usage of any of its backends as defined in the user's
2935 2949
2936 2950 \family typewriter
2937 2951 .matplotlibrc
2938 2952 \family default
2939 2953 file.
2940 2954 It automatically activates GTK or WX threading for IPyhton if the choice
2941 2955 of matplotlib backend requires it.
2942 2956 It also modifies the
2943 2957 \family typewriter
2944 2958 %run
2945 2959 \family default
2946 2960 command to correctly execute (without blocking) any matplotlib-based script
2947 2961 which calls
2948 2962 \family typewriter
2949 2963 show()
2950 2964 \family default
2951 2965 at the end.
2952 2966 See Sec.\SpecialChar ~
2953 2967
2954 2968 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2955 2969
2956 2970 \end_inset
2957 2971
2958 2972 for more details.
2959 2973 \layout List
2960 2974 \labelwidthstring 00.00.0000
2961 2975
2962 2976
2963 2977 \family typewriter
2964 2978 \series bold
2965 2979 -autocall <val>:
2966 2980 \family default
2967 2981 \series default
2968 2982 Make IPython automatically call any callable object even if you didn't
2969 2983 type explicit parentheses.
2970 2984 For example, `str 43' becomes `str(43)' automatically.
2971 2985 The value can be `0' to disable the feature, `1' for
2972 2986 \emph on
2973 2987 smart
2974 2988 \emph default
2975 2989 autocall, where it is not applied if there are no more arguments on the
2976 2990 line, and `2' for
2977 2991 \emph on
2978 2992 full
2979 2993 \emph default
2980 2994 autocall, where all callable objects are automatically called (even if
2981 2995 no arguments are present).
2982 2996 The default is `1'.
2983 2997 \layout List
2984 2998 \labelwidthstring 00.00.0000
2985 2999
2986 3000
2987 3001 \family typewriter
2988 3002 \series bold
2989 3003 -[no]autoindent:
2990 3004 \family default
2991 3005 \series default
2992 3006 Turn automatic indentation on/off.
2993 3007 \layout List
2994 3008 \labelwidthstring 00.00.0000
2995 3009
2996 3010
2997 3011 \family typewriter
2998 3012 \series bold
2999 3013 -[no]automagic
3000 3014 \series default
3001 3015 :
3002 3016 \family default
3003 3017 make magic commands automatic (without needing their first character to
3004 3018 be
3005 3019 \family typewriter
3006 3020 %
3007 3021 \family default
3008 3022 ).
3009 3023 Type
3010 3024 \family typewriter
3011 3025 %magic
3012 3026 \family default
3013 3027 at the IPython prompt for more information.
3014 3028 \layout List
3015 3029 \labelwidthstring 00.00.0000
3016 3030
3017 3031
3018 3032 \family typewriter
3019 3033 \series bold
3020 3034 -[no]autoedit_syntax:
3021 3035 \family default
3022 3036 \series default
3023 3037 When a syntax error occurs after editing a file, automatically open the
3024 3038 file to the trouble causing line for convenient fixing.
3025 3039
3026 3040 \layout List
3027 3041 \labelwidthstring 00.00.0000
3028 3042
3029 3043
3030 3044 \family typewriter
3031 3045 \series bold
3032 3046 -[no]banner
3033 3047 \series default
3034 3048 :
3035 3049 \family default
3036 3050 Print the initial information banner (default on).
3037 3051 \layout List
3038 3052 \labelwidthstring 00.00.0000
3039 3053
3040 3054
3041 3055 \family typewriter
3042 3056 \series bold
3043 3057 -c\SpecialChar ~
3044 3058 <command>:
3045 3059 \family default
3046 3060 \series default
3047 3061 execute the given command string, and set sys.argv to
3048 3062 \family typewriter
3049 3063 ['c']
3050 3064 \family default
3051 3065 .
3052 3066 This is similar to the
3053 3067 \family typewriter
3054 3068 -c
3055 3069 \family default
3056 3070 option in the normal Python interpreter.
3057 3071
3058 3072 \layout List
3059 3073 \labelwidthstring 00.00.0000
3060 3074
3061 3075
3062 3076 \family typewriter
3063 3077 \series bold
3064 3078 -cache_size|cs\SpecialChar ~
3065 3079 <n>
3066 3080 \series default
3067 3081 :
3068 3082 \family default
3069 3083 size of the output cache (maximum number of entries to hold in memory).
3070 3084 The default is 1000, you can change it permanently in your config file.
3071 3085 Setting it to 0 completely disables the caching system, and the minimum
3072 3086 value accepted is 20 (if you provide a value less than 20, it is reset
3073 3087 to 0 and a warning is issued) This limit is defined because otherwise you'll
3074 3088 spend more time re-flushing a too small cache than working.
3075 3089 \layout List
3076 3090 \labelwidthstring 00.00.0000
3077 3091
3078 3092
3079 3093 \family typewriter
3080 3094 \series bold
3081 3095 -classic|cl
3082 3096 \series default
3083 3097 :
3084 3098 \family default
3085 3099 Gives IPython a similar feel to the classic Python prompt.
3086 3100 \layout List
3087 3101 \labelwidthstring 00.00.0000
3088 3102
3089 3103
3090 3104 \family typewriter
3091 3105 \series bold
3092 3106 -colors\SpecialChar ~
3093 3107 <scheme>:
3094 3108 \family default
3095 3109 \series default
3096 3110 Color scheme for prompts and exception reporting.
3097 3111 Currently implemented: NoColor, Linux and LightBG.
3098 3112 \layout List
3099 3113 \labelwidthstring 00.00.0000
3100 3114
3101 3115
3102 3116 \family typewriter
3103 3117 \series bold
3104 3118 -[no]color_info:
3105 3119 \family default
3106 3120 \series default
3107 3121 IPython can display information about objects via a set of functions, and
3108 3122 optionally can use colors for this, syntax highlighting source code and
3109 3123 various other elements.
3110 3124 However, because this information is passed through a pager (like 'less')
3111 3125 and many pagers get confused with color codes, this option is off by default.
3112 3126 You can test it and turn it on permanently in your ipythonrc file if it
3113 3127 works for you.
3114 3128 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
3115 3129 that in RedHat 7.2 doesn't.
3116 3130 \layout List
3117 3131 \labelwidthstring 00.00.0000
3118 3132
3119 3133 \SpecialChar ~
3120 3134 Test it and turn it on permanently if it works with your system.
3121 3135 The magic function
3122 3136 \family typewriter
3123 3137 %color_info
3124 3138 \family default
3125 3139 allows you to toggle this interactively for testing.
3126 3140 \layout List
3127 3141 \labelwidthstring 00.00.0000
3128 3142
3129 3143
3130 3144 \family typewriter
3131 3145 \series bold
3132 3146 -[no]debug
3133 3147 \family default
3134 3148 \series default
3135 3149 : Show information about the loading process.
3136 3150 Very useful to pin down problems with your configuration files or to get
3137 3151 details about session restores.
3138 3152 \layout List
3139 3153 \labelwidthstring 00.00.0000
3140 3154
3141 3155
3142 3156 \family typewriter
3143 3157 \series bold
3144 3158 -[no]deep_reload
3145 3159 \series default
3146 3160 :
3147 3161 \family default
3148 3162 IPython can use the
3149 3163 \family typewriter
3150 3164 deep_reload
3151 3165 \family default
3152 3166 module which reloads changes in modules recursively (it replaces the
3153 3167 \family typewriter
3154 3168 reload()
3155 3169 \family default
3156 3170 function, so you don't need to change anything to use it).
3157 3171
3158 3172 \family typewriter
3159 3173 deep_reload()
3160 3174 \family default
3161 3175 forces a full reload of modules whose code may have changed, which the
3162 3176 default
3163 3177 \family typewriter
3164 3178 reload()
3165 3179 \family default
3166 3180 function does not.
3167 3181 \layout List
3168 3182 \labelwidthstring 00.00.0000
3169 3183
3170 3184 \SpecialChar ~
3171 3185 When deep_reload is off, IPython will use the normal
3172 3186 \family typewriter
3173 3187 reload()
3174 3188 \family default
3175 3189 , but deep_reload will still be available as
3176 3190 \family typewriter
3177 3191 dreload()
3178 3192 \family default
3179 3193 .
3180 3194 This feature is off by default [which means that you have both normal
3181 3195 \family typewriter
3182 3196 reload()
3183 3197 \family default
3184 3198 and
3185 3199 \family typewriter
3186 3200 dreload()
3187 3201 \family default
3188 3202 ].
3189 3203 \layout List
3190 3204 \labelwidthstring 00.00.0000
3191 3205
3192 3206
3193 3207 \family typewriter
3194 3208 \series bold
3195 3209 -editor\SpecialChar ~
3196 3210 <name>
3197 3211 \family default
3198 3212 \series default
3199 3213 : Which editor to use with the
3200 3214 \family typewriter
3201 3215 %edit
3202 3216 \family default
3203 3217 command.
3204 3218 By default, IPython will honor your
3205 3219 \family typewriter
3206 3220 EDITOR
3207 3221 \family default
3208 3222 environment variable (if not set, vi is the Unix default and notepad the
3209 3223 Windows one).
3210 3224 Since this editor is invoked on the fly by IPython and is meant for editing
3211 3225 small code snippets, you may want to use a small, lightweight editor here
3212 3226 (in case your default
3213 3227 \family typewriter
3214 3228 EDITOR
3215 3229 \family default
3216 3230 is something like Emacs).
3217 3231 \layout List
3218 3232 \labelwidthstring 00.00.0000
3219 3233
3220 3234
3221 3235 \family typewriter
3222 3236 \series bold
3223 3237 -ipythondir\SpecialChar ~
3224 3238 <name>
3225 3239 \series default
3226 3240 :
3227 3241 \family default
3228 3242 name of your IPython configuration directory
3229 3243 \family typewriter
3230 3244 IPYTHONDIR
3231 3245 \family default
3232 3246 .
3233 3247 This can also be specified through the environment variable
3234 3248 \family typewriter
3235 3249 IPYTHONDIR
3236 3250 \family default
3237 3251 .
3238 3252 \layout List
3239 3253 \labelwidthstring 00.00.0000
3240 3254
3241 3255
3242 3256 \family typewriter
3243 3257 \series bold
3244 3258 -log|l
3245 3259 \family default
3246 3260 \series default
3247 3261 : generate a log file of all input.
3248 3262 The file is named
3249 3263 \family typewriter
3250 3264 ipython_log.py
3251 3265 \family default
3252 3266 in your current directory (which prevents logs from multiple IPython sessions
3253 3267 from trampling each other).
3254 3268 You can use this to later restore a session by loading your logfile as
3255 3269 a file to be executed with option
3256 3270 \family typewriter
3257 3271 -logplay
3258 3272 \family default
3259 3273 (see below).
3260 3274 \layout List
3261 3275 \labelwidthstring 00.00.0000
3262 3276
3263 3277
3264 3278 \family typewriter
3265 3279 \series bold
3266 3280 -logfile|lf\SpecialChar ~
3267 3281 <name>
3268 3282 \series default
3269 3283 :
3270 3284 \family default
3271 3285 specify the name of your logfile.
3272 3286 \layout List
3273 3287 \labelwidthstring 00.00.0000
3274 3288
3275 3289
3276 3290 \family typewriter
3277 3291 \series bold
3278 3292 -logplay|lp\SpecialChar ~
3279 3293 <name>
3280 3294 \series default
3281 3295 :
3282 3296 \family default
3283 3297 you can replay a previous log.
3284 3298 For restoring a session as close as possible to the state you left it in,
3285 3299 use this option (don't just run the logfile).
3286 3300 With
3287 3301 \family typewriter
3288 3302 -logplay
3289 3303 \family default
3290 3304 , IPython will try to reconstruct the previous working environment in full,
3291 3305 not just execute the commands in the logfile.
3292 3306 \layout List
3293 3307 \labelwidthstring 00.00.0000
3294 3308
3295 3309 \SpecialChar ~
3296 3310 When a session is restored, logging is automatically turned on again with
3297 3311 the name of the logfile it was invoked with (it is read from the log header).
3298 3312 So once you've turned logging on for a session, you can quit IPython and
3299 3313 reload it as many times as you want and it will continue to log its history
3300 3314 and restore from the beginning every time.
3301 3315 \layout List
3302 3316 \labelwidthstring 00.00.0000
3303 3317
3304 3318 \SpecialChar ~
3305 3319 Caveats: there are limitations in this option.
3306 3320 The history variables
3307 3321 \family typewriter
3308 3322 _i*
3309 3323 \family default
3310 3324 ,
3311 3325 \family typewriter
3312 3326 _*
3313 3327 \family default
3314 3328 and
3315 3329 \family typewriter
3316 3330 _dh
3317 3331 \family default
3318 3332 don't get restored properly.
3319 3333 In the future we will try to implement full session saving by writing and
3320 3334 retrieving a 'snapshot' of the memory state of IPython.
3321 3335 But our first attempts failed because of inherent limitations of Python's
3322 3336 Pickle module, so this may have to wait.
3323 3337 \layout List
3324 3338 \labelwidthstring 00.00.0000
3325 3339
3326 3340
3327 3341 \family typewriter
3328 3342 \series bold
3329 3343 -[no]messages
3330 3344 \series default
3331 3345 :
3332 3346 \family default
3333 3347 Print messages which IPython collects about its startup process (default
3334 3348 on).
3335 3349 \layout List
3336 3350 \labelwidthstring 00.00.0000
3337 3351
3338 3352
3339 3353 \family typewriter
3340 3354 \series bold
3341 3355 -[no]pdb
3342 3356 \family default
3343 3357 \series default
3344 3358 : Automatically call the pdb debugger after every uncaught exception.
3345 3359 If you are used to debugging using pdb, this puts you automatically inside
3346 3360 of it after any call (either in IPython or in code called by it) which
3347 3361 triggers an exception which goes uncaught.
3348 3362 \layout List
3349 3363 \labelwidthstring 00.00.0000
3350 3364
3351 3365
3352 3366 \family typewriter
3353 3367 \series bold
3354 3368 -[no]pprint
3355 3369 \series default
3356 3370 :
3357 3371 \family default
3358 3372 ipython can optionally use the pprint (pretty printer) module for displaying
3359 3373 results.
3360 3374 pprint tends to give a nicer display of nested data structures.
3361 3375 If you like it, you can turn it on permanently in your config file (default
3362 3376 off).
3363 3377 \layout List
3364 3378 \labelwidthstring 00.00.0000
3365 3379
3366 3380
3367 3381 \family typewriter
3368 3382 \series bold
3369 3383 -profile|p <name>
3370 3384 \series default
3371 3385 :
3372 3386 \family default
3373 3387 assume that your config file is
3374 3388 \family typewriter
3375 3389 ipythonrc-<name>
3376 3390 \family default
3377 3391 (looks in current dir first, then in
3378 3392 \family typewriter
3379 3393 IPYTHONDIR
3380 3394 \family default
3381 3395 ).
3382 3396 This is a quick way to keep and load multiple config files for different
3383 3397 tasks, especially if you use the include option of config files.
3384 3398 You can keep a basic
3385 3399 \family typewriter
3386 3400 IPYTHONDIR/ipythonrc
3387 3401 \family default
3388 3402 file and then have other 'profiles' which include this one and load extra
3389 3403 things for particular tasks.
3390 3404 For example:
3391 3405 \layout List
3392 3406 \labelwidthstring 00.00.0000
3393 3407
3394 3408
3395 3409 \family typewriter
3396 3410 \SpecialChar ~
3397 3411
3398 3412 \family default
3399 3413 1.
3400 3414
3401 3415 \family typewriter
3402 3416 $HOME/.ipython/ipythonrc
3403 3417 \family default
3404 3418 : load basic things you always want.
3405 3419 \layout List
3406 3420 \labelwidthstring 00.00.0000
3407 3421
3408 3422
3409 3423 \family typewriter
3410 3424 \SpecialChar ~
3411 3425
3412 3426 \family default
3413 3427 2.
3414 3428
3415 3429 \family typewriter
3416 3430 $HOME/.ipython/ipythonrc-math
3417 3431 \family default
3418 3432 : load (1) and basic math-related modules.
3419 3433
3420 3434 \layout List
3421 3435 \labelwidthstring 00.00.0000
3422 3436
3423 3437
3424 3438 \family typewriter
3425 3439 \SpecialChar ~
3426 3440
3427 3441 \family default
3428 3442 3.
3429 3443
3430 3444 \family typewriter
3431 3445 $HOME/.ipython/ipythonrc-numeric
3432 3446 \family default
3433 3447 : load (1) and Numeric and plotting modules.
3434 3448 \layout List
3435 3449 \labelwidthstring 00.00.0000
3436 3450
3437 3451 \SpecialChar ~
3438 3452 Since it is possible to create an endless loop by having circular file
3439 3453 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3440 3454 \layout List
3441 3455 \labelwidthstring 00.00.0000
3442 3456
3443 3457
3444 3458 \family typewriter
3445 3459 \series bold
3446 3460 -prompt_in1|pi1\SpecialChar ~
3447 3461 <string>:
3448 3462 \family default
3449 3463 \series default
3450 3464 Specify the string used for input prompts.
3451 3465 Note that if you are using numbered prompts, the number is represented
3452 3466 with a '
3453 3467 \backslash
3454 3468 #' in the string.
3455 3469 Don't forget to quote strings with spaces embedded in them.
3456 3470 Default: '
3457 3471 \family typewriter
3458 3472 In\SpecialChar ~
3459 3473 [
3460 3474 \backslash
3461 3475 #]:
3462 3476 \family default
3463 3477 '.
3464 3478 Sec.\SpecialChar ~
3465 3479
3466 3480 \begin_inset LatexCommand \ref{sec:prompts}
3467 3481
3468 3482 \end_inset
3469 3483
3470 3484 discusses in detail all the available escapes to customize your prompts.
3471 3485 \layout List
3472 3486 \labelwidthstring 00.00.0000
3473 3487
3474 3488
3475 3489 \family typewriter
3476 3490 \series bold
3477 3491 -prompt_in2|pi2\SpecialChar ~
3478 3492 <string>:
3479 3493 \family default
3480 3494 \series default
3481 3495 Similar to the previous option, but used for the continuation prompts.
3482 3496 The special sequence '
3483 3497 \family typewriter
3484 3498
3485 3499 \backslash
3486 3500 D
3487 3501 \family default
3488 3502 ' is similar to '
3489 3503 \family typewriter
3490 3504
3491 3505 \backslash
3492 3506 #
3493 3507 \family default
3494 3508 ', but with all digits replaced dots (so you can have your continuation
3495 3509 prompt aligned with your input prompt).
3496 3510 Default: '
3497 3511 \family typewriter
3498 3512 \SpecialChar ~
3499 3513 \SpecialChar ~
3500 3514 \SpecialChar ~
3501 3515 .
3502 3516 \backslash
3503 3517 D.:
3504 3518 \family default
3505 3519 ' (note three spaces at the start for alignment with '
3506 3520 \family typewriter
3507 3521 In\SpecialChar ~
3508 3522 [
3509 3523 \backslash
3510 3524 #]
3511 3525 \family default
3512 3526 ').
3513 3527 \layout List
3514 3528 \labelwidthstring 00.00.0000
3515 3529
3516 3530
3517 3531 \family typewriter
3518 3532 \series bold
3519 3533 -prompt_out|po\SpecialChar ~
3520 3534 <string>:
3521 3535 \family default
3522 3536 \series default
3523 3537 String used for output prompts, also uses numbers like
3524 3538 \family typewriter
3525 3539 prompt_in1
3526 3540 \family default
3527 3541 .
3528 3542 Default: '
3529 3543 \family typewriter
3530 3544 Out[
3531 3545 \backslash
3532 3546 #]:
3533 3547 \family default
3534 3548 '
3535 3549 \layout List
3536 3550 \labelwidthstring 00.00.0000
3537 3551
3538 3552
3539 3553 \family typewriter
3540 3554 \series bold
3541 3555 -quick
3542 3556 \family default
3543 3557 \series default
3544 3558 : start in bare bones mode (no config file loaded).
3545 3559 \layout List
3546 3560 \labelwidthstring 00.00.0000
3547 3561
3548 3562
3549 3563 \family typewriter
3550 3564 \series bold
3551 3565 -rcfile\SpecialChar ~
3552 3566 <name>
3553 3567 \series default
3554 3568 :
3555 3569 \family default
3556 3570 name of your IPython resource configuration file.
3557 3571 Normally IPython loads ipythonrc (from current directory) or
3558 3572 \family typewriter
3559 3573 IPYTHONDIR/ipythonrc
3560 3574 \family default
3561 3575 .
3562 3576 \layout List
3563 3577 \labelwidthstring 00.00.0000
3564 3578
3565 3579 \SpecialChar ~
3566 3580 If the loading of your config file fails, IPython starts with a bare bones
3567 3581 configuration (no modules loaded at all).
3568 3582 \layout List
3569 3583 \labelwidthstring 00.00.0000
3570 3584
3571 3585
3572 3586 \family typewriter
3573 3587 \series bold
3574 3588 -[no]readline
3575 3589 \family default
3576 3590 \series default
3577 3591 : use the readline library, which is needed to support name completion and
3578 3592 command history, among other things.
3579 3593 It is enabled by default, but may cause problems for users of X/Emacs in
3580 3594 Python comint or shell buffers.
3581 3595 \layout List
3582 3596 \labelwidthstring 00.00.0000
3583 3597
3584 3598 \SpecialChar ~
3585 3599 Note that X/Emacs 'eterm' buffers (opened with
3586 3600 \family typewriter
3587 3601 M-x\SpecialChar ~
3588 3602 term
3589 3603 \family default
3590 3604 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3591 3605 \family typewriter
3592 3606 M-x\SpecialChar ~
3593 3607 shell
3594 3608 \family default
3595 3609 and
3596 3610 \family typewriter
3597 3611 C-c\SpecialChar ~
3598 3612 !
3599 3613 \family default
3600 3614 ) buffers do not.
3601 3615 \layout List
3602 3616 \labelwidthstring 00.00.0000
3603 3617
3604 3618
3605 3619 \family typewriter
3606 3620 \series bold
3607 3621 -screen_length|sl\SpecialChar ~
3608 3622 <n>
3609 3623 \series default
3610 3624 :
3611 3625 \family default
3612 3626 number of lines of your screen.
3613 3627 This is used to control printing of very long strings.
3614 3628 Strings longer than this number of lines will be sent through a pager instead
3615 3629 of directly printed.
3616 3630 \layout List
3617 3631 \labelwidthstring 00.00.0000
3618 3632
3619 3633 \SpecialChar ~
3620 3634 The default value for this is 0, which means IPython will auto-detect your
3621 3635 screen size every time it needs to print certain potentially long strings
3622 3636 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3623 3637 internally).
3624 3638 If for some reason this isn't working well (it needs curses support), specify
3625 3639 it yourself.
3626 3640 Otherwise don't change the default.
3627 3641 \layout List
3628 3642 \labelwidthstring 00.00.0000
3629 3643
3630 3644
3631 3645 \family typewriter
3632 3646 \series bold
3633 3647 -separate_in|si\SpecialChar ~
3634 3648 <string>
3635 3649 \series default
3636 3650 :
3637 3651 \family default
3638 3652 separator before input prompts.
3639 3653 Default: '
3640 3654 \family typewriter
3641 3655
3642 3656 \backslash
3643 3657 n
3644 3658 \family default
3645 3659 '
3646 3660 \layout List
3647 3661 \labelwidthstring 00.00.0000
3648 3662
3649 3663
3650 3664 \family typewriter
3651 3665 \series bold
3652 3666 -separate_out|so\SpecialChar ~
3653 3667 <string>
3654 3668 \family default
3655 3669 \series default
3656 3670 : separator before output prompts.
3657 3671 Default: nothing.
3658 3672 \layout List
3659 3673 \labelwidthstring 00.00.0000
3660 3674
3661 3675
3662 3676 \family typewriter
3663 3677 \series bold
3664 3678 -separate_out2|so2\SpecialChar ~
3665 3679 <string>
3666 3680 \series default
3667 3681 :
3668 3682 \family default
3669 3683 separator after output prompts.
3670 3684 Default: nothing.
3671 3685 \layout List
3672 3686 \labelwidthstring 00.00.0000
3673 3687
3674 3688 \SpecialChar ~
3675 3689 For these three options, use the value 0 to specify no separator.
3676 3690 \layout List
3677 3691 \labelwidthstring 00.00.0000
3678 3692
3679 3693
3680 3694 \family typewriter
3681 3695 \series bold
3682 3696 -nosep
3683 3697 \series default
3684 3698 :
3685 3699 \family default
3686 3700 shorthand for
3687 3701 \family typewriter
3688 3702 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3689 3703 \family default
3690 3704 .
3691 3705 Simply removes all input/output separators.
3692 3706 \layout List
3693 3707 \labelwidthstring 00.00.0000
3694 3708
3695 3709
3696 3710 \family typewriter
3697 3711 \series bold
3698 3712 -upgrade
3699 3713 \family default
3700 3714 \series default
3701 3715 : allows you to upgrade your
3702 3716 \family typewriter
3703 3717 IPYTHONDIR
3704 3718 \family default
3705 3719 configuration when you install a new version of IPython.
3706 3720 Since new versions may include new command line options or example files,
3707 3721 this copies updated ipythonrc-type files.
3708 3722 However, it backs up (with a
3709 3723 \family typewriter
3710 3724 .old
3711 3725 \family default
3712 3726 extension) all files which it overwrites so that you can merge back any
3713 3727 customizations you might have in your personal files.
3714 3728 \layout List
3715 3729 \labelwidthstring 00.00.0000
3716 3730
3717 3731
3718 3732 \family typewriter
3719 3733 \series bold
3720 3734 -Version
3721 3735 \series default
3722 3736 :
3723 3737 \family default
3724 3738 print version information and exit.
3725 3739 \layout List
3726 3740 \labelwidthstring 00.00.0000
3727 3741
3728 3742
3729 3743 \family typewriter
3730 3744 \series bold
3731 3745 -wxversion\SpecialChar ~
3732 3746 <string>:
3733 3747 \family default
3734 3748 \series default
3735 3749 Select a specific version of wxPython (used in conjunction with
3736 3750 \family typewriter
3737 3751 -wthread
3738 3752 \family default
3739 3753 ).
3740 3754 Requires the wxversion module, part of recent wxPython distributions
3741 3755 \layout List
3742 3756 \labelwidthstring 00.00.0000
3743 3757
3744 3758
3745 3759 \family typewriter
3746 3760 \series bold
3747 3761 -xmode\SpecialChar ~
3748 3762 <modename>
3749 3763 \series default
3750 3764 :
3751 3765 \family default
3752 3766 Mode for exception reporting.
3753 3767 \layout List
3754 3768 \labelwidthstring 00.00.0000
3755 3769
3756 3770 \SpecialChar ~
3757 3771 Valid modes: Plain, Context and Verbose.
3758 3772 \layout List
3759 3773 \labelwidthstring 00.00.0000
3760 3774
3761 3775 \SpecialChar ~
3762 3776 Plain: similar to python's normal traceback printing.
3763 3777 \layout List
3764 3778 \labelwidthstring 00.00.0000
3765 3779
3766 3780 \SpecialChar ~
3767 3781 Context: prints 5 lines of context source code around each line in the
3768 3782 traceback.
3769 3783 \layout List
3770 3784 \labelwidthstring 00.00.0000
3771 3785
3772 3786 \SpecialChar ~
3773 3787 Verbose: similar to Context, but additionally prints the variables currently
3774 3788 visible where the exception happened (shortening their strings if too long).
3775 3789 This can potentially be very slow, if you happen to have a huge data structure
3776 3790 whose string representation is complex to compute.
3777 3791 Your computer may appear to freeze for a while with cpu usage at 100%.
3778 3792 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3779 3793 it more than once).
3780 3794 \layout Section
3781 3795
3782 3796 Interactive use
3783 3797 \layout Standard
3784 3798
3785 3799
3786 3800 \series bold
3787 3801 Warning
3788 3802 \series default
3789 3803 : IPython relies on the existence of a global variable called
3790 3804 \family typewriter
3791 3805 __IP
3792 3806 \family default
3793 3807 which controls the shell itself.
3794 3808 If you redefine
3795 3809 \family typewriter
3796 3810 __IP
3797 3811 \family default
3798 3812 to anything, bizarre behavior will quickly occur.
3799 3813 \layout Standard
3800 3814
3801 3815 Other than the above warning, IPython is meant to work as a drop-in replacement
3802 3816 for the standard interactive interpreter.
3803 3817 As such, any code which is valid python should execute normally under IPython
3804 3818 (cases where this is not true should be reported as bugs).
3805 3819 It does, however, offer many features which are not available at a standard
3806 3820 python prompt.
3807 3821 What follows is a list of these.
3808 3822 \layout Subsection
3809 3823
3810 3824 Caution for Windows users
3811 3825 \layout Standard
3812 3826
3813 3827 Windows, unfortunately, uses the `
3814 3828 \family typewriter
3815 3829
3816 3830 \backslash
3817 3831
3818 3832 \family default
3819 3833 ' character as a path separator.
3820 3834 This is a terrible choice, because `
3821 3835 \family typewriter
3822 3836
3823 3837 \backslash
3824 3838
3825 3839 \family default
3826 3840 ' also represents the escape character in most modern programming languages,
3827 3841 including Python.
3828 3842 For this reason, issuing many of the commands discussed below (especially
3829 3843 magics which affect the filesystem) with `
3830 3844 \family typewriter
3831 3845
3832 3846 \backslash
3833 3847
3834 3848 \family default
3835 3849 ' in them will cause strange errors.
3836 3850 \layout Standard
3837 3851
3838 3852 A partial solution is to use instead the `
3839 3853 \family typewriter
3840 3854 /
3841 3855 \family default
3842 3856 ' character as a path separator, which Windows recognizes in
3843 3857 \emph on
3844 3858 most
3845 3859 \emph default
3846 3860 situations.
3847 3861 However, in Windows commands `
3848 3862 \family typewriter
3849 3863 /
3850 3864 \family default
3851 3865 ' flags options, so you can not use it for the root directory.
3852 3866 This means that paths beginning at the root must be typed in a contrived
3853 3867 manner like:
3854 3868 \newline
3855 3869
3856 3870 \family typewriter
3857 3871 %copy
3858 3872 \backslash
3859 3873 opt/foo/bar.txt
3860 3874 \backslash
3861 3875 tmp
3862 3876 \layout Standard
3863 3877
3864 3878 There is no sensible thing IPython can do to truly work around this flaw
3865 3879 in Windows
3866 3880 \begin_inset Foot
3867 3881 collapsed true
3868 3882
3869 3883 \layout Standard
3870 3884
3871 3885 If anyone comes up with a
3872 3886 \emph on
3873 3887 clean
3874 3888 \emph default
3875 3889 solution which works consistently and does not negatively impact other
3876 3890 platforms at all, I'll gladly accept a patch.
3877 3891 \end_inset
3878 3892
3879 3893 .
3880 3894 \layout Subsection
3881 3895
3882 3896
3883 3897 \begin_inset LatexCommand \label{sec:magic}
3884 3898
3885 3899 \end_inset
3886 3900
3887 3901 Magic command system
3888 3902 \layout Standard
3889 3903
3890 3904 IPython will treat any line whose first character is a
3891 3905 \family typewriter
3892 3906 %
3893 3907 \family default
3894 3908 as a special call to a 'magic' function.
3895 3909 These allow you to control the behavior of IPython itself, plus a lot of
3896 3910 system-type features.
3897 3911 They are all prefixed with a
3898 3912 \family typewriter
3899 3913 %
3900 3914 \family default
3901 3915 character, but parameters are given without parentheses or quotes.
3902 3916 \layout Standard
3903 3917
3904 3918 Example: typing
3905 3919 \family typewriter
3906 3920 '%cd mydir'
3907 3921 \family default
3908 3922 (without the quotes) changes you working directory to
3909 3923 \family typewriter
3910 3924 'mydir'
3911 3925 \family default
3912 3926 , if it exists.
3913 3927 \layout Standard
3914 3928
3915 3929 If you have 'automagic' enabled (in your
3916 3930 \family typewriter
3917 3931 ipythonrc
3918 3932 \family default
3919 3933 file, via the command line option
3920 3934 \family typewriter
3921 3935 -automagic
3922 3936 \family default
3923 3937 or with the
3924 3938 \family typewriter
3925 3939 %automagic
3926 3940 \family default
3927 3941 function), you don't need to type in the
3928 3942 \family typewriter
3929 3943 %
3930 3944 \family default
3931 3945 explicitly.
3932 3946 IPython will scan its internal list of magic functions and call one if
3933 3947 it exists.
3934 3948 With automagic on you can then just type '
3935 3949 \family typewriter
3936 3950 cd mydir
3937 3951 \family default
3938 3952 ' to go to directory '
3939 3953 \family typewriter
3940 3954 mydir
3941 3955 \family default
3942 3956 '.
3943 3957 The automagic system has the lowest possible precedence in name searches,
3944 3958 so defining an identifier with the same name as an existing magic function
3945 3959 will shadow it for automagic use.
3946 3960 You can still access the shadowed magic function by explicitly using the
3947 3961
3948 3962 \family typewriter
3949 3963 %
3950 3964 \family default
3951 3965 character at the beginning of the line.
3952 3966 \layout Standard
3953 3967
3954 3968 An example (with automagic on) should clarify all this:
3955 3969 \layout LyX-Code
3956 3970
3957 3971 In [1]: cd ipython # %cd is called by automagic
3958 3972 \layout LyX-Code
3959 3973
3960 3974 /home/fperez/ipython
3961 3975 \layout LyX-Code
3962 3976
3963 3977 In [2]: cd=1 # now cd is just a variable
3964 3978 \layout LyX-Code
3965 3979
3966 3980 In [3]: cd ..
3967 3981 # and doesn't work as a function anymore
3968 3982 \layout LyX-Code
3969 3983
3970 3984 ------------------------------------------------------------
3971 3985 \layout LyX-Code
3972 3986
3973 3987 File "<console>", line 1
3974 3988 \layout LyX-Code
3975 3989
3976 3990 cd ..
3977 3991 \layout LyX-Code
3978 3992
3979 3993 ^
3980 3994 \layout LyX-Code
3981 3995
3982 3996 SyntaxError: invalid syntax
3983 3997 \layout LyX-Code
3984 3998
3985 3999 \layout LyX-Code
3986 4000
3987 4001 In [4]: %cd ..
3988 4002 # but %cd always works
3989 4003 \layout LyX-Code
3990 4004
3991 4005 /home/fperez
3992 4006 \layout LyX-Code
3993 4007
3994 4008 In [5]: del cd # if you remove the cd variable
3995 4009 \layout LyX-Code
3996 4010
3997 4011 In [6]: cd ipython # automagic can work again
3998 4012 \layout LyX-Code
3999 4013
4000 4014 /home/fperez/ipython
4001 4015 \layout Standard
4002 4016
4003 4017 You can define your own magic functions to extend the system.
4004 4018 The following is a snippet of code which shows how to do it.
4005 4019 It is provided as file
4006 4020 \family typewriter
4007 4021 example-magic.py
4008 4022 \family default
4009 4023 in the examples directory:
4010 4024 \layout Standard
4011 4025
4012 4026
4013 4027 \begin_inset ERT
4014 4028 status Open
4015 4029
4016 4030 \layout Standard
4017 4031
4018 4032 \backslash
4019 4033 codelist{examples/example-magic.py}
4020 4034 \end_inset
4021 4035
4022 4036
4023 4037 \layout Standard
4024 4038
4025 4039 You can also define your own aliased names for magic functions.
4026 4040 In your
4027 4041 \family typewriter
4028 4042 ipythonrc
4029 4043 \family default
4030 4044 file, placing a line like:
4031 4045 \layout Standard
4032 4046
4033 4047
4034 4048 \family typewriter
4035 4049 execute __IP.magic_cl = __IP.magic_clear
4036 4050 \layout Standard
4037 4051
4038 4052 will define
4039 4053 \family typewriter
4040 4054 %cl
4041 4055 \family default
4042 4056 as a new name for
4043 4057 \family typewriter
4044 4058 %clear
4045 4059 \family default
4046 4060 .
4047 4061 \layout Standard
4048 4062
4049 4063 Type
4050 4064 \family typewriter
4051 4065 %magic
4052 4066 \family default
4053 4067 for more information, including a list of all available magic functions
4054 4068 at any time and their docstrings.
4055 4069 You can also type
4056 4070 \family typewriter
4057 4071 %magic_function_name?
4058 4072 \family default
4059 4073 (see sec.
4060 4074
4061 4075 \begin_inset LatexCommand \ref{sec:dyn-object-info}
4062 4076
4063 4077 \end_inset
4064 4078
4065 4079 for information on the
4066 4080 \family typewriter
4067 4081 '?'
4068 4082 \family default
4069 4083 system) to get information about any particular magic function you are
4070 4084 interested in.
4071 4085 \layout Subsubsection
4072 4086
4073 4087 Magic commands
4074 4088 \layout Standard
4075 4089
4076 4090 The rest of this section is automatically generated for each release from
4077 4091 the docstrings in the IPython code.
4078 4092 Therefore the formatting is somewhat minimal, but this method has the advantage
4079 4093 of having information always in sync with the code.
4080 4094 \layout Standard
4081 4095
4082 4096 A list of all the magic commands available in IPython's
4083 4097 \emph on
4084 4098 default
4085 4099 \emph default
4086 4100 installation follows.
4087 4101 This is similar to what you'll see by simply typing
4088 4102 \family typewriter
4089 4103 %magic
4090 4104 \family default
4091 4105 at the prompt, but that will also give you information about magic commands
4092 4106 you may have added as part of your personal customizations.
4093 4107 \layout Standard
4094 4108
4095 4109
4096 4110 \begin_inset Include \input{magic.tex}
4097 4111 preview false
4098 4112
4099 4113 \end_inset
4100 4114
4101 4115
4102 4116 \layout Subsection
4103 4117
4104 4118 Access to the standard Python help
4105 4119 \layout Standard
4106 4120
4107 4121 As of Python 2.1, a help system is available with access to object docstrings
4108 4122 and the Python manuals.
4109 4123 Simply type
4110 4124 \family typewriter
4111 4125 'help'
4112 4126 \family default
4113 4127 (no quotes) to access it.
4114 4128 You can also type
4115 4129 \family typewriter
4116 4130 help(object)
4117 4131 \family default
4118 4132 to obtain information about a given object, and
4119 4133 \family typewriter
4120 4134 help('keyword')
4121 4135 \family default
4122 4136 for information on a keyword.
4123 4137 As noted in sec.
4124 4138
4125 4139 \begin_inset LatexCommand \ref{sec:help-access}
4126 4140
4127 4141 \end_inset
4128 4142
4129 4143 , you need to properly configure your environment variable
4130 4144 \family typewriter
4131 4145 PYTHONDOCS
4132 4146 \family default
4133 4147 for this feature to work correctly.
4134 4148 \layout Subsection
4135 4149
4136 4150
4137 4151 \begin_inset LatexCommand \label{sec:dyn-object-info}
4138 4152
4139 4153 \end_inset
4140 4154
4141 4155 Dynamic object information
4142 4156 \layout Standard
4143 4157
4144 4158 Typing
4145 4159 \family typewriter
4146 4160 ?word
4147 4161 \family default
4148 4162 or
4149 4163 \family typewriter
4150 4164 word?
4151 4165 \family default
4152 4166 prints detailed information about an object.
4153 4167 If certain strings in the object are too long (docstrings, code, etc.) they
4154 4168 get snipped in the center for brevity.
4155 4169 This system gives access variable types and values, full source code for
4156 4170 any object (if available), function prototypes and other useful information.
4157 4171 \layout Standard
4158 4172
4159 4173 Typing
4160 4174 \family typewriter
4161 4175 ??word
4162 4176 \family default
4163 4177 or
4164 4178 \family typewriter
4165 4179 word??
4166 4180 \family default
4167 4181 gives access to the full information without snipping long strings.
4168 4182 Long strings are sent to the screen through the
4169 4183 \family typewriter
4170 4184 less
4171 4185 \family default
4172 4186 pager if longer than the screen and printed otherwise.
4173 4187 On systems lacking the
4174 4188 \family typewriter
4175 4189 less
4176 4190 \family default
4177 4191 command, IPython uses a very basic internal pager.
4178 4192 \layout Standard
4179 4193
4180 4194 The following magic functions are particularly useful for gathering information
4181 4195 about your working environment.
4182 4196 You can get more details by typing
4183 4197 \family typewriter
4184 4198 %magic
4185 4199 \family default
4186 4200 or querying them individually (use
4187 4201 \family typewriter
4188 4202 %function_name?
4189 4203 \family default
4190 4204 with or without the
4191 4205 \family typewriter
4192 4206 %
4193 4207 \family default
4194 4208 ), this is just a summary:
4195 4209 \layout List
4196 4210 \labelwidthstring 00.00.0000
4197 4211
4198 4212
4199 4213 \family typewriter
4200 4214 \series bold
4201 4215 %pdoc\SpecialChar ~
4202 4216 <object>
4203 4217 \family default
4204 4218 \series default
4205 4219 : Print (or run through a pager if too long) the docstring for an object.
4206 4220 If the given object is a class, it will print both the class and the constructo
4207 4221 r docstrings.
4208 4222 \layout List
4209 4223 \labelwidthstring 00.00.0000
4210 4224
4211 4225
4212 4226 \family typewriter
4213 4227 \series bold
4214 4228 %pdef\SpecialChar ~
4215 4229 <object>
4216 4230 \family default
4217 4231 \series default
4218 4232 : Print the definition header for any callable object.
4219 4233 If the object is a class, print the constructor information.
4220 4234 \layout List
4221 4235 \labelwidthstring 00.00.0000
4222 4236
4223 4237
4224 4238 \family typewriter
4225 4239 \series bold
4226 4240 %psource\SpecialChar ~
4227 4241 <object>
4228 4242 \family default
4229 4243 \series default
4230 4244 : Print (or run through a pager if too long) the source code for an object.
4231 4245 \layout List
4232 4246 \labelwidthstring 00.00.0000
4233 4247
4234 4248
4235 4249 \family typewriter
4236 4250 \series bold
4237 4251 %pfile\SpecialChar ~
4238 4252 <object>
4239 4253 \family default
4240 4254 \series default
4241 4255 : Show the entire source file where an object was defined via a pager, opening
4242 4256 it at the line where the object definition begins.
4243 4257 \layout List
4244 4258 \labelwidthstring 00.00.0000
4245 4259
4246 4260
4247 4261 \family typewriter
4248 4262 \series bold
4249 4263 %who/%whos
4250 4264 \family default
4251 4265 \series default
4252 4266 : These functions give information about identifiers you have defined interactiv
4253 4267 ely (not things you loaded or defined in your configuration files).
4254 4268
4255 4269 \family typewriter
4256 4270 %who
4257 4271 \family default
4258 4272 just prints a list of identifiers and
4259 4273 \family typewriter
4260 4274 %whos
4261 4275 \family default
4262 4276 prints a table with some basic details about each identifier.
4263 4277 \layout Standard
4264 4278
4265 4279 Note that the dynamic object information functions (
4266 4280 \family typewriter
4267 4281 ?/??, %pdoc, %pfile, %pdef, %psource
4268 4282 \family default
4269 4283 ) give you access to documentation even on things which are not really defined
4270 4284 as separate identifiers.
4271 4285 Try for example typing
4272 4286 \family typewriter
4273 4287 {}.get?
4274 4288 \family default
4275 4289 or after doing
4276 4290 \family typewriter
4277 4291 import os
4278 4292 \family default
4279 4293 , type
4280 4294 \family typewriter
4281 4295 os.path.abspath??
4282 4296 \family default
4283 4297 .
4284 4298 \layout Subsection
4285 4299
4286 4300
4287 4301 \begin_inset LatexCommand \label{sec:readline}
4288 4302
4289 4303 \end_inset
4290 4304
4291 4305 Readline-based features
4292 4306 \layout Standard
4293 4307
4294 4308 These features require the GNU readline library, so they won't work if your
4295 4309 Python installation lacks readline support.
4296 4310 We will first describe the default behavior IPython uses, and then how
4297 4311 to change it to suit your preferences.
4298 4312 \layout Subsubsection
4299 4313
4300 4314 Command line completion
4301 4315 \layout Standard
4302 4316
4303 4317 At any time, hitting TAB will complete any available python commands or
4304 4318 variable names, and show you a list of the possible completions if there's
4305 4319 no unambiguous one.
4306 4320 It will also complete filenames in the current directory if no python names
4307 4321 match what you've typed so far.
4308 4322 \layout Subsubsection
4309 4323
4310 4324 Search command history
4311 4325 \layout Standard
4312 4326
4313 4327 IPython provides two ways for searching through previous input and thus
4314 4328 reduce the need for repetitive typing:
4315 4329 \layout Enumerate
4316 4330
4317 4331 Start typing, and then use
4318 4332 \family typewriter
4319 4333 Ctrl-p
4320 4334 \family default
4321 4335 (previous,up) and
4322 4336 \family typewriter
4323 4337 Ctrl-n
4324 4338 \family default
4325 4339 (next,down) to search through only the history items that match what you've
4326 4340 typed so far.
4327 4341 If you use
4328 4342 \family typewriter
4329 4343 Ctrl-p/Ctrl-n
4330 4344 \family default
4331 4345 at a blank prompt, they just behave like normal arrow keys.
4332 4346 \layout Enumerate
4333 4347
4334 4348 Hit
4335 4349 \family typewriter
4336 4350 Ctrl-r
4337 4351 \family default
4338 4352 : opens a search prompt.
4339 4353 Begin typing and the system searches your history for lines that contain
4340 4354 what you've typed so far, completing as much as it can.
4341 4355 \layout Subsubsection
4342 4356
4343 4357 Persistent command history across sessions
4344 4358 \layout Standard
4345 4359
4346 4360 IPython will save your input history when it leaves and reload it next time
4347 4361 you restart it.
4348 4362 By default, the history file is named
4349 4363 \family typewriter
4350 4364 $IPYTHONDIR/history
4351 4365 \family default
4352 4366 , but if you've loaded a named profile, '
4353 4367 \family typewriter
4354 4368 -PROFILE_NAME
4355 4369 \family default
4356 4370 ' is appended to the name.
4357 4371 This allows you to keep separate histories related to various tasks: commands
4358 4372 related to numerical work will not be clobbered by a system shell history,
4359 4373 for example.
4360 4374 \layout Subsubsection
4361 4375
4362 4376 Autoindent
4363 4377 \layout Standard
4364 4378
4365 4379 IPython can recognize lines ending in ':' and indent the next line, while
4366 4380 also un-indenting automatically after 'raise' or 'return'.
4367 4381
4368 4382 \layout Standard
4369 4383
4370 4384 This feature uses the readline library, so it will honor your
4371 4385 \family typewriter
4372 4386 ~/.inputrc
4373 4387 \family default
4374 4388 configuration (or whatever file your
4375 4389 \family typewriter
4376 4390 INPUTRC
4377 4391 \family default
4378 4392 variable points to).
4379 4393 Adding the following lines to your
4380 4394 \family typewriter
4381 4395 .inputrc
4382 4396 \family default
4383 4397 file can make indenting/unindenting more convenient (
4384 4398 \family typewriter
4385 4399 M-i
4386 4400 \family default
4387 4401 indents,
4388 4402 \family typewriter
4389 4403 M-u
4390 4404 \family default
4391 4405 unindents):
4392 4406 \layout Standard
4393 4407
4394 4408
4395 4409 \family typewriter
4396 4410 $if Python
4397 4411 \newline
4398 4412 "
4399 4413 \backslash
4400 4414 M-i": "\SpecialChar ~
4401 4415 \SpecialChar ~
4402 4416 \SpecialChar ~
4403 4417 \SpecialChar ~
4404 4418 "
4405 4419 \newline
4406 4420 "
4407 4421 \backslash
4408 4422 M-u": "
4409 4423 \backslash
4410 4424 d
4411 4425 \backslash
4412 4426 d
4413 4427 \backslash
4414 4428 d
4415 4429 \backslash
4416 4430 d"
4417 4431 \newline
4418 4432 $endif
4419 4433 \layout Standard
4420 4434
4421 4435 Note that there are 4 spaces between the quote marks after
4422 4436 \family typewriter
4423 4437 "M-i"
4424 4438 \family default
4425 4439 above.
4426 4440 \layout Standard
4427 4441
4428 4442
4429 4443 \series bold
4430 4444 Warning:
4431 4445 \series default
4432 4446 this feature is ON by default, but it can cause problems with the pasting
4433 4447 of multi-line indented code (the pasted code gets re-indented on each line).
4434 4448 A magic function
4435 4449 \family typewriter
4436 4450 %autoindent
4437 4451 \family default
4438 4452 allows you to toggle it on/off at runtime.
4439 4453 You can also disable it permanently on in your
4440 4454 \family typewriter
4441 4455 ipythonrc
4442 4456 \family default
4443 4457 file (set
4444 4458 \family typewriter
4445 4459 autoindent 0
4446 4460 \family default
4447 4461 ).
4448 4462 \layout Subsubsection
4449 4463
4450 4464 Customizing readline behavior
4451 4465 \layout Standard
4452 4466
4453 4467 All these features are based on the GNU readline library, which has an extremely
4454 4468 customizable interface.
4455 4469 Normally, readline is configured via a file which defines the behavior
4456 4470 of the library; the details of the syntax for this can be found in the
4457 4471 readline documentation available with your system or on the Internet.
4458 4472 IPython doesn't read this file (if it exists) directly, but it does support
4459 4473 passing to readline valid options via a simple interface.
4460 4474 In brief, you can customize readline by setting the following options in
4461 4475 your
4462 4476 \family typewriter
4463 4477 ipythonrc
4464 4478 \family default
4465 4479 configuration file (note that these options can
4466 4480 \emph on
4467 4481 not
4468 4482 \emph default
4469 4483 be specified at the command line):
4470 4484 \layout List
4471 4485 \labelwidthstring 00.00.0000
4472 4486
4473 4487
4474 4488 \family typewriter
4475 4489 \series bold
4476 4490 readline_parse_and_bind:
4477 4491 \family default
4478 4492 \series default
4479 4493 this option can appear as many times as you want, each time defining a
4480 4494 string to be executed via a
4481 4495 \family typewriter
4482 4496 readline.parse_and_bind()
4483 4497 \family default
4484 4498 command.
4485 4499 The syntax for valid commands of this kind can be found by reading the
4486 4500 documentation for the GNU readline library, as these commands are of the
4487 4501 kind which readline accepts in its configuration file.
4488 4502 \layout List
4489 4503 \labelwidthstring 00.00.0000
4490 4504
4491 4505
4492 4506 \family typewriter
4493 4507 \series bold
4494 4508 readline_remove_delims:
4495 4509 \family default
4496 4510 \series default
4497 4511 a string of characters to be removed from the default word-delimiters list
4498 4512 used by readline, so that completions may be performed on strings which
4499 4513 contain them.
4500 4514 Do not change the default value unless you know what you're doing.
4501 4515 \layout List
4502 4516 \labelwidthstring 00.00.0000
4503 4517
4504 4518
4505 4519 \family typewriter
4506 4520 \series bold
4507 4521 readline_omit__names
4508 4522 \family default
4509 4523 \series default
4510 4524 : when tab-completion is enabled, hitting
4511 4525 \family typewriter
4512 4526 <tab>
4513 4527 \family default
4514 4528 after a '
4515 4529 \family typewriter
4516 4530 .
4517 4531 \family default
4518 4532 ' in a name will complete all attributes of an object, including all the
4519 4533 special methods whose names include double underscores (like
4520 4534 \family typewriter
4521 4535 __getitem__
4522 4536 \family default
4523 4537 or
4524 4538 \family typewriter
4525 4539 __class__
4526 4540 \family default
4527 4541 ).
4528 4542 If you'd rather not see these names by default, you can set this option
4529 4543 to 1.
4530 4544 Note that even when this option is set, you can still see those names by
4531 4545 explicitly typing a
4532 4546 \family typewriter
4533 4547 _
4534 4548 \family default
4535 4549 after the period and hitting
4536 4550 \family typewriter
4537 4551 <tab>
4538 4552 \family default
4539 4553 : '
4540 4554 \family typewriter
4541 4555 name._<tab>
4542 4556 \family default
4543 4557 ' will always complete attribute names starting with '
4544 4558 \family typewriter
4545 4559 _
4546 4560 \family default
4547 4561 '.
4548 4562 \layout List
4549 4563 \labelwidthstring 00.00.0000
4550 4564
4551 4565 \SpecialChar ~
4552 4566 This option is off by default so that new users see all attributes of any
4553 4567 objects they are dealing with.
4554 4568 \layout Standard
4555 4569
4556 4570 You will find the default values along with a corresponding detailed explanation
4557 4571 in your
4558 4572 \family typewriter
4559 4573 ipythonrc
4560 4574 \family default
4561 4575 file.
4562 4576 \layout Subsection
4563 4577
4564 4578 Session logging and restoring
4565 4579 \layout Standard
4566 4580
4567 4581 You can log all input from a session either by starting IPython with the
4568 4582 command line switches
4569 4583 \family typewriter
4570 4584 -log
4571 4585 \family default
4572 4586 or
4573 4587 \family typewriter
4574 4588 -logfile
4575 4589 \family default
4576 4590 (see sec.
4577 4591
4578 4592 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4579 4593
4580 4594 \end_inset
4581 4595
4582 4596 )or by activating the logging at any moment with the magic function
4583 4597 \family typewriter
4584 4598 %logstart
4585 4599 \family default
4586 4600 .
4587 4601
4588 4602 \layout Standard
4589 4603
4590 4604 Log files can later be reloaded with the
4591 4605 \family typewriter
4592 4606 -logplay
4593 4607 \family default
4594 4608 option and IPython will attempt to 'replay' the log by executing all the
4595 4609 lines in it, thus restoring the state of a previous session.
4596 4610 This feature is not quite perfect, but can still be useful in many cases.
4597 4611 \layout Standard
4598 4612
4599 4613 The log files can also be used as a way to have a permanent record of any
4600 4614 code you wrote while experimenting.
4601 4615 Log files are regular text files which you can later open in your favorite
4602 4616 text editor to extract code or to 'clean them up' before using them to
4603 4617 replay a session.
4604 4618 \layout Standard
4605 4619
4606 4620 The
4607 4621 \family typewriter
4608 4622 %logstart
4609 4623 \family default
4610 4624 function for activating logging in mid-session is used as follows:
4611 4625 \layout Standard
4612 4626
4613 4627
4614 4628 \family typewriter
4615 4629 %logstart [log_name [log_mode]]
4616 4630 \layout Standard
4617 4631
4618 4632 If no name is given, it defaults to a file named
4619 4633 \family typewriter
4620 4634 'log'
4621 4635 \family default
4622 4636 in your IPYTHONDIR directory, in
4623 4637 \family typewriter
4624 4638 'rotate'
4625 4639 \family default
4626 4640 mode (see below).
4627 4641 \layout Standard
4628 4642
4629 4643 '
4630 4644 \family typewriter
4631 4645 %logstart name
4632 4646 \family default
4633 4647 ' saves to file
4634 4648 \family typewriter
4635 4649 'name'
4636 4650 \family default
4637 4651 in
4638 4652 \family typewriter
4639 4653 'backup'
4640 4654 \family default
4641 4655 mode.
4642 4656 It saves your history up to that point and then continues logging.
4643 4657 \layout Standard
4644 4658
4645 4659
4646 4660 \family typewriter
4647 4661 %logstart
4648 4662 \family default
4649 4663 takes a second optional parameter: logging mode.
4650 4664 This can be one of (note that the modes are given unquoted):
4651 4665 \layout List
4652 4666 \labelwidthstring 00.00.0000
4653 4667
4654 4668
4655 4669 \family typewriter
4656 4670 over
4657 4671 \family default
4658 4672 : overwrite existing
4659 4673 \family typewriter
4660 4674 log_name
4661 4675 \family default
4662 4676 .
4663 4677 \layout List
4664 4678 \labelwidthstring 00.00.0000
4665 4679
4666 4680
4667 4681 \family typewriter
4668 4682 backup
4669 4683 \family default
4670 4684 : rename (if exists) to
4671 4685 \family typewriter
4672 4686 log_name~
4673 4687 \family default
4674 4688 and start
4675 4689 \family typewriter
4676 4690 log_name
4677 4691 \family default
4678 4692 .
4679 4693 \layout List
4680 4694 \labelwidthstring 00.00.0000
4681 4695
4682 4696
4683 4697 \family typewriter
4684 4698 append
4685 4699 \family default
4686 4700 : well, that says it.
4687 4701 \layout List
4688 4702 \labelwidthstring 00.00.0000
4689 4703
4690 4704
4691 4705 \family typewriter
4692 4706 rotate
4693 4707 \family default
4694 4708 : create rotating logs
4695 4709 \family typewriter
4696 4710 log_name
4697 4711 \family default
4698 4712 .
4699 4713 \family typewriter
4700 4714 1~
4701 4715 \family default
4702 4716 ,
4703 4717 \family typewriter
4704 4718 log_name.2~
4705 4719 \family default
4706 4720 , etc.
4707 4721 \layout Standard
4708 4722
4709 4723 The
4710 4724 \family typewriter
4711 4725 %logoff
4712 4726 \family default
4713 4727 and
4714 4728 \family typewriter
4715 4729 %logon
4716 4730 \family default
4717 4731 functions allow you to temporarily stop and resume logging to a file which
4718 4732 had previously been started with
4719 4733 \family typewriter
4720 4734 %logstart
4721 4735 \family default
4722 4736 .
4723 4737 They will fail (with an explanation) if you try to use them before logging
4724 4738 has been started.
4725 4739 \layout Subsection
4726 4740
4727 4741
4728 4742 \begin_inset LatexCommand \label{sub:System-shell-access}
4729 4743
4730 4744 \end_inset
4731 4745
4732 4746 System shell access
4733 4747 \layout Standard
4734 4748
4735 4749 Any input line beginning with a
4736 4750 \family typewriter
4737 4751 !
4738 4752 \family default
4739 4753 character is passed verbatim (minus the
4740 4754 \family typewriter
4741 4755 !
4742 4756 \family default
4743 4757 , of course) to the underlying operating system.
4744 4758 For example, typing
4745 4759 \family typewriter
4746 4760 !ls
4747 4761 \family default
4748 4762 will run
4749 4763 \family typewriter
4750 4764 'ls'
4751 4765 \family default
4752 4766 in the current directory.
4753 4767 \layout Subsubsection
4754 4768
4755 4769 Manual capture of command output
4756 4770 \layout Standard
4757 4771
4758 4772 If the input line begins with
4759 4773 \emph on
4760 4774 two
4761 4775 \emph default
4762 4776 exclamation marks,
4763 4777 \family typewriter
4764 4778 !!
4765 4779 \family default
4766 4780 , the command is executed but its output is captured and returned as a python
4767 4781 list, split on newlines.
4768 4782 Any output sent by the subprocess to standard error is printed separately,
4769 4783 so that the resulting list only captures standard output.
4770 4784 The
4771 4785 \family typewriter
4772 4786 !!
4773 4787 \family default
4774 4788 syntax is a shorthand for the
4775 4789 \family typewriter
4776 4790 %sx
4777 4791 \family default
4778 4792 magic command.
4779 4793 \layout Standard
4780 4794
4781 4795 Finally, the
4782 4796 \family typewriter
4783 4797 %sc
4784 4798 \family default
4785 4799 magic (short for `shell capture') is similar to
4786 4800 \family typewriter
4787 4801 %sx
4788 4802 \family default
4789 4803 , but allowing more fine-grained control of the capture details, and storing
4790 4804 the result directly into a named variable.
4791 4805 \layout Standard
4792 4806
4793 4807 See Sec.\SpecialChar ~
4794 4808
4795 4809 \begin_inset LatexCommand \ref{sec:magic}
4796 4810
4797 4811 \end_inset
4798 4812
4799 4813 for details on the magics
4800 4814 \family typewriter
4801 4815 %sc
4802 4816 \family default
4803 4817 and
4804 4818 \family typewriter
4805 4819 %sx
4806 4820 \family default
4807 4821 , or use IPython's own help (
4808 4822 \family typewriter
4809 4823 sc?
4810 4824 \family default
4811 4825 and
4812 4826 \family typewriter
4813 4827 sx?
4814 4828 \family default
4815 4829 ) for further details.
4816 4830 \layout Standard
4817 4831
4818 4832 IPython also allows you to expand the value of python variables when making
4819 4833 system calls.
4820 4834 Any python variable or expression which you prepend with
4821 4835 \family typewriter
4822 4836 $
4823 4837 \family default
4824 4838 will get expanded before the system call is made.
4825 4839
4826 4840 \layout Standard
4827 4841
4828 4842
4829 4843 \family typewriter
4830 4844 In [1]: pyvar='Hello world'
4831 4845 \newline
4832 4846 In [2]: !echo "A python variable: $pyvar"
4833 4847 \newline
4834 4848 A python variable: Hello world
4835 4849 \layout Standard
4836 4850
4837 4851 If you want the shell to actually see a literal
4838 4852 \family typewriter
4839 4853 $
4840 4854 \family default
4841 4855 , you need to type it twice:
4842 4856 \layout Standard
4843 4857
4844 4858
4845 4859 \family typewriter
4846 4860 In [3]: !echo "A system variable: $$HOME"
4847 4861 \newline
4848 4862 A system variable: /home/fperez
4849 4863 \layout Standard
4850 4864
4851 4865 You can pass arbitrary expressions, though you'll need to delimit them with
4852 4866
4853 4867 \family typewriter
4854 4868 {}
4855 4869 \family default
4856 4870 if there is ambiguity as to the extent of the expression:
4857 4871 \layout Standard
4858 4872
4859 4873
4860 4874 \family typewriter
4861 4875 In [5]: x=10
4862 4876 \newline
4863 4877 In [6]: y=20
4864 4878 \newline
4865 4879 In [13]: !echo $x+y
4866 4880 \newline
4867 4881 10+y
4868 4882 \newline
4869 4883 In [7]: !echo ${x+y}
4870 4884 \newline
4871 4885 30
4872 4886 \layout Standard
4873 4887
4874 4888 Even object attributes can be expanded:
4875 4889 \layout Standard
4876 4890
4877 4891
4878 4892 \family typewriter
4879 4893 In [12]: !echo $sys.argv
4880 4894 \newline
4881 4895 [/home/fperez/usr/bin/ipython]
4882 4896 \layout Subsection
4883 4897
4884 4898 System command aliases
4885 4899 \layout Standard
4886 4900
4887 4901 The
4888 4902 \family typewriter
4889 4903 %alias
4890 4904 \family default
4891 4905 magic function and the
4892 4906 \family typewriter
4893 4907 alias
4894 4908 \family default
4895 4909 option in the
4896 4910 \family typewriter
4897 4911 ipythonrc
4898 4912 \family default
4899 4913 configuration file allow you to define magic functions which are in fact
4900 4914 system shell commands.
4901 4915 These aliases can have parameters.
4902 4916
4903 4917 \layout Standard
4904 4918
4905 4919 '
4906 4920 \family typewriter
4907 4921 %alias alias_name cmd
4908 4922 \family default
4909 4923 ' defines '
4910 4924 \family typewriter
4911 4925 alias_name
4912 4926 \family default
4913 4927 ' as an alias for '
4914 4928 \family typewriter
4915 4929 cmd
4916 4930 \family default
4917 4931 '
4918 4932 \layout Standard
4919 4933
4920 4934 Then, typing '
4921 4935 \family typewriter
4922 4936 %alias_name params
4923 4937 \family default
4924 4938 ' will execute the system command '
4925 4939 \family typewriter
4926 4940 cmd params
4927 4941 \family default
4928 4942 ' (from your underlying operating system).
4929 4943
4930 4944 \layout Standard
4931 4945
4932 4946 You can also define aliases with parameters using
4933 4947 \family typewriter
4934 4948 %s
4935 4949 \family default
4936 4950 specifiers (one per parameter).
4937 4951 The following example defines the
4938 4952 \family typewriter
4939 4953 %parts
4940 4954 \family default
4941 4955 function as an alias to the command '
4942 4956 \family typewriter
4943 4957 echo first %s second %s
4944 4958 \family default
4945 4959 ' where each
4946 4960 \family typewriter
4947 4961 %s
4948 4962 \family default
4949 4963 will be replaced by a positional parameter to the call to
4950 4964 \family typewriter
4951 4965 %parts:
4952 4966 \layout Standard
4953 4967
4954 4968
4955 4969 \family typewriter
4956 4970 In [1]: alias parts echo first %s second %s
4957 4971 \newline
4958 4972 In [2]: %parts A B
4959 4973 \newline
4960 4974 first A second B
4961 4975 \newline
4962 4976 In [3]: %parts A
4963 4977 \newline
4964 4978 Incorrect number of arguments: 2 expected.
4965 4979
4966 4980 \newline
4967 4981 parts is an alias to: 'echo first %s second %s'
4968 4982 \layout Standard
4969 4983
4970 4984 If called with no parameters,
4971 4985 \family typewriter
4972 4986 %alias
4973 4987 \family default
4974 4988 prints the table of currently defined aliases.
4975 4989 \layout Standard
4976 4990
4977 4991 The
4978 4992 \family typewriter
4979 4993 %rehash/rehashx
4980 4994 \family default
4981 4995 magics allow you to load your entire
4982 4996 \family typewriter
4983 4997 $PATH
4984 4998 \family default
4985 4999 as ipython aliases.
4986 5000 See their respective docstrings (or sec.\SpecialChar ~
4987 5001
4988 5002 \begin_inset LatexCommand \ref{sec:magic}
4989 5003
4990 5004 \end_inset
4991 5005
4992 5006 for further details).
4993 5007 \layout Subsection
4994 5008
4995 5009
4996 5010 \begin_inset LatexCommand \label{sec:dreload}
4997 5011
4998 5012 \end_inset
4999 5013
5000 5014 Recursive reload
5001 5015 \layout Standard
5002 5016
5003 5017 The
5004 5018 \family typewriter
5005 5019 %dreload
5006 5020 \family default
5007 5021 command does a recursive reload of a module: changes made to the module
5008 5022 since you imported will actually be available without having to exit.
5009 5023 \layout Subsection
5010 5024
5011 5025 Verbose and colored exception traceback printouts
5012 5026 \layout Standard
5013 5027
5014 5028 IPython provides the option to see very detailed exception tracebacks, which
5015 5029 can be especially useful when debugging large programs.
5016 5030 You can run any Python file with the
5017 5031 \family typewriter
5018 5032 %run
5019 5033 \family default
5020 5034 function to benefit from these detailed tracebacks.
5021 5035 Furthermore, both normal and verbose tracebacks can be colored (if your
5022 5036 terminal supports it) which makes them much easier to parse visually.
5023 5037 \layout Standard
5024 5038
5025 5039 See the magic
5026 5040 \family typewriter
5027 5041 xmode
5028 5042 \family default
5029 5043 and
5030 5044 \family typewriter
5031 5045 colors
5032 5046 \family default
5033 5047 functions for details (just type
5034 5048 \family typewriter
5035 5049 %magic
5036 5050 \family default
5037 5051 ).
5038 5052 \layout Standard
5039 5053
5040 5054 These features are basically a terminal version of Ka-Ping Yee's
5041 5055 \family typewriter
5042 5056 cgitb
5043 5057 \family default
5044 5058 module, now part of the standard Python library.
5045 5059 \layout Subsection
5046 5060
5047 5061
5048 5062 \begin_inset LatexCommand \label{sec:cache_input}
5049 5063
5050 5064 \end_inset
5051 5065
5052 5066 Input caching system
5053 5067 \layout Standard
5054 5068
5055 5069 IPython offers numbered prompts (In/Out) with input and output caching.
5056 5070 All input is saved and can be retrieved as variables (besides the usual
5057 5071 arrow key recall).
5058 5072 \layout Standard
5059 5073
5060 5074 The following GLOBAL variables always exist (so don't overwrite them!):
5061 5075
5062 5076 \family typewriter
5063 5077 _i
5064 5078 \family default
5065 5079 : stores previous input.
5066 5080
5067 5081 \family typewriter
5068 5082 _ii
5069 5083 \family default
5070 5084 : next previous.
5071 5085
5072 5086 \family typewriter
5073 5087 _iii
5074 5088 \family default
5075 5089 : next-next previous.
5076 5090
5077 5091 \family typewriter
5078 5092 _ih
5079 5093 \family default
5080 5094 : a list of all input
5081 5095 \family typewriter
5082 5096 _ih[n]
5083 5097 \family default
5084 5098 is the input from line
5085 5099 \family typewriter
5086 5100 n
5087 5101 \family default
5088 5102 and this list is aliased to the global variable
5089 5103 \family typewriter
5090 5104 In
5091 5105 \family default
5092 5106 .
5093 5107 If you overwrite
5094 5108 \family typewriter
5095 5109 In
5096 5110 \family default
5097 5111 with a variable of your own, you can remake the assignment to the internal
5098 5112 list with a simple
5099 5113 \family typewriter
5100 5114 'In=_ih'
5101 5115 \family default
5102 5116 .
5103 5117 \layout Standard
5104 5118
5105 5119 Additionally, global variables named
5106 5120 \family typewriter
5107 5121 _i<n>
5108 5122 \family default
5109 5123 are dynamically created (
5110 5124 \family typewriter
5111 5125 <n>
5112 5126 \family default
5113 5127 being the prompt counter), such that
5114 5128 \newline
5115 5129
5116 5130 \family typewriter
5117 5131 _i<n> == _ih[<n>] == In[<n>].
5118 5132 \layout Standard
5119 5133
5120 5134 For example, what you typed at prompt 14 is available as
5121 5135 \family typewriter
5122 5136 _i14,
5123 5137 \family default
5124 5138
5125 5139 \family typewriter
5126 5140 _ih[14]
5127 5141 \family default
5128 5142 and
5129 5143 \family typewriter
5130 5144 In[14]
5131 5145 \family default
5132 5146 .
5133 5147 \layout Standard
5134 5148
5135 5149 This allows you to easily cut and paste multi line interactive prompts by
5136 5150 printing them out: they print like a clean string, without prompt characters.
5137 5151 You can also manipulate them like regular variables (they are strings),
5138 5152 modify or exec them (typing
5139 5153 \family typewriter
5140 5154 'exec _i9'
5141 5155 \family default
5142 5156 will re-execute the contents of input prompt 9, '
5143 5157 \family typewriter
5144 5158 exec In[9:14]+In[18]
5145 5159 \family default
5146 5160 ' will re-execute lines 9 through 13 and line 18).
5147 5161 \layout Standard
5148 5162
5149 5163 You can also re-execute multiple lines of input easily by using the magic
5150 5164
5151 5165 \family typewriter
5152 5166 %macro
5153 5167 \family default
5154 5168 function (which automates the process and allows re-execution without having
5155 5169 to type '
5156 5170 \family typewriter
5157 5171 exec
5158 5172 \family default
5159 5173 ' every time).
5160 5174 The macro system also allows you to re-execute previous lines which include
5161 5175 magic function calls (which require special processing).
5162 5176 Type
5163 5177 \family typewriter
5164 5178 %macro?
5165 5179 \family default
5166 5180 or see sec.
5167 5181
5168 5182 \begin_inset LatexCommand \ref{sec:magic}
5169 5183
5170 5184 \end_inset
5171 5185
5172 5186 for more details on the macro system.
5173 5187 \layout Standard
5174 5188
5175 5189 A history function
5176 5190 \family typewriter
5177 5191 %hist
5178 5192 \family default
5179 5193 allows you to see any part of your input history by printing a range of
5180 5194 the
5181 5195 \family typewriter
5182 5196 _i
5183 5197 \family default
5184 5198 variables.
5185 5199 \layout Subsection
5186 5200
5187 5201
5188 5202 \begin_inset LatexCommand \label{sec:cache_output}
5189 5203
5190 5204 \end_inset
5191 5205
5192 5206 Output caching system
5193 5207 \layout Standard
5194 5208
5195 5209 For output that is returned from actions, a system similar to the input
5196 5210 cache exists but using
5197 5211 \family typewriter
5198 5212 _
5199 5213 \family default
5200 5214 instead of
5201 5215 \family typewriter
5202 5216 _i
5203 5217 \family default
5204 5218 .
5205 5219 Only actions that produce a result (NOT assignments, for example) are cached.
5206 5220 If you are familiar with Mathematica, IPython's
5207 5221 \family typewriter
5208 5222 _
5209 5223 \family default
5210 5224 variables behave exactly like Mathematica's
5211 5225 \family typewriter
5212 5226 %
5213 5227 \family default
5214 5228 variables.
5215 5229 \layout Standard
5216 5230
5217 5231 The following GLOBAL variables always exist (so don't overwrite them!):
5218 5232
5219 5233 \layout List
5220 5234 \labelwidthstring 00.00.0000
5221 5235
5222 5236
5223 5237 \family typewriter
5224 5238 \series bold
5225 5239 _
5226 5240 \family default
5227 5241 \series default
5228 5242 (a
5229 5243 \emph on
5230 5244 single
5231 5245 \emph default
5232 5246 underscore) : stores previous output, like Python's default interpreter.
5233 5247 \layout List
5234 5248 \labelwidthstring 00.00.0000
5235 5249
5236 5250
5237 5251 \family typewriter
5238 5252 \series bold
5239 5253 __
5240 5254 \family default
5241 5255 \series default
5242 5256 (two underscores): next previous.
5243 5257 \layout List
5244 5258 \labelwidthstring 00.00.0000
5245 5259
5246 5260
5247 5261 \family typewriter
5248 5262 \series bold
5249 5263 ___
5250 5264 \family default
5251 5265 \series default
5252 5266 (three underscores): next-next previous.
5253 5267 \layout Standard
5254 5268
5255 5269 Additionally, global variables named
5256 5270 \family typewriter
5257 5271 _<n>
5258 5272 \family default
5259 5273 are dynamically created (
5260 5274 \family typewriter
5261 5275 <n>
5262 5276 \family default
5263 5277 being the prompt counter), such that the result of output
5264 5278 \family typewriter
5265 5279 <n>
5266 5280 \family default
5267 5281 is always available as
5268 5282 \family typewriter
5269 5283 _<n>
5270 5284 \family default
5271 5285 (don't use the angle brackets, just the number, e.g.
5272 5286
5273 5287 \family typewriter
5274 5288 _21
5275 5289 \family default
5276 5290 ).
5277 5291 \layout Standard
5278 5292
5279 5293 These global variables are all stored in a global dictionary (not a list,
5280 5294 since it only has entries for lines which returned a result) available
5281 5295 under the names
5282 5296 \family typewriter
5283 5297 _oh
5284 5298 \family default
5285 5299 and
5286 5300 \family typewriter
5287 5301 Out
5288 5302 \family default
5289 5303 (similar to
5290 5304 \family typewriter
5291 5305 _ih
5292 5306 \family default
5293 5307 and
5294 5308 \family typewriter
5295 5309 In
5296 5310 \family default
5297 5311 ).
5298 5312 So the output from line 12 can be obtained as
5299 5313 \family typewriter
5300 5314 _12
5301 5315 \family default
5302 5316 ,
5303 5317 \family typewriter
5304 5318 Out[12]
5305 5319 \family default
5306 5320 or
5307 5321 \family typewriter
5308 5322 _oh[12]
5309 5323 \family default
5310 5324 .
5311 5325 If you accidentally overwrite the
5312 5326 \family typewriter
5313 5327 Out
5314 5328 \family default
5315 5329 variable you can recover it by typing
5316 5330 \family typewriter
5317 5331 'Out=_oh
5318 5332 \family default
5319 5333 ' at the prompt.
5320 5334 \layout Standard
5321 5335
5322 5336 This system obviously can potentially put heavy memory demands on your system,
5323 5337 since it prevents Python's garbage collector from removing any previously
5324 5338 computed results.
5325 5339 You can control how many results are kept in memory with the option (at
5326 5340 the command line or in your
5327 5341 \family typewriter
5328 5342 ipythonrc
5329 5343 \family default
5330 5344 file)
5331 5345 \family typewriter
5332 5346 cache_size
5333 5347 \family default
5334 5348 .
5335 5349 If you set it to 0, the whole system is completely disabled and the prompts
5336 5350 revert to the classic
5337 5351 \family typewriter
5338 5352 '>>>'
5339 5353 \family default
5340 5354 of normal Python.
5341 5355 \layout Subsection
5342 5356
5343 5357 Directory history
5344 5358 \layout Standard
5345 5359
5346 5360 Your history of visited directories is kept in the global list
5347 5361 \family typewriter
5348 5362 _dh
5349 5363 \family default
5350 5364 , and the magic
5351 5365 \family typewriter
5352 5366 %cd
5353 5367 \family default
5354 5368 command can be used to go to any entry in that list.
5355 5369 The
5356 5370 \family typewriter
5357 5371 %dhist
5358 5372 \family default
5359 5373 command allows you to view this history.
5360 5374 \layout Subsection
5361 5375
5362 5376 Automatic parentheses and quotes
5363 5377 \layout Standard
5364 5378
5365 5379 These features were adapted from Nathan Gray's LazyPython.
5366 5380 They are meant to allow less typing for common situations.
5367 5381 \layout Subsubsection
5368 5382
5369 5383 Automatic parentheses
5370 5384 \layout Standard
5371 5385
5372 5386 Callable objects (i.e.
5373 5387 functions, methods, etc) can be invoked like this (notice the commas between
5374 5388 the arguments):
5375 5389 \layout Standard
5376 5390
5377 5391
5378 5392 \family typewriter
5379 5393 >>> callable_ob arg1, arg2, arg3
5380 5394 \layout Standard
5381 5395
5382 5396 and the input will be translated to this:
5383 5397 \layout Standard
5384 5398
5385 5399
5386 5400 \family typewriter
5387 5401 --> callable_ob(arg1, arg2, arg3)
5388 5402 \layout Standard
5389 5403
5390 5404 You can force automatic parentheses by using '/' as the first character
5391 5405 of a line.
5392 5406 For example:
5393 5407 \layout Standard
5394 5408
5395 5409
5396 5410 \family typewriter
5397 5411 >>> /globals # becomes 'globals()'
5398 5412 \layout Standard
5399 5413
5400 5414 Note that the '/' MUST be the first character on the line! This won't work:
5401 5415
5402 5416 \layout Standard
5403 5417
5404 5418
5405 5419 \family typewriter
5406 5420 >>> print /globals # syntax error
5407 5421 \layout Standard
5408 5422
5409 5423 In most cases the automatic algorithm should work, so you should rarely
5410 5424 need to explicitly invoke /.
5411 5425 One notable exception is if you are trying to call a function with a list
5412 5426 of tuples as arguments (the parenthesis will confuse IPython):
5413 5427 \layout Standard
5414 5428
5415 5429
5416 5430 \family typewriter
5417 5431 In [1]: zip (1,2,3),(4,5,6) # won't work
5418 5432 \layout Standard
5419 5433
5420 5434 but this will work:
5421 5435 \layout Standard
5422 5436
5423 5437
5424 5438 \family typewriter
5425 5439 In [2]: /zip (1,2,3),(4,5,6)
5426 5440 \newline
5427 5441 ------> zip ((1,2,3),(4,5,6))
5428 5442 \newline
5429 5443 Out[2]= [(1, 4), (2, 5), (3, 6)]
5430 5444 \layout Standard
5431 5445
5432 5446 IPython tells you that it has altered your command line by displaying the
5433 5447 new command line preceded by
5434 5448 \family typewriter
5435 5449 -->
5436 5450 \family default
5437 5451 .
5438 5452 e.g.:
5439 5453 \layout Standard
5440 5454
5441 5455
5442 5456 \family typewriter
5443 5457 In [18]: callable list
5444 5458 \newline
5445 5459 -------> callable (list)
5446 5460 \layout Subsubsection
5447 5461
5448 5462 Automatic quoting
5449 5463 \layout Standard
5450 5464
5451 5465 You can force automatic quoting of a function's arguments by using
5452 5466 \family typewriter
5453 5467 `,'
5454 5468 \family default
5455 5469 or
5456 5470 \family typewriter
5457 5471 `;'
5458 5472 \family default
5459 5473 as the first character of a line.
5460 5474 For example:
5461 5475 \layout Standard
5462 5476
5463 5477
5464 5478 \family typewriter
5465 5479 >>> ,my_function /home/me # becomes my_function("/home/me")
5466 5480 \layout Standard
5467 5481
5468 5482 If you use
5469 5483 \family typewriter
5470 5484 `;'
5471 5485 \family default
5472 5486 instead, the whole argument is quoted as a single string (while
5473 5487 \family typewriter
5474 5488 `,'
5475 5489 \family default
5476 5490 splits on whitespace):
5477 5491 \layout Standard
5478 5492
5479 5493
5480 5494 \family typewriter
5481 5495 >>> ,my_function a b c # becomes my_function("a","b","c")
5482 5496 \layout Standard
5483 5497
5484 5498
5485 5499 \family typewriter
5486 5500 >>> ;my_function a b c # becomes my_function("a b c")
5487 5501 \layout Standard
5488 5502
5489 5503 Note that the `
5490 5504 \family typewriter
5491 5505 ,
5492 5506 \family default
5493 5507 ' or `
5494 5508 \family typewriter
5495 5509 ;
5496 5510 \family default
5497 5511 ' MUST be the first character on the line! This won't work:
5498 5512 \layout Standard
5499 5513
5500 5514
5501 5515 \family typewriter
5502 5516 >>> x = ,my_function /home/me # syntax error
5503 5517 \layout Section
5504 5518
5505 5519
5506 5520 \begin_inset LatexCommand \label{sec:customization}
5507 5521
5508 5522 \end_inset
5509 5523
5510 5524 Customization
5511 5525 \layout Standard
5512 5526
5513 5527 As we've already mentioned, IPython reads a configuration file which can
5514 5528 be specified at the command line (
5515 5529 \family typewriter
5516 5530 -rcfile
5517 5531 \family default
5518 5532 ) or which by default is assumed to be called
5519 5533 \family typewriter
5520 5534 ipythonrc
5521 5535 \family default
5522 5536 .
5523 5537 Such a file is looked for in the current directory where IPython is started
5524 5538 and then in your
5525 5539 \family typewriter
5526 5540 IPYTHONDIR
5527 5541 \family default
5528 5542 , which allows you to have local configuration files for specific projects.
5529 5543 In this section we will call these types of configuration files simply
5530 5544 rcfiles (short for resource configuration file).
5531 5545 \layout Standard
5532 5546
5533 5547 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5534 5548 one per line.
5535 5549 Lines beginning with a
5536 5550 \family typewriter
5537 5551 #
5538 5552 \family default
5539 5553 are ignored as comments, but comments can
5540 5554 \series bold
5541 5555 not
5542 5556 \series default
5543 5557 be put on lines with data (the parser is fairly primitive).
5544 5558 Note that these are not python files, and this is deliberate, because it
5545 5559 allows us to do some things which would be quite tricky to implement if
5546 5560 they were normal python files.
5547 5561 \layout Standard
5548 5562
5549 5563 First, an rcfile can contain permanent default values for almost all command
5550 5564 line options (except things like
5551 5565 \family typewriter
5552 5566 -help
5553 5567 \family default
5554 5568 or
5555 5569 \family typewriter
5556 5570 -Version
5557 5571 \family default
5558 5572 ).
5559 5573 Sec\SpecialChar ~
5560 5574
5561 5575 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5562 5576
5563 5577 \end_inset
5564 5578
5565 5579 contains a description of all command-line options.
5566 5580 However, values you explicitly specify at the command line override the
5567 5581 values defined in the rcfile.
5568 5582 \layout Standard
5569 5583
5570 5584 Besides command line option values, the rcfile can specify values for certain
5571 5585 extra special options which are not available at the command line.
5572 5586 These options are briefly described below.
5573 5587
5574 5588 \layout Standard
5575 5589
5576 5590 Each of these options may appear as many times as you need it in the file.
5577 5591 \layout List
5578 5592 \labelwidthstring 00.00.0000
5579 5593
5580 5594
5581 5595 \family typewriter
5582 5596 \series bold
5583 5597 include\SpecialChar ~
5584 5598 <file1>\SpecialChar ~
5585 5599 <file2>\SpecialChar ~
5586 5600 ...
5587 5601 \family default
5588 5602 \series default
5589 5603 : you can name
5590 5604 \emph on
5591 5605 other
5592 5606 \emph default
5593 5607 rcfiles you want to recursively load up to 15 levels (don't use the
5594 5608 \family typewriter
5595 5609 <>
5596 5610 \family default
5597 5611 brackets in your names!).
5598 5612 This feature allows you to define a 'base' rcfile with general options
5599 5613 and special-purpose files which can be loaded only when needed with particular
5600 5614 configuration options.
5601 5615 To make this more convenient, IPython accepts the
5602 5616 \family typewriter
5603 5617 -profile <name>
5604 5618 \family default
5605 5619 option (abbreviates to
5606 5620 \family typewriter
5607 5621 -p <name
5608 5622 \family default
5609 5623 >)
5610 5624 \family typewriter
5611 5625 which
5612 5626 \family default
5613 5627 tells it to look for an rcfile named
5614 5628 \family typewriter
5615 5629 ipythonrc-<name>
5616 5630 \family default
5617 5631 .
5618 5632
5619 5633 \layout List
5620 5634 \labelwidthstring 00.00.0000
5621 5635
5622 5636
5623 5637 \family typewriter
5624 5638 \series bold
5625 5639 import_mod\SpecialChar ~
5626 5640 <mod1>\SpecialChar ~
5627 5641 <mod2>\SpecialChar ~
5628 5642 ...
5629 5643 \family default
5630 5644 \series default
5631 5645 : import modules with '
5632 5646 \family typewriter
5633 5647 import
5634 5648 \family default
5635 5649
5636 5650 \family typewriter
5637 5651 <mod1>,<mod2>,...
5638 5652 \family default
5639 5653 '
5640 5654 \layout List
5641 5655 \labelwidthstring 00.00.0000
5642 5656
5643 5657
5644 5658 \family typewriter
5645 5659 \series bold
5646 5660 import_some\SpecialChar ~
5647 5661 <mod>\SpecialChar ~
5648 5662 <f1>\SpecialChar ~
5649 5663 <f2>\SpecialChar ~
5650 5664 ...
5651 5665 \family default
5652 5666 \series default
5653 5667 : import functions with '
5654 5668 \family typewriter
5655 5669 from <mod> import
5656 5670 \family default
5657 5671
5658 5672 \family typewriter
5659 5673 <f1>,<f2>,...
5660 5674 \family default
5661 5675 '
5662 5676 \layout List
5663 5677 \labelwidthstring 00.00.0000
5664 5678
5665 5679
5666 5680 \family typewriter
5667 5681 \series bold
5668 5682 import_all\SpecialChar ~
5669 5683 <mod1>\SpecialChar ~
5670 5684 <mod2>\SpecialChar ~
5671 5685 ...
5672 5686 \family default
5673 5687 \series default
5674 5688 : for each module listed import functions with '
5675 5689 \family typewriter
5676 5690 from <mod> import *
5677 5691 \family default
5678 5692 '
5679 5693 \layout List
5680 5694 \labelwidthstring 00.00.0000
5681 5695
5682 5696
5683 5697 \family typewriter
5684 5698 \series bold
5685 5699 execute\SpecialChar ~
5686 5700 <python\SpecialChar ~
5687 5701 code>
5688 5702 \family default
5689 5703 \series default
5690 5704 : give any single-line python code to be executed.
5691 5705 \layout List
5692 5706 \labelwidthstring 00.00.0000
5693 5707
5694 5708
5695 5709 \family typewriter
5696 5710 \series bold
5697 5711 execfile\SpecialChar ~
5698 5712 <filename>
5699 5713 \family default
5700 5714 \series default
5701 5715 : execute the python file given with an '
5702 5716 \family typewriter
5703 5717 execfile(filename)
5704 5718 \family default
5705 5719 ' command.
5706 5720 Username expansion is performed on the given names.
5707 5721 So if you need any amount of extra fancy customization that won't fit in
5708 5722 any of the above 'canned' options, you can just put it in a separate python
5709 5723 file and execute it.
5710 5724 \layout List
5711 5725 \labelwidthstring 00.00.0000
5712 5726
5713 5727
5714 5728 \family typewriter
5715 5729 \series bold
5716 5730 alias\SpecialChar ~
5717 5731 <alias_def>
5718 5732 \family default
5719 5733 \series default
5720 5734 : this is equivalent to calling '
5721 5735 \family typewriter
5722 5736 %alias\SpecialChar ~
5723 5737 <alias_def>
5724 5738 \family default
5725 5739 ' at the IPython command line.
5726 5740 This way, from within IPython you can do common system tasks without having
5727 5741 to exit it or use the
5728 5742 \family typewriter
5729 5743 !
5730 5744 \family default
5731 5745 escape.
5732 5746 IPython isn't meant to be a shell replacement, but it is often very useful
5733 5747 to be able to do things with files while testing code.
5734 5748 This gives you the flexibility to have within IPython any aliases you may
5735 5749 be used to under your normal system shell.
5736 5750 \layout Subsection
5737 5751
5738 5752
5739 5753 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5740 5754
5741 5755 \end_inset
5742 5756
5743 5757 Sample
5744 5758 \family typewriter
5745 5759 ipythonrc
5746 5760 \family default
5747 5761 file
5748 5762 \layout Standard
5749 5763
5750 5764 The default rcfile, called
5751 5765 \family typewriter
5752 5766 ipythonrc
5753 5767 \family default
5754 5768 and supplied in your
5755 5769 \family typewriter
5756 5770 IPYTHONDIR
5757 5771 \family default
5758 5772 directory contains lots of comments on all of these options.
5759 5773 We reproduce it here for reference:
5760 5774 \layout Standard
5761 5775
5762 5776
5763 5777 \begin_inset ERT
5764 5778 status Open
5765 5779
5766 5780 \layout Standard
5767 5781
5768 5782 \backslash
5769 5783 codelist{../IPython/UserConfig/ipythonrc}
5770 5784 \end_inset
5771 5785
5772 5786
5773 5787 \layout Subsection
5774 5788
5775 5789
5776 5790 \begin_inset LatexCommand \label{sec:prompts}
5777 5791
5778 5792 \end_inset
5779 5793
5780 5794 Fine-tuning your prompt
5781 5795 \layout Standard
5782 5796
5783 5797 IPython's prompts can be customized using a syntax similar to that of the
5784 5798
5785 5799 \family typewriter
5786 5800 bash
5787 5801 \family default
5788 5802 shell.
5789 5803 Many of
5790 5804 \family typewriter
5791 5805 bash
5792 5806 \family default
5793 5807 's escapes are supported, as well as a few additional ones.
5794 5808 We list them below:
5795 5809 \layout Description
5796 5810
5797 5811
5798 5812 \backslash
5799 5813 # the prompt/history count number
5800 5814 \layout Description
5801 5815
5802 5816
5803 5817 \backslash
5804 5818 D the prompt/history count, with the actual digits replaced by dots.
5805 5819 Used mainly in continuation prompts (prompt_in2)
5806 5820 \layout Description
5807 5821
5808 5822
5809 5823 \backslash
5810 5824 w the current working directory
5811 5825 \layout Description
5812 5826
5813 5827
5814 5828 \backslash
5815 5829 W the basename of current working directory
5816 5830 \layout Description
5817 5831
5818 5832
5819 5833 \backslash
5820 5834 X
5821 5835 \emph on
5822 5836 n
5823 5837 \emph default
5824 5838 where
5825 5839 \begin_inset Formula $n=0\ldots5.$
5826 5840 \end_inset
5827 5841
5828 5842 The current working directory, with
5829 5843 \family typewriter
5830 5844 $HOME
5831 5845 \family default
5832 5846 replaced by
5833 5847 \family typewriter
5834 5848 ~
5835 5849 \family default
5836 5850 , and filtered out to contain only
5837 5851 \begin_inset Formula $n$
5838 5852 \end_inset
5839 5853
5840 5854 path elements
5841 5855 \layout Description
5842 5856
5843 5857
5844 5858 \backslash
5845 5859 Y
5846 5860 \emph on
5847 5861 n
5848 5862 \emph default
5849 5863 Similar to
5850 5864 \backslash
5851 5865 X
5852 5866 \emph on
5853 5867 n
5854 5868 \emph default
5855 5869 , but with the
5856 5870 \begin_inset Formula $n+1$
5857 5871 \end_inset
5858 5872
5859 5873 element included if it is
5860 5874 \family typewriter
5861 5875 ~
5862 5876 \family default
5863 5877 (this is similar to the behavior of the %c
5864 5878 \emph on
5865 5879 n
5866 5880 \emph default
5867 5881 escapes in
5868 5882 \family typewriter
5869 5883 tcsh
5870 5884 \family default
5871 5885 )
5872 5886 \layout Description
5873 5887
5874 5888
5875 5889 \backslash
5876 5890 u the username of the current user
5877 5891 \layout Description
5878 5892
5879 5893
5880 5894 \backslash
5881 5895 $ if the effective UID is 0, a #, otherwise a $
5882 5896 \layout Description
5883 5897
5884 5898
5885 5899 \backslash
5886 5900 h the hostname up to the first `.'
5887 5901 \layout Description
5888 5902
5889 5903
5890 5904 \backslash
5891 5905 H the hostname
5892 5906 \layout Description
5893 5907
5894 5908
5895 5909 \backslash
5896 5910 n a newline
5897 5911 \layout Description
5898 5912
5899 5913
5900 5914 \backslash
5901 5915 r a carriage return
5902 5916 \layout Description
5903 5917
5904 5918
5905 5919 \backslash
5906 5920 v IPython version string
5907 5921 \layout Standard
5908 5922
5909 5923 In addition to these, ANSI color escapes can be insterted into the prompts,
5910 5924 as
5911 5925 \family typewriter
5912 5926
5913 5927 \backslash
5914 5928 C_
5915 5929 \emph on
5916 5930 ColorName
5917 5931 \family default
5918 5932 \emph default
5919 5933 .
5920 5934 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5921 5935 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5922 5936 Normal, Purple, Red, White, Yellow.
5923 5937 \layout Standard
5924 5938
5925 5939 Finally, IPython supports the evaluation of arbitrary expressions in your
5926 5940 prompt string.
5927 5941 The prompt strings are evaluated through the syntax of PEP 215, but basically
5928 5942 you can use
5929 5943 \family typewriter
5930 5944 $x.y
5931 5945 \family default
5932 5946 to expand the value of
5933 5947 \family typewriter
5934 5948 x.y
5935 5949 \family default
5936 5950 , and for more complicated expressions you can use braces:
5937 5951 \family typewriter
5938 5952 ${foo()+x}
5939 5953 \family default
5940 5954 will call function
5941 5955 \family typewriter
5942 5956 foo
5943 5957 \family default
5944 5958 and add to it the value of
5945 5959 \family typewriter
5946 5960 x
5947 5961 \family default
5948 5962 , before putting the result into your prompt.
5949 5963 For example, using
5950 5964 \newline
5951 5965
5952 5966 \family typewriter
5953 5967 prompt_in1 '${commands.getoutput("uptime")}
5954 5968 \backslash
5955 5969 nIn [
5956 5970 \backslash
5957 5971 #]: '
5958 5972 \newline
5959 5973
5960 5974 \family default
5961 5975 will print the result of the uptime command on each prompt (assuming the
5962 5976
5963 5977 \family typewriter
5964 5978 commands
5965 5979 \family default
5966 5980 module has been imported in your
5967 5981 \family typewriter
5968 5982 ipythonrc
5969 5983 \family default
5970 5984 file).
5971 5985 \layout Subsubsection
5972 5986
5973 5987 Prompt examples
5974 5988 \layout Standard
5975 5989
5976 5990 The following options in an ipythonrc file will give you IPython's default
5977 5991 prompts:
5978 5992 \layout Standard
5979 5993
5980 5994
5981 5995 \family typewriter
5982 5996 prompt_in1 'In [
5983 5997 \backslash
5984 5998 #]:'
5985 5999 \newline
5986 6000 prompt_in2 '\SpecialChar ~
5987 6001 \SpecialChar ~
5988 6002 \SpecialChar ~
5989 6003 .
5990 6004 \backslash
5991 6005 D.:'
5992 6006 \newline
5993 6007 prompt_out 'Out[
5994 6008 \backslash
5995 6009 #]:'
5996 6010 \layout Standard
5997 6011
5998 6012 which look like this:
5999 6013 \layout Standard
6000 6014
6001 6015
6002 6016 \family typewriter
6003 6017 In [1]: 1+2
6004 6018 \newline
6005 6019 Out[1]: 3
6006 6020 \layout Standard
6007 6021
6008 6022
6009 6023 \family typewriter
6010 6024 In [2]: for i in (1,2,3):
6011 6025 \newline
6012 6026
6013 6027 \begin_inset ERT
6014 6028 status Collapsed
6015 6029
6016 6030 \layout Standard
6017 6031
6018 6032 \backslash
6019 6033 hspace*{0mm}
6020 6034 \end_inset
6021 6035
6022 6036 \SpecialChar ~
6023 6037 \SpecialChar ~
6024 6038 \SpecialChar ~
6025 6039 ...: \SpecialChar ~
6026 6040 \SpecialChar ~
6027 6041 \SpecialChar ~
6028 6042 \SpecialChar ~
6029 6043 print i,
6030 6044 \newline
6031 6045
6032 6046 \begin_inset ERT
6033 6047 status Collapsed
6034 6048
6035 6049 \layout Standard
6036 6050
6037 6051 \backslash
6038 6052 hspace*{0mm}
6039 6053 \end_inset
6040 6054
6041 6055 \SpecialChar ~
6042 6056 \SpecialChar ~
6043 6057 \SpecialChar ~
6044 6058 ...:
6045 6059 \newline
6046 6060 1 2 3
6047 6061 \layout Standard
6048 6062
6049 6063 These will give you a very colorful prompt with path information:
6050 6064 \layout Standard
6051 6065
6052 6066
6053 6067 \family typewriter
6054 6068 #prompt_in1 '
6055 6069 \backslash
6056 6070 C_Red
6057 6071 \backslash
6058 6072 u
6059 6073 \backslash
6060 6074 C_Blue[
6061 6075 \backslash
6062 6076 C_Cyan
6063 6077 \backslash
6064 6078 Y1
6065 6079 \backslash
6066 6080 C_Blue]
6067 6081 \backslash
6068 6082 C_LightGreen
6069 6083 \backslash
6070 6084 #>'
6071 6085 \newline
6072 6086 prompt_in2 ' ..
6073 6087 \backslash
6074 6088 D>'
6075 6089 \newline
6076 6090 prompt_out '<
6077 6091 \backslash
6078 6092 #>'
6079 6093 \layout Standard
6080 6094
6081 6095 which look like this:
6082 6096 \layout Standard
6083 6097
6084 6098
6085 6099 \family typewriter
6086 6100 \color red
6087 6101 fperez
6088 6102 \color blue
6089 6103 [
6090 6104 \color cyan
6091 6105 ~/ipython
6092 6106 \color blue
6093 6107 ]
6094 6108 \color green
6095 6109 1>
6096 6110 \color default
6097 6111 1+2
6098 6112 \newline
6099 6113
6100 6114 \begin_inset ERT
6101 6115 status Collapsed
6102 6116
6103 6117 \layout Standard
6104 6118
6105 6119 \backslash
6106 6120 hspace*{0mm}
6107 6121 \end_inset
6108 6122
6109 6123 \SpecialChar ~
6110 6124 \SpecialChar ~
6111 6125 \SpecialChar ~
6112 6126 \SpecialChar ~
6113 6127 \SpecialChar ~
6114 6128 \SpecialChar ~
6115 6129 \SpecialChar ~
6116 6130 \SpecialChar ~
6117 6131 \SpecialChar ~
6118 6132 \SpecialChar ~
6119 6133 \SpecialChar ~
6120 6134 \SpecialChar ~
6121 6135 \SpecialChar ~
6122 6136 \SpecialChar ~
6123 6137 \SpecialChar ~
6124 6138 \SpecialChar ~
6125 6139
6126 6140 \color red
6127 6141 <1>
6128 6142 \color default
6129 6143 3
6130 6144 \newline
6131 6145
6132 6146 \color red
6133 6147 fperez
6134 6148 \color blue
6135 6149 [
6136 6150 \color cyan
6137 6151 ~/ipython
6138 6152 \color blue
6139 6153 ]
6140 6154 \color green
6141 6155 2>
6142 6156 \color default
6143 6157 for i in (1,2,3):
6144 6158 \newline
6145 6159
6146 6160 \begin_inset ERT
6147 6161 status Collapsed
6148 6162
6149 6163 \layout Standard
6150 6164
6151 6165 \backslash
6152 6166 hspace*{0mm}
6153 6167 \end_inset
6154 6168
6155 6169 \SpecialChar ~
6156 6170 \SpecialChar ~
6157 6171 \SpecialChar ~
6158 6172 \SpecialChar ~
6159 6173 \SpecialChar ~
6160 6174 \SpecialChar ~
6161 6175 \SpecialChar ~
6162 6176 \SpecialChar ~
6163 6177 \SpecialChar ~
6164 6178 \SpecialChar ~
6165 6179 \SpecialChar ~
6166 6180 \SpecialChar ~
6167 6181 \SpecialChar ~
6168 6182 \SpecialChar ~
6169 6183 \SpecialChar ~
6170 6184
6171 6185 \color green
6172 6186 ...>
6173 6187 \color default
6174 6188 \SpecialChar ~
6175 6189 \SpecialChar ~
6176 6190 \SpecialChar ~
6177 6191 \SpecialChar ~
6178 6192 print i,
6179 6193 \newline
6180 6194
6181 6195 \begin_inset ERT
6182 6196 status Collapsed
6183 6197
6184 6198 \layout Standard
6185 6199
6186 6200 \backslash
6187 6201 hspace*{0mm}
6188 6202 \end_inset
6189 6203
6190 6204 \SpecialChar ~
6191 6205 \SpecialChar ~
6192 6206 \SpecialChar ~
6193 6207 \SpecialChar ~
6194 6208 \SpecialChar ~
6195 6209 \SpecialChar ~
6196 6210 \SpecialChar ~
6197 6211 \SpecialChar ~
6198 6212 \SpecialChar ~
6199 6213 \SpecialChar ~
6200 6214 \SpecialChar ~
6201 6215 \SpecialChar ~
6202 6216 \SpecialChar ~
6203 6217 \SpecialChar ~
6204 6218 \SpecialChar ~
6205 6219
6206 6220 \color green
6207 6221 ...>
6208 6222 \color default
6209 6223
6210 6224 \newline
6211 6225 1 2 3
6212 6226 \layout Standard
6213 6227
6214 6228 The following shows the usage of dynamic expression evaluation:
6215 6229 \layout Subsection
6216 6230
6217 6231
6218 6232 \begin_inset LatexCommand \label{sec:profiles}
6219 6233
6220 6234 \end_inset
6221 6235
6222 6236 IPython profiles
6223 6237 \layout Standard
6224 6238
6225 6239 As we already mentioned, IPython supports the
6226 6240 \family typewriter
6227 6241 -profile
6228 6242 \family default
6229 6243 command-line option (see sec.
6230 6244
6231 6245 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
6232 6246
6233 6247 \end_inset
6234 6248
6235 6249 ).
6236 6250 A profile is nothing more than a particular configuration file like your
6237 6251 basic
6238 6252 \family typewriter
6239 6253 ipythonrc
6240 6254 \family default
6241 6255 one, but with particular customizations for a specific purpose.
6242 6256 When you start IPython with '
6243 6257 \family typewriter
6244 6258 ipython -profile <name>
6245 6259 \family default
6246 6260 ', it assumes that in your
6247 6261 \family typewriter
6248 6262 IPYTHONDIR
6249 6263 \family default
6250 6264 there is a file called
6251 6265 \family typewriter
6252 6266 ipythonrc-<name>
6253 6267 \family default
6254 6268 , and loads it instead of the normal
6255 6269 \family typewriter
6256 6270 ipythonrc
6257 6271 \family default
6258 6272 .
6259 6273 \layout Standard
6260 6274
6261 6275 This system allows you to maintain multiple configurations which load modules,
6262 6276 set options, define functions, etc.
6263 6277 suitable for different tasks and activate them in a very simple manner.
6264 6278 In order to avoid having to repeat all of your basic options (common things
6265 6279 that don't change such as your color preferences, for example), any profile
6266 6280 can include another configuration file.
6267 6281 The most common way to use profiles is then to have each one include your
6268 6282 basic
6269 6283 \family typewriter
6270 6284 ipythonrc
6271 6285 \family default
6272 6286 file as a starting point, and then add further customizations.
6273 6287 \layout Standard
6274 6288
6275 6289 In sections
6276 6290 \begin_inset LatexCommand \ref{sec:syntax-extensions}
6277 6291
6278 6292 \end_inset
6279 6293
6280 6294 and
6281 6295 \begin_inset LatexCommand \ref{sec:Gnuplot}
6282 6296
6283 6297 \end_inset
6284 6298
6285 6299 we discuss some particular profiles which come as part of the standard
6286 6300 IPython distribution.
6287 6301 You may also look in your
6288 6302 \family typewriter
6289 6303 IPYTHONDIR
6290 6304 \family default
6291 6305 directory, any file whose name begins with
6292 6306 \family typewriter
6293 6307 ipythonrc-
6294 6308 \family default
6295 6309 is a profile.
6296 6310 You can use those as examples for further customizations to suit your own
6297 6311 needs.
6298 6312 \layout Section
6299 6313
6300 6314
6301 6315 \begin_inset OptArg
6302 6316 collapsed false
6303 6317
6304 6318 \layout Standard
6305 6319
6306 6320 IPython as default...
6307 6321 \end_inset
6308 6322
6309 6323 IPython as your default Python environment
6310 6324 \layout Standard
6311 6325
6312 6326 Python honors the environment variable
6313 6327 \family typewriter
6314 6328 PYTHONSTARTUP
6315 6329 \family default
6316 6330 and will execute at startup the file referenced by this variable.
6317 6331 If you put at the end of this file the following two lines of code:
6318 6332 \layout Standard
6319 6333
6320 6334
6321 6335 \family typewriter
6322 6336 import IPython
6323 6337 \newline
6324 6338 IPython.Shell.IPShell().mainloop(sys_exit=1)
6325 6339 \layout Standard
6326 6340
6327 6341 then IPython will be your working environment anytime you start Python.
6328 6342 The
6329 6343 \family typewriter
6330 6344 sys_exit=1
6331 6345 \family default
6332 6346 is needed to have IPython issue a call to
6333 6347 \family typewriter
6334 6348 sys.exit()
6335 6349 \family default
6336 6350 when it finishes, otherwise you'll be back at the normal Python '
6337 6351 \family typewriter
6338 6352 >>>
6339 6353 \family default
6340 6354 ' prompt
6341 6355 \begin_inset Foot
6342 6356 collapsed true
6343 6357
6344 6358 \layout Standard
6345 6359
6346 6360 Based on an idea by Holger Krekel.
6347 6361 \end_inset
6348 6362
6349 6363 .
6350 6364 \layout Standard
6351 6365
6352 6366 This is probably useful to developers who manage multiple Python versions
6353 6367 and don't want to have correspondingly multiple IPython versions.
6354 6368 Note that in this mode, there is no way to pass IPython any command-line
6355 6369 options, as those are trapped first by Python itself.
6356 6370 \layout Section
6357 6371
6358 6372
6359 6373 \begin_inset LatexCommand \label{sec:embed}
6360 6374
6361 6375 \end_inset
6362 6376
6363 6377 Embedding IPython
6364 6378 \layout Standard
6365 6379
6366 6380 It is possible to start an IPython instance
6367 6381 \emph on
6368 6382 inside
6369 6383 \emph default
6370 6384 your own Python programs.
6371 6385 This allows you to evaluate dynamically the state of your code, operate
6372 6386 with your variables, analyze them, etc.
6373 6387 Note however that any changes you make to values while in the shell do
6374 6388
6375 6389 \emph on
6376 6390 not
6377 6391 \emph default
6378 6392 propagate back to the running code, so it is safe to modify your values
6379 6393 because you won't break your code in bizarre ways by doing so.
6380 6394 \layout Standard
6381 6395
6382 6396 This feature allows you to easily have a fully functional python environment
6383 6397 for doing object introspection anywhere in your code with a simple function
6384 6398 call.
6385 6399 In some cases a simple print statement is enough, but if you need to do
6386 6400 more detailed analysis of a code fragment this feature can be very valuable.
6387 6401 \layout Standard
6388 6402
6389 6403 It can also be useful in scientific computing situations where it is common
6390 6404 to need to do some automatic, computationally intensive part and then stop
6391 6405 to look at data, plots, etc
6392 6406 \begin_inset Foot
6393 6407 collapsed true
6394 6408
6395 6409 \layout Standard
6396 6410
6397 6411 This functionality was inspired by IDL's combination of the
6398 6412 \family typewriter
6399 6413 stop
6400 6414 \family default
6401 6415 keyword and the
6402 6416 \family typewriter
6403 6417 .continue
6404 6418 \family default
6405 6419 executive command, which I have found very useful in the past, and by a
6406 6420 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6407 6421 06/01 concerning similar uses of pyrepl.
6408 6422 \end_inset
6409 6423
6410 6424 .
6411 6425 Opening an IPython instance will give you full access to your data and
6412 6426 functions, and you can resume program execution once you are done with
6413 6427 the interactive part (perhaps to stop again later, as many times as needed).
6414 6428 \layout Standard
6415 6429
6416 6430 The following code snippet is the bare minimum you need to include in your
6417 6431 Python programs for this to work (detailed examples follow later):
6418 6432 \layout LyX-Code
6419 6433
6420 6434 from IPython.Shell import IPShellEmbed
6421 6435 \layout LyX-Code
6422 6436
6423 6437 ipshell = IPShellEmbed()
6424 6438 \layout LyX-Code
6425 6439
6426 6440 ipshell() # this call anywhere in your program will start IPython
6427 6441 \layout Standard
6428 6442
6429 6443 You can run embedded instances even in code which is itself being run at
6430 6444 the IPython interactive prompt with '
6431 6445 \family typewriter
6432 6446 %run\SpecialChar ~
6433 6447 <filename>
6434 6448 \family default
6435 6449 '.
6436 6450 Since it's easy to get lost as to where you are (in your top-level IPython
6437 6451 or in your embedded one), it's a good idea in such cases to set the in/out
6438 6452 prompts to something different for the embedded instances.
6439 6453 The code examples below illustrate this.
6440 6454 \layout Standard
6441 6455
6442 6456 You can also have multiple IPython instances in your program and open them
6443 6457 separately, for example with different options for data presentation.
6444 6458 If you close and open the same instance multiple times, its prompt counters
6445 6459 simply continue from each execution to the next.
6446 6460 \layout Standard
6447 6461
6448 6462 Please look at the docstrings in the
6449 6463 \family typewriter
6450 6464 Shell.py
6451 6465 \family default
6452 6466 module for more details on the use of this system.
6453 6467 \layout Standard
6454 6468
6455 6469 The following sample file illustrating how to use the embedding functionality
6456 6470 is provided in the examples directory as
6457 6471 \family typewriter
6458 6472 example-embed.py
6459 6473 \family default
6460 6474 .
6461 6475 It should be fairly self-explanatory:
6462 6476 \layout Standard
6463 6477
6464 6478
6465 6479 \begin_inset ERT
6466 6480 status Open
6467 6481
6468 6482 \layout Standard
6469 6483
6470 6484 \backslash
6471 6485 codelist{examples/example-embed.py}
6472 6486 \end_inset
6473 6487
6474 6488
6475 6489 \layout Standard
6476 6490
6477 6491 Once you understand how the system functions, you can use the following
6478 6492 code fragments in your programs which are ready for cut and paste:
6479 6493 \layout Standard
6480 6494
6481 6495
6482 6496 \begin_inset ERT
6483 6497 status Open
6484 6498
6485 6499 \layout Standard
6486 6500
6487 6501 \backslash
6488 6502 codelist{examples/example-embed-short.py}
6489 6503 \end_inset
6490 6504
6491 6505
6492 6506 \layout Section
6493 6507
6494 6508
6495 6509 \begin_inset LatexCommand \label{sec:using-pdb}
6496 6510
6497 6511 \end_inset
6498 6512
6499 6513 Using the Python debugger (
6500 6514 \family typewriter
6501 6515 pdb
6502 6516 \family default
6503 6517 )
6504 6518 \layout Subsection
6505 6519
6506 6520 Running entire programs via
6507 6521 \family typewriter
6508 6522 pdb
6509 6523 \layout Standard
6510 6524
6511 6525
6512 6526 \family typewriter
6513 6527 pdb
6514 6528 \family default
6515 6529 , the Python debugger, is a powerful interactive debugger which allows you
6516 6530 to step through code, set breakpoints, watch variables, etc.
6517 6531 IPython makes it very easy to start any script under the control of
6518 6532 \family typewriter
6519 6533 pdb
6520 6534 \family default
6521 6535 , regardless of whether you have wrapped it into a
6522 6536 \family typewriter
6523 6537 `main()'
6524 6538 \family default
6525 6539 function or not.
6526 6540 For this, simply type
6527 6541 \family typewriter
6528 6542 `%run -d myscript'
6529 6543 \family default
6530 6544 at an IPython prompt.
6531 6545 See the
6532 6546 \family typewriter
6533 6547 %run
6534 6548 \family default
6535 6549 command's documentation (via
6536 6550 \family typewriter
6537 6551 `%run?'
6538 6552 \family default
6539 6553 or in Sec.\SpecialChar ~
6540 6554
6541 6555 \begin_inset LatexCommand \ref{sec:magic}
6542 6556
6543 6557 \end_inset
6544 6558
6545 6559 ) for more details, including how to control where
6546 6560 \family typewriter
6547 6561 pdb
6548 6562 \family default
6549 6563 will stop execution first.
6550 6564 \layout Standard
6551 6565
6552 6566 For more information on the use of the
6553 6567 \family typewriter
6554 6568 pdb
6555 6569 \family default
6556 6570 debugger, read the included
6557 6571 \family typewriter
6558 6572 pdb.doc
6559 6573 \family default
6560 6574 file (part of the standard Python distribution).
6561 6575 On a stock Linux system it is located at
6562 6576 \family typewriter
6563 6577 /usr/lib/python2.3/pdb.doc
6564 6578 \family default
6565 6579 , but the easiest way to read it is by using the
6566 6580 \family typewriter
6567 6581 help()
6568 6582 \family default
6569 6583 function of the
6570 6584 \family typewriter
6571 6585 pdb
6572 6586 \family default
6573 6587 module as follows (in an IPython prompt):
6574 6588 \layout Standard
6575 6589
6576 6590
6577 6591 \family typewriter
6578 6592 In [1]: import pdb
6579 6593 \newline
6580 6594 In [2]: pdb.help()
6581 6595 \layout Standard
6582 6596
6583 6597 This will load the
6584 6598 \family typewriter
6585 6599 pdb.doc
6586 6600 \family default
6587 6601 document in a file viewer for you automatically.
6588 6602 \layout Subsection
6589 6603
6590 6604 Automatic invocation of
6591 6605 \family typewriter
6592 6606 pdb
6593 6607 \family default
6594 6608 on exceptions
6595 6609 \layout Standard
6596 6610
6597 6611 IPython, if started with the
6598 6612 \family typewriter
6599 6613 -pdb
6600 6614 \family default
6601 6615 option (or if the option is set in your rc file) can call the Python
6602 6616 \family typewriter
6603 6617 pdb
6604 6618 \family default
6605 6619 debugger every time your code triggers an uncaught exception
6606 6620 \begin_inset Foot
6607 6621 collapsed true
6608 6622
6609 6623 \layout Standard
6610 6624
6611 6625 Many thanks to Christopher Hart for the request which prompted adding this
6612 6626 feature to IPython.
6613 6627 \end_inset
6614 6628
6615 6629 .
6616 6630 This feature can also be toggled at any time with the
6617 6631 \family typewriter
6618 6632 %pdb
6619 6633 \family default
6620 6634 magic command.
6621 6635 This can be extremely useful in order to find the origin of subtle bugs,
6622 6636 because
6623 6637 \family typewriter
6624 6638 pdb
6625 6639 \family default
6626 6640 opens up at the point in your code which triggered the exception, and while
6627 6641 your program is at this point `dead', all the data is still available and
6628 6642 you can walk up and down the stack frame and understand the origin of the
6629 6643 problem.
6630 6644 \layout Standard
6631 6645
6632 6646 Furthermore, you can use these debugging facilities both with the embedded
6633 6647 IPython mode and without IPython at all.
6634 6648 For an embedded shell (see sec.
6635 6649
6636 6650 \begin_inset LatexCommand \ref{sec:embed}
6637 6651
6638 6652 \end_inset
6639 6653
6640 6654 ), simply call the constructor with
6641 6655 \family typewriter
6642 6656 `-pdb'
6643 6657 \family default
6644 6658 in the argument string and automatically
6645 6659 \family typewriter
6646 6660 pdb
6647 6661 \family default
6648 6662 will be called if an uncaught exception is triggered by your code.
6649 6663
6650 6664 \layout Standard
6651 6665
6652 6666 For stand-alone use of the feature in your programs which do not use IPython
6653 6667 at all, put the following lines toward the top of your `main' routine:
6654 6668 \layout Standard
6655 6669 \align left
6656 6670
6657 6671 \family typewriter
6658 6672 import sys,IPython.ultraTB
6659 6673 \newline
6660 6674 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6661 6675 call_pdb=1)
6662 6676 \layout Standard
6663 6677
6664 6678 The
6665 6679 \family typewriter
6666 6680 mode
6667 6681 \family default
6668 6682 keyword can be either
6669 6683 \family typewriter
6670 6684 `Verbose'
6671 6685 \family default
6672 6686 or
6673 6687 \family typewriter
6674 6688 `Plain'
6675 6689 \family default
6676 6690 , giving either very detailed or normal tracebacks respectively.
6677 6691 The
6678 6692 \family typewriter
6679 6693 color_scheme
6680 6694 \family default
6681 6695 keyword can be one of
6682 6696 \family typewriter
6683 6697 `NoColor'
6684 6698 \family default
6685 6699 ,
6686 6700 \family typewriter
6687 6701 `Linux'
6688 6702 \family default
6689 6703 (default) or
6690 6704 \family typewriter
6691 6705 `LightBG'
6692 6706 \family default
6693 6707 .
6694 6708 These are the same options which can be set in IPython with
6695 6709 \family typewriter
6696 6710 -colors
6697 6711 \family default
6698 6712 and
6699 6713 \family typewriter
6700 6714 -xmode
6701 6715 \family default
6702 6716 .
6703 6717 \layout Standard
6704 6718
6705 6719 This will give any of your programs detailed, colored tracebacks with automatic
6706 6720 invocation of
6707 6721 \family typewriter
6708 6722 pdb
6709 6723 \family default
6710 6724 .
6711 6725 \layout Section
6712 6726
6713 6727
6714 6728 \begin_inset LatexCommand \label{sec:syntax-extensions}
6715 6729
6716 6730 \end_inset
6717 6731
6718 6732 Extensions for syntax processing
6719 6733 \layout Standard
6720 6734
6721 6735 This isn't for the faint of heart, because the potential for breaking things
6722 6736 is quite high.
6723 6737 But it can be a very powerful and useful feature.
6724 6738 In a nutshell, you can redefine the way IPython processes the user input
6725 6739 line to accept new, special extensions to the syntax without needing to
6726 6740 change any of IPython's own code.
6727 6741 \layout Standard
6728 6742
6729 6743 In the
6730 6744 \family typewriter
6731 6745 IPython/Extensions
6732 6746 \family default
6733 6747 directory you will find some examples supplied, which we will briefly describe
6734 6748 now.
6735 6749 These can be used `as is' (and both provide very useful functionality),
6736 6750 or you can use them as a starting point for writing your own extensions.
6737 6751 \layout Subsection
6738 6752
6739 6753 Pasting of code starting with
6740 6754 \family typewriter
6741 6755 `>>>
6742 6756 \family default
6743 6757 ' or
6744 6758 \family typewriter
6745 6759 `...
6746 6760
6747 6761 \family default
6748 6762 '
6749 6763 \layout Standard
6750 6764
6751 6765 In the python tutorial it is common to find code examples which have been
6752 6766 taken from real python sessions.
6753 6767 The problem with those is that all the lines begin with either
6754 6768 \family typewriter
6755 6769 `>>>
6756 6770 \family default
6757 6771 ' or
6758 6772 \family typewriter
6759 6773 `...
6760 6774
6761 6775 \family default
6762 6776 ', which makes it impossible to paste them all at once.
6763 6777 One must instead do a line by line manual copying, carefully removing the
6764 6778 leading extraneous characters.
6765 6779 \layout Standard
6766 6780
6767 6781 This extension identifies those starting characters and removes them from
6768 6782 the input automatically, so that one can paste multi-line examples directly
6769 6783 into IPython, saving a lot of time.
6770 6784 Please look at the file
6771 6785 \family typewriter
6772 6786 InterpreterPasteInput.py
6773 6787 \family default
6774 6788 in the
6775 6789 \family typewriter
6776 6790 IPython/Extensions
6777 6791 \family default
6778 6792 directory for details on how this is done.
6779 6793 \layout Standard
6780 6794
6781 6795 IPython comes with a special profile enabling this feature, called
6782 6796 \family typewriter
6783 6797 tutorial
6784 6798 \family default
6785 6799 \emph on
6786 6800 .
6787 6801
6788 6802 \emph default
6789 6803 Simply start IPython via
6790 6804 \family typewriter
6791 6805 `ipython\SpecialChar ~
6792 6806 -p\SpecialChar ~
6793 6807 tutorial'
6794 6808 \family default
6795 6809 and the feature will be available.
6796 6810 In a normal IPython session you can activate the feature by importing the
6797 6811 corresponding module with:
6798 6812 \newline
6799 6813
6800 6814 \family typewriter
6801 6815 In [1]: import IPython.Extensions.InterpreterPasteInput
6802 6816 \layout Standard
6803 6817
6804 6818 The following is a 'screenshot' of how things work when this extension is
6805 6819 on, copying an example from the standard tutorial:
6806 6820 \layout Standard
6807 6821
6808 6822
6809 6823 \family typewriter
6810 6824 IPython profile: tutorial
6811 6825 \newline
6812 6826 \SpecialChar ~
6813 6827
6814 6828 \newline
6815 6829 *** Pasting of code with ">>>" or "..." has been enabled.
6816 6830 \newline
6817 6831 \SpecialChar ~
6818 6832
6819 6833 \newline
6820 6834 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6821 6835 \newline
6822 6836
6823 6837 \begin_inset ERT
6824 6838 status Collapsed
6825 6839
6826 6840 \layout Standard
6827 6841
6828 6842 \backslash
6829 6843 hspace*{0mm}
6830 6844 \end_inset
6831 6845
6832 6846 \SpecialChar ~
6833 6847 \SpecialChar ~
6834 6848 ...: ...\SpecialChar ~
6835 6849 \SpecialChar ~
6836 6850 \SpecialChar ~
6837 6851 \SpecialChar ~
6838 6852 """Return a list containing the Fibonacci series up to n."""
6839 6853 \newline
6840 6854
6841 6855 \begin_inset ERT
6842 6856 status Collapsed
6843 6857
6844 6858 \layout Standard
6845 6859
6846 6860 \backslash
6847 6861 hspace*{0mm}
6848 6862 \end_inset
6849 6863
6850 6864 \SpecialChar ~
6851 6865 \SpecialChar ~
6852 6866 ...: ...\SpecialChar ~
6853 6867 \SpecialChar ~
6854 6868 \SpecialChar ~
6855 6869 \SpecialChar ~
6856 6870 result = []
6857 6871 \newline
6858 6872
6859 6873 \begin_inset ERT
6860 6874 status Collapsed
6861 6875
6862 6876 \layout Standard
6863 6877
6864 6878 \backslash
6865 6879 hspace*{0mm}
6866 6880 \end_inset
6867 6881
6868 6882 \SpecialChar ~
6869 6883 \SpecialChar ~
6870 6884 ...: ...\SpecialChar ~
6871 6885 \SpecialChar ~
6872 6886 \SpecialChar ~
6873 6887 \SpecialChar ~
6874 6888 a, b = 0, 1
6875 6889 \newline
6876 6890
6877 6891 \begin_inset ERT
6878 6892 status Collapsed
6879 6893
6880 6894 \layout Standard
6881 6895
6882 6896 \backslash
6883 6897 hspace*{0mm}
6884 6898 \end_inset
6885 6899
6886 6900 \SpecialChar ~
6887 6901 \SpecialChar ~
6888 6902 ...: ...\SpecialChar ~
6889 6903 \SpecialChar ~
6890 6904 \SpecialChar ~
6891 6905 \SpecialChar ~
6892 6906 while b < n:
6893 6907 \newline
6894 6908
6895 6909 \begin_inset ERT
6896 6910 status Collapsed
6897 6911
6898 6912 \layout Standard
6899 6913
6900 6914 \backslash
6901 6915 hspace*{0mm}
6902 6916 \end_inset
6903 6917
6904 6918 \SpecialChar ~
6905 6919 \SpecialChar ~
6906 6920 ...: ...\SpecialChar ~
6907 6921 \SpecialChar ~
6908 6922 \SpecialChar ~
6909 6923 \SpecialChar ~
6910 6924 \SpecialChar ~
6911 6925 \SpecialChar ~
6912 6926 \SpecialChar ~
6913 6927 \SpecialChar ~
6914 6928 result.append(b)\SpecialChar ~
6915 6929 \SpecialChar ~
6916 6930 \SpecialChar ~
6917 6931 # see below
6918 6932 \newline
6919 6933
6920 6934 \begin_inset ERT
6921 6935 status Collapsed
6922 6936
6923 6937 \layout Standard
6924 6938
6925 6939 \backslash
6926 6940 hspace*{0mm}
6927 6941 \end_inset
6928 6942
6929 6943 \SpecialChar ~
6930 6944 \SpecialChar ~
6931 6945 ...: ...\SpecialChar ~
6932 6946 \SpecialChar ~
6933 6947 \SpecialChar ~
6934 6948 \SpecialChar ~
6935 6949 \SpecialChar ~
6936 6950 \SpecialChar ~
6937 6951 \SpecialChar ~
6938 6952 \SpecialChar ~
6939 6953 a, b = b, a+b
6940 6954 \newline
6941 6955
6942 6956 \begin_inset ERT
6943 6957 status Collapsed
6944 6958
6945 6959 \layout Standard
6946 6960
6947 6961 \backslash
6948 6962 hspace*{0mm}
6949 6963 \end_inset
6950 6964
6951 6965 \SpecialChar ~
6952 6966 \SpecialChar ~
6953 6967 ...: ...\SpecialChar ~
6954 6968 \SpecialChar ~
6955 6969 \SpecialChar ~
6956 6970 \SpecialChar ~
6957 6971 return result
6958 6972 \newline
6959 6973
6960 6974 \begin_inset ERT
6961 6975 status Collapsed
6962 6976
6963 6977 \layout Standard
6964 6978
6965 6979 \backslash
6966 6980 hspace*{0mm}
6967 6981 \end_inset
6968 6982
6969 6983 \SpecialChar ~
6970 6984 \SpecialChar ~
6971 6985 ...:
6972 6986 \newline
6973 6987 \SpecialChar ~
6974 6988
6975 6989 \newline
6976 6990 In [2]: fib2(10)
6977 6991 \newline
6978 6992 Out[2]: [1, 1, 2, 3, 5, 8]
6979 6993 \layout Standard
6980 6994
6981 6995 Note that as currently written, this extension does
6982 6996 \emph on
6983 6997 not
6984 6998 \emph default
6985 6999 recognize IPython's prompts for pasting.
6986 7000 Those are more complicated, since the user can change them very easily,
6987 7001 they involve numbers and can vary in length.
6988 7002 One could however extract all the relevant information from the IPython
6989 7003 instance and build an appropriate regular expression.
6990 7004 This is left as an exercise for the reader.
6991 7005 \layout Subsection
6992 7006
6993 7007 Input of physical quantities with units
6994 7008 \layout Standard
6995 7009
6996 7010 The module
6997 7011 \family typewriter
6998 7012 PhysicalQInput
6999 7013 \family default
7000 7014 allows a simplified form of input for physical quantities with units.
7001 7015 This file is meant to be used in conjunction with the
7002 7016 \family typewriter
7003 7017 PhysicalQInteractive
7004 7018 \family default
7005 7019 module (in the same directory) and
7006 7020 \family typewriter
7007 7021 Physics.PhysicalQuantities
7008 7022 \family default
7009 7023 from Konrad Hinsen's ScientificPython (
7010 7024 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
7011 7025
7012 7026 \end_inset
7013 7027
7014 7028 ).
7015 7029 \layout Standard
7016 7030
7017 7031 The
7018 7032 \family typewriter
7019 7033 Physics.PhysicalQuantities
7020 7034 \family default
7021 7035 module defines
7022 7036 \family typewriter
7023 7037 PhysicalQuantity
7024 7038 \family default
7025 7039 objects, but these must be declared as instances of a class.
7026 7040 For example, to define
7027 7041 \family typewriter
7028 7042 v
7029 7043 \family default
7030 7044 as a velocity of 3\SpecialChar ~
7031 7045 m/s, normally you would write:
7032 7046 \family typewriter
7033 7047
7034 7048 \newline
7035 7049 In [1]: v = PhysicalQuantity(3,'m/s')
7036 7050 \layout Standard
7037 7051
7038 7052 Using the
7039 7053 \family typewriter
7040 7054 PhysicalQ_Input
7041 7055 \family default
7042 7056 extension this can be input instead as:
7043 7057 \family typewriter
7044 7058
7045 7059 \newline
7046 7060 In [1]: v = 3 m/s
7047 7061 \family default
7048 7062
7049 7063 \newline
7050 7064 which is much more convenient for interactive use (even though it is blatantly
7051 7065 invalid Python syntax).
7052 7066 \layout Standard
7053 7067
7054 7068 The
7055 7069 \family typewriter
7056 7070 physics
7057 7071 \family default
7058 7072 profile supplied with IPython (enabled via
7059 7073 \family typewriter
7060 7074 'ipython -p physics'
7061 7075 \family default
7062 7076 ) uses these extensions, which you can also activate with:
7063 7077 \layout Standard
7064 7078
7065 7079
7066 7080 \family typewriter
7067 7081 from math import * # math MUST be imported BEFORE PhysicalQInteractive
7068 7082 \newline
7069 7083 from IPython.Extensions.PhysicalQInteractive import *
7070 7084 \newline
7071 7085 import IPython.Extensions.PhysicalQInput
7072 7086 \layout Section
7073 7087
7074 7088
7075 7089 \begin_inset LatexCommand \label{sec:IPython-as-shell}
7076 7090
7077 7091 \end_inset
7078 7092
7079 7093 IPython as a system shell
7080 7094 \layout Standard
7081 7095
7082 7096 IPython ships with a special profile called
7083 7097 \family typewriter
7084 7098 pysh
7085 7099 \family default
7086 7100 , which you can activate at the command line as
7087 7101 \family typewriter
7088 7102 `ipython -p pysh'
7089 7103 \family default
7090 7104 .
7091 7105 This loads
7092 7106 \family typewriter
7093 7107 InterpreterExec
7094 7108 \family default
7095 7109 , along with some additional facilities and a prompt customized for filesystem
7096 7110 navigation.
7097 7111 \layout Standard
7098 7112
7099 7113 Note that this does
7100 7114 \emph on
7101 7115 not
7102 7116 \emph default
7103 7117 make IPython a full-fledged system shell.
7104 7118 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
7105 7119 you'll suspend pysh itself, not the process you just started.
7106 7120
7107 7121 \layout Standard
7108 7122
7109 7123 What the shell profile allows you to do is to use the convenient and powerful
7110 7124 syntax of Python to do quick scripting at the command line.
7111 7125 Below we describe some of its features.
7112 7126 \layout Subsection
7113 7127
7114 7128 Aliases
7115 7129 \layout Standard
7116 7130
7117 7131 All of your
7118 7132 \family typewriter
7119 7133 $PATH
7120 7134 \family default
7121 7135 has been loaded as IPython aliases, so you should be able to type any normal
7122 7136 system command and have it executed.
7123 7137 See
7124 7138 \family typewriter
7125 7139 %alias?
7126 7140 \family default
7127 7141 and
7128 7142 \family typewriter
7129 7143 %unalias?
7130 7144 \family default
7131 7145 for details on the alias facilities.
7132 7146 See also
7133 7147 \family typewriter
7134 7148 %rehash?
7135 7149 \family default
7136 7150 and
7137 7151 \family typewriter
7138 7152 %rehashx?
7139 7153 \family default
7140 7154 for details on the mechanism used to load
7141 7155 \family typewriter
7142 7156 $PATH
7143 7157 \family default
7144 7158 .
7145 7159 \layout Subsection
7146 7160
7147 7161 Special syntax
7148 7162 \layout Standard
7149 7163
7150 7164 Any lines which begin with
7151 7165 \family typewriter
7152 7166 `~'
7153 7167 \family default
7154 7168 ,
7155 7169 \family typewriter
7156 7170 `/'
7157 7171 \family default
7158 7172 and
7159 7173 \family typewriter
7160 7174 `.'
7161 7175 \family default
7162 7176 will be executed as shell commands instead of as Python code.
7163 7177 The special escapes below are also recognized.
7164 7178
7165 7179 \family typewriter
7166 7180 !cmd
7167 7181 \family default
7168 7182 is valid in single or multi-line input, all others are only valid in single-lin
7169 7183 e input:
7170 7184 \layout Description
7171 7185
7172 7186
7173 7187 \family typewriter
7174 7188 !cmd
7175 7189 \family default
7176 7190 pass `cmd' directly to the shell
7177 7191 \layout Description
7178 7192
7179 7193
7180 7194 \family typewriter
7181 7195 !!cmd
7182 7196 \family default
7183 7197 execute `cmd' and return output as a list (split on `
7184 7198 \backslash
7185 7199 n')
7186 7200 \layout Description
7187 7201
7188 7202
7189 7203 \family typewriter
7190 7204 $var=cmd
7191 7205 \family default
7192 7206 capture output of cmd into var, as a string
7193 7207 \layout Description
7194 7208
7195 7209
7196 7210 \family typewriter
7197 7211 $$var=cmd
7198 7212 \family default
7199 7213 capture output of cmd into var, as a list (split on `
7200 7214 \backslash
7201 7215 n')
7202 7216 \layout Standard
7203 7217
7204 7218 The
7205 7219 \family typewriter
7206 7220 $
7207 7221 \family default
7208 7222 /
7209 7223 \family typewriter
7210 7224 $$
7211 7225 \family default
7212 7226 syntaxes make Python variables from system output, which you can later
7213 7227 use for further scripting.
7214 7228 The converse is also possible: when executing an alias or calling to the
7215 7229 system via
7216 7230 \family typewriter
7217 7231 !
7218 7232 \family default
7219 7233 /
7220 7234 \family typewriter
7221 7235 !!
7222 7236 \family default
7223 7237 , you can expand any python variable or expression by prepending it with
7224 7238
7225 7239 \family typewriter
7226 7240 $
7227 7241 \family default
7228 7242 .
7229 7243 Full details of the allowed syntax can be found in Python's PEP 215.
7230 7244 \layout Standard
7231 7245
7232 7246 A few brief examples will illustrate these (note that the indentation below
7233 7247 may be incorrectly displayed):
7234 7248 \layout Standard
7235 7249
7236 7250
7237 7251 \family typewriter
7238 7252 fperez[~/test]|3> !ls *s.py
7239 7253 \newline
7240 7254 scopes.py strings.py
7241 7255 \layout Standard
7242 7256
7243 7257 ls is an internal alias, so there's no need to use
7244 7258 \family typewriter
7245 7259 !
7246 7260 \family default
7247 7261 :
7248 7262 \layout Standard
7249 7263
7250 7264
7251 7265 \family typewriter
7252 7266 fperez[~/test]|4> ls *s.py
7253 7267 \newline
7254 7268 scopes.py* strings.py
7255 7269 \layout Standard
7256 7270
7257 7271 !!ls will return the output into a Python variable:
7258 7272 \layout Standard
7259 7273
7260 7274
7261 7275 \family typewriter
7262 7276 fperez[~/test]|5> !!ls *s.py
7263 7277 \newline
7264 7278
7265 7279 \begin_inset ERT
7266 7280 status Collapsed
7267 7281
7268 7282 \layout Standard
7269 7283
7270 7284 \backslash
7271 7285 hspace*{0mm}
7272 7286 \end_inset
7273 7287
7274 7288 \SpecialChar ~
7275 7289 \SpecialChar ~
7276 7290 \SpecialChar ~
7277 7291 \SpecialChar ~
7278 7292 \SpecialChar ~
7279 7293 \SpecialChar ~
7280 7294 \SpecialChar ~
7281 7295 \SpecialChar ~
7282 7296 \SpecialChar ~
7283 7297 \SpecialChar ~
7284 7298 \SpecialChar ~
7285 7299 \SpecialChar ~
7286 7300 \SpecialChar ~
7287 7301 \SpecialChar ~
7288 7302 <5> ['scopes.py', 'strings.py']
7289 7303 \newline
7290 7304 fperez[~/test]|6> print _5
7291 7305 \newline
7292 7306 ['scopes.py', 'strings.py']
7293 7307 \layout Standard
7294 7308
7295 7309
7296 7310 \family typewriter
7297 7311 $
7298 7312 \family default
7299 7313 and
7300 7314 \family typewriter
7301 7315 $$
7302 7316 \family default
7303 7317 allow direct capture to named variables:
7304 7318 \layout Standard
7305 7319
7306 7320
7307 7321 \family typewriter
7308 7322 fperez[~/test]|7> $astr = ls *s.py
7309 7323 \newline
7310 7324 fperez[~/test]|8> astr
7311 7325 \newline
7312 7326
7313 7327 \begin_inset ERT
7314 7328 status Collapsed
7315 7329
7316 7330 \layout Standard
7317 7331
7318 7332 \backslash
7319 7333 hspace*{0mm}
7320 7334 \end_inset
7321 7335
7322 7336 \SpecialChar ~
7323 7337 \SpecialChar ~
7324 7338 \SpecialChar ~
7325 7339 \SpecialChar ~
7326 7340 \SpecialChar ~
7327 7341 \SpecialChar ~
7328 7342 \SpecialChar ~
7329 7343 \SpecialChar ~
7330 7344 \SpecialChar ~
7331 7345 \SpecialChar ~
7332 7346 \SpecialChar ~
7333 7347 \SpecialChar ~
7334 7348 \SpecialChar ~
7335 7349 \SpecialChar ~
7336 7350 <8> 'scopes.py
7337 7351 \backslash
7338 7352 nstrings.py'
7339 7353 \layout Standard
7340 7354
7341 7355
7342 7356 \family typewriter
7343 7357 fperez[~/test]|9> $$alist = ls *s.py
7344 7358 \newline
7345 7359 fperez[~/test]|10> alist
7346 7360 \newline
7347 7361
7348 7362 \begin_inset ERT
7349 7363 status Collapsed
7350 7364
7351 7365 \layout Standard
7352 7366
7353 7367 \backslash
7354 7368 hspace*{0mm}
7355 7369 \end_inset
7356 7370
7357 7371 \SpecialChar ~
7358 7372 \SpecialChar ~
7359 7373 \SpecialChar ~
7360 7374 \SpecialChar ~
7361 7375 \SpecialChar ~
7362 7376 \SpecialChar ~
7363 7377 \SpecialChar ~
7364 7378 \SpecialChar ~
7365 7379 \SpecialChar ~
7366 7380 \SpecialChar ~
7367 7381 \SpecialChar ~
7368 7382 \SpecialChar ~
7369 7383 \SpecialChar ~
7370 7384 \SpecialChar ~
7371 7385 <10> ['scopes.py', 'strings.py']
7372 7386 \layout Standard
7373 7387
7374 7388 alist is now a normal python list you can loop over.
7375 7389 Using
7376 7390 \family typewriter
7377 7391 $
7378 7392 \family default
7379 7393 will expand back the python values when alias calls are made:
7380 7394 \layout Standard
7381 7395
7382 7396
7383 7397 \family typewriter
7384 7398 fperez[~/test]|11> for f in alist:
7385 7399 \newline
7386 7400
7387 7401 \begin_inset ERT
7388 7402 status Collapsed
7389 7403
7390 7404 \layout Standard
7391 7405
7392 7406 \backslash
7393 7407 hspace*{0mm}
7394 7408 \end_inset
7395 7409
7396 7410 \SpecialChar ~
7397 7411 \SpecialChar ~
7398 7412 \SpecialChar ~
7399 7413 \SpecialChar ~
7400 7414 \SpecialChar ~
7401 7415 \SpecialChar ~
7402 7416 \SpecialChar ~
7403 7417 \SpecialChar ~
7404 7418 \SpecialChar ~
7405 7419 \SpecialChar ~
7406 7420 \SpecialChar ~
7407 7421 \SpecialChar ~
7408 7422 \SpecialChar ~
7409 7423 \SpecialChar ~
7410 7424 |..> \SpecialChar ~
7411 7425 \SpecialChar ~
7412 7426 \SpecialChar ~
7413 7427 \SpecialChar ~
7414 7428 print 'file',f,
7415 7429 \newline
7416 7430
7417 7431 \begin_inset ERT
7418 7432 status Collapsed
7419 7433
7420 7434 \layout Standard
7421 7435
7422 7436 \backslash
7423 7437 hspace*{0mm}
7424 7438 \end_inset
7425 7439
7426 7440 \SpecialChar ~
7427 7441 \SpecialChar ~
7428 7442 \SpecialChar ~
7429 7443 \SpecialChar ~
7430 7444 \SpecialChar ~
7431 7445 \SpecialChar ~
7432 7446 \SpecialChar ~
7433 7447 \SpecialChar ~
7434 7448 \SpecialChar ~
7435 7449 \SpecialChar ~
7436 7450 \SpecialChar ~
7437 7451 \SpecialChar ~
7438 7452 \SpecialChar ~
7439 7453 \SpecialChar ~
7440 7454 |..> \SpecialChar ~
7441 7455 \SpecialChar ~
7442 7456 \SpecialChar ~
7443 7457 \SpecialChar ~
7444 7458 wc -l $f
7445 7459 \newline
7446 7460
7447 7461 \begin_inset ERT
7448 7462 status Collapsed
7449 7463
7450 7464 \layout Standard
7451 7465
7452 7466 \backslash
7453 7467 hspace*{0mm}
7454 7468 \end_inset
7455 7469
7456 7470 \SpecialChar ~
7457 7471 \SpecialChar ~
7458 7472 \SpecialChar ~
7459 7473 \SpecialChar ~
7460 7474 \SpecialChar ~
7461 7475 \SpecialChar ~
7462 7476 \SpecialChar ~
7463 7477 \SpecialChar ~
7464 7478 \SpecialChar ~
7465 7479 \SpecialChar ~
7466 7480 \SpecialChar ~
7467 7481 \SpecialChar ~
7468 7482 \SpecialChar ~
7469 7483 \SpecialChar ~
7470 7484 |..>
7471 7485 \newline
7472 7486 file scopes.py 13 scopes.py
7473 7487 \newline
7474 7488 file strings.py 4 strings.py
7475 7489 \layout Standard
7476 7490
7477 7491 Note that you may need to protect your variables with braces if you want
7478 7492 to append strings to their names.
7479 7493 To copy all files in alist to
7480 7494 \family typewriter
7481 7495 .bak
7482 7496 \family default
7483 7497 extensions, you must use:
7484 7498 \layout Standard
7485 7499
7486 7500
7487 7501 \family typewriter
7488 7502 fperez[~/test]|12> for f in alist:
7489 7503 \newline
7490 7504
7491 7505 \begin_inset ERT
7492 7506 status Collapsed
7493 7507
7494 7508 \layout Standard
7495 7509
7496 7510 \backslash
7497 7511 hspace*{0mm}
7498 7512 \end_inset
7499 7513
7500 7514 \SpecialChar ~
7501 7515 \SpecialChar ~
7502 7516 \SpecialChar ~
7503 7517 \SpecialChar ~
7504 7518 \SpecialChar ~
7505 7519 \SpecialChar ~
7506 7520 \SpecialChar ~
7507 7521 \SpecialChar ~
7508 7522 \SpecialChar ~
7509 7523 \SpecialChar ~
7510 7524 \SpecialChar ~
7511 7525 \SpecialChar ~
7512 7526 \SpecialChar ~
7513 7527 \SpecialChar ~
7514 7528 |..> \SpecialChar ~
7515 7529 \SpecialChar ~
7516 7530 \SpecialChar ~
7517 7531 \SpecialChar ~
7518 7532 cp $f ${f}.bak
7519 7533 \layout Standard
7520 7534
7521 7535 If you try using
7522 7536 \family typewriter
7523 7537 $f.bak
7524 7538 \family default
7525 7539 , you'll get an AttributeError exception saying that your string object
7526 7540 doesn't have a
7527 7541 \family typewriter
7528 7542 .bak
7529 7543 \family default
7530 7544 attribute.
7531 7545 This is because the
7532 7546 \family typewriter
7533 7547 $
7534 7548 \family default
7535 7549 expansion mechanism allows you to expand full Python expressions:
7536 7550 \layout Standard
7537 7551
7538 7552
7539 7553 \family typewriter
7540 7554 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7541 7555 \newline
7542 7556 sys.platform is: linux2
7543 7557 \layout Standard
7544 7558
7545 7559 IPython's input history handling is still active, which allows you to rerun
7546 7560 a single block of multi-line input by simply using exec:
7547 7561 \newline
7548 7562
7549 7563 \family typewriter
7550 7564 fperez[~/test]|14> $$alist = ls *.eps
7551 7565 \newline
7552 7566 fperez[~/test]|15> exec _i11
7553 7567 \newline
7554 7568 file image2.eps 921 image2.eps
7555 7569 \newline
7556 7570 file image.eps 921 image.eps
7557 7571 \layout Standard
7558 7572
7559 7573 While these are new special-case syntaxes, they are designed to allow very
7560 7574 efficient use of the shell with minimal typing.
7561 7575 At an interactive shell prompt, conciseness of expression wins over readability.
7562 7576 \layout Subsection
7563 7577
7564 7578 Useful functions and modules
7565 7579 \layout Standard
7566 7580
7567 7581 The os, sys and shutil modules from the Python standard library are automaticall
7568 7582 y loaded.
7569 7583 Some additional functions, useful for shell usage, are listed below.
7570 7584 You can request more help about them with `
7571 7585 \family typewriter
7572 7586 ?
7573 7587 \family default
7574 7588 '.
7575 7589 \layout Description
7576 7590
7577 7591
7578 7592 \family typewriter
7579 7593 shell
7580 7594 \family default
7581 7595 - execute a command in the underlying system shell
7582 7596 \layout Description
7583 7597
7584 7598
7585 7599 \family typewriter
7586 7600 system
7587 7601 \family default
7588 7602 - like
7589 7603 \family typewriter
7590 7604 shell()
7591 7605 \family default
7592 7606 , but return the exit status of the command
7593 7607 \layout Description
7594 7608
7595 7609
7596 7610 \family typewriter
7597 7611 sout
7598 7612 \family default
7599 7613 - capture the output of a command as a string
7600 7614 \layout Description
7601 7615
7602 7616
7603 7617 \family typewriter
7604 7618 lout
7605 7619 \family default
7606 7620 - capture the output of a command as a list (split on `
7607 7621 \backslash
7608 7622 n')
7609 7623 \layout Description
7610 7624
7611 7625
7612 7626 \family typewriter
7613 7627 getoutputerror
7614 7628 \family default
7615 7629 - capture (output,error) of a shell commandss
7616 7630 \layout Standard
7617 7631
7618 7632
7619 7633 \family typewriter
7620 7634 sout
7621 7635 \family default
7622 7636 /
7623 7637 \family typewriter
7624 7638 lout
7625 7639 \family default
7626 7640 are the functional equivalents of
7627 7641 \family typewriter
7628 7642 $
7629 7643 \family default
7630 7644 /
7631 7645 \family typewriter
7632 7646 $$
7633 7647 \family default
7634 7648 .
7635 7649 They are provided to allow you to capture system output in the middle of
7636 7650 true python code, function definitions, etc (where
7637 7651 \family typewriter
7638 7652 $
7639 7653 \family default
7640 7654 and
7641 7655 \family typewriter
7642 7656 $$
7643 7657 \family default
7644 7658 are invalid).
7645 7659 \layout Subsection
7646 7660
7647 7661 Directory management
7648 7662 \layout Standard
7649 7663
7650 7664 Since each command passed by pysh to the underlying system is executed in
7651 7665 a subshell which exits immediately, you can NOT use !cd to navigate the
7652 7666 filesystem.
7653 7667 \layout Standard
7654 7668
7655 7669 Pysh provides its own builtin
7656 7670 \family typewriter
7657 7671 `%cd
7658 7672 \family default
7659 7673 ' magic command to move in the filesystem (the
7660 7674 \family typewriter
7661 7675 %
7662 7676 \family default
7663 7677 is not required with automagic on).
7664 7678 It also maintains a list of visited directories (use
7665 7679 \family typewriter
7666 7680 %dhist
7667 7681 \family default
7668 7682 to see it) and allows direct switching to any of them.
7669 7683 Type
7670 7684 \family typewriter
7671 7685 `cd?
7672 7686 \family default
7673 7687 ' for more details.
7674 7688 \layout Standard
7675 7689
7676 7690
7677 7691 \family typewriter
7678 7692 %pushd
7679 7693 \family default
7680 7694 ,
7681 7695 \family typewriter
7682 7696 %popd
7683 7697 \family default
7684 7698 and
7685 7699 \family typewriter
7686 7700 %dirs
7687 7701 \family default
7688 7702 are provided for directory stack handling.
7689 7703 \layout Subsection
7690 7704
7691 7705 Prompt customization
7692 7706 \layout Standard
7693 7707
7694 7708 The supplied
7695 7709 \family typewriter
7696 7710 ipythonrc-pysh
7697 7711 \family default
7698 7712 profile comes with an example of a very colored and detailed prompt, mainly
7699 7713 to serve as an illustration.
7700 7714 The valid escape sequences, besides color names, are:
7701 7715 \layout Description
7702 7716
7703 7717
7704 7718 \backslash
7705 7719 # - Prompt number.
7706 7720 \layout Description
7707 7721
7708 7722
7709 7723 \backslash
7710 7724 D - Dots, as many as there are digits in
7711 7725 \backslash
7712 7726 # (so they align).
7713 7727 \layout Description
7714 7728
7715 7729
7716 7730 \backslash
7717 7731 w - Current working directory (cwd).
7718 7732 \layout Description
7719 7733
7720 7734
7721 7735 \backslash
7722 7736 W - Basename of current working directory.
7723 7737 \layout Description
7724 7738
7725 7739
7726 7740 \backslash
7727 7741 X
7728 7742 \emph on
7729 7743 N
7730 7744 \emph default
7731 7745 - Where
7732 7746 \emph on
7733 7747 N
7734 7748 \emph default
7735 7749 =0..5.
7736 7750 N terms of the cwd, with $HOME written as ~.
7737 7751 \layout Description
7738 7752
7739 7753
7740 7754 \backslash
7741 7755 Y
7742 7756 \emph on
7743 7757 N
7744 7758 \emph default
7745 7759 - Where
7746 7760 \emph on
7747 7761 N
7748 7762 \emph default
7749 7763 =0..5.
7750 7764 Like X
7751 7765 \emph on
7752 7766 N
7753 7767 \emph default
7754 7768 , but if ~ is term
7755 7769 \emph on
7756 7770 N
7757 7771 \emph default
7758 7772 +1 it's also shown.
7759 7773 \layout Description
7760 7774
7761 7775
7762 7776 \backslash
7763 7777 u - Username.
7764 7778 \layout Description
7765 7779
7766 7780
7767 7781 \backslash
7768 7782 H - Full hostname.
7769 7783 \layout Description
7770 7784
7771 7785
7772 7786 \backslash
7773 7787 h - Hostname up to first '.'
7774 7788 \layout Description
7775 7789
7776 7790
7777 7791 \backslash
7778 7792 $ - Root symbol ($ or #).
7779 7793
7780 7794 \layout Description
7781 7795
7782 7796
7783 7797 \backslash
7784 7798 t - Current time, in H:M:S format.
7785 7799 \layout Description
7786 7800
7787 7801
7788 7802 \backslash
7789 7803 v - IPython release version.
7790 7804
7791 7805 \layout Description
7792 7806
7793 7807
7794 7808 \backslash
7795 7809 n - Newline.
7796 7810
7797 7811 \layout Description
7798 7812
7799 7813
7800 7814 \backslash
7801 7815 r - Carriage return.
7802 7816
7803 7817 \layout Description
7804 7818
7805 7819
7806 7820 \backslash
7807 7821
7808 7822 \backslash
7809 7823 - An explicitly escaped '
7810 7824 \backslash
7811 7825 '.
7812 7826 \layout Standard
7813 7827
7814 7828 You can configure your prompt colors using any ANSI color escape.
7815 7829 Each color escape sets the color for any subsequent text, until another
7816 7830 escape comes in and changes things.
7817 7831 The valid color escapes are:
7818 7832 \layout Description
7819 7833
7820 7834
7821 7835 \backslash
7822 7836 C_Black
7823 7837 \layout Description
7824 7838
7825 7839
7826 7840 \backslash
7827 7841 C_Blue
7828 7842 \layout Description
7829 7843
7830 7844
7831 7845 \backslash
7832 7846 C_Brown
7833 7847 \layout Description
7834 7848
7835 7849
7836 7850 \backslash
7837 7851 C_Cyan
7838 7852 \layout Description
7839 7853
7840 7854
7841 7855 \backslash
7842 7856 C_DarkGray
7843 7857 \layout Description
7844 7858
7845 7859
7846 7860 \backslash
7847 7861 C_Green
7848 7862 \layout Description
7849 7863
7850 7864
7851 7865 \backslash
7852 7866 C_LightBlue
7853 7867 \layout Description
7854 7868
7855 7869
7856 7870 \backslash
7857 7871 C_LightCyan
7858 7872 \layout Description
7859 7873
7860 7874
7861 7875 \backslash
7862 7876 C_LightGray
7863 7877 \layout Description
7864 7878
7865 7879
7866 7880 \backslash
7867 7881 C_LightGreen
7868 7882 \layout Description
7869 7883
7870 7884
7871 7885 \backslash
7872 7886 C_LightPurple
7873 7887 \layout Description
7874 7888
7875 7889
7876 7890 \backslash
7877 7891 C_LightRed
7878 7892 \layout Description
7879 7893
7880 7894
7881 7895 \backslash
7882 7896 C_Purple
7883 7897 \layout Description
7884 7898
7885 7899
7886 7900 \backslash
7887 7901 C_Red
7888 7902 \layout Description
7889 7903
7890 7904
7891 7905 \backslash
7892 7906 C_White
7893 7907 \layout Description
7894 7908
7895 7909
7896 7910 \backslash
7897 7911 C_Yellow
7898 7912 \layout Description
7899 7913
7900 7914
7901 7915 \backslash
7902 7916 C_Normal Stop coloring, defaults to your terminal settings.
7903 7917 \layout Section
7904 7918
7905 7919
7906 7920 \begin_inset LatexCommand \label{sec:Threading-support}
7907 7921
7908 7922 \end_inset
7909 7923
7910 7924 Threading support
7911 7925 \layout Standard
7912 7926
7913 7927
7914 7928 \series bold
7915 7929 WARNING:
7916 7930 \series default
7917 7931 The threading support is still somewhat experimental, and it has only seen
7918 7932 reasonable testing under Linux.
7919 7933 Threaded code is particularly tricky to debug, and it tends to show extremely
7920 7934 platform-dependent behavior.
7921 7935 Since I only have access to Linux machines, I will have to rely on user's
7922 7936 experiences and assistance for this area of IPython to improve under other
7923 7937 platforms.
7924 7938 \layout Standard
7925 7939
7926 7940 IPython, via the
7927 7941 \family typewriter
7928 7942 -gthread
7929 7943 \family default
7930 7944 ,
7931 7945 \family typewriter
7932 7946 -qthread
7933 7947 \family default
7934 7948 and
7935 7949 \family typewriter
7936 7950 -wthread
7937 7951 \family default
7938 7952 options (described in Sec.\SpecialChar ~
7939 7953
7940 7954 \begin_inset LatexCommand \ref{sec:threading-opts}
7941 7955
7942 7956 \end_inset
7943 7957
7944 7958 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7945 7959 respectively.
7946 7960 These GUI toolkits need to control the python main loop of execution, so
7947 7961 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7948 7962 will immediately freeze the shell.
7949 7963
7950 7964 \layout Standard
7951 7965
7952 7966 IPython, with one of these options (you can only use one at a time), separates
7953 7967 the graphical loop and IPython's code execution run into different threads.
7954 7968 This allows you to test interactively (with
7955 7969 \family typewriter
7956 7970 %run
7957 7971 \family default
7958 7972 , for example) your GUI code without blocking.
7959 7973 \layout Standard
7960 7974
7961 7975 A nice mini-tutorial on using IPython along with the Qt Designer application
7962 7976 is available at the SciPy wiki:
7963 7977 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7964 7978
7965 7979 \end_inset
7966 7980
7967 7981 .
7968 7982 \layout Subsection
7969 7983
7970 7984 Tk issues
7971 7985 \layout Standard
7972 7986
7973 7987 As indicated in Sec.\SpecialChar ~
7974 7988
7975 7989 \begin_inset LatexCommand \ref{sec:threading-opts}
7976 7990
7977 7991 \end_inset
7978 7992
7979 7993 , a special
7980 7994 \family typewriter
7981 7995 -tk
7982 7996 \family default
7983 7997 option is provided to try and allow Tk graphical applications to coexist
7984 7998 interactively with WX, Qt or GTK ones.
7985 7999 Whether this works at all, however, is very platform and configuration
7986 8000 dependent.
7987 8001 Please experiment with simple test cases before committing to using this
7988 8002 combination of Tk and GTK/Qt/WX threading in a production environment.
7989 8003 \layout Subsection
7990 8004
7991 8005 Signals and Threads
7992 8006 \layout Standard
7993 8007
7994 8008 When any of the thread systems (GTK, Qt or WX) are active, either directly
7995 8009 or via
7996 8010 \family typewriter
7997 8011 -pylab
7998 8012 \family default
7999 8013 with a threaded backend, it is impossible to interrupt long-running Python
8000 8014 code via
8001 8015 \family typewriter
8002 8016 Ctrl-C
8003 8017 \family default
8004 8018 .
8005 8019 IPython can not pass the KeyboardInterrupt exception (or the underlying
8006 8020
8007 8021 \family typewriter
8008 8022 SIGINT
8009 8023 \family default
8010 8024 ) across threads, so any long-running process started from IPython will
8011 8025 run to completion, or will have to be killed via an external (OS-based)
8012 8026 mechanism.
8013 8027 \layout Standard
8014 8028
8015 8029 To the best of my knowledge, this limitation is imposed by the Python interprete
8016 8030 r itself, and it comes from the difficulty of writing portable signal/threaded
8017 8031 code.
8018 8032 If any user is an expert on this topic and can suggest a better solution,
8019 8033 I would love to hear about it.
8020 8034 In the IPython sources, look at the
8021 8035 \family typewriter
8022 8036 Shell.py
8023 8037 \family default
8024 8038 module, and in particular at the
8025 8039 \family typewriter
8026 8040 runcode()
8027 8041 \family default
8028 8042 method.
8029 8043
8030 8044 \layout Subsection
8031 8045
8032 8046 I/O pitfalls
8033 8047 \layout Standard
8034 8048
8035 8049 Be mindful that the Python interpreter switches between threads every
8036 8050 \begin_inset Formula $N$
8037 8051 \end_inset
8038 8052
8039 8053 bytecodes, where the default value as of Python\SpecialChar ~
8040 8054 2.3 is
8041 8055 \begin_inset Formula $N=100.$
8042 8056 \end_inset
8043 8057
8044 8058 This value can be read by using the
8045 8059 \family typewriter
8046 8060 sys.getcheckinterval()
8047 8061 \family default
8048 8062 function, and it can be reset via
8049 8063 \family typewriter
8050 8064 sys.setcheckinterval(
8051 8065 \emph on
8052 8066 N
8053 8067 \emph default
8054 8068 )
8055 8069 \family default
8056 8070 .
8057 8071 This switching of threads can cause subtly confusing effects if one of
8058 8072 your threads is doing file I/O.
8059 8073 In text mode, most systems only flush file buffers when they encounter
8060 8074 a
8061 8075 \family typewriter
8062 8076 `
8063 8077 \backslash
8064 8078 n'
8065 8079 \family default
8066 8080 .
8067 8081 An instruction as simple as
8068 8082 \family typewriter
8069 8083
8070 8084 \newline
8071 8085 \SpecialChar ~
8072 8086 \SpecialChar ~
8073 8087 print >> filehandle,
8074 8088 \begin_inset Quotes eld
8075 8089 \end_inset
8076 8090
8077 8091 hello world
8078 8092 \begin_inset Quotes erd
8079 8093 \end_inset
8080 8094
8081 8095
8082 8096 \family default
8083 8097
8084 8098 \newline
8085 8099 actually consists of several bytecodes, so it is possible that the newline
8086 8100 does not reach your file before the next thread switch.
8087 8101 Similarly, if you are writing to a file in binary mode, the file won't
8088 8102 be flushed until the buffer fills, and your other thread may see apparently
8089 8103 truncated files.
8090 8104
8091 8105 \layout Standard
8092 8106
8093 8107 For this reason, if you are using IPython's thread support and have (for
8094 8108 example) a GUI application which will read data generated by files written
8095 8109 to from the IPython thread, the safest approach is to open all of your
8096 8110 files in unbuffered mode (the third argument to the
8097 8111 \family typewriter
8098 8112 file/open
8099 8113 \family default
8100 8114 function is the buffering value):
8101 8115 \newline
8102 8116
8103 8117 \family typewriter
8104 8118 \SpecialChar ~
8105 8119 \SpecialChar ~
8106 8120 filehandle = open(filename,mode,0)
8107 8121 \layout Standard
8108 8122
8109 8123 This is obviously a brute force way of avoiding race conditions with the
8110 8124 file buffering.
8111 8125 If you want to do it cleanly, and you have a resource which is being shared
8112 8126 by the interactive IPython loop and your GUI thread, you should really
8113 8127 handle it with thread locking and syncrhonization properties.
8114 8128 The Python documentation discusses these.
8115 8129 \layout Section
8116 8130
8117 8131
8118 8132 \begin_inset LatexCommand \label{sec:interactive-demos}
8119 8133
8120 8134 \end_inset
8121 8135
8122 8136 Interactive demos with IPython
8123 8137 \layout Standard
8124 8138
8125 8139 IPython ships with a basic system for running scripts interactively in sections,
8126 8140 useful when presenting code to audiences.
8127 8141 A few tags embedded in comments (so that the script remains valid Python
8128 8142 code) divide a file into separate blocks, and the demo can be run one block
8129 8143 at a time, with IPython printing (with syntax highlighting) the block before
8130 8144 executing it, and returning to the interactive prompt after each block.
8131 8145 The interactive namespace is updated after each block is run with the contents
8132 8146 of the demo's namespace.
8133 8147 \layout Standard
8134 8148
8135 8149 This allows you to show a piece of code, run it and then execute interactively
8136 8150 commands based on the variables just created.
8137 8151 Once you want to continue, you simply execute the next block of the demo.
8138 8152 The following listing shows the markup necessary for dividing a script
8139 8153 into sections for execution as a demo.
8140 8154 \layout Standard
8141 8155
8142 8156
8143 8157 \begin_inset ERT
8144 8158 status Open
8145 8159
8146 8160 \layout Standard
8147 8161
8148 8162 \backslash
8149 8163 codelist{examples/example-demo.py}
8150 8164 \end_inset
8151 8165
8152 8166
8153 8167 \layout Standard
8154 8168
8155 8169 In order to run a file as a demo, you must first make a
8156 8170 \family typewriter
8157 8171 Demo
8158 8172 \family default
8159 8173 object out of it.
8160 8174 If the file is named
8161 8175 \family typewriter
8162 8176 myscript.py
8163 8177 \family default
8164 8178 , the following code will make a demo:
8165 8179 \layout LyX-Code
8166 8180
8167 8181 from IPython.demo import Demo
8168 8182 \layout LyX-Code
8169 8183
8170 8184 mydemo = Demo('myscript.py')
8171 8185 \layout Standard
8172 8186
8173 8187 This creates the
8174 8188 \family typewriter
8175 8189 mydemo
8176 8190 \family default
8177 8191 object, whose blocks you run one at a time by simply calling the object
8178 8192 with no arguments.
8179 8193 If you have autocall active in IPython (the default), all you need to do
8180 8194 is type
8181 8195 \layout LyX-Code
8182 8196
8183 8197 mydemo
8184 8198 \layout Standard
8185 8199
8186 8200 and IPython will call it, executing each block.
8187 8201 Demo objects can be restarted, you can move forward or back skipping blocks,
8188 8202 re-execute the last block, etc.
8189 8203 Simply use the Tab key on a demo object to see its methods, and call
8190 8204 \family typewriter
8191 8205 `?'
8192 8206 \family default
8193 8207 on them to see their docstrings for more usage details.
8194 8208 In addition, the
8195 8209 \family typewriter
8196 8210 demo
8197 8211 \family default
8198 8212 module itself contains a comprehensive docstring, which you can access
8199 8213 via
8200 8214 \layout LyX-Code
8201 8215
8202 8216 from IPython import demo
8203 8217 \layout LyX-Code
8204 8218
8205 8219 demo?
8206 8220 \layout Standard
8207 8221
8208 8222
8209 8223 \series bold
8210 8224 Limitations:
8211 8225 \series default
8212 8226 It is important to note that these demos are limited to fairly simple uses.
8213 8227 In particular, you can
8214 8228 \emph on
8215 8229 not
8216 8230 \emph default
8217 8231 put division marks in indented code (loops, if statements, function definitions
8218 8232 , etc.) Supporting something like this would basically require tracking the
8219 8233 internal execution state of the Python interpreter, so only top-level divisions
8220 8234 are allowed.
8221 8235 If you want to be able to open an IPython instance at an arbitrary point
8222 8236 in a program, you can use IPython's embedding facilities, described in
8223 8237 detail in Sec\SpecialChar \@.
8224 8238 \SpecialChar ~
8225 8239
8226 8240 \begin_inset LatexCommand \ref{sec:embed}
8227 8241
8228 8242 \end_inset
8229 8243
8230 8244 .
8231 8245 \layout Section
8232 8246
8233 8247
8234 8248 \begin_inset LatexCommand \label{sec:matplotlib-support}
8235 8249
8236 8250 \end_inset
8237 8251
8238 8252 Plotting with
8239 8253 \family typewriter
8240 8254 matplotlib
8241 8255 \family default
8242 8256
8243 8257 \layout Standard
8244 8258
8245 8259 The matplotlib library (
8246 8260 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
8247 8261
8248 8262 \end_inset
8249 8263
8250 8264 ) provides high quality 2D plotting for Python.
8251 8265 Matplotlib can produce plots on screen using a variety of GUI toolkits,
8252 8266 including Tk, GTK and WXPython.
8253 8267 It also provides a number of commands useful for scientific computing,
8254 8268 all with a syntax compatible with that of the popular Matlab program.
8255 8269 \layout Standard
8256 8270
8257 8271 IPython accepts the special option
8258 8272 \family typewriter
8259 8273 -pylab
8260 8274 \family default
8261 8275 (Sec.\SpecialChar ~
8262 8276
8263 8277 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
8264 8278
8265 8279 \end_inset
8266 8280
8267 8281 ).
8268 8282 This configures it to support matplotlib, honoring the settings in the
8269 8283
8270 8284 \family typewriter
8271 8285 .matplotlibrc
8272 8286 \family default
8273 8287 file.
8274 8288 IPython will detect the user's choice of matplotlib GUI backend, and automatica
8275 8289 lly select the proper threading model to prevent blocking.
8276 8290 It also sets matplotlib in interactive mode and modifies
8277 8291 \family typewriter
8278 8292 %run
8279 8293 \family default
8280 8294 slightly, so that any matplotlib-based script can be executed using
8281 8295 \family typewriter
8282 8296 %run
8283 8297 \family default
8284 8298 and the final
8285 8299 \family typewriter
8286 8300 show()
8287 8301 \family default
8288 8302 command does not block the interactive shell.
8289 8303 \layout Standard
8290 8304
8291 8305 The
8292 8306 \family typewriter
8293 8307 -pylab
8294 8308 \family default
8295 8309 option must be given first in order for IPython to configure its threading
8296 8310 mode.
8297 8311 However, you can still issue other options afterwards.
8298 8312 This allows you to have a matplotlib-based environment customized with
8299 8313 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
8300 8314
8301 8315 \begin_inset LatexCommand \ref{sec:profiles}
8302 8316
8303 8317 \end_inset
8304 8318
8305 8319 ): ``
8306 8320 \family typewriter
8307 8321 ipython -pylab -p myprofile
8308 8322 \family default
8309 8323 '' will load the profile defined in
8310 8324 \family typewriter
8311 8325 ipythonrc-myprofile
8312 8326 \family default
8313 8327 after configuring matplotlib.
8314 8328 \layout Section
8315 8329
8316 8330
8317 8331 \begin_inset LatexCommand \label{sec:Gnuplot}
8318 8332
8319 8333 \end_inset
8320 8334
8321 8335 Plotting with
8322 8336 \family typewriter
8323 8337 Gnuplot
8324 8338 \layout Standard
8325 8339
8326 8340 Through the magic extension system described in sec.
8327 8341
8328 8342 \begin_inset LatexCommand \ref{sec:magic}
8329 8343
8330 8344 \end_inset
8331 8345
8332 8346 , IPython incorporates a mechanism for conveniently interfacing with the
8333 8347 Gnuplot system (
8334 8348 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8335 8349
8336 8350 \end_inset
8337 8351
8338 8352 ).
8339 8353 Gnuplot is a very complete 2D and 3D plotting package available for many
8340 8354 operating systems and commonly included in modern Linux distributions.
8341 8355
8342 8356 \layout Standard
8343 8357
8344 8358 Besides having Gnuplot installed, this functionality requires the
8345 8359 \family typewriter
8346 8360 Gnuplot.py
8347 8361 \family default
8348 8362 module for interfacing python with Gnuplot.
8349 8363 It can be downloaded from:
8350 8364 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8351 8365
8352 8366 \end_inset
8353 8367
8354 8368 .
8355 8369 \layout Subsection
8356 8370
8357 8371 Proper Gnuplot configuration
8358 8372 \layout Standard
8359 8373
8360 8374 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8361 8375 However, as of
8362 8376 \family typewriter
8363 8377 Gnuplot.py
8364 8378 \family default
8365 8379 version 1.7, a new option was added to communicate between Python and Gnuplot
8366 8380 via FIFOs (pipes).
8367 8381 This mechanism, while fast, also breaks the mouse system.
8368 8382 You must therefore set the variable
8369 8383 \family typewriter
8370 8384 prefer_fifo_data
8371 8385 \family default
8372 8386 to
8373 8387 \family typewriter
8374 8388 0
8375 8389 \family default
8376 8390 in file
8377 8391 \family typewriter
8378 8392 gp_unix.py
8379 8393 \family default
8380 8394 if you wish to keep the interactive mouse and keyboard features working
8381 8395 properly (
8382 8396 \family typewriter
8383 8397 prefer_inline_data
8384 8398 \family default
8385 8399 also must be
8386 8400 \family typewriter
8387 8401 0
8388 8402 \family default
8389 8403 , but this is the default so unless you've changed it manually you should
8390 8404 be fine).
8391 8405 \layout Standard
8392 8406
8393 8407 'Out of the box', Gnuplot is configured with a rather poor set of size,
8394 8408 color and linewidth choices which make the graphs fairly hard to read on
8395 8409 modern high-resolution displays (although they work fine on old 640x480
8396 8410 ones).
8397 8411 Below is a section of my
8398 8412 \family typewriter
8399 8413 .Xdefaults
8400 8414 \family default
8401 8415 file which I use for having a more convenient Gnuplot setup.
8402 8416 Remember to load it by running
8403 8417 \family typewriter
8404 8418 `xrdb .Xdefaults`
8405 8419 \family default
8406 8420 :
8407 8421 \layout Standard
8408 8422
8409 8423
8410 8424 \family typewriter
8411 8425 !******************************************************************
8412 8426 \newline
8413 8427 ! gnuplot options
8414 8428 \newline
8415 8429 ! modify this for a convenient window size
8416 8430 \newline
8417 8431 gnuplot*geometry: 780x580
8418 8432 \layout Standard
8419 8433
8420 8434
8421 8435 \family typewriter
8422 8436 ! on-screen font (not for PostScript)
8423 8437 \newline
8424 8438 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8425 8439 \layout Standard
8426 8440
8427 8441
8428 8442 \family typewriter
8429 8443 ! color options
8430 8444 \newline
8431 8445 gnuplot*background: black
8432 8446 \newline
8433 8447 gnuplot*textColor: white
8434 8448 \newline
8435 8449 gnuplot*borderColor: white
8436 8450 \newline
8437 8451 gnuplot*axisColor: white
8438 8452 \newline
8439 8453 gnuplot*line1Color: red
8440 8454 \newline
8441 8455 gnuplot*line2Color: green
8442 8456 \newline
8443 8457 gnuplot*line3Color: blue
8444 8458 \newline
8445 8459 gnuplot*line4Color: magenta
8446 8460 \newline
8447 8461 gnuplot*line5Color: cyan
8448 8462 \newline
8449 8463 gnuplot*line6Color: sienna
8450 8464 \newline
8451 8465 gnuplot*line7Color: orange
8452 8466 \newline
8453 8467 gnuplot*line8Color: coral
8454 8468 \layout Standard
8455 8469
8456 8470
8457 8471 \family typewriter
8458 8472 ! multiplicative factor for point styles
8459 8473 \newline
8460 8474 gnuplot*pointsize: 2
8461 8475 \layout Standard
8462 8476
8463 8477
8464 8478 \family typewriter
8465 8479 ! line width options (in pixels)
8466 8480 \newline
8467 8481 gnuplot*borderWidth: 2
8468 8482 \newline
8469 8483 gnuplot*axisWidth: 2
8470 8484 \newline
8471 8485 gnuplot*line1Width: 2
8472 8486 \newline
8473 8487 gnuplot*line2Width: 2
8474 8488 \newline
8475 8489 gnuplot*line3Width: 2
8476 8490 \newline
8477 8491 gnuplot*line4Width: 2
8478 8492 \newline
8479 8493 gnuplot*line5Width: 2
8480 8494 \newline
8481 8495 gnuplot*line6Width: 2
8482 8496 \newline
8483 8497 gnuplot*line7Width: 2
8484 8498 \newline
8485 8499 gnuplot*line8Width: 2
8486 8500 \layout Subsection
8487 8501
8488 8502 The
8489 8503 \family typewriter
8490 8504 IPython.GnuplotRuntime
8491 8505 \family default
8492 8506 module
8493 8507 \layout Standard
8494 8508
8495 8509 IPython includes a module called
8496 8510 \family typewriter
8497 8511 Gnuplot2.py
8498 8512 \family default
8499 8513 which extends and improves the default
8500 8514 \family typewriter
8501 8515 Gnuplot
8502 8516 \family default
8503 8517 .
8504 8518 \family typewriter
8505 8519 py
8506 8520 \family default
8507 8521 (which it still relies upon).
8508 8522 For example, the new
8509 8523 \family typewriter
8510 8524 plot
8511 8525 \family default
8512 8526 function adds several improvements to the original making it more convenient
8513 8527 for interactive use, and
8514 8528 \family typewriter
8515 8529 hardcopy
8516 8530 \family default
8517 8531 fixes a bug in the original which under some circumstances blocks the creation
8518 8532 of PostScript output.
8519 8533 \layout Standard
8520 8534
8521 8535 For scripting use,
8522 8536 \family typewriter
8523 8537 GnuplotRuntime.py
8524 8538 \family default
8525 8539 is provided, which wraps
8526 8540 \family typewriter
8527 8541 Gnuplot2.py
8528 8542 \family default
8529 8543 and creates a series of global aliases.
8530 8544 These make it easy to control Gnuplot plotting jobs through the Python
8531 8545 language.
8532 8546 \layout Standard
8533 8547
8534 8548 Below is some example code which illustrates how to configure Gnuplot inside
8535 8549 your own programs but have it available for further interactive use through
8536 8550 an embedded IPython instance.
8537 8551 Simply run this file at a system prompt.
8538 8552 This file is provided as
8539 8553 \family typewriter
8540 8554 example-gnuplot.py
8541 8555 \family default
8542 8556 in the examples directory:
8543 8557 \layout Standard
8544 8558
8545 8559
8546 8560 \begin_inset ERT
8547 8561 status Open
8548 8562
8549 8563 \layout Standard
8550 8564
8551 8565 \backslash
8552 8566 codelist{examples/example-gnuplot.py}
8553 8567 \end_inset
8554 8568
8555 8569
8556 8570 \layout Subsection
8557 8571
8558 8572 The
8559 8573 \family typewriter
8560 8574 numeric
8561 8575 \family default
8562 8576 profile: a scientific computing environment
8563 8577 \layout Standard
8564 8578
8565 8579 The
8566 8580 \family typewriter
8567 8581 numeric
8568 8582 \family default
8569 8583 IPython profile, which you can activate with
8570 8584 \family typewriter
8571 8585 `ipython -p numeric
8572 8586 \family default
8573 8587 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8574 8588 other useful things for numerical computing), contained in the
8575 8589 \family typewriter
8576 8590 IPython.GnuplotInteractive
8577 8591 \family default
8578 8592 module.
8579 8593 This will create the globals
8580 8594 \family typewriter
8581 8595 Gnuplot
8582 8596 \family default
8583 8597 (an alias to the improved Gnuplot2 module),
8584 8598 \family typewriter
8585 8599 gp
8586 8600 \family default
8587 8601 (a Gnuplot active instance), the new magic commands
8588 8602 \family typewriter
8589 8603 %gpc
8590 8604 \family default
8591 8605 and
8592 8606 \family typewriter
8593 8607 %gp_set_instance
8594 8608 \family default
8595 8609 and several other convenient globals.
8596 8610 Type
8597 8611 \family typewriter
8598 8612 gphelp()
8599 8613 \family default
8600 8614 for further details.
8601 8615 \layout Standard
8602 8616
8603 8617 This should turn IPython into a convenient environment for numerical computing,
8604 8618 with all the functions in the NumPy library and the Gnuplot facilities
8605 8619 for plotting.
8606 8620 Further improvements can be obtained by loading the SciPy libraries for
8607 8621 scientific computing, available at
8608 8622 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8609 8623
8610 8624 \end_inset
8611 8625
8612 8626 .
8613 8627 \layout Standard
8614 8628
8615 8629 If you are in the middle of a working session with numerical objects and
8616 8630 need to plot them but you didn't start the
8617 8631 \family typewriter
8618 8632 numeric
8619 8633 \family default
8620 8634 profile, you can load these extensions at any time by typing
8621 8635 \newline
8622 8636
8623 8637 \family typewriter
8624 8638 from IPython.GnuplotInteractive import *
8625 8639 \newline
8626 8640
8627 8641 \family default
8628 8642 at the IPython prompt.
8629 8643 This will allow you to keep your objects intact and start using Gnuplot
8630 8644 to view them.
8631 8645 \layout Section
8632 8646
8633 8647 Reporting bugs
8634 8648 \layout Subsection*
8635 8649
8636 8650 Automatic crash reports
8637 8651 \layout Standard
8638 8652
8639 8653 Ideally, IPython itself shouldn't crash.
8640 8654 It will catch exceptions produced by you, but bugs in its internals will
8641 8655 still crash it.
8642 8656 \layout Standard
8643 8657
8644 8658 In such a situation, IPython will leave a file named
8645 8659 \family typewriter
8646 8660 IPython_crash_report.txt
8647 8661 \family default
8648 8662 in your IPYTHONDIR directory (that way if crashes happen several times
8649 8663 it won't litter many directories, the post-mortem file is always located
8650 8664 in the same place and new occurrences just overwrite the previous one).
8651 8665 If you can mail this file to the developers (see sec.
8652 8666
8653 8667 \begin_inset LatexCommand \ref{sec:credits}
8654 8668
8655 8669 \end_inset
8656 8670
8657 8671 for names and addresses), it will help us
8658 8672 \emph on
8659 8673 a lot
8660 8674 \emph default
8661 8675 in understanding the cause of the problem and fixing it sooner.
8662 8676 \layout Subsection*
8663 8677
8664 8678 The bug tracker
8665 8679 \layout Standard
8666 8680
8667 8681 IPython also has an online bug-tracker, located at
8668 8682 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8669 8683
8670 8684 \end_inset
8671 8685
8672 8686 .
8673 8687 In addition to mailing the developers, it would be a good idea to file
8674 8688 a bug report here.
8675 8689 This will ensure that the issue is properly followed to conclusion.
8676 8690 \layout Standard
8677 8691
8678 8692 You can also use this bug tracker to file feature requests.
8679 8693 \layout Section
8680 8694
8681 8695 Brief history
8682 8696 \layout Subsection
8683 8697
8684 8698 Origins
8685 8699 \layout Standard
8686 8700
8687 8701 The current IPython system grew out of the following three projects:
8688 8702 \layout List
8689 8703 \labelwidthstring 00.00.0000
8690 8704
8691 8705 ipython by Fernando P
8692 8706 \begin_inset ERT
8693 8707 status Collapsed
8694 8708
8695 8709 \layout Standard
8696 8710
8697 8711 \backslash
8698 8712 '{e}
8699 8713 \end_inset
8700 8714
8701 8715 rez.
8702 8716 I was working on adding Mathematica-type prompts and a flexible configuration
8703 8717 system (something better than
8704 8718 \family typewriter
8705 8719 $PYTHONSTARTUP
8706 8720 \family default
8707 8721 ) to the standard Python interactive interpreter.
8708 8722 \layout List
8709 8723 \labelwidthstring 00.00.0000
8710 8724
8711 8725 IPP by Janko Hauser.
8712 8726 Very well organized, great usability.
8713 8727 Had an old help system.
8714 8728 IPP was used as the `container' code into which I added the functionality
8715 8729 from ipython and LazyPython.
8716 8730 \layout List
8717 8731 \labelwidthstring 00.00.0000
8718 8732
8719 8733 LazyPython by Nathan Gray.
8720 8734 Simple but
8721 8735 \emph on
8722 8736 very
8723 8737 \emph default
8724 8738 powerful.
8725 8739 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8726 8740 were all taken from here.
8727 8741 \layout Standard
8728 8742
8729 8743 When I found out (see sec.
8730 8744
8731 8745 \begin_inset LatexCommand \ref{figgins}
8732 8746
8733 8747 \end_inset
8734 8748
8735 8749 ) about IPP and LazyPython I tried to join all three into a unified system.
8736 8750 I thought this could provide a very nice working environment, both for
8737 8751 regular programming and scientific computing: shell-like features, IDL/Matlab
8738 8752 numerics, Mathematica-type prompt history and great object introspection
8739 8753 and help facilities.
8740 8754 I think it worked reasonably well, though it was a lot more work than I
8741 8755 had initially planned.
8742 8756 \layout Subsection
8743 8757
8744 8758 Current status
8745 8759 \layout Standard
8746 8760
8747 8761 The above listed features work, and quite well for the most part.
8748 8762 But until a major internal restructuring is done (see below), only bug
8749 8763 fixing will be done, no other features will be added (unless very minor
8750 8764 and well localized in the cleaner parts of the code).
8751 8765 \layout Standard
8752 8766
8753 8767 IPython consists of some 18000 lines of pure python code, of which roughly
8754 8768 two thirds is reasonably clean.
8755 8769 The rest is, messy code which needs a massive restructuring before any
8756 8770 further major work is done.
8757 8771 Even the messy code is fairly well documented though, and most of the problems
8758 8772 in the (non-existent) class design are well pointed to by a PyChecker run.
8759 8773 So the rewriting work isn't that bad, it will just be time-consuming.
8760 8774 \layout Subsection
8761 8775
8762 8776 Future
8763 8777 \layout Standard
8764 8778
8765 8779 See the separate
8766 8780 \family typewriter
8767 8781 new_design
8768 8782 \family default
8769 8783 document for details.
8770 8784 Ultimately, I would like to see IPython become part of the standard Python
8771 8785 distribution as a `big brother with batteries' to the standard Python interacti
8772 8786 ve interpreter.
8773 8787 But that will never happen with the current state of the code, so all contribut
8774 8788 ions are welcome.
8775 8789 \layout Section
8776 8790
8777 8791 License
8778 8792 \layout Standard
8779 8793
8780 8794 IPython is released under the terms of the BSD license, whose general form
8781 8795 can be found at:
8782 8796 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8783 8797
8784 8798 \end_inset
8785 8799
8786 8800 .
8787 8801 The full text of the IPython license is reproduced below:
8788 8802 \layout Quote
8789 8803
8790 8804
8791 8805 \family typewriter
8792 8806 \size small
8793 8807 IPython is released under a BSD-type license.
8794 8808 \layout Quote
8795 8809
8796 8810
8797 8811 \family typewriter
8798 8812 \size small
8799 8813 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8800 8814 \layout Quote
8801 8815
8802 8816
8803 8817 \family typewriter
8804 8818 \size small
8805 8819 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8806 8820 \newline
8807 8821 Nathaniel Gray <n8gray@caltech.edu>.
8808 8822 \layout Quote
8809 8823
8810 8824
8811 8825 \family typewriter
8812 8826 \size small
8813 8827 All rights reserved.
8814 8828 \layout Quote
8815 8829
8816 8830
8817 8831 \family typewriter
8818 8832 \size small
8819 8833 Redistribution and use in source and binary forms, with or without modification,
8820 8834 are permitted provided that the following conditions are met:
8821 8835 \layout Quote
8822 8836
8823 8837
8824 8838 \family typewriter
8825 8839 \size small
8826 8840 a.
8827 8841 Redistributions of source code must retain the above copyright notice,
8828 8842 this list of conditions and the following disclaimer.
8829 8843 \layout Quote
8830 8844
8831 8845
8832 8846 \family typewriter
8833 8847 \size small
8834 8848 b.
8835 8849 Redistributions in binary form must reproduce the above copyright notice,
8836 8850 this list of conditions and the following disclaimer in the documentation
8837 8851 and/or other materials provided with the distribution.
8838 8852 \layout Quote
8839 8853
8840 8854
8841 8855 \family typewriter
8842 8856 \size small
8843 8857 c.
8844 8858 Neither the name of the copyright holders nor the names of any contributors
8845 8859 to this software may be used to endorse or promote products derived from
8846 8860 this software without specific prior written permission.
8847 8861 \layout Quote
8848 8862
8849 8863
8850 8864 \family typewriter
8851 8865 \size small
8852 8866 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8853 8867 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8854 8868 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8855 8869 PURPOSE ARE DISCLAIMED.
8856 8870 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8857 8871 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8858 8872 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8859 8873 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8860 8874 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8861 8875 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8862 8876 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8863 8877
8864 8878 \layout Standard
8865 8879
8866 8880 Individual authors are the holders of the copyright for their code and are
8867 8881 listed in each file.
8868 8882 \layout Standard
8869 8883
8870 8884 Some files (
8871 8885 \family typewriter
8872 8886 DPyGetOpt.py
8873 8887 \family default
8874 8888 , for example) may be licensed under different conditions.
8875 8889 Ultimately each file indicates clearly the conditions under which its author/au
8876 8890 thors have decided to publish the code.
8877 8891 \layout Standard
8878 8892
8879 8893 Versions of IPython up to and including 0.6.3 were released under the GNU
8880 8894 Lesser General Public License (LGPL), available at
8881 8895 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8882 8896
8883 8897 \end_inset
8884 8898
8885 8899 .
8886 8900 \layout Section
8887 8901
8888 8902
8889 8903 \begin_inset LatexCommand \label{sec:credits}
8890 8904
8891 8905 \end_inset
8892 8906
8893 8907 Credits
8894 8908 \layout Standard
8895 8909
8896 8910 IPython is mainly developed by Fernando P
8897 8911 \begin_inset ERT
8898 8912 status Collapsed
8899 8913
8900 8914 \layout Standard
8901 8915
8902 8916 \backslash
8903 8917 '{e}
8904 8918 \end_inset
8905 8919
8906 8920 rez
8907 8921 \family typewriter
8908 <fperez@colorado.edu>
8922 <Fernando.Perez@colorado.edu>
8909 8923 \family default
8910 8924 , but the project was born from mixing in Fernando's code with the IPP project
8911 8925 by Janko Hauser
8912 8926 \family typewriter
8913 8927 <jhauser-AT-zscout.de>
8914 8928 \family default
8915 8929 and LazyPython by Nathan Gray
8916 8930 \family typewriter
8917 8931 <n8gray-AT-caltech.edu>
8918 8932 \family default
8919 8933 .
8920 8934 For all IPython-related requests, please contact Fernando.
8921 8935
8922 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 8939 \layout List
8926 8940 \labelwidthstring 00.00.0000
8927 8941
8928 8942 Robert\SpecialChar ~
8929 8943 Kern
8930 8944 \family typewriter
8931 8945 <rkern-AT-enthought.com>
8932 8946 \family default
8933 8947 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8934 8948 ve notebooks (XML documents) and graphical interface.
8935 8949 This project was awarded to the students Tzanko Matev
8936 8950 \family typewriter
8937 8951 <tsanko-AT-gmail.com>
8938 8952 \family default
8939 8953 and Toni Alatalo
8940 8954 \family typewriter
8941 8955 <antont-AT-an.org>
8942 8956 \layout List
8943 8957 \labelwidthstring 00.00.0000
8944 8958
8945 8959 Brian\SpecialChar ~
8946 8960 Granger
8947 8961 \family typewriter
8948 8962 <bgranger-AT-scu.edu>
8949 8963 \family default
8950 8964 : extending IPython to allow support for interactive parallel computing.
8951 8965 \layout List
8952 8966 \labelwidthstring 00.00.0000
8953 8967
8954 8968 Ville\SpecialChar ~
8955 8969 Vainio
8956 8970 \family typewriter
8957 8971 <vivainio-AT-gmail.com>
8958 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 8974 0.7.1.
8961 8975 \layout Standard
8962 8976
8963 8977 User or development help should be requested via the IPython mailing lists:
8964 8978 \layout Description
8965 8979
8966 8980 User\SpecialChar ~
8967 8981 list:
8968 8982 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8969 8983
8970 8984 \end_inset
8971 8985
8972 8986
8973 8987 \layout Description
8974 8988
8975 8989 Developer's\SpecialChar ~
8976 8990 list:
8977 8991 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8978 8992
8979 8993 \end_inset
8980 8994
8981 8995
8982 8996 \layout Standard
8983 8997
8984 8998 The IPython project is also very grateful to
8985 8999 \begin_inset Foot
8986 9000 collapsed true
8987 9001
8988 9002 \layout Standard
8989 9003
8990 9004 I've mangled email addresses to reduce spam, since the IPython manuals can
8991 9005 be accessed online.
8992 9006 \end_inset
8993 9007
8994 9008 :
8995 9009 \layout Standard
8996 9010
8997 9011 Bill Bumgarner
8998 9012 \family typewriter
8999 9013 <bbum-AT-friday.com>
9000 9014 \family default
9001 9015 : for providing the DPyGetOpt module which gives very powerful and convenient
9002 9016 handling of command-line options (light years ahead of what Python 2.1.1's
9003 9017 getopt module does).
9004 9018 \layout Standard
9005 9019
9006 9020 Ka-Ping Yee
9007 9021 \family typewriter
9008 9022 <ping-AT-lfw.org>
9009 9023 \family default
9010 9024 : for providing the Itpl module for convenient and powerful string interpolation
9011 9025 with a much nicer syntax than formatting through the '%' operator.
9012 9026 \layout Standard
9013 9027
9014 9028 Arnd Baecker
9015 9029 \family typewriter
9016 9030 <baecker-AT-physik.tu-dresden.de>
9017 9031 \family default
9018 9032 : for his many very useful suggestions and comments, and lots of help with
9019 9033 testing and documentation checking.
9020 9034 Many of IPython's newer features are a result of discussions with him (bugs
9021 9035 are still my fault, not his).
9022 9036 \layout Standard
9023 9037
9024 9038 Obviously Guido van\SpecialChar ~
9025 9039 Rossum and the whole Python development team, that goes
9026 9040 without saying.
9027 9041 \layout Standard
9028 9042
9029 9043 IPython's website is generously hosted at
9030 9044 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
9031 9045
9032 9046 \end_inset
9033 9047
9034 9048 by Enthought (
9035 9049 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
9036 9050
9037 9051 \end_inset
9038 9052
9039 9053 ).
9040 9054 I am very grateful to them and all of the SciPy team for their contribution.
9041 9055 \layout Standard
9042 9056
9043 9057
9044 9058 \begin_inset LatexCommand \label{figgins}
9045 9059
9046 9060 \end_inset
9047 9061
9048 9062 Fernando would also like to thank Stephen Figgins
9049 9063 \family typewriter
9050 9064 <fig-AT-monitor.net>
9051 9065 \family default
9052 9066 , an O'Reilly Python editor.
9053 9067 His Oct/11/2001 article about IPP and LazyPython, was what got this project
9054 9068 started.
9055 9069 You can read it at:
9056 9070 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
9057 9071
9058 9072 \end_inset
9059 9073
9060 9074 .
9061 9075 \layout Standard
9062 9076
9063 9077 And last but not least, all the kind IPython users who have emailed new
9064 9078 code, bug reports, fixes, comments and ideas.
9065 9079 A brief list follows, please let me know if I have ommitted your name by
9066 9080 accident:
9067 9081 \layout List
9068 9082 \labelwidthstring 00.00.0000
9069 9083
9070 9084 Jack\SpecialChar ~
9071 9085 Moffit
9072 9086 \family typewriter
9073 9087 <jack-AT-xiph.org>
9074 9088 \family default
9075 9089 Bug fixes, including the infamous color problem.
9076 9090 This bug alone caused many lost hours and frustration, many thanks to him
9077 9091 for the fix.
9078 9092 I've always been a fan of Ogg & friends, now I have one more reason to
9079 9093 like these folks.
9080 9094 \newline
9081 9095 Jack is also contributing with Debian packaging and many other things.
9082 9096 \layout List
9083 9097 \labelwidthstring 00.00.0000
9084 9098
9085 9099 Alexander\SpecialChar ~
9086 9100 Schmolck
9087 9101 \family typewriter
9088 9102 <a.schmolck-AT-gmx.net>
9089 9103 \family default
9090 9104 Emacs work, bug reports, bug fixes, ideas, lots more.
9091 9105 The ipython.el mode for (X)Emacs is Alex's code, providing full support
9092 9106 for IPython under (X)Emacs.
9093 9107 \layout List
9094 9108 \labelwidthstring 00.00.0000
9095 9109
9096 9110 Andrea\SpecialChar ~
9097 9111 Riciputi
9098 9112 \family typewriter
9099 9113 <andrea.riciputi-AT-libero.it>
9100 9114 \family default
9101 9115 Mac OSX information, Fink package management.
9102 9116 \layout List
9103 9117 \labelwidthstring 00.00.0000
9104 9118
9105 9119 Gary\SpecialChar ~
9106 9120 Bishop
9107 9121 \family typewriter
9108 9122 <gb-AT-cs.unc.edu>
9109 9123 \family default
9110 9124 Bug reports, and patches to work around the exception handling idiosyncracies
9111 9125 of WxPython.
9112 9126 Readline and color support for Windows.
9113 9127 \layout List
9114 9128 \labelwidthstring 00.00.0000
9115 9129
9116 9130 Jeffrey\SpecialChar ~
9117 9131 Collins
9118 9132 \family typewriter
9119 9133 <Jeff.Collins-AT-vexcel.com>
9120 9134 \family default
9121 9135 Bug reports.
9122 9136 Much improved readline support, including fixes for Python 2.3.
9123 9137 \layout List
9124 9138 \labelwidthstring 00.00.0000
9125 9139
9126 9140 Dryice\SpecialChar ~
9127 9141 Liu
9128 9142 \family typewriter
9129 9143 <dryice-AT-liu.com.cn>
9130 9144 \family default
9131 9145 FreeBSD port.
9132 9146 \layout List
9133 9147 \labelwidthstring 00.00.0000
9134 9148
9135 9149 Mike\SpecialChar ~
9136 9150 Heeter
9137 9151 \family typewriter
9138 9152 <korora-AT-SDF.LONESTAR.ORG>
9139 9153 \layout List
9140 9154 \labelwidthstring 00.00.0000
9141 9155
9142 9156 Christopher\SpecialChar ~
9143 9157 Hart
9144 9158 \family typewriter
9145 9159 <hart-AT-caltech.edu>
9146 9160 \family default
9147 9161 PDB integration.
9148 9162 \layout List
9149 9163 \labelwidthstring 00.00.0000
9150 9164
9151 9165 Milan\SpecialChar ~
9152 9166 Zamazal
9153 9167 \family typewriter
9154 9168 <pdm-AT-zamazal.org>
9155 9169 \family default
9156 9170 Emacs info.
9157 9171 \layout List
9158 9172 \labelwidthstring 00.00.0000
9159 9173
9160 9174 Philip\SpecialChar ~
9161 9175 Hisley
9162 9176 \family typewriter
9163 9177 <compsys-AT-starpower.net>
9164 9178 \layout List
9165 9179 \labelwidthstring 00.00.0000
9166 9180
9167 9181 Holger\SpecialChar ~
9168 9182 Krekel
9169 9183 \family typewriter
9170 9184 <pyth-AT-devel.trillke.net>
9171 9185 \family default
9172 9186 Tab completion, lots more.
9173 9187 \layout List
9174 9188 \labelwidthstring 00.00.0000
9175 9189
9176 9190 Robin\SpecialChar ~
9177 9191 Siebler
9178 9192 \family typewriter
9179 9193 <robinsiebler-AT-starband.net>
9180 9194 \layout List
9181 9195 \labelwidthstring 00.00.0000
9182 9196
9183 9197 Ralf\SpecialChar ~
9184 9198 Ahlbrink
9185 9199 \family typewriter
9186 9200 <ralf_ahlbrink-AT-web.de>
9187 9201 \layout List
9188 9202 \labelwidthstring 00.00.0000
9189 9203
9190 9204 Thorsten\SpecialChar ~
9191 9205 Kampe
9192 9206 \family typewriter
9193 9207 <thorsten-AT-thorstenkampe.de>
9194 9208 \layout List
9195 9209 \labelwidthstring 00.00.0000
9196 9210
9197 9211 Fredrik\SpecialChar ~
9198 9212 Kant
9199 9213 \family typewriter
9200 9214 <fredrik.kant-AT-front.com>
9201 9215 \family default
9202 9216 Windows setup.
9203 9217 \layout List
9204 9218 \labelwidthstring 00.00.0000
9205 9219
9206 9220 Syver\SpecialChar ~
9207 9221 Enstad
9208 9222 \family typewriter
9209 9223 <syver-en-AT-online.no>
9210 9224 \family default
9211 9225 Windows setup.
9212 9226 \layout List
9213 9227 \labelwidthstring 00.00.0000
9214 9228
9215 9229 Richard
9216 9230 \family typewriter
9217 9231 <rxe-AT-renre-europe.com>
9218 9232 \family default
9219 9233 Global embedding.
9220 9234 \layout List
9221 9235 \labelwidthstring 00.00.0000
9222 9236
9223 9237 Hayden\SpecialChar ~
9224 9238 Callow
9225 9239 \family typewriter
9226 9240 <h.callow-AT-elec.canterbury.ac.nz>
9227 9241 \family default
9228 9242 Gnuplot.py 1.6 compatibility.
9229 9243 \layout List
9230 9244 \labelwidthstring 00.00.0000
9231 9245
9232 9246 Leonardo\SpecialChar ~
9233 9247 Santagada
9234 9248 \family typewriter
9235 9249 <retype-AT-terra.com.br>
9236 9250 \family default
9237 9251 Fixes for Windows installation.
9238 9252 \layout List
9239 9253 \labelwidthstring 00.00.0000
9240 9254
9241 9255 Christopher\SpecialChar ~
9242 9256 Armstrong
9243 9257 \family typewriter
9244 9258 <radix-AT-twistedmatrix.com>
9245 9259 \family default
9246 9260 Bugfixes.
9247 9261 \layout List
9248 9262 \labelwidthstring 00.00.0000
9249 9263
9250 9264 Francois\SpecialChar ~
9251 9265 Pinard
9252 9266 \family typewriter
9253 9267 <pinard-AT-iro.umontreal.ca>
9254 9268 \family default
9255 9269 Code and documentation fixes.
9256 9270 \layout List
9257 9271 \labelwidthstring 00.00.0000
9258 9272
9259 9273 Cory\SpecialChar ~
9260 9274 Dodt
9261 9275 \family typewriter
9262 9276 <cdodt-AT-fcoe.k12.ca.us>
9263 9277 \family default
9264 9278 Bug reports and Windows ideas.
9265 9279 Patches for Windows installer.
9266 9280 \layout List
9267 9281 \labelwidthstring 00.00.0000
9268 9282
9269 9283 Olivier\SpecialChar ~
9270 9284 Aubert
9271 9285 \family typewriter
9272 9286 <oaubert-AT-bat710.univ-lyon1.fr>
9273 9287 \family default
9274 9288 New magics.
9275 9289 \layout List
9276 9290 \labelwidthstring 00.00.0000
9277 9291
9278 9292 King\SpecialChar ~
9279 9293 C.\SpecialChar ~
9280 9294 Shu
9281 9295 \family typewriter
9282 9296 <kingshu-AT-myrealbox.com>
9283 9297 \family default
9284 9298 Autoindent patch.
9285 9299 \layout List
9286 9300 \labelwidthstring 00.00.0000
9287 9301
9288 9302 Chris\SpecialChar ~
9289 9303 Drexler
9290 9304 \family typewriter
9291 9305 <chris-AT-ac-drexler.de>
9292 9306 \family default
9293 9307 Readline packages for Win32/CygWin.
9294 9308 \layout List
9295 9309 \labelwidthstring 00.00.0000
9296 9310
9297 9311 Gustavo\SpecialChar ~
9298 9312 Cordova\SpecialChar ~
9299 9313 Avila
9300 9314 \family typewriter
9301 9315 <gcordova-AT-sismex.com>
9302 9316 \family default
9303 9317 EvalDict code for nice, lightweight string interpolation.
9304 9318 \layout List
9305 9319 \labelwidthstring 00.00.0000
9306 9320
9307 9321 Kasper\SpecialChar ~
9308 9322 Souren
9309 9323 \family typewriter
9310 9324 <Kasper.Souren-AT-ircam.fr>
9311 9325 \family default
9312 9326 Bug reports, ideas.
9313 9327 \layout List
9314 9328 \labelwidthstring 00.00.0000
9315 9329
9316 9330 Gever\SpecialChar ~
9317 9331 Tulley
9318 9332 \family typewriter
9319 9333 <gever-AT-helium.com>
9320 9334 \family default
9321 9335 Code contributions.
9322 9336 \layout List
9323 9337 \labelwidthstring 00.00.0000
9324 9338
9325 9339 Ralf\SpecialChar ~
9326 9340 Schmitt
9327 9341 \family typewriter
9328 9342 <ralf-AT-brainbot.com>
9329 9343 \family default
9330 9344 Bug reports & fixes.
9331 9345 \layout List
9332 9346 \labelwidthstring 00.00.0000
9333 9347
9334 9348 Oliver\SpecialChar ~
9335 9349 Sander
9336 9350 \family typewriter
9337 9351 <osander-AT-gmx.de>
9338 9352 \family default
9339 9353 Bug reports.
9340 9354 \layout List
9341 9355 \labelwidthstring 00.00.0000
9342 9356
9343 9357 Rod\SpecialChar ~
9344 9358 Holland
9345 9359 \family typewriter
9346 9360 <rhh-AT-structurelabs.com>
9347 9361 \family default
9348 9362 Bug reports and fixes to logging module.
9349 9363 \layout List
9350 9364 \labelwidthstring 00.00.0000
9351 9365
9352 9366 Daniel\SpecialChar ~
9353 9367 'Dang'\SpecialChar ~
9354 9368 Griffith
9355 9369 \family typewriter
9356 9370 <pythondev-dang-AT-lazytwinacres.net>
9357 9371 \family default
9358 9372 Fixes, enhancement suggestions for system shell use.
9359 9373 \layout List
9360 9374 \labelwidthstring 00.00.0000
9361 9375
9362 9376 Viktor\SpecialChar ~
9363 9377 Ransmayr
9364 9378 \family typewriter
9365 9379 <viktor.ransmayr-AT-t-online.de>
9366 9380 \family default
9367 9381 Tests and reports on Windows installation issues.
9368 9382 Contributed a true Windows binary installer.
9369 9383 \layout List
9370 9384 \labelwidthstring 00.00.0000
9371 9385
9372 9386 Mike\SpecialChar ~
9373 9387 Salib
9374 9388 \family typewriter
9375 9389 <msalib-AT-mit.edu>
9376 9390 \family default
9377 9391 Help fixing a subtle bug related to traceback printing.
9378 9392 \layout List
9379 9393 \labelwidthstring 00.00.0000
9380 9394
9381 9395 W.J.\SpecialChar ~
9382 9396 van\SpecialChar ~
9383 9397 der\SpecialChar ~
9384 9398 Laan
9385 9399 \family typewriter
9386 9400 <gnufnork-AT-hetdigitalegat.nl>
9387 9401 \family default
9388 9402 Bash-like prompt specials.
9389 9403 \layout List
9390 9404 \labelwidthstring 00.00.0000
9391 9405
9392 9406 Antoon\SpecialChar ~
9393 9407 Pardon
9394 9408 \family typewriter
9395 9409 <Antoon.Pardon-AT-rece.vub.ac.be>
9396 9410 \family default
9397 9411 Critical fix for the multithreaded IPython.
9398 9412 \layout List
9399 9413 \labelwidthstring 00.00.0000
9400 9414
9401 9415 John\SpecialChar ~
9402 9416 Hunter
9403 9417 \family typewriter
9404 9418 <jdhunter-AT-nitace.bsd.uchicago.edu>
9405 9419 \family default
9406 9420 Matplotlib author, helped with all the development of support for matplotlib
9407 9421 in IPyhton, including making necessary changes to matplotlib itself.
9408 9422 \layout List
9409 9423 \labelwidthstring 00.00.0000
9410 9424
9411 9425 Matthew\SpecialChar ~
9412 9426 Arnison
9413 9427 \family typewriter
9414 9428 <maffew-AT-cat.org.au>
9415 9429 \family default
9416 9430 Bug reports, `
9417 9431 \family typewriter
9418 9432 %run -d
9419 9433 \family default
9420 9434 ' idea.
9421 9435 \layout List
9422 9436 \labelwidthstring 00.00.0000
9423 9437
9424 9438 Prabhu\SpecialChar ~
9425 9439 Ramachandran
9426 9440 \family typewriter
9427 9441 <prabhu_r-AT-users.sourceforge.net>
9428 9442 \family default
9429 9443 Help with (X)Emacs support, threading patches, ideas...
9430 9444 \layout List
9431 9445 \labelwidthstring 00.00.0000
9432 9446
9433 9447 Norbert\SpecialChar ~
9434 9448 Tretkowski
9435 9449 \family typewriter
9436 9450 <tretkowski-AT-inittab.de>
9437 9451 \family default
9438 9452 help with Debian packaging and distribution.
9439 9453 \layout List
9440 9454 \labelwidthstring 00.00.0000
9441 9455
9442 9456 George\SpecialChar ~
9443 9457 Sakkis <
9444 9458 \family typewriter
9445 9459 gsakkis-AT-eden.rutgers.edu>
9446 9460 \family default
9447 9461 New matcher for tab-completing named arguments of user-defined functions.
9448 9462 \layout List
9449 9463 \labelwidthstring 00.00.0000
9450 9464
9451 9465 J�rgen\SpecialChar ~
9452 9466 Stenarson
9453 9467 \family typewriter
9454 9468 <jorgen.stenarson-AT-bostream.nu>
9455 9469 \family default
9456 9470 Wildcard support implementation for searching namespaces.
9457 9471 \layout List
9458 9472 \labelwidthstring 00.00.0000
9459 9473
9460 9474 Vivian\SpecialChar ~
9461 9475 De\SpecialChar ~
9462 9476 Smedt
9463 9477 \family typewriter
9464 9478 <vivian-AT-vdesmedt.com>
9465 9479 \family default
9466 9480 Debugger enhancements, so that when pdb is activated from within IPython,
9467 9481 coloring, tab completion and other features continue to work seamlessly.
9468 9482 \layout List
9469 9483 \labelwidthstring 00.00.0000
9470 9484
9471 9485 Scott\SpecialChar ~
9472 9486 Tsai
9473 9487 \family typewriter
9474 9488 <scottt958-AT-yahoo.com.tw>
9475 9489 \family default
9476 9490 Support for automatic editor invocation on syntax errors (see
9477 9491 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
9478 9492
9479 9493 \end_inset
9480 9494
9481 9495 ).
9482 9496 \layout List
9483 9497 \labelwidthstring 00.00.0000
9484 9498
9485 9499 Alexander\SpecialChar ~
9486 9500 Belchenko
9487 9501 \family typewriter
9488 9502 <bialix-AT-ukr.net>
9489 9503 \family default
9490 9504 Improvements for win32 paging system.
9491 9505 \the_end
@@ -1,103 +1,102 b''
1 1 #!/bin/sh
2 2 # IPython release script
3 3
4 4 PYVER=`python -V 2>&1 | awk '{print $2}' | awk -F '.' '{print $1$2}' `
5 5 version=`ipython -Version`
6 6 ipdir=~/ipython/ipython
7 7
8 8 echo
9 9 echo "Releasing IPython version $version"
10 10 echo "=================================="
11 11
12 12 echo "Marking ChangeLog with release information and making NEWS file..."
13 13
14 14 # Stamp changelog and save a copy of the status at each version, in case later
15 15 # we want the NEWS file to start from a point before the very last release (if
16 16 # very small interim releases have no significant changes).
17 17
18 18 cd $ipdir/doc
19 19 cp ChangeLog ChangeLog.old
20 20 cp ChangeLog ChangeLog.$version
21 21 daystamp=`date +%Y-%m-%d`
22 22 echo $daystamp " ***" Released version $version > ChangeLog
23 23 echo >> ChangeLog
24 24 cat ChangeLog.old >> ChangeLog
25 25 rm ChangeLog.old
26 26
27 27 # Build NEWS file
28 28 echo "Changes between the last two releases (major or minor)" > NEWS
29 29 echo "Note that this is an auto-generated diff of the ChangeLogs" >> NEWS
30 30 echo >> NEWS
31 31 diff ChangeLog.previous ChangeLog | grep -v '^0a' | sed 's/^> //g' >> NEWS
32 32 cp ChangeLog ChangeLog.previous
33 33
34 34 # Clean up build/dist directories
35 35 rm -rf $ipdir/build/*
36 36 rm -rf $ipdir/dist/*
37 37
38 38 # Perform local backup
39 39 cd $ipdir/tools
40 40 ./bkp.py
41 41
42 42 # Build source and binary distros
43 43 cd $ipdir
44 44 ./setup.py sdist --formats=gztar
45 45 #./setup.py bdist_rpm --release=py$PYVER
46 46 python2.3 ./setup.py bdist_rpm --release=py23 --python=/usr/bin/python2.3
47 47
48 48 # A 2.4-specific RPM, where we must use the --python option to ensure that
49 49 # the resulting RPM is really built with 2.4 (so things go to
50 50 # lib/python2.4/...)
51 51 python2.4 ./setup.py bdist_rpm --release=py24 --python=/usr/bin/python2.4
52 52
53 53 # Build eggs
54 python2.3 ./setup_bdist_egg.py
55 python2.4 ./setup_bdist_egg.py
54 python2.3 ./eggsetup.py bdist_egg
55 python2.4 ./eggsetup.py bdist_egg
56 56
57 57 # Call the windows build separately, so that the extra Windows scripts don't
58 58 # get pulled into Unix builds (setup.py has code which checks for
59 59 # bdist_wininst)
60 60 #./setup.py bdist_wininst --install-script=ipython_win_post_install.py
61 61
62 62 # For now, make the win32 installer with a hand-built 2.3.5 python, which is
63 63 # the only one that fixes a crash in the post-install phase.
64 64 $HOME/tmp/local/bin/python2.3 setup.py bdist_wininst \
65 65 --install-script=ipython_win_post_install.py
66 66
67
68 67 # Register with the Python Package Index (PyPI)
69 68 echo "Registering with PyPI..."
70 69 cd $ipdir
71 70 ./setup.py register
72 71
73 72 # Upload all files
74 73 cd $ipdir/dist
75 74 echo "Uploading distribution files..."
76 75 scp * ipython@ipython.scipy.org:www/dist/
77 76
78 77 echo "Uploading backup files..."
79 78 cd ~/ipython/backup
80 79 scp `ls -1tr | tail -1` ipython@ipython.scipy.org:www/backup/
81 80
82 81 echo "Updating webpage..."
83 82 cd $ipdir/doc
84 83 www=~/ipython/homepage
85 84 cp ChangeLog NEWS $www
86 85 rm -rf $www/doc/*
87 86 cp -r manual.pdf manual/ $www/doc
88 87 cd $www
89 88 ./update
90 89
91 90 # Alert package maintainers
92 91 echo "Alerting package maintainers..."
93 92 maintainers='fperez@colorado.edu ariciputi@users.sourceforge.net jack@xiph.org tretkowski@inittab.de dryice@hotpop.com'
94 93 #maintainers='fperez@colorado.edu'
95 94
96 95 for email in $maintainers
97 96 do
98 97 echo "Emailing $email..."
99 98 mail -s "[Package maintainer notice] A new IPython is out. Version: $version" \
100 99 $email < NEWS
101 100 done
102 101
103 102 echo "Done!"
@@ -1,28 +1,28 b''
1 1 #!/bin/sh
2 2
3 3 # release test
4 4
5 5 # clean up build/dist directories
6 6 rm -rf ~/ipython/ipython/build/*
7 7 rm -rf ~/ipython/ipython/dist/*
8 8
9 9 # build source distros
10 10 cd ~/ipython/ipython
11 11
12 12 ./setup.py sdist --formats=gztar
13 13
14 14 python2.3 ./setup.py bdist_rpm --release=py23 --python=/usr/bin/python2.3
15 15 python2.4 ./setup.py bdist_rpm --release=py24 --python=/usr/bin/python2.4
16 16
17 17 # Build eggs
18 python2.3 ./setup_bdist_egg.py
19 python2.4 ./setup_bdist_egg.py
18 python2.3 ./eggsetup.py bdist_egg
19 python2.4 ./eggsetup.py bdist_egg
20 20
21 21 # Call the windows build separately, so that the extra Windows scripts don't
22 22 # get pulled into Unix builds (setup.py has code which checks for
23 23 # bdist_wininst)
24 24
25 25 # For now, make the win32 installer with a hand-built 2.3.5 python, which is
26 26 # the only one that fixes a crash in the post-install phase.
27 27 $HOME/tmp/local/bin/python2.3 setup.py bdist_wininst \
28 28 --install-script=ipython_win_post_install.py
General Comments 0
You need to be logged in to leave comments. Login now