##// END OF EJS Templates
- Add autocall 'smart' mode....
fperez -
Show More
@@ -1,2706 +1,2707 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 988 2006-01-02 21:21:47Z fperez $"""
4 $Id: Magic.py 990 2006-01-04 06:59:02Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 from cStringIO import StringIO
34 from cStringIO import StringIO
35 from getopt import getopt
35 from getopt import getopt
36 from pprint import pprint, pformat
36 from pprint import pprint, pformat
37
37
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # Homebrewed
44 # Homebrewed
45 from IPython import Debugger, OInspect, wildcard
45 from IPython import Debugger, OInspect, wildcard
46 from IPython.FakeModule import FakeModule
46 from IPython.FakeModule import FakeModule
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.PyColorize import Parser
48 from IPython.PyColorize import Parser
49 from IPython.Struct import Struct
49 from IPython.Struct import Struct
50 from IPython.macro import Macro
50 from IPython.macro import Macro
51 from IPython.genutils import *
51 from IPython.genutils import *
52
52
53 #***************************************************************************
53 #***************************************************************************
54 # Utility functions
54 # Utility functions
55 def on_off(tag):
55 def on_off(tag):
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 return ['OFF','ON'][tag]
57 return ['OFF','ON'][tag]
58
58
59
59
60 #***************************************************************************
60 #***************************************************************************
61 # Main class implementing Magic functionality
61 # Main class implementing Magic functionality
62 class Magic:
62 class Magic:
63 """Magic functions for InteractiveShell.
63 """Magic functions for InteractiveShell.
64
64
65 Shell functions which can be reached as %function_name. All magic
65 Shell functions which can be reached as %function_name. All magic
66 functions should accept a string, which they can parse for their own
66 functions should accept a string, which they can parse for their own
67 needs. This can make some functions easier to type, eg `%cd ../`
67 needs. This can make some functions easier to type, eg `%cd ../`
68 vs. `%cd("../")`
68 vs. `%cd("../")`
69
69
70 ALL definitions MUST begin with the prefix magic_. The user won't need it
70 ALL definitions MUST begin with the prefix magic_. The user won't need it
71 at the command line, but it is is needed in the definition. """
71 at the command line, but it is is needed in the definition. """
72
72
73 # class globals
73 # class globals
74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
75 'Automagic is ON, % prefix NOT needed for magic functions.']
75 'Automagic is ON, % prefix NOT needed for magic functions.']
76
76
77 #......................................................................
77 #......................................................................
78 # some utility functions
78 # some utility functions
79
79
80 def __init__(self,shell):
80 def __init__(self,shell):
81
81
82 self.options_table = {}
82 self.options_table = {}
83 if profile is None:
83 if profile is None:
84 self.magic_prun = self.profile_missing_notice
84 self.magic_prun = self.profile_missing_notice
85 self.shell = shell
85 self.shell = shell
86
86
87 def profile_missing_notice(self, *args, **kwargs):
87 def profile_missing_notice(self, *args, **kwargs):
88 error("""\
88 error("""\
89 The profile module could not be found. If you are a Debian user,
89 The profile module could not be found. If you are a Debian user,
90 it has been removed from the standard Debian package because of its non-free
90 it has been removed from the standard Debian package because of its non-free
91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
92
92
93 def default_option(self,fn,optstr):
93 def default_option(self,fn,optstr):
94 """Make an entry in the options_table for fn, with value optstr"""
94 """Make an entry in the options_table for fn, with value optstr"""
95
95
96 if fn not in self.lsmagic():
96 if fn not in self.lsmagic():
97 error("%s is not a magic function" % fn)
97 error("%s is not a magic function" % fn)
98 self.options_table[fn] = optstr
98 self.options_table[fn] = optstr
99
99
100 def lsmagic(self):
100 def lsmagic(self):
101 """Return a list of currently available magic functions.
101 """Return a list of currently available magic functions.
102
102
103 Gives a list of the bare names after mangling (['ls','cd', ...], not
103 Gives a list of the bare names after mangling (['ls','cd', ...], not
104 ['magic_ls','magic_cd',...]"""
104 ['magic_ls','magic_cd',...]"""
105
105
106 # FIXME. This needs a cleanup, in the way the magics list is built.
106 # FIXME. This needs a cleanup, in the way the magics list is built.
107
107
108 # magics in class definition
108 # magics in class definition
109 class_magic = lambda fn: fn.startswith('magic_') and \
109 class_magic = lambda fn: fn.startswith('magic_') and \
110 callable(Magic.__dict__[fn])
110 callable(Magic.__dict__[fn])
111 # in instance namespace (run-time user additions)
111 # in instance namespace (run-time user additions)
112 inst_magic = lambda fn: fn.startswith('magic_') and \
112 inst_magic = lambda fn: fn.startswith('magic_') and \
113 callable(self.__dict__[fn])
113 callable(self.__dict__[fn])
114 # and bound magics by user (so they can access self):
114 # and bound magics by user (so they can access self):
115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
116 callable(self.__class__.__dict__[fn])
116 callable(self.__class__.__dict__[fn])
117 magics = filter(class_magic,Magic.__dict__.keys()) + \
117 magics = filter(class_magic,Magic.__dict__.keys()) + \
118 filter(inst_magic,self.__dict__.keys()) + \
118 filter(inst_magic,self.__dict__.keys()) + \
119 filter(inst_bound_magic,self.__class__.__dict__.keys())
119 filter(inst_bound_magic,self.__class__.__dict__.keys())
120 out = []
120 out = []
121 for fn in magics:
121 for fn in magics:
122 out.append(fn.replace('magic_','',1))
122 out.append(fn.replace('magic_','',1))
123 out.sort()
123 out.sort()
124 return out
124 return out
125
125
126 def extract_input_slices(self,slices):
126 def extract_input_slices(self,slices):
127 """Return as a string a set of input history slices.
127 """Return as a string a set of input history slices.
128
128
129 The set of slices is given as a list of strings (like ['1','4:8','9'],
129 The set of slices is given as a list of strings (like ['1','4:8','9'],
130 since this function is for use by magic functions which get their
130 since this function is for use by magic functions which get their
131 arguments as strings.
131 arguments as strings.
132
132
133 Note that slices can be called with two notations:
133 Note that slices can be called with two notations:
134
134
135 N:M -> standard python form, means including items N...(M-1).
135 N:M -> standard python form, means including items N...(M-1).
136
136
137 N-M -> include items N..M (closed endpoint)."""
137 N-M -> include items N..M (closed endpoint)."""
138
138
139 cmds = []
139 cmds = []
140 for chunk in slices:
140 for chunk in slices:
141 if ':' in chunk:
141 if ':' in chunk:
142 ini,fin = map(int,chunk.split(':'))
142 ini,fin = map(int,chunk.split(':'))
143 elif '-' in chunk:
143 elif '-' in chunk:
144 ini,fin = map(int,chunk.split('-'))
144 ini,fin = map(int,chunk.split('-'))
145 fin += 1
145 fin += 1
146 else:
146 else:
147 ini = int(chunk)
147 ini = int(chunk)
148 fin = ini+1
148 fin = ini+1
149 cmds.append(self.shell.input_hist[ini:fin])
149 cmds.append(self.shell.input_hist[ini:fin])
150 return cmds
150 return cmds
151
151
152 def _ofind(self,oname):
152 def _ofind(self,oname):
153 """Find an object in the available namespaces.
153 """Find an object in the available namespaces.
154
154
155 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
155 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
156
156
157 Has special code to detect magic functions.
157 Has special code to detect magic functions.
158 """
158 """
159
159
160 oname = oname.strip()
160 oname = oname.strip()
161
161
162 # Namespaces to search in:
162 # Namespaces to search in:
163 user_ns = self.shell.user_ns
163 user_ns = self.shell.user_ns
164 internal_ns = self.shell.internal_ns
164 internal_ns = self.shell.internal_ns
165 builtin_ns = __builtin__.__dict__
165 builtin_ns = __builtin__.__dict__
166 alias_ns = self.shell.alias_table
166 alias_ns = self.shell.alias_table
167
167
168 # Put them in a list. The order is important so that we find things in
168 # Put them in a list. The order is important so that we find things in
169 # the same order that Python finds them.
169 # the same order that Python finds them.
170 namespaces = [ ('Interactive',user_ns),
170 namespaces = [ ('Interactive',user_ns),
171 ('IPython internal',internal_ns),
171 ('IPython internal',internal_ns),
172 ('Python builtin',builtin_ns),
172 ('Python builtin',builtin_ns),
173 ('Alias',alias_ns),
173 ('Alias',alias_ns),
174 ]
174 ]
175
175
176 # initialize results to 'null'
176 # initialize results to 'null'
177 found = 0; obj = None; ospace = None; ds = None;
177 found = 0; obj = None; ospace = None; ds = None;
178 ismagic = 0; isalias = 0
178 ismagic = 0; isalias = 0
179
179
180 # Look for the given name by splitting it in parts. If the head is
180 # Look for the given name by splitting it in parts. If the head is
181 # found, then we look for all the remaining parts as members, and only
181 # found, then we look for all the remaining parts as members, and only
182 # declare success if we can find them all.
182 # declare success if we can find them all.
183 oname_parts = oname.split('.')
183 oname_parts = oname.split('.')
184 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
184 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
185 for nsname,ns in namespaces:
185 for nsname,ns in namespaces:
186 try:
186 try:
187 obj = ns[oname_head]
187 obj = ns[oname_head]
188 except KeyError:
188 except KeyError:
189 continue
189 continue
190 else:
190 else:
191 for part in oname_rest:
191 for part in oname_rest:
192 try:
192 try:
193 obj = getattr(obj,part)
193 obj = getattr(obj,part)
194 except:
194 except:
195 # Blanket except b/c some badly implemented objects
195 # Blanket except b/c some badly implemented objects
196 # allow __getattr__ to raise exceptions other than
196 # allow __getattr__ to raise exceptions other than
197 # AttributeError, which then crashes IPython.
197 # AttributeError, which then crashes IPython.
198 break
198 break
199 else:
199 else:
200 # If we finish the for loop (no break), we got all members
200 # If we finish the for loop (no break), we got all members
201 found = 1
201 found = 1
202 ospace = nsname
202 ospace = nsname
203 if ns == alias_ns:
203 if ns == alias_ns:
204 isalias = 1
204 isalias = 1
205 break # namespace loop
205 break # namespace loop
206
206
207 # Try to see if it's magic
207 # Try to see if it's magic
208 if not found:
208 if not found:
209 if oname.startswith(self.shell.ESC_MAGIC):
209 if oname.startswith(self.shell.ESC_MAGIC):
210 oname = oname[1:]
210 oname = oname[1:]
211 obj = getattr(self,'magic_'+oname,None)
211 obj = getattr(self,'magic_'+oname,None)
212 if obj is not None:
212 if obj is not None:
213 found = 1
213 found = 1
214 ospace = 'IPython internal'
214 ospace = 'IPython internal'
215 ismagic = 1
215 ismagic = 1
216
216
217 # Last try: special-case some literals like '', [], {}, etc:
217 # Last try: special-case some literals like '', [], {}, etc:
218 if not found and oname_head in ["''",'""','[]','{}','()']:
218 if not found and oname_head in ["''",'""','[]','{}','()']:
219 obj = eval(oname_head)
219 obj = eval(oname_head)
220 found = 1
220 found = 1
221 ospace = 'Interactive'
221 ospace = 'Interactive'
222
222
223 return {'found':found, 'obj':obj, 'namespace':ospace,
223 return {'found':found, 'obj':obj, 'namespace':ospace,
224 'ismagic':ismagic, 'isalias':isalias}
224 'ismagic':ismagic, 'isalias':isalias}
225
225
226 def arg_err(self,func):
226 def arg_err(self,func):
227 """Print docstring if incorrect arguments were passed"""
227 """Print docstring if incorrect arguments were passed"""
228 print 'Error in arguments:'
228 print 'Error in arguments:'
229 print OInspect.getdoc(func)
229 print OInspect.getdoc(func)
230
230
231 def format_latex(self,strng):
231 def format_latex(self,strng):
232 """Format a string for latex inclusion."""
232 """Format a string for latex inclusion."""
233
233
234 # Characters that need to be escaped for latex:
234 # Characters that need to be escaped for latex:
235 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
235 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
236 # Magic command names as headers:
236 # Magic command names as headers:
237 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
237 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
238 re.MULTILINE)
238 re.MULTILINE)
239 # Magic commands
239 # Magic commands
240 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
240 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
241 re.MULTILINE)
241 re.MULTILINE)
242 # Paragraph continue
242 # Paragraph continue
243 par_re = re.compile(r'\\$',re.MULTILINE)
243 par_re = re.compile(r'\\$',re.MULTILINE)
244
244
245 # The "\n" symbol
245 # The "\n" symbol
246 newline_re = re.compile(r'\\n')
246 newline_re = re.compile(r'\\n')
247
247
248 # Now build the string for output:
248 # Now build the string for output:
249 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
249 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
250 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
250 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
251 strng = par_re.sub(r'\\\\',strng)
251 strng = par_re.sub(r'\\\\',strng)
252 strng = escape_re.sub(r'\\\1',strng)
252 strng = escape_re.sub(r'\\\1',strng)
253 strng = newline_re.sub(r'\\textbackslash{}n',strng)
253 strng = newline_re.sub(r'\\textbackslash{}n',strng)
254 return strng
254 return strng
255
255
256 def format_screen(self,strng):
256 def format_screen(self,strng):
257 """Format a string for screen printing.
257 """Format a string for screen printing.
258
258
259 This removes some latex-type format codes."""
259 This removes some latex-type format codes."""
260 # Paragraph continue
260 # Paragraph continue
261 par_re = re.compile(r'\\$',re.MULTILINE)
261 par_re = re.compile(r'\\$',re.MULTILINE)
262 strng = par_re.sub('',strng)
262 strng = par_re.sub('',strng)
263 return strng
263 return strng
264
264
265 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
265 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
266 """Parse options passed to an argument string.
266 """Parse options passed to an argument string.
267
267
268 The interface is similar to that of getopt(), but it returns back a
268 The interface is similar to that of getopt(), but it returns back a
269 Struct with the options as keys and the stripped argument string still
269 Struct with the options as keys and the stripped argument string still
270 as a string.
270 as a string.
271
271
272 arg_str is quoted as a true sys.argv vector by using shlex.split.
272 arg_str is quoted as a true sys.argv vector by using shlex.split.
273 This allows us to easily expand variables, glob files, quote
273 This allows us to easily expand variables, glob files, quote
274 arguments, etc.
274 arguments, etc.
275
275
276 Options:
276 Options:
277 -mode: default 'string'. If given as 'list', the argument string is
277 -mode: default 'string'. If given as 'list', the argument string is
278 returned as a list (split on whitespace) instead of a string.
278 returned as a list (split on whitespace) instead of a string.
279
279
280 -list_all: put all option values in lists. Normally only options
280 -list_all: put all option values in lists. Normally only options
281 appearing more than once are put in a list."""
281 appearing more than once are put in a list."""
282
282
283 # inject default options at the beginning of the input line
283 # inject default options at the beginning of the input line
284 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
284 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
285 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
285 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
286
286
287 mode = kw.get('mode','string')
287 mode = kw.get('mode','string')
288 if mode not in ['string','list']:
288 if mode not in ['string','list']:
289 raise ValueError,'incorrect mode given: %s' % mode
289 raise ValueError,'incorrect mode given: %s' % mode
290 # Get options
290 # Get options
291 list_all = kw.get('list_all',0)
291 list_all = kw.get('list_all',0)
292
292
293 # Check if we have more than one argument to warrant extra processing:
293 # Check if we have more than one argument to warrant extra processing:
294 odict = {} # Dictionary with options
294 odict = {} # Dictionary with options
295 args = arg_str.split()
295 args = arg_str.split()
296 if len(args) >= 1:
296 if len(args) >= 1:
297 # If the list of inputs only has 0 or 1 thing in it, there's no
297 # If the list of inputs only has 0 or 1 thing in it, there's no
298 # need to look for options
298 # need to look for options
299 argv = shlex_split(arg_str)
299 argv = shlex_split(arg_str)
300 # Do regular option processing
300 # Do regular option processing
301 opts,args = getopt(argv,opt_str,*long_opts)
301 opts,args = getopt(argv,opt_str,*long_opts)
302 for o,a in opts:
302 for o,a in opts:
303 if o.startswith('--'):
303 if o.startswith('--'):
304 o = o[2:]
304 o = o[2:]
305 else:
305 else:
306 o = o[1:]
306 o = o[1:]
307 try:
307 try:
308 odict[o].append(a)
308 odict[o].append(a)
309 except AttributeError:
309 except AttributeError:
310 odict[o] = [odict[o],a]
310 odict[o] = [odict[o],a]
311 except KeyError:
311 except KeyError:
312 if list_all:
312 if list_all:
313 odict[o] = [a]
313 odict[o] = [a]
314 else:
314 else:
315 odict[o] = a
315 odict[o] = a
316
316
317 # Prepare opts,args for return
317 # Prepare opts,args for return
318 opts = Struct(odict)
318 opts = Struct(odict)
319 if mode == 'string':
319 if mode == 'string':
320 args = ' '.join(args)
320 args = ' '.join(args)
321
321
322 return opts,args
322 return opts,args
323
323
324 #......................................................................
324 #......................................................................
325 # And now the actual magic functions
325 # And now the actual magic functions
326
326
327 # Functions for IPython shell work (vars,funcs, config, etc)
327 # Functions for IPython shell work (vars,funcs, config, etc)
328 def magic_lsmagic(self, parameter_s = ''):
328 def magic_lsmagic(self, parameter_s = ''):
329 """List currently available magic functions."""
329 """List currently available magic functions."""
330 mesc = self.shell.ESC_MAGIC
330 mesc = self.shell.ESC_MAGIC
331 print 'Available magic functions:\n'+mesc+\
331 print 'Available magic functions:\n'+mesc+\
332 (' '+mesc).join(self.lsmagic())
332 (' '+mesc).join(self.lsmagic())
333 print '\n' + Magic.auto_status[self.shell.rc.automagic]
333 print '\n' + Magic.auto_status[self.shell.rc.automagic]
334 return None
334 return None
335
335
336 def magic_magic(self, parameter_s = ''):
336 def magic_magic(self, parameter_s = ''):
337 """Print information about the magic function system."""
337 """Print information about the magic function system."""
338
338
339 mode = ''
339 mode = ''
340 try:
340 try:
341 if parameter_s.split()[0] == '-latex':
341 if parameter_s.split()[0] == '-latex':
342 mode = 'latex'
342 mode = 'latex'
343 except:
343 except:
344 pass
344 pass
345
345
346 magic_docs = []
346 magic_docs = []
347 for fname in self.lsmagic():
347 for fname in self.lsmagic():
348 mname = 'magic_' + fname
348 mname = 'magic_' + fname
349 for space in (Magic,self,self.__class__):
349 for space in (Magic,self,self.__class__):
350 try:
350 try:
351 fn = space.__dict__[mname]
351 fn = space.__dict__[mname]
352 except KeyError:
352 except KeyError:
353 pass
353 pass
354 else:
354 else:
355 break
355 break
356 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
356 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
357 fname,fn.__doc__))
357 fname,fn.__doc__))
358 magic_docs = ''.join(magic_docs)
358 magic_docs = ''.join(magic_docs)
359
359
360 if mode == 'latex':
360 if mode == 'latex':
361 print self.format_latex(magic_docs)
361 print self.format_latex(magic_docs)
362 return
362 return
363 else:
363 else:
364 magic_docs = self.format_screen(magic_docs)
364 magic_docs = self.format_screen(magic_docs)
365
365
366 outmsg = """
366 outmsg = """
367 IPython's 'magic' functions
367 IPython's 'magic' functions
368 ===========================
368 ===========================
369
369
370 The magic function system provides a series of functions which allow you to
370 The magic function system provides a series of functions which allow you to
371 control the behavior of IPython itself, plus a lot of system-type
371 control the behavior of IPython itself, plus a lot of system-type
372 features. All these functions are prefixed with a % character, but parameters
372 features. All these functions are prefixed with a % character, but parameters
373 are given without parentheses or quotes.
373 are given without parentheses or quotes.
374
374
375 NOTE: If you have 'automagic' enabled (via the command line option or with the
375 NOTE: If you have 'automagic' enabled (via the command line option or with the
376 %automagic function), you don't need to type in the % explicitly. By default,
376 %automagic function), you don't need to type in the % explicitly. By default,
377 IPython ships with automagic on, so you should only rarely need the % escape.
377 IPython ships with automagic on, so you should only rarely need the % escape.
378
378
379 Example: typing '%cd mydir' (without the quotes) changes you working directory
379 Example: typing '%cd mydir' (without the quotes) changes you working directory
380 to 'mydir', if it exists.
380 to 'mydir', if it exists.
381
381
382 You can define your own magic functions to extend the system. See the supplied
382 You can define your own magic functions to extend the system. See the supplied
383 ipythonrc and example-magic.py files for details (in your ipython
383 ipythonrc and example-magic.py files for details (in your ipython
384 configuration directory, typically $HOME/.ipython/).
384 configuration directory, typically $HOME/.ipython/).
385
385
386 You can also define your own aliased names for magic functions. In your
386 You can also define your own aliased names for magic functions. In your
387 ipythonrc file, placing a line like:
387 ipythonrc file, placing a line like:
388
388
389 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
389 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
390
390
391 will define %pf as a new name for %profile.
391 will define %pf as a new name for %profile.
392
392
393 You can also call magics in code using the ipmagic() function, which IPython
393 You can also call magics in code using the ipmagic() function, which IPython
394 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
394 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
395
395
396 For a list of the available magic functions, use %lsmagic. For a description
396 For a list of the available magic functions, use %lsmagic. For a description
397 of any of them, type %magic_name?, e.g. '%cd?'.
397 of any of them, type %magic_name?, e.g. '%cd?'.
398
398
399 Currently the magic system has the following functions:\n"""
399 Currently the magic system has the following functions:\n"""
400
400
401 mesc = self.shell.ESC_MAGIC
401 mesc = self.shell.ESC_MAGIC
402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
403 "\n\n%s%s\n\n%s" % (outmsg,
403 "\n\n%s%s\n\n%s" % (outmsg,
404 magic_docs,mesc,mesc,
404 magic_docs,mesc,mesc,
405 (' '+mesc).join(self.lsmagic()),
405 (' '+mesc).join(self.lsmagic()),
406 Magic.auto_status[self.shell.rc.automagic] ) )
406 Magic.auto_status[self.shell.rc.automagic] ) )
407
407
408 page(outmsg,screen_lines=self.shell.rc.screen_length)
408 page(outmsg,screen_lines=self.shell.rc.screen_length)
409
409
410 def magic_automagic(self, parameter_s = ''):
410 def magic_automagic(self, parameter_s = ''):
411 """Make magic functions callable without having to type the initial %.
411 """Make magic functions callable without having to type the initial %.
412
412
413 Toggles on/off (when off, you must call it as %automagic, of
413 Toggles on/off (when off, you must call it as %automagic, of
414 course). Note that magic functions have lowest priority, so if there's
414 course). Note that magic functions have lowest priority, so if there's
415 a variable whose name collides with that of a magic fn, automagic
415 a variable whose name collides with that of a magic fn, automagic
416 won't work for that function (you get the variable instead). However,
416 won't work for that function (you get the variable instead). However,
417 if you delete the variable (del var), the previously shadowed magic
417 if you delete the variable (del var), the previously shadowed magic
418 function becomes visible to automagic again."""
418 function becomes visible to automagic again."""
419
419
420 rc = self.shell.rc
420 rc = self.shell.rc
421 rc.automagic = not rc.automagic
421 rc.automagic = not rc.automagic
422 print '\n' + Magic.auto_status[rc.automagic]
422 print '\n' + Magic.auto_status[rc.automagic]
423
423
424 def magic_autocall(self, parameter_s = ''):
424 def magic_autocall(self, parameter_s = ''):
425 """Make functions callable without having to type parentheses.
425 """Make functions callable without having to type parentheses.
426
426
427 This toggles the autocall command line option on and off."""
427 This cycles the autocall command line through its three valid values
428 (0->Off, 1->Smart, 2->Full)"""
428
429
429 rc = self.shell.rc
430 rc = self.shell.rc
430 rc.autocall = not rc.autocall
431 rc.autocall = not rc.autocall
431 print "Automatic calling is:",['OFF','ON'][rc.autocall]
432 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
432
433
433 def magic_autoindent(self, parameter_s = ''):
434 def magic_autoindent(self, parameter_s = ''):
434 """Toggle autoindent on/off (if available)."""
435 """Toggle autoindent on/off (if available)."""
435
436
436 self.shell.set_autoindent()
437 self.shell.set_autoindent()
437 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
438 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
438
439
439 def magic_system_verbose(self, parameter_s = ''):
440 def magic_system_verbose(self, parameter_s = ''):
440 """Toggle verbose printing of system calls on/off."""
441 """Toggle verbose printing of system calls on/off."""
441
442
442 self.shell.rc_set_toggle('system_verbose')
443 self.shell.rc_set_toggle('system_verbose')
443 print "System verbose printing is:",\
444 print "System verbose printing is:",\
444 ['OFF','ON'][self.shell.rc.system_verbose]
445 ['OFF','ON'][self.shell.rc.system_verbose]
445
446
446 def magic_history(self, parameter_s = ''):
447 def magic_history(self, parameter_s = ''):
447 """Print input history (_i<n> variables), with most recent last.
448 """Print input history (_i<n> variables), with most recent last.
448
449
449 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
450 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
450 %history [-n] n -> print at most n inputs\\
451 %history [-n] n -> print at most n inputs\\
451 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
452 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
452
453
453 Each input's number <n> is shown, and is accessible as the
454 Each input's number <n> is shown, and is accessible as the
454 automatically generated variable _i<n>. Multi-line statements are
455 automatically generated variable _i<n>. Multi-line statements are
455 printed starting at a new line for easy copy/paste.
456 printed starting at a new line for easy copy/paste.
456
457
457 If option -n is used, input numbers are not printed. This is useful if
458 If option -n is used, input numbers are not printed. This is useful if
458 you want to get a printout of many lines which can be directly pasted
459 you want to get a printout of many lines which can be directly pasted
459 into a text editor.
460 into a text editor.
460
461
461 This feature is only available if numbered prompts are in use."""
462 This feature is only available if numbered prompts are in use."""
462
463
463 shell = self.shell
464 shell = self.shell
464 if not shell.outputcache.do_full_cache:
465 if not shell.outputcache.do_full_cache:
465 print 'This feature is only available if numbered prompts are in use.'
466 print 'This feature is only available if numbered prompts are in use.'
466 return
467 return
467 opts,args = self.parse_options(parameter_s,'n',mode='list')
468 opts,args = self.parse_options(parameter_s,'n',mode='list')
468
469
469 input_hist = shell.input_hist
470 input_hist = shell.input_hist
470 default_length = 40
471 default_length = 40
471 if len(args) == 0:
472 if len(args) == 0:
472 final = len(input_hist)
473 final = len(input_hist)
473 init = max(1,final-default_length)
474 init = max(1,final-default_length)
474 elif len(args) == 1:
475 elif len(args) == 1:
475 final = len(input_hist)
476 final = len(input_hist)
476 init = max(1,final-int(args[0]))
477 init = max(1,final-int(args[0]))
477 elif len(args) == 2:
478 elif len(args) == 2:
478 init,final = map(int,args)
479 init,final = map(int,args)
479 else:
480 else:
480 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
481 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
481 print self.magic_hist.__doc__
482 print self.magic_hist.__doc__
482 return
483 return
483 width = len(str(final))
484 width = len(str(final))
484 line_sep = ['','\n']
485 line_sep = ['','\n']
485 print_nums = not opts.has_key('n')
486 print_nums = not opts.has_key('n')
486 for in_num in range(init,final):
487 for in_num in range(init,final):
487 inline = input_hist[in_num]
488 inline = input_hist[in_num]
488 multiline = int(inline.count('\n') > 1)
489 multiline = int(inline.count('\n') > 1)
489 if print_nums:
490 if print_nums:
490 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
491 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
491 print inline,
492 print inline,
492
493
493 def magic_hist(self, parameter_s=''):
494 def magic_hist(self, parameter_s=''):
494 """Alternate name for %history."""
495 """Alternate name for %history."""
495 return self.magic_history(parameter_s)
496 return self.magic_history(parameter_s)
496
497
497 def magic_p(self, parameter_s=''):
498 def magic_p(self, parameter_s=''):
498 """Just a short alias for Python's 'print'."""
499 """Just a short alias for Python's 'print'."""
499 exec 'print ' + parameter_s in self.shell.user_ns
500 exec 'print ' + parameter_s in self.shell.user_ns
500
501
501 def magic_r(self, parameter_s=''):
502 def magic_r(self, parameter_s=''):
502 """Repeat previous input.
503 """Repeat previous input.
503
504
504 If given an argument, repeats the previous command which starts with
505 If given an argument, repeats the previous command which starts with
505 the same string, otherwise it just repeats the previous input.
506 the same string, otherwise it just repeats the previous input.
506
507
507 Shell escaped commands (with ! as first character) are not recognized
508 Shell escaped commands (with ! as first character) are not recognized
508 by this system, only pure python code and magic commands.
509 by this system, only pure python code and magic commands.
509 """
510 """
510
511
511 start = parameter_s.strip()
512 start = parameter_s.strip()
512 esc_magic = self.shell.ESC_MAGIC
513 esc_magic = self.shell.ESC_MAGIC
513 # Identify magic commands even if automagic is on (which means
514 # Identify magic commands even if automagic is on (which means
514 # the in-memory version is different from that typed by the user).
515 # the in-memory version is different from that typed by the user).
515 if self.shell.rc.automagic:
516 if self.shell.rc.automagic:
516 start_magic = esc_magic+start
517 start_magic = esc_magic+start
517 else:
518 else:
518 start_magic = start
519 start_magic = start
519 # Look through the input history in reverse
520 # Look through the input history in reverse
520 for n in range(len(self.shell.input_hist)-2,0,-1):
521 for n in range(len(self.shell.input_hist)-2,0,-1):
521 input = self.shell.input_hist[n]
522 input = self.shell.input_hist[n]
522 # skip plain 'r' lines so we don't recurse to infinity
523 # skip plain 'r' lines so we don't recurse to infinity
523 if input != 'ipmagic("r")\n' and \
524 if input != 'ipmagic("r")\n' and \
524 (input.startswith(start) or input.startswith(start_magic)):
525 (input.startswith(start) or input.startswith(start_magic)):
525 #print 'match',`input` # dbg
526 #print 'match',`input` # dbg
526 print 'Executing:',input,
527 print 'Executing:',input,
527 self.shell.runlines(input)
528 self.shell.runlines(input)
528 return
529 return
529 print 'No previous input matching `%s` found.' % start
530 print 'No previous input matching `%s` found.' % start
530
531
531 def magic_page(self, parameter_s=''):
532 def magic_page(self, parameter_s=''):
532 """Pretty print the object and display it through a pager.
533 """Pretty print the object and display it through a pager.
533
534
534 If no parameter is given, use _ (last output)."""
535 If no parameter is given, use _ (last output)."""
535 # After a function contributed by Olivier Aubert, slightly modified.
536 # After a function contributed by Olivier Aubert, slightly modified.
536
537
537 oname = parameter_s and parameter_s or '_'
538 oname = parameter_s and parameter_s or '_'
538 info = self._ofind(oname)
539 info = self._ofind(oname)
539 if info['found']:
540 if info['found']:
540 page(pformat(info['obj']))
541 page(pformat(info['obj']))
541 else:
542 else:
542 print 'Object `%s` not found' % oname
543 print 'Object `%s` not found' % oname
543
544
544 def magic_profile(self, parameter_s=''):
545 def magic_profile(self, parameter_s=''):
545 """Print your currently active IPyhton profile."""
546 """Print your currently active IPyhton profile."""
546 if self.shell.rc.profile:
547 if self.shell.rc.profile:
547 printpl('Current IPython profile: $self.shell.rc.profile.')
548 printpl('Current IPython profile: $self.shell.rc.profile.')
548 else:
549 else:
549 print 'No profile active.'
550 print 'No profile active.'
550
551
551 def _inspect(self,meth,oname,**kw):
552 def _inspect(self,meth,oname,**kw):
552 """Generic interface to the inspector system.
553 """Generic interface to the inspector system.
553
554
554 This function is meant to be called by pdef, pdoc & friends."""
555 This function is meant to be called by pdef, pdoc & friends."""
555
556
556 oname = oname.strip()
557 oname = oname.strip()
557 info = Struct(self._ofind(oname))
558 info = Struct(self._ofind(oname))
558 if info.found:
559 if info.found:
559 pmethod = getattr(self.shell.inspector,meth)
560 pmethod = getattr(self.shell.inspector,meth)
560 formatter = info.ismagic and self.format_screen or None
561 formatter = info.ismagic and self.format_screen or None
561 if meth == 'pdoc':
562 if meth == 'pdoc':
562 pmethod(info.obj,oname,formatter)
563 pmethod(info.obj,oname,formatter)
563 elif meth == 'pinfo':
564 elif meth == 'pinfo':
564 pmethod(info.obj,oname,formatter,info,**kw)
565 pmethod(info.obj,oname,formatter,info,**kw)
565 else:
566 else:
566 pmethod(info.obj,oname)
567 pmethod(info.obj,oname)
567 else:
568 else:
568 print 'Object `%s` not found.' % oname
569 print 'Object `%s` not found.' % oname
569 return 'not found' # so callers can take other action
570 return 'not found' # so callers can take other action
570
571
571 def magic_pdef(self, parameter_s=''):
572 def magic_pdef(self, parameter_s=''):
572 """Print the definition header for any callable object.
573 """Print the definition header for any callable object.
573
574
574 If the object is a class, print the constructor information."""
575 If the object is a class, print the constructor information."""
575 self._inspect('pdef',parameter_s)
576 self._inspect('pdef',parameter_s)
576
577
577 def magic_pdoc(self, parameter_s=''):
578 def magic_pdoc(self, parameter_s=''):
578 """Print the docstring for an object.
579 """Print the docstring for an object.
579
580
580 If the given object is a class, it will print both the class and the
581 If the given object is a class, it will print both the class and the
581 constructor docstrings."""
582 constructor docstrings."""
582 self._inspect('pdoc',parameter_s)
583 self._inspect('pdoc',parameter_s)
583
584
584 def magic_psource(self, parameter_s=''):
585 def magic_psource(self, parameter_s=''):
585 """Print (or run through pager) the source code for an object."""
586 """Print (or run through pager) the source code for an object."""
586 self._inspect('psource',parameter_s)
587 self._inspect('psource',parameter_s)
587
588
588 def magic_pfile(self, parameter_s=''):
589 def magic_pfile(self, parameter_s=''):
589 """Print (or run through pager) the file where an object is defined.
590 """Print (or run through pager) the file where an object is defined.
590
591
591 The file opens at the line where the object definition begins. IPython
592 The file opens at the line where the object definition begins. IPython
592 will honor the environment variable PAGER if set, and otherwise will
593 will honor the environment variable PAGER if set, and otherwise will
593 do its best to print the file in a convenient form.
594 do its best to print the file in a convenient form.
594
595
595 If the given argument is not an object currently defined, IPython will
596 If the given argument is not an object currently defined, IPython will
596 try to interpret it as a filename (automatically adding a .py extension
597 try to interpret it as a filename (automatically adding a .py extension
597 if needed). You can thus use %pfile as a syntax highlighting code
598 if needed). You can thus use %pfile as a syntax highlighting code
598 viewer."""
599 viewer."""
599
600
600 # first interpret argument as an object name
601 # first interpret argument as an object name
601 out = self._inspect('pfile',parameter_s)
602 out = self._inspect('pfile',parameter_s)
602 # if not, try the input as a filename
603 # if not, try the input as a filename
603 if out == 'not found':
604 if out == 'not found':
604 try:
605 try:
605 filename = get_py_filename(parameter_s)
606 filename = get_py_filename(parameter_s)
606 except IOError,msg:
607 except IOError,msg:
607 print msg
608 print msg
608 return
609 return
609 page(self.shell.inspector.format(file(filename).read()))
610 page(self.shell.inspector.format(file(filename).read()))
610
611
611 def magic_pinfo(self, parameter_s=''):
612 def magic_pinfo(self, parameter_s=''):
612 """Provide detailed information about an object.
613 """Provide detailed information about an object.
613
614
614 '%pinfo object' is just a synonym for object? or ?object."""
615 '%pinfo object' is just a synonym for object? or ?object."""
615
616
616 #print 'pinfo par: <%s>' % parameter_s # dbg
617 #print 'pinfo par: <%s>' % parameter_s # dbg
617
618
618 # detail_level: 0 -> obj? , 1 -> obj??
619 # detail_level: 0 -> obj? , 1 -> obj??
619 detail_level = 0
620 detail_level = 0
620 # We need to detect if we got called as 'pinfo pinfo foo', which can
621 # We need to detect if we got called as 'pinfo pinfo foo', which can
621 # happen if the user types 'pinfo foo?' at the cmd line.
622 # happen if the user types 'pinfo foo?' at the cmd line.
622 pinfo,qmark1,oname,qmark2 = \
623 pinfo,qmark1,oname,qmark2 = \
623 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
624 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
624 if pinfo or qmark1 or qmark2:
625 if pinfo or qmark1 or qmark2:
625 detail_level = 1
626 detail_level = 1
626 if "*" in oname:
627 if "*" in oname:
627 self.magic_psearch(oname)
628 self.magic_psearch(oname)
628 else:
629 else:
629 self._inspect('pinfo',oname,detail_level=detail_level)
630 self._inspect('pinfo',oname,detail_level=detail_level)
630
631
631 def magic_psearch(self, parameter_s=''):
632 def magic_psearch(self, parameter_s=''):
632 """Search for object in namespaces by wildcard.
633 """Search for object in namespaces by wildcard.
633
634
634 %psearch [options] PATTERN [OBJECT TYPE]
635 %psearch [options] PATTERN [OBJECT TYPE]
635
636
636 Note: ? can be used as a synonym for %psearch, at the beginning or at
637 Note: ? can be used as a synonym for %psearch, at the beginning or at
637 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
638 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
638 rest of the command line must be unchanged (options come first), so
639 rest of the command line must be unchanged (options come first), so
639 for example the following forms are equivalent
640 for example the following forms are equivalent
640
641
641 %psearch -i a* function
642 %psearch -i a* function
642 -i a* function?
643 -i a* function?
643 ?-i a* function
644 ?-i a* function
644
645
645 Arguments:
646 Arguments:
646
647
647 PATTERN
648 PATTERN
648
649
649 where PATTERN is a string containing * as a wildcard similar to its
650 where PATTERN is a string containing * as a wildcard similar to its
650 use in a shell. The pattern is matched in all namespaces on the
651 use in a shell. The pattern is matched in all namespaces on the
651 search path. By default objects starting with a single _ are not
652 search path. By default objects starting with a single _ are not
652 matched, many IPython generated objects have a single
653 matched, many IPython generated objects have a single
653 underscore. The default is case insensitive matching. Matching is
654 underscore. The default is case insensitive matching. Matching is
654 also done on the attributes of objects and not only on the objects
655 also done on the attributes of objects and not only on the objects
655 in a module.
656 in a module.
656
657
657 [OBJECT TYPE]
658 [OBJECT TYPE]
658
659
659 Is the name of a python type from the types module. The name is
660 Is the name of a python type from the types module. The name is
660 given in lowercase without the ending type, ex. StringType is
661 given in lowercase without the ending type, ex. StringType is
661 written string. By adding a type here only objects matching the
662 written string. By adding a type here only objects matching the
662 given type are matched. Using all here makes the pattern match all
663 given type are matched. Using all here makes the pattern match all
663 types (this is the default).
664 types (this is the default).
664
665
665 Options:
666 Options:
666
667
667 -a: makes the pattern match even objects whose names start with a
668 -a: makes the pattern match even objects whose names start with a
668 single underscore. These names are normally ommitted from the
669 single underscore. These names are normally ommitted from the
669 search.
670 search.
670
671
671 -i/-c: make the pattern case insensitive/sensitive. If neither of
672 -i/-c: make the pattern case insensitive/sensitive. If neither of
672 these options is given, the default is read from your ipythonrc
673 these options is given, the default is read from your ipythonrc
673 file. The option name which sets this value is
674 file. The option name which sets this value is
674 'wildcards_case_sensitive'. If this option is not specified in your
675 'wildcards_case_sensitive'. If this option is not specified in your
675 ipythonrc file, IPython's internal default is to do a case sensitive
676 ipythonrc file, IPython's internal default is to do a case sensitive
676 search.
677 search.
677
678
678 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
679 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
679 specifiy can be searched in any of the following namespaces:
680 specifiy can be searched in any of the following namespaces:
680 'builtin', 'user', 'user_global','internal', 'alias', where
681 'builtin', 'user', 'user_global','internal', 'alias', where
681 'builtin' and 'user' are the search defaults. Note that you should
682 'builtin' and 'user' are the search defaults. Note that you should
682 not use quotes when specifying namespaces.
683 not use quotes when specifying namespaces.
683
684
684 'Builtin' contains the python module builtin, 'user' contains all
685 'Builtin' contains the python module builtin, 'user' contains all
685 user data, 'alias' only contain the shell aliases and no python
686 user data, 'alias' only contain the shell aliases and no python
686 objects, 'internal' contains objects used by IPython. The
687 objects, 'internal' contains objects used by IPython. The
687 'user_global' namespace is only used by embedded IPython instances,
688 'user_global' namespace is only used by embedded IPython instances,
688 and it contains module-level globals. You can add namespaces to the
689 and it contains module-level globals. You can add namespaces to the
689 search with -s or exclude them with -e (these options can be given
690 search with -s or exclude them with -e (these options can be given
690 more than once).
691 more than once).
691
692
692 Examples:
693 Examples:
693
694
694 %psearch a* -> objects beginning with an a
695 %psearch a* -> objects beginning with an a
695 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
696 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
696 %psearch a* function -> all functions beginning with an a
697 %psearch a* function -> all functions beginning with an a
697 %psearch re.e* -> objects beginning with an e in module re
698 %psearch re.e* -> objects beginning with an e in module re
698 %psearch r*.e* -> objects that start with e in modules starting in r
699 %psearch r*.e* -> objects that start with e in modules starting in r
699 %psearch r*.* string -> all strings in modules beginning with r
700 %psearch r*.* string -> all strings in modules beginning with r
700
701
701 Case sensitve search:
702 Case sensitve search:
702
703
703 %psearch -c a* list all object beginning with lower case a
704 %psearch -c a* list all object beginning with lower case a
704
705
705 Show objects beginning with a single _:
706 Show objects beginning with a single _:
706
707
707 %psearch -a _* list objects beginning with a single underscore"""
708 %psearch -a _* list objects beginning with a single underscore"""
708
709
709 # default namespaces to be searched
710 # default namespaces to be searched
710 def_search = ['user','builtin']
711 def_search = ['user','builtin']
711
712
712 # Process options/args
713 # Process options/args
713 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
714 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
714 opt = opts.get
715 opt = opts.get
715 shell = self.shell
716 shell = self.shell
716 psearch = shell.inspector.psearch
717 psearch = shell.inspector.psearch
717
718
718 # select case options
719 # select case options
719 if opts.has_key('i'):
720 if opts.has_key('i'):
720 ignore_case = True
721 ignore_case = True
721 elif opts.has_key('c'):
722 elif opts.has_key('c'):
722 ignore_case = False
723 ignore_case = False
723 else:
724 else:
724 ignore_case = not shell.rc.wildcards_case_sensitive
725 ignore_case = not shell.rc.wildcards_case_sensitive
725
726
726 # Build list of namespaces to search from user options
727 # Build list of namespaces to search from user options
727 def_search.extend(opt('s',[]))
728 def_search.extend(opt('s',[]))
728 ns_exclude = ns_exclude=opt('e',[])
729 ns_exclude = ns_exclude=opt('e',[])
729 ns_search = [nm for nm in def_search if nm not in ns_exclude]
730 ns_search = [nm for nm in def_search if nm not in ns_exclude]
730
731
731 # Call the actual search
732 # Call the actual search
732 try:
733 try:
733 psearch(args,shell.ns_table,ns_search,
734 psearch(args,shell.ns_table,ns_search,
734 show_all=opt('a'),ignore_case=ignore_case)
735 show_all=opt('a'),ignore_case=ignore_case)
735 except:
736 except:
736 shell.showtraceback()
737 shell.showtraceback()
737
738
738 def magic_who_ls(self, parameter_s=''):
739 def magic_who_ls(self, parameter_s=''):
739 """Return a sorted list of all interactive variables.
740 """Return a sorted list of all interactive variables.
740
741
741 If arguments are given, only variables of types matching these
742 If arguments are given, only variables of types matching these
742 arguments are returned."""
743 arguments are returned."""
743
744
744 user_ns = self.shell.user_ns
745 user_ns = self.shell.user_ns
745 internal_ns = self.shell.internal_ns
746 internal_ns = self.shell.internal_ns
746 user_config_ns = self.shell.user_config_ns
747 user_config_ns = self.shell.user_config_ns
747 out = []
748 out = []
748 typelist = parameter_s.split()
749 typelist = parameter_s.split()
749
750
750 for i in user_ns:
751 for i in user_ns:
751 if not (i.startswith('_') or i.startswith('_i')) \
752 if not (i.startswith('_') or i.startswith('_i')) \
752 and not (i in internal_ns or i in user_config_ns):
753 and not (i in internal_ns or i in user_config_ns):
753 if typelist:
754 if typelist:
754 if type(user_ns[i]).__name__ in typelist:
755 if type(user_ns[i]).__name__ in typelist:
755 out.append(i)
756 out.append(i)
756 else:
757 else:
757 out.append(i)
758 out.append(i)
758 out.sort()
759 out.sort()
759 return out
760 return out
760
761
761 def magic_who(self, parameter_s=''):
762 def magic_who(self, parameter_s=''):
762 """Print all interactive variables, with some minimal formatting.
763 """Print all interactive variables, with some minimal formatting.
763
764
764 If any arguments are given, only variables whose type matches one of
765 If any arguments are given, only variables whose type matches one of
765 these are printed. For example:
766 these are printed. For example:
766
767
767 %who function str
768 %who function str
768
769
769 will only list functions and strings, excluding all other types of
770 will only list functions and strings, excluding all other types of
770 variables. To find the proper type names, simply use type(var) at a
771 variables. To find the proper type names, simply use type(var) at a
771 command line to see how python prints type names. For example:
772 command line to see how python prints type names. For example:
772
773
773 In [1]: type('hello')\\
774 In [1]: type('hello')\\
774 Out[1]: <type 'str'>
775 Out[1]: <type 'str'>
775
776
776 indicates that the type name for strings is 'str'.
777 indicates that the type name for strings is 'str'.
777
778
778 %who always excludes executed names loaded through your configuration
779 %who always excludes executed names loaded through your configuration
779 file and things which are internal to IPython.
780 file and things which are internal to IPython.
780
781
781 This is deliberate, as typically you may load many modules and the
782 This is deliberate, as typically you may load many modules and the
782 purpose of %who is to show you only what you've manually defined."""
783 purpose of %who is to show you only what you've manually defined."""
783
784
784 varlist = self.magic_who_ls(parameter_s)
785 varlist = self.magic_who_ls(parameter_s)
785 if not varlist:
786 if not varlist:
786 print 'Interactive namespace is empty.'
787 print 'Interactive namespace is empty.'
787 return
788 return
788
789
789 # if we have variables, move on...
790 # if we have variables, move on...
790
791
791 # stupid flushing problem: when prompts have no separators, stdout is
792 # stupid flushing problem: when prompts have no separators, stdout is
792 # getting lost. I'm starting to think this is a python bug. I'm having
793 # getting lost. I'm starting to think this is a python bug. I'm having
793 # to force a flush with a print because even a sys.stdout.flush
794 # to force a flush with a print because even a sys.stdout.flush
794 # doesn't seem to do anything!
795 # doesn't seem to do anything!
795
796
796 count = 0
797 count = 0
797 for i in varlist:
798 for i in varlist:
798 print i+'\t',
799 print i+'\t',
799 count += 1
800 count += 1
800 if count > 8:
801 if count > 8:
801 count = 0
802 count = 0
802 print
803 print
803 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
804 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
804
805
805 print # well, this does force a flush at the expense of an extra \n
806 print # well, this does force a flush at the expense of an extra \n
806
807
807 def magic_whos(self, parameter_s=''):
808 def magic_whos(self, parameter_s=''):
808 """Like %who, but gives some extra information about each variable.
809 """Like %who, but gives some extra information about each variable.
809
810
810 The same type filtering of %who can be applied here.
811 The same type filtering of %who can be applied here.
811
812
812 For all variables, the type is printed. Additionally it prints:
813 For all variables, the type is printed. Additionally it prints:
813
814
814 - For {},[],(): their length.
815 - For {},[],(): their length.
815
816
816 - For Numeric arrays, a summary with shape, number of elements,
817 - For Numeric arrays, a summary with shape, number of elements,
817 typecode and size in memory.
818 typecode and size in memory.
818
819
819 - Everything else: a string representation, snipping their middle if
820 - Everything else: a string representation, snipping their middle if
820 too long."""
821 too long."""
821
822
822 varnames = self.magic_who_ls(parameter_s)
823 varnames = self.magic_who_ls(parameter_s)
823 if not varnames:
824 if not varnames:
824 print 'Interactive namespace is empty.'
825 print 'Interactive namespace is empty.'
825 return
826 return
826
827
827 # if we have variables, move on...
828 # if we have variables, move on...
828
829
829 # for these types, show len() instead of data:
830 # for these types, show len() instead of data:
830 seq_types = [types.DictType,types.ListType,types.TupleType]
831 seq_types = [types.DictType,types.ListType,types.TupleType]
831
832
832 # for Numeric arrays, display summary info
833 # for Numeric arrays, display summary info
833 try:
834 try:
834 import Numeric
835 import Numeric
835 except ImportError:
836 except ImportError:
836 array_type = None
837 array_type = None
837 else:
838 else:
838 array_type = Numeric.ArrayType.__name__
839 array_type = Numeric.ArrayType.__name__
839
840
840 # Find all variable names and types so we can figure out column sizes
841 # Find all variable names and types so we can figure out column sizes
841 get_vars = lambda i: self.shell.user_ns[i]
842 get_vars = lambda i: self.shell.user_ns[i]
842 type_name = lambda v: type(v).__name__
843 type_name = lambda v: type(v).__name__
843 varlist = map(get_vars,varnames)
844 varlist = map(get_vars,varnames)
844
845
845 typelist = []
846 typelist = []
846 for vv in varlist:
847 for vv in varlist:
847 tt = type_name(vv)
848 tt = type_name(vv)
848 if tt=='instance':
849 if tt=='instance':
849 typelist.append(str(vv.__class__))
850 typelist.append(str(vv.__class__))
850 else:
851 else:
851 typelist.append(tt)
852 typelist.append(tt)
852
853
853 # column labels and # of spaces as separator
854 # column labels and # of spaces as separator
854 varlabel = 'Variable'
855 varlabel = 'Variable'
855 typelabel = 'Type'
856 typelabel = 'Type'
856 datalabel = 'Data/Info'
857 datalabel = 'Data/Info'
857 colsep = 3
858 colsep = 3
858 # variable format strings
859 # variable format strings
859 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
860 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
860 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
861 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
861 aformat = "%s: %s elems, type `%s`, %s bytes"
862 aformat = "%s: %s elems, type `%s`, %s bytes"
862 # find the size of the columns to format the output nicely
863 # find the size of the columns to format the output nicely
863 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
864 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
864 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
865 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
865 # table header
866 # table header
866 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
867 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
867 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
868 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
868 # and the table itself
869 # and the table itself
869 kb = 1024
870 kb = 1024
870 Mb = 1048576 # kb**2
871 Mb = 1048576 # kb**2
871 for vname,var,vtype in zip(varnames,varlist,typelist):
872 for vname,var,vtype in zip(varnames,varlist,typelist):
872 print itpl(vformat),
873 print itpl(vformat),
873 if vtype in seq_types:
874 if vtype in seq_types:
874 print len(var)
875 print len(var)
875 elif vtype==array_type:
876 elif vtype==array_type:
876 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
877 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
877 vsize = Numeric.size(var)
878 vsize = Numeric.size(var)
878 vbytes = vsize*var.itemsize()
879 vbytes = vsize*var.itemsize()
879 if vbytes < 100000:
880 if vbytes < 100000:
880 print aformat % (vshape,vsize,var.typecode(),vbytes)
881 print aformat % (vshape,vsize,var.typecode(),vbytes)
881 else:
882 else:
882 print aformat % (vshape,vsize,var.typecode(),vbytes),
883 print aformat % (vshape,vsize,var.typecode(),vbytes),
883 if vbytes < Mb:
884 if vbytes < Mb:
884 print '(%s kb)' % (vbytes/kb,)
885 print '(%s kb)' % (vbytes/kb,)
885 else:
886 else:
886 print '(%s Mb)' % (vbytes/Mb,)
887 print '(%s Mb)' % (vbytes/Mb,)
887 else:
888 else:
888 vstr = str(var).replace('\n','\\n')
889 vstr = str(var).replace('\n','\\n')
889 if len(vstr) < 50:
890 if len(vstr) < 50:
890 print vstr
891 print vstr
891 else:
892 else:
892 printpl(vfmt_short)
893 printpl(vfmt_short)
893
894
894 def magic_reset(self, parameter_s=''):
895 def magic_reset(self, parameter_s=''):
895 """Resets the namespace by removing all names defined by the user.
896 """Resets the namespace by removing all names defined by the user.
896
897
897 Input/Output history are left around in case you need them."""
898 Input/Output history are left around in case you need them."""
898
899
899 ans = raw_input(
900 ans = raw_input(
900 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
901 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
901 if not ans.lower() == 'y':
902 if not ans.lower() == 'y':
902 print 'Nothing done.'
903 print 'Nothing done.'
903 return
904 return
904 user_ns = self.shell.user_ns
905 user_ns = self.shell.user_ns
905 for i in self.magic_who_ls():
906 for i in self.magic_who_ls():
906 del(user_ns[i])
907 del(user_ns[i])
907
908
908 def magic_config(self,parameter_s=''):
909 def magic_config(self,parameter_s=''):
909 """Show IPython's internal configuration."""
910 """Show IPython's internal configuration."""
910
911
911 page('Current configuration structure:\n'+
912 page('Current configuration structure:\n'+
912 pformat(self.shell.rc.dict()))
913 pformat(self.shell.rc.dict()))
913
914
914 def magic_logstart(self,parameter_s=''):
915 def magic_logstart(self,parameter_s=''):
915 """Start logging anywhere in a session.
916 """Start logging anywhere in a session.
916
917
917 %logstart [-o|-t] [log_name [log_mode]]
918 %logstart [-o|-t] [log_name [log_mode]]
918
919
919 If no name is given, it defaults to a file named 'ipython_log.py' in your
920 If no name is given, it defaults to a file named 'ipython_log.py' in your
920 current directory, in 'rotate' mode (see below).
921 current directory, in 'rotate' mode (see below).
921
922
922 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
923 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
923 history up to that point and then continues logging.
924 history up to that point and then continues logging.
924
925
925 %logstart takes a second optional parameter: logging mode. This can be one
926 %logstart takes a second optional parameter: logging mode. This can be one
926 of (note that the modes are given unquoted):\\
927 of (note that the modes are given unquoted):\\
927 append: well, that says it.\\
928 append: well, that says it.\\
928 backup: rename (if exists) to name~ and start name.\\
929 backup: rename (if exists) to name~ and start name.\\
929 global: single logfile in your home dir, appended to.\\
930 global: single logfile in your home dir, appended to.\\
930 over : overwrite existing log.\\
931 over : overwrite existing log.\\
931 rotate: create rotating logs name.1~, name.2~, etc.
932 rotate: create rotating logs name.1~, name.2~, etc.
932
933
933 Options:
934 Options:
934
935
935 -o: log also IPython's output. In this mode, all commands which
936 -o: log also IPython's output. In this mode, all commands which
936 generate an Out[NN] prompt are recorded to the logfile, right after
937 generate an Out[NN] prompt are recorded to the logfile, right after
937 their corresponding input line. The output lines are always
938 their corresponding input line. The output lines are always
938 prepended with a '#[Out]# ' marker, so that the log remains valid
939 prepended with a '#[Out]# ' marker, so that the log remains valid
939 Python code.
940 Python code.
940
941
941 Since this marker is always the same, filtering only the output from
942 Since this marker is always the same, filtering only the output from
942 a log is very easy, using for example a simple awk call:
943 a log is very easy, using for example a simple awk call:
943
944
944 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
945 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
945
946
946 -t: put timestamps before each input line logged (these are put in
947 -t: put timestamps before each input line logged (these are put in
947 comments)."""
948 comments)."""
948
949
949 opts,par = self.parse_options(parameter_s,'ot')
950 opts,par = self.parse_options(parameter_s,'ot')
950 log_output = 'o' in opts
951 log_output = 'o' in opts
951 timestamp = 't' in opts
952 timestamp = 't' in opts
952
953
953 rc = self.shell.rc
954 rc = self.shell.rc
954 logger = self.shell.logger
955 logger = self.shell.logger
955
956
956 # if no args are given, the defaults set in the logger constructor by
957 # if no args are given, the defaults set in the logger constructor by
957 # ipytohn remain valid
958 # ipytohn remain valid
958 if par:
959 if par:
959 try:
960 try:
960 logfname,logmode = par.split()
961 logfname,logmode = par.split()
961 except:
962 except:
962 logfname = par
963 logfname = par
963 logmode = 'backup'
964 logmode = 'backup'
964 else:
965 else:
965 logfname = logger.logfname
966 logfname = logger.logfname
966 logmode = logger.logmode
967 logmode = logger.logmode
967 # put logfname into rc struct as if it had been called on the command
968 # put logfname into rc struct as if it had been called on the command
968 # line, so it ends up saved in the log header Save it in case we need
969 # line, so it ends up saved in the log header Save it in case we need
969 # to restore it...
970 # to restore it...
970 old_logfile = rc.opts.get('logfile','')
971 old_logfile = rc.opts.get('logfile','')
971 if logfname:
972 if logfname:
972 logfname = os.path.expanduser(logfname)
973 logfname = os.path.expanduser(logfname)
973 rc.opts.logfile = logfname
974 rc.opts.logfile = logfname
974 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
975 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
975 try:
976 try:
976 started = logger.logstart(logfname,loghead,logmode,
977 started = logger.logstart(logfname,loghead,logmode,
977 log_output,timestamp)
978 log_output,timestamp)
978 except:
979 except:
979 rc.opts.logfile = old_logfile
980 rc.opts.logfile = old_logfile
980 warn("Couldn't start log: %s" % sys.exc_info()[1])
981 warn("Couldn't start log: %s" % sys.exc_info()[1])
981 else:
982 else:
982 # log input history up to this point, optionally interleaving
983 # log input history up to this point, optionally interleaving
983 # output if requested
984 # output if requested
984
985
985 if timestamp:
986 if timestamp:
986 # disable timestamping for the previous history, since we've
987 # disable timestamping for the previous history, since we've
987 # lost those already (no time machine here).
988 # lost those already (no time machine here).
988 logger.timestamp = False
989 logger.timestamp = False
989 if log_output:
990 if log_output:
990 log_write = logger.log_write
991 log_write = logger.log_write
991 input_hist = self.shell.input_hist
992 input_hist = self.shell.input_hist
992 output_hist = self.shell.output_hist
993 output_hist = self.shell.output_hist
993 for n in range(1,len(input_hist)-1):
994 for n in range(1,len(input_hist)-1):
994 log_write(input_hist[n].rstrip())
995 log_write(input_hist[n].rstrip())
995 if n in output_hist:
996 if n in output_hist:
996 log_write(repr(output_hist[n]),'output')
997 log_write(repr(output_hist[n]),'output')
997 else:
998 else:
998 logger.log_write(self.shell.input_hist[1:])
999 logger.log_write(self.shell.input_hist[1:])
999 if timestamp:
1000 if timestamp:
1000 # re-enable timestamping
1001 # re-enable timestamping
1001 logger.timestamp = True
1002 logger.timestamp = True
1002
1003
1003 print ('Activating auto-logging. '
1004 print ('Activating auto-logging. '
1004 'Current session state plus future input saved.')
1005 'Current session state plus future input saved.')
1005 logger.logstate()
1006 logger.logstate()
1006
1007
1007 def magic_logoff(self,parameter_s=''):
1008 def magic_logoff(self,parameter_s=''):
1008 """Temporarily stop logging.
1009 """Temporarily stop logging.
1009
1010
1010 You must have previously started logging."""
1011 You must have previously started logging."""
1011 self.shell.logger.switch_log(0)
1012 self.shell.logger.switch_log(0)
1012
1013
1013 def magic_logon(self,parameter_s=''):
1014 def magic_logon(self,parameter_s=''):
1014 """Restart logging.
1015 """Restart logging.
1015
1016
1016 This function is for restarting logging which you've temporarily
1017 This function is for restarting logging which you've temporarily
1017 stopped with %logoff. For starting logging for the first time, you
1018 stopped with %logoff. For starting logging for the first time, you
1018 must use the %logstart function, which allows you to specify an
1019 must use the %logstart function, which allows you to specify an
1019 optional log filename."""
1020 optional log filename."""
1020
1021
1021 self.shell.logger.switch_log(1)
1022 self.shell.logger.switch_log(1)
1022
1023
1023 def magic_logstate(self,parameter_s=''):
1024 def magic_logstate(self,parameter_s=''):
1024 """Print the status of the logging system."""
1025 """Print the status of the logging system."""
1025
1026
1026 self.shell.logger.logstate()
1027 self.shell.logger.logstate()
1027
1028
1028 def magic_pdb(self, parameter_s=''):
1029 def magic_pdb(self, parameter_s=''):
1029 """Control the calling of the pdb interactive debugger.
1030 """Control the calling of the pdb interactive debugger.
1030
1031
1031 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1032 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1032 argument it works as a toggle.
1033 argument it works as a toggle.
1033
1034
1034 When an exception is triggered, IPython can optionally call the
1035 When an exception is triggered, IPython can optionally call the
1035 interactive pdb debugger after the traceback printout. %pdb toggles
1036 interactive pdb debugger after the traceback printout. %pdb toggles
1036 this feature on and off."""
1037 this feature on and off."""
1037
1038
1038 par = parameter_s.strip().lower()
1039 par = parameter_s.strip().lower()
1039
1040
1040 if par:
1041 if par:
1041 try:
1042 try:
1042 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1043 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1043 except KeyError:
1044 except KeyError:
1044 print ('Incorrect argument. Use on/1, off/0, '
1045 print ('Incorrect argument. Use on/1, off/0, '
1045 'or nothing for a toggle.')
1046 'or nothing for a toggle.')
1046 return
1047 return
1047 else:
1048 else:
1048 # toggle
1049 # toggle
1049 new_pdb = not self.shell.InteractiveTB.call_pdb
1050 new_pdb = not self.shell.InteractiveTB.call_pdb
1050
1051
1051 # set on the shell
1052 # set on the shell
1052 self.shell.call_pdb = new_pdb
1053 self.shell.call_pdb = new_pdb
1053 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1054 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1054
1055
1055 def magic_prun(self, parameter_s ='',user_mode=1,
1056 def magic_prun(self, parameter_s ='',user_mode=1,
1056 opts=None,arg_lst=None,prog_ns=None):
1057 opts=None,arg_lst=None,prog_ns=None):
1057
1058
1058 """Run a statement through the python code profiler.
1059 """Run a statement through the python code profiler.
1059
1060
1060 Usage:\\
1061 Usage:\\
1061 %prun [options] statement
1062 %prun [options] statement
1062
1063
1063 The given statement (which doesn't require quote marks) is run via the
1064 The given statement (which doesn't require quote marks) is run via the
1064 python profiler in a manner similar to the profile.run() function.
1065 python profiler in a manner similar to the profile.run() function.
1065 Namespaces are internally managed to work correctly; profile.run
1066 Namespaces are internally managed to work correctly; profile.run
1066 cannot be used in IPython because it makes certain assumptions about
1067 cannot be used in IPython because it makes certain assumptions about
1067 namespaces which do not hold under IPython.
1068 namespaces which do not hold under IPython.
1068
1069
1069 Options:
1070 Options:
1070
1071
1071 -l <limit>: you can place restrictions on what or how much of the
1072 -l <limit>: you can place restrictions on what or how much of the
1072 profile gets printed. The limit value can be:
1073 profile gets printed. The limit value can be:
1073
1074
1074 * A string: only information for function names containing this string
1075 * A string: only information for function names containing this string
1075 is printed.
1076 is printed.
1076
1077
1077 * An integer: only these many lines are printed.
1078 * An integer: only these many lines are printed.
1078
1079
1079 * A float (between 0 and 1): this fraction of the report is printed
1080 * A float (between 0 and 1): this fraction of the report is printed
1080 (for example, use a limit of 0.4 to see the topmost 40% only).
1081 (for example, use a limit of 0.4 to see the topmost 40% only).
1081
1082
1082 You can combine several limits with repeated use of the option. For
1083 You can combine several limits with repeated use of the option. For
1083 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1084 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1084 information about class constructors.
1085 information about class constructors.
1085
1086
1086 -r: return the pstats.Stats object generated by the profiling. This
1087 -r: return the pstats.Stats object generated by the profiling. This
1087 object has all the information about the profile in it, and you can
1088 object has all the information about the profile in it, and you can
1088 later use it for further analysis or in other functions.
1089 later use it for further analysis or in other functions.
1089
1090
1090 Since magic functions have a particular form of calling which prevents
1091 Since magic functions have a particular form of calling which prevents
1091 you from writing something like:\\
1092 you from writing something like:\\
1092 In [1]: p = %prun -r print 4 # invalid!\\
1093 In [1]: p = %prun -r print 4 # invalid!\\
1093 you must instead use IPython's automatic variables to assign this:\\
1094 you must instead use IPython's automatic variables to assign this:\\
1094 In [1]: %prun -r print 4 \\
1095 In [1]: %prun -r print 4 \\
1095 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1096 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1096 In [2]: stats = _
1097 In [2]: stats = _
1097
1098
1098 If you really need to assign this value via an explicit function call,
1099 If you really need to assign this value via an explicit function call,
1099 you can always tap directly into the true name of the magic function
1100 you can always tap directly into the true name of the magic function
1100 by using the ipmagic function (which IPython automatically adds to the
1101 by using the ipmagic function (which IPython automatically adds to the
1101 builtins):\\
1102 builtins):\\
1102 In [3]: stats = ipmagic('prun','-r print 4')
1103 In [3]: stats = ipmagic('prun','-r print 4')
1103
1104
1104 You can type ipmagic? for more details on ipmagic.
1105 You can type ipmagic? for more details on ipmagic.
1105
1106
1106 -s <key>: sort profile by given key. You can provide more than one key
1107 -s <key>: sort profile by given key. You can provide more than one key
1107 by using the option several times: '-s key1 -s key2 -s key3...'. The
1108 by using the option several times: '-s key1 -s key2 -s key3...'. The
1108 default sorting key is 'time'.
1109 default sorting key is 'time'.
1109
1110
1110 The following is copied verbatim from the profile documentation
1111 The following is copied verbatim from the profile documentation
1111 referenced below:
1112 referenced below:
1112
1113
1113 When more than one key is provided, additional keys are used as
1114 When more than one key is provided, additional keys are used as
1114 secondary criteria when the there is equality in all keys selected
1115 secondary criteria when the there is equality in all keys selected
1115 before them.
1116 before them.
1116
1117
1117 Abbreviations can be used for any key names, as long as the
1118 Abbreviations can be used for any key names, as long as the
1118 abbreviation is unambiguous. The following are the keys currently
1119 abbreviation is unambiguous. The following are the keys currently
1119 defined:
1120 defined:
1120
1121
1121 Valid Arg Meaning\\
1122 Valid Arg Meaning\\
1122 "calls" call count\\
1123 "calls" call count\\
1123 "cumulative" cumulative time\\
1124 "cumulative" cumulative time\\
1124 "file" file name\\
1125 "file" file name\\
1125 "module" file name\\
1126 "module" file name\\
1126 "pcalls" primitive call count\\
1127 "pcalls" primitive call count\\
1127 "line" line number\\
1128 "line" line number\\
1128 "name" function name\\
1129 "name" function name\\
1129 "nfl" name/file/line\\
1130 "nfl" name/file/line\\
1130 "stdname" standard name\\
1131 "stdname" standard name\\
1131 "time" internal time
1132 "time" internal time
1132
1133
1133 Note that all sorts on statistics are in descending order (placing
1134 Note that all sorts on statistics are in descending order (placing
1134 most time consuming items first), where as name, file, and line number
1135 most time consuming items first), where as name, file, and line number
1135 searches are in ascending order (i.e., alphabetical). The subtle
1136 searches are in ascending order (i.e., alphabetical). The subtle
1136 distinction between "nfl" and "stdname" is that the standard name is a
1137 distinction between "nfl" and "stdname" is that the standard name is a
1137 sort of the name as printed, which means that the embedded line
1138 sort of the name as printed, which means that the embedded line
1138 numbers get compared in an odd way. For example, lines 3, 20, and 40
1139 numbers get compared in an odd way. For example, lines 3, 20, and 40
1139 would (if the file names were the same) appear in the string order
1140 would (if the file names were the same) appear in the string order
1140 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1141 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1141 line numbers. In fact, sort_stats("nfl") is the same as
1142 line numbers. In fact, sort_stats("nfl") is the same as
1142 sort_stats("name", "file", "line").
1143 sort_stats("name", "file", "line").
1143
1144
1144 -T <filename>: save profile results as shown on screen to a text
1145 -T <filename>: save profile results as shown on screen to a text
1145 file. The profile is still shown on screen.
1146 file. The profile is still shown on screen.
1146
1147
1147 -D <filename>: save (via dump_stats) profile statistics to given
1148 -D <filename>: save (via dump_stats) profile statistics to given
1148 filename. This data is in a format understod by the pstats module, and
1149 filename. This data is in a format understod by the pstats module, and
1149 is generated by a call to the dump_stats() method of profile
1150 is generated by a call to the dump_stats() method of profile
1150 objects. The profile is still shown on screen.
1151 objects. The profile is still shown on screen.
1151
1152
1152 If you want to run complete programs under the profiler's control, use
1153 If you want to run complete programs under the profiler's control, use
1153 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1154 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1154 contains profiler specific options as described here.
1155 contains profiler specific options as described here.
1155
1156
1156 You can read the complete documentation for the profile module with:\\
1157 You can read the complete documentation for the profile module with:\\
1157 In [1]: import profile; profile.help() """
1158 In [1]: import profile; profile.help() """
1158
1159
1159 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1160 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1160 # protect user quote marks
1161 # protect user quote marks
1161 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1162 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1162
1163
1163 if user_mode: # regular user call
1164 if user_mode: # regular user call
1164 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1165 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1165 list_all=1)
1166 list_all=1)
1166 namespace = self.shell.user_ns
1167 namespace = self.shell.user_ns
1167 else: # called to run a program by %run -p
1168 else: # called to run a program by %run -p
1168 try:
1169 try:
1169 filename = get_py_filename(arg_lst[0])
1170 filename = get_py_filename(arg_lst[0])
1170 except IOError,msg:
1171 except IOError,msg:
1171 error(msg)
1172 error(msg)
1172 return
1173 return
1173
1174
1174 arg_str = 'execfile(filename,prog_ns)'
1175 arg_str = 'execfile(filename,prog_ns)'
1175 namespace = locals()
1176 namespace = locals()
1176
1177
1177 opts.merge(opts_def)
1178 opts.merge(opts_def)
1178
1179
1179 prof = profile.Profile()
1180 prof = profile.Profile()
1180 try:
1181 try:
1181 prof = prof.runctx(arg_str,namespace,namespace)
1182 prof = prof.runctx(arg_str,namespace,namespace)
1182 sys_exit = ''
1183 sys_exit = ''
1183 except SystemExit:
1184 except SystemExit:
1184 sys_exit = """*** SystemExit exception caught in code being profiled."""
1185 sys_exit = """*** SystemExit exception caught in code being profiled."""
1185
1186
1186 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1187 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1187
1188
1188 lims = opts.l
1189 lims = opts.l
1189 if lims:
1190 if lims:
1190 lims = [] # rebuild lims with ints/floats/strings
1191 lims = [] # rebuild lims with ints/floats/strings
1191 for lim in opts.l:
1192 for lim in opts.l:
1192 try:
1193 try:
1193 lims.append(int(lim))
1194 lims.append(int(lim))
1194 except ValueError:
1195 except ValueError:
1195 try:
1196 try:
1196 lims.append(float(lim))
1197 lims.append(float(lim))
1197 except ValueError:
1198 except ValueError:
1198 lims.append(lim)
1199 lims.append(lim)
1199
1200
1200 # trap output
1201 # trap output
1201 sys_stdout = sys.stdout
1202 sys_stdout = sys.stdout
1202 stdout_trap = StringIO()
1203 stdout_trap = StringIO()
1203 try:
1204 try:
1204 sys.stdout = stdout_trap
1205 sys.stdout = stdout_trap
1205 stats.print_stats(*lims)
1206 stats.print_stats(*lims)
1206 finally:
1207 finally:
1207 sys.stdout = sys_stdout
1208 sys.stdout = sys_stdout
1208 output = stdout_trap.getvalue()
1209 output = stdout_trap.getvalue()
1209 output = output.rstrip()
1210 output = output.rstrip()
1210
1211
1211 page(output,screen_lines=self.shell.rc.screen_length)
1212 page(output,screen_lines=self.shell.rc.screen_length)
1212 print sys_exit,
1213 print sys_exit,
1213
1214
1214 dump_file = opts.D[0]
1215 dump_file = opts.D[0]
1215 text_file = opts.T[0]
1216 text_file = opts.T[0]
1216 if dump_file:
1217 if dump_file:
1217 prof.dump_stats(dump_file)
1218 prof.dump_stats(dump_file)
1218 print '\n*** Profile stats marshalled to file',\
1219 print '\n*** Profile stats marshalled to file',\
1219 `dump_file`+'.',sys_exit
1220 `dump_file`+'.',sys_exit
1220 if text_file:
1221 if text_file:
1221 file(text_file,'w').write(output)
1222 file(text_file,'w').write(output)
1222 print '\n*** Profile printout saved to text file',\
1223 print '\n*** Profile printout saved to text file',\
1223 `text_file`+'.',sys_exit
1224 `text_file`+'.',sys_exit
1224
1225
1225 if opts.has_key('r'):
1226 if opts.has_key('r'):
1226 return stats
1227 return stats
1227 else:
1228 else:
1228 return None
1229 return None
1229
1230
1230 def magic_run(self, parameter_s ='',runner=None):
1231 def magic_run(self, parameter_s ='',runner=None):
1231 """Run the named file inside IPython as a program.
1232 """Run the named file inside IPython as a program.
1232
1233
1233 Usage:\\
1234 Usage:\\
1234 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1235 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1235
1236
1236 Parameters after the filename are passed as command-line arguments to
1237 Parameters after the filename are passed as command-line arguments to
1237 the program (put in sys.argv). Then, control returns to IPython's
1238 the program (put in sys.argv). Then, control returns to IPython's
1238 prompt.
1239 prompt.
1239
1240
1240 This is similar to running at a system prompt:\\
1241 This is similar to running at a system prompt:\\
1241 $ python file args\\
1242 $ python file args\\
1242 but with the advantage of giving you IPython's tracebacks, and of
1243 but with the advantage of giving you IPython's tracebacks, and of
1243 loading all variables into your interactive namespace for further use
1244 loading all variables into your interactive namespace for further use
1244 (unless -p is used, see below).
1245 (unless -p is used, see below).
1245
1246
1246 The file is executed in a namespace initially consisting only of
1247 The file is executed in a namespace initially consisting only of
1247 __name__=='__main__' and sys.argv constructed as indicated. It thus
1248 __name__=='__main__' and sys.argv constructed as indicated. It thus
1248 sees its environment as if it were being run as a stand-alone
1249 sees its environment as if it were being run as a stand-alone
1249 program. But after execution, the IPython interactive namespace gets
1250 program. But after execution, the IPython interactive namespace gets
1250 updated with all variables defined in the program (except for __name__
1251 updated with all variables defined in the program (except for __name__
1251 and sys.argv). This allows for very convenient loading of code for
1252 and sys.argv). This allows for very convenient loading of code for
1252 interactive work, while giving each program a 'clean sheet' to run in.
1253 interactive work, while giving each program a 'clean sheet' to run in.
1253
1254
1254 Options:
1255 Options:
1255
1256
1256 -n: __name__ is NOT set to '__main__', but to the running file's name
1257 -n: __name__ is NOT set to '__main__', but to the running file's name
1257 without extension (as python does under import). This allows running
1258 without extension (as python does under import). This allows running
1258 scripts and reloading the definitions in them without calling code
1259 scripts and reloading the definitions in them without calling code
1259 protected by an ' if __name__ == "__main__" ' clause.
1260 protected by an ' if __name__ == "__main__" ' clause.
1260
1261
1261 -i: run the file in IPython's namespace instead of an empty one. This
1262 -i: run the file in IPython's namespace instead of an empty one. This
1262 is useful if you are experimenting with code written in a text editor
1263 is useful if you are experimenting with code written in a text editor
1263 which depends on variables defined interactively.
1264 which depends on variables defined interactively.
1264
1265
1265 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1266 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1266 being run. This is particularly useful if IPython is being used to
1267 being run. This is particularly useful if IPython is being used to
1267 run unittests, which always exit with a sys.exit() call. In such
1268 run unittests, which always exit with a sys.exit() call. In such
1268 cases you are interested in the output of the test results, not in
1269 cases you are interested in the output of the test results, not in
1269 seeing a traceback of the unittest module.
1270 seeing a traceback of the unittest module.
1270
1271
1271 -t: print timing information at the end of the run. IPython will give
1272 -t: print timing information at the end of the run. IPython will give
1272 you an estimated CPU time consumption for your script, which under
1273 you an estimated CPU time consumption for your script, which under
1273 Unix uses the resource module to avoid the wraparound problems of
1274 Unix uses the resource module to avoid the wraparound problems of
1274 time.clock(). Under Unix, an estimate of time spent on system tasks
1275 time.clock(). Under Unix, an estimate of time spent on system tasks
1275 is also given (for Windows platforms this is reported as 0.0).
1276 is also given (for Windows platforms this is reported as 0.0).
1276
1277
1277 If -t is given, an additional -N<N> option can be given, where <N>
1278 If -t is given, an additional -N<N> option can be given, where <N>
1278 must be an integer indicating how many times you want the script to
1279 must be an integer indicating how many times you want the script to
1279 run. The final timing report will include total and per run results.
1280 run. The final timing report will include total and per run results.
1280
1281
1281 For example (testing the script uniq_stable.py):
1282 For example (testing the script uniq_stable.py):
1282
1283
1283 In [1]: run -t uniq_stable
1284 In [1]: run -t uniq_stable
1284
1285
1285 IPython CPU timings (estimated):\\
1286 IPython CPU timings (estimated):\\
1286 User : 0.19597 s.\\
1287 User : 0.19597 s.\\
1287 System: 0.0 s.\\
1288 System: 0.0 s.\\
1288
1289
1289 In [2]: run -t -N5 uniq_stable
1290 In [2]: run -t -N5 uniq_stable
1290
1291
1291 IPython CPU timings (estimated):\\
1292 IPython CPU timings (estimated):\\
1292 Total runs performed: 5\\
1293 Total runs performed: 5\\
1293 Times : Total Per run\\
1294 Times : Total Per run\\
1294 User : 0.910862 s, 0.1821724 s.\\
1295 User : 0.910862 s, 0.1821724 s.\\
1295 System: 0.0 s, 0.0 s.
1296 System: 0.0 s, 0.0 s.
1296
1297
1297 -d: run your program under the control of pdb, the Python debugger.
1298 -d: run your program under the control of pdb, the Python debugger.
1298 This allows you to execute your program step by step, watch variables,
1299 This allows you to execute your program step by step, watch variables,
1299 etc. Internally, what IPython does is similar to calling:
1300 etc. Internally, what IPython does is similar to calling:
1300
1301
1301 pdb.run('execfile("YOURFILENAME")')
1302 pdb.run('execfile("YOURFILENAME")')
1302
1303
1303 with a breakpoint set on line 1 of your file. You can change the line
1304 with a breakpoint set on line 1 of your file. You can change the line
1304 number for this automatic breakpoint to be <N> by using the -bN option
1305 number for this automatic breakpoint to be <N> by using the -bN option
1305 (where N must be an integer). For example:
1306 (where N must be an integer). For example:
1306
1307
1307 %run -d -b40 myscript
1308 %run -d -b40 myscript
1308
1309
1309 will set the first breakpoint at line 40 in myscript.py. Note that
1310 will set the first breakpoint at line 40 in myscript.py. Note that
1310 the first breakpoint must be set on a line which actually does
1311 the first breakpoint must be set on a line which actually does
1311 something (not a comment or docstring) for it to stop execution.
1312 something (not a comment or docstring) for it to stop execution.
1312
1313
1313 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1314 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1314 first enter 'c' (without qoutes) to start execution up to the first
1315 first enter 'c' (without qoutes) to start execution up to the first
1315 breakpoint.
1316 breakpoint.
1316
1317
1317 Entering 'help' gives information about the use of the debugger. You
1318 Entering 'help' gives information about the use of the debugger. You
1318 can easily see pdb's full documentation with "import pdb;pdb.help()"
1319 can easily see pdb's full documentation with "import pdb;pdb.help()"
1319 at a prompt.
1320 at a prompt.
1320
1321
1321 -p: run program under the control of the Python profiler module (which
1322 -p: run program under the control of the Python profiler module (which
1322 prints a detailed report of execution times, function calls, etc).
1323 prints a detailed report of execution times, function calls, etc).
1323
1324
1324 You can pass other options after -p which affect the behavior of the
1325 You can pass other options after -p which affect the behavior of the
1325 profiler itself. See the docs for %prun for details.
1326 profiler itself. See the docs for %prun for details.
1326
1327
1327 In this mode, the program's variables do NOT propagate back to the
1328 In this mode, the program's variables do NOT propagate back to the
1328 IPython interactive namespace (because they remain in the namespace
1329 IPython interactive namespace (because they remain in the namespace
1329 where the profiler executes them).
1330 where the profiler executes them).
1330
1331
1331 Internally this triggers a call to %prun, see its documentation for
1332 Internally this triggers a call to %prun, see its documentation for
1332 details on the options available specifically for profiling."""
1333 details on the options available specifically for profiling."""
1333
1334
1334 # get arguments and set sys.argv for program to be run.
1335 # get arguments and set sys.argv for program to be run.
1335 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1336 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1336 mode='list',list_all=1)
1337 mode='list',list_all=1)
1337
1338
1338 try:
1339 try:
1339 filename = get_py_filename(arg_lst[0])
1340 filename = get_py_filename(arg_lst[0])
1340 except IndexError:
1341 except IndexError:
1341 warn('you must provide at least a filename.')
1342 warn('you must provide at least a filename.')
1342 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1343 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1343 return
1344 return
1344 except IOError,msg:
1345 except IOError,msg:
1345 error(msg)
1346 error(msg)
1346 return
1347 return
1347
1348
1348 # Control the response to exit() calls made by the script being run
1349 # Control the response to exit() calls made by the script being run
1349 exit_ignore = opts.has_key('e')
1350 exit_ignore = opts.has_key('e')
1350
1351
1351 # Make sure that the running script gets a proper sys.argv as if it
1352 # Make sure that the running script gets a proper sys.argv as if it
1352 # were run from a system shell.
1353 # were run from a system shell.
1353 save_argv = sys.argv # save it for later restoring
1354 save_argv = sys.argv # save it for later restoring
1354 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1355 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1355
1356
1356 if opts.has_key('i'):
1357 if opts.has_key('i'):
1357 prog_ns = self.shell.user_ns
1358 prog_ns = self.shell.user_ns
1358 __name__save = self.shell.user_ns['__name__']
1359 __name__save = self.shell.user_ns['__name__']
1359 prog_ns['__name__'] = '__main__'
1360 prog_ns['__name__'] = '__main__'
1360 else:
1361 else:
1361 if opts.has_key('n'):
1362 if opts.has_key('n'):
1362 name = os.path.splitext(os.path.basename(filename))[0]
1363 name = os.path.splitext(os.path.basename(filename))[0]
1363 else:
1364 else:
1364 name = '__main__'
1365 name = '__main__'
1365 prog_ns = {'__name__':name}
1366 prog_ns = {'__name__':name}
1366
1367
1367 # pickle fix. See iplib for an explanation. But we need to make sure
1368 # pickle fix. See iplib for an explanation. But we need to make sure
1368 # that, if we overwrite __main__, we replace it at the end
1369 # that, if we overwrite __main__, we replace it at the end
1369 if prog_ns['__name__'] == '__main__':
1370 if prog_ns['__name__'] == '__main__':
1370 restore_main = sys.modules['__main__']
1371 restore_main = sys.modules['__main__']
1371 else:
1372 else:
1372 restore_main = False
1373 restore_main = False
1373
1374
1374 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1375 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1375
1376
1376 stats = None
1377 stats = None
1377 try:
1378 try:
1378 if opts.has_key('p'):
1379 if opts.has_key('p'):
1379 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1380 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1380 else:
1381 else:
1381 if opts.has_key('d'):
1382 if opts.has_key('d'):
1382 deb = Debugger.Pdb(self.shell.rc.colors)
1383 deb = Debugger.Pdb(self.shell.rc.colors)
1383 # reset Breakpoint state, which is moronically kept
1384 # reset Breakpoint state, which is moronically kept
1384 # in a class
1385 # in a class
1385 bdb.Breakpoint.next = 1
1386 bdb.Breakpoint.next = 1
1386 bdb.Breakpoint.bplist = {}
1387 bdb.Breakpoint.bplist = {}
1387 bdb.Breakpoint.bpbynumber = [None]
1388 bdb.Breakpoint.bpbynumber = [None]
1388 # Set an initial breakpoint to stop execution
1389 # Set an initial breakpoint to stop execution
1389 maxtries = 10
1390 maxtries = 10
1390 bp = int(opts.get('b',[1])[0])
1391 bp = int(opts.get('b',[1])[0])
1391 checkline = deb.checkline(filename,bp)
1392 checkline = deb.checkline(filename,bp)
1392 if not checkline:
1393 if not checkline:
1393 for bp in range(bp+1,bp+maxtries+1):
1394 for bp in range(bp+1,bp+maxtries+1):
1394 if deb.checkline(filename,bp):
1395 if deb.checkline(filename,bp):
1395 break
1396 break
1396 else:
1397 else:
1397 msg = ("\nI failed to find a valid line to set "
1398 msg = ("\nI failed to find a valid line to set "
1398 "a breakpoint\n"
1399 "a breakpoint\n"
1399 "after trying up to line: %s.\n"
1400 "after trying up to line: %s.\n"
1400 "Please set a valid breakpoint manually "
1401 "Please set a valid breakpoint manually "
1401 "with the -b option." % bp)
1402 "with the -b option." % bp)
1402 error(msg)
1403 error(msg)
1403 return
1404 return
1404 # if we find a good linenumber, set the breakpoint
1405 # if we find a good linenumber, set the breakpoint
1405 deb.do_break('%s:%s' % (filename,bp))
1406 deb.do_break('%s:%s' % (filename,bp))
1406 # Start file run
1407 # Start file run
1407 print "NOTE: Enter 'c' at the",
1408 print "NOTE: Enter 'c' at the",
1408 print "ipdb> prompt to start your script."
1409 print "ipdb> prompt to start your script."
1409 try:
1410 try:
1410 deb.run('execfile("%s")' % filename,prog_ns)
1411 deb.run('execfile("%s")' % filename,prog_ns)
1411 except:
1412 except:
1412 etype, value, tb = sys.exc_info()
1413 etype, value, tb = sys.exc_info()
1413 # Skip three frames in the traceback: the %run one,
1414 # Skip three frames in the traceback: the %run one,
1414 # one inside bdb.py, and the command-line typed by the
1415 # one inside bdb.py, and the command-line typed by the
1415 # user (run by exec in pdb itself).
1416 # user (run by exec in pdb itself).
1416 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1417 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1417 else:
1418 else:
1418 if runner is None:
1419 if runner is None:
1419 runner = self.shell.safe_execfile
1420 runner = self.shell.safe_execfile
1420 if opts.has_key('t'):
1421 if opts.has_key('t'):
1421 try:
1422 try:
1422 nruns = int(opts['N'][0])
1423 nruns = int(opts['N'][0])
1423 if nruns < 1:
1424 if nruns < 1:
1424 error('Number of runs must be >=1')
1425 error('Number of runs must be >=1')
1425 return
1426 return
1426 except (KeyError):
1427 except (KeyError):
1427 nruns = 1
1428 nruns = 1
1428 if nruns == 1:
1429 if nruns == 1:
1429 t0 = clock2()
1430 t0 = clock2()
1430 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1431 t1 = clock2()
1432 t1 = clock2()
1432 t_usr = t1[0]-t0[0]
1433 t_usr = t1[0]-t0[0]
1433 t_sys = t1[1]-t1[1]
1434 t_sys = t1[1]-t1[1]
1434 print "\nIPython CPU timings (estimated):"
1435 print "\nIPython CPU timings (estimated):"
1435 print " User : %10s s." % t_usr
1436 print " User : %10s s." % t_usr
1436 print " System: %10s s." % t_sys
1437 print " System: %10s s." % t_sys
1437 else:
1438 else:
1438 runs = range(nruns)
1439 runs = range(nruns)
1439 t0 = clock2()
1440 t0 = clock2()
1440 for nr in runs:
1441 for nr in runs:
1441 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1442 t1 = clock2()
1443 t1 = clock2()
1443 t_usr = t1[0]-t0[0]
1444 t_usr = t1[0]-t0[0]
1444 t_sys = t1[1]-t1[1]
1445 t_sys = t1[1]-t1[1]
1445 print "\nIPython CPU timings (estimated):"
1446 print "\nIPython CPU timings (estimated):"
1446 print "Total runs performed:",nruns
1447 print "Total runs performed:",nruns
1447 print " Times : %10s %10s" % ('Total','Per run')
1448 print " Times : %10s %10s" % ('Total','Per run')
1448 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1449 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1449 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1450 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1450
1451
1451 else:
1452 else:
1452 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1453 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1453 if opts.has_key('i'):
1454 if opts.has_key('i'):
1454 self.shell.user_ns['__name__'] = __name__save
1455 self.shell.user_ns['__name__'] = __name__save
1455 else:
1456 else:
1456 # update IPython interactive namespace
1457 # update IPython interactive namespace
1457 del prog_ns['__name__']
1458 del prog_ns['__name__']
1458 self.shell.user_ns.update(prog_ns)
1459 self.shell.user_ns.update(prog_ns)
1459 finally:
1460 finally:
1460 sys.argv = save_argv
1461 sys.argv = save_argv
1461 if restore_main:
1462 if restore_main:
1462 sys.modules['__main__'] = restore_main
1463 sys.modules['__main__'] = restore_main
1463 return stats
1464 return stats
1464
1465
1465 def magic_runlog(self, parameter_s =''):
1466 def magic_runlog(self, parameter_s =''):
1466 """Run files as logs.
1467 """Run files as logs.
1467
1468
1468 Usage:\\
1469 Usage:\\
1469 %runlog file1 file2 ...
1470 %runlog file1 file2 ...
1470
1471
1471 Run the named files (treating them as log files) in sequence inside
1472 Run the named files (treating them as log files) in sequence inside
1472 the interpreter, and return to the prompt. This is much slower than
1473 the interpreter, and return to the prompt. This is much slower than
1473 %run because each line is executed in a try/except block, but it
1474 %run because each line is executed in a try/except block, but it
1474 allows running files with syntax errors in them.
1475 allows running files with syntax errors in them.
1475
1476
1476 Normally IPython will guess when a file is one of its own logfiles, so
1477 Normally IPython will guess when a file is one of its own logfiles, so
1477 you can typically use %run even for logs. This shorthand allows you to
1478 you can typically use %run even for logs. This shorthand allows you to
1478 force any file to be treated as a log file."""
1479 force any file to be treated as a log file."""
1479
1480
1480 for f in parameter_s.split():
1481 for f in parameter_s.split():
1481 self.shell.safe_execfile(f,self.shell.user_ns,
1482 self.shell.safe_execfile(f,self.shell.user_ns,
1482 self.shell.user_ns,islog=1)
1483 self.shell.user_ns,islog=1)
1483
1484
1484 def magic_time(self,parameter_s = ''):
1485 def magic_time(self,parameter_s = ''):
1485 """Time execution of a Python statement or expression.
1486 """Time execution of a Python statement or expression.
1486
1487
1487 The CPU and wall clock times are printed, and the value of the
1488 The CPU and wall clock times are printed, and the value of the
1488 expression (if any) is returned. Note that under Win32, system time
1489 expression (if any) is returned. Note that under Win32, system time
1489 is always reported as 0, since it can not be measured.
1490 is always reported as 0, since it can not be measured.
1490
1491
1491 This function provides very basic timing functionality. In Python
1492 This function provides very basic timing functionality. In Python
1492 2.3, the timeit module offers more control and sophistication, but for
1493 2.3, the timeit module offers more control and sophistication, but for
1493 now IPython supports Python 2.2, so we can not rely on timeit being
1494 now IPython supports Python 2.2, so we can not rely on timeit being
1494 present.
1495 present.
1495
1496
1496 Some examples:
1497 Some examples:
1497
1498
1498 In [1]: time 2**128
1499 In [1]: time 2**128
1499 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1500 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1500 Wall time: 0.00
1501 Wall time: 0.00
1501 Out[1]: 340282366920938463463374607431768211456L
1502 Out[1]: 340282366920938463463374607431768211456L
1502
1503
1503 In [2]: n = 1000000
1504 In [2]: n = 1000000
1504
1505
1505 In [3]: time sum(range(n))
1506 In [3]: time sum(range(n))
1506 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1507 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1507 Wall time: 1.37
1508 Wall time: 1.37
1508 Out[3]: 499999500000L
1509 Out[3]: 499999500000L
1509
1510
1510 In [4]: time print 'hello world'
1511 In [4]: time print 'hello world'
1511 hello world
1512 hello world
1512 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1513 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1513 Wall time: 0.00
1514 Wall time: 0.00
1514 """
1515 """
1515
1516
1516 # fail immediately if the given expression can't be compiled
1517 # fail immediately if the given expression can't be compiled
1517 try:
1518 try:
1518 mode = 'eval'
1519 mode = 'eval'
1519 code = compile(parameter_s,'<timed eval>',mode)
1520 code = compile(parameter_s,'<timed eval>',mode)
1520 except SyntaxError:
1521 except SyntaxError:
1521 mode = 'exec'
1522 mode = 'exec'
1522 code = compile(parameter_s,'<timed exec>',mode)
1523 code = compile(parameter_s,'<timed exec>',mode)
1523 # skew measurement as little as possible
1524 # skew measurement as little as possible
1524 glob = self.shell.user_ns
1525 glob = self.shell.user_ns
1525 clk = clock2
1526 clk = clock2
1526 wtime = time.time
1527 wtime = time.time
1527 # time execution
1528 # time execution
1528 wall_st = wtime()
1529 wall_st = wtime()
1529 if mode=='eval':
1530 if mode=='eval':
1530 st = clk()
1531 st = clk()
1531 out = eval(code,glob)
1532 out = eval(code,glob)
1532 end = clk()
1533 end = clk()
1533 else:
1534 else:
1534 st = clk()
1535 st = clk()
1535 exec code in glob
1536 exec code in glob
1536 end = clk()
1537 end = clk()
1537 out = None
1538 out = None
1538 wall_end = wtime()
1539 wall_end = wtime()
1539 # Compute actual times and report
1540 # Compute actual times and report
1540 wall_time = wall_end-wall_st
1541 wall_time = wall_end-wall_st
1541 cpu_user = end[0]-st[0]
1542 cpu_user = end[0]-st[0]
1542 cpu_sys = end[1]-st[1]
1543 cpu_sys = end[1]-st[1]
1543 cpu_tot = cpu_user+cpu_sys
1544 cpu_tot = cpu_user+cpu_sys
1544 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1545 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1545 (cpu_user,cpu_sys,cpu_tot)
1546 (cpu_user,cpu_sys,cpu_tot)
1546 print "Wall time: %.2f" % wall_time
1547 print "Wall time: %.2f" % wall_time
1547 return out
1548 return out
1548
1549
1549 def magic_macro(self,parameter_s = ''):
1550 def magic_macro(self,parameter_s = ''):
1550 """Define a set of input lines as a macro for future re-execution.
1551 """Define a set of input lines as a macro for future re-execution.
1551
1552
1552 Usage:\\
1553 Usage:\\
1553 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1554 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1554
1555
1555 This will define a global variable called `name` which is a string
1556 This will define a global variable called `name` which is a string
1556 made of joining the slices and lines you specify (n1,n2,... numbers
1557 made of joining the slices and lines you specify (n1,n2,... numbers
1557 above) from your input history into a single string. This variable
1558 above) from your input history into a single string. This variable
1558 acts like an automatic function which re-executes those lines as if
1559 acts like an automatic function which re-executes those lines as if
1559 you had typed them. You just type 'name' at the prompt and the code
1560 you had typed them. You just type 'name' at the prompt and the code
1560 executes.
1561 executes.
1561
1562
1562 The notation for indicating number ranges is: n1-n2 means 'use line
1563 The notation for indicating number ranges is: n1-n2 means 'use line
1563 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1564 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1564 using the lines numbered 5,6 and 7.
1565 using the lines numbered 5,6 and 7.
1565
1566
1566 Note: as a 'hidden' feature, you can also use traditional python slice
1567 Note: as a 'hidden' feature, you can also use traditional python slice
1567 notation, where N:M means numbers N through M-1.
1568 notation, where N:M means numbers N through M-1.
1568
1569
1569 For example, if your history contains (%hist prints it):
1570 For example, if your history contains (%hist prints it):
1570
1571
1571 44: x=1\\
1572 44: x=1\\
1572 45: y=3\\
1573 45: y=3\\
1573 46: z=x+y\\
1574 46: z=x+y\\
1574 47: print x\\
1575 47: print x\\
1575 48: a=5\\
1576 48: a=5\\
1576 49: print 'x',x,'y',y\\
1577 49: print 'x',x,'y',y\\
1577
1578
1578 you can create a macro with lines 44 through 47 (included) and line 49
1579 you can create a macro with lines 44 through 47 (included) and line 49
1579 called my_macro with:
1580 called my_macro with:
1580
1581
1581 In [51]: %macro my_macro 44-47 49
1582 In [51]: %macro my_macro 44-47 49
1582
1583
1583 Now, typing `my_macro` (without quotes) will re-execute all this code
1584 Now, typing `my_macro` (without quotes) will re-execute all this code
1584 in one pass.
1585 in one pass.
1585
1586
1586 You don't need to give the line-numbers in order, and any given line
1587 You don't need to give the line-numbers in order, and any given line
1587 number can appear multiple times. You can assemble macros with any
1588 number can appear multiple times. You can assemble macros with any
1588 lines from your input history in any order.
1589 lines from your input history in any order.
1589
1590
1590 The macro is a simple object which holds its value in an attribute,
1591 The macro is a simple object which holds its value in an attribute,
1591 but IPython's display system checks for macros and executes them as
1592 but IPython's display system checks for macros and executes them as
1592 code instead of printing them when you type their name.
1593 code instead of printing them when you type their name.
1593
1594
1594 You can view a macro's contents by explicitly printing it with:
1595 You can view a macro's contents by explicitly printing it with:
1595
1596
1596 'print macro_name'.
1597 'print macro_name'.
1597
1598
1598 For one-off cases which DON'T contain magic function calls in them you
1599 For one-off cases which DON'T contain magic function calls in them you
1599 can obtain similar results by explicitly executing slices from your
1600 can obtain similar results by explicitly executing slices from your
1600 input history with:
1601 input history with:
1601
1602
1602 In [60]: exec In[44:48]+In[49]"""
1603 In [60]: exec In[44:48]+In[49]"""
1603
1604
1604 args = parameter_s.split()
1605 args = parameter_s.split()
1605 name,ranges = args[0], args[1:]
1606 name,ranges = args[0], args[1:]
1606 #print 'rng',ranges # dbg
1607 #print 'rng',ranges # dbg
1607 lines = self.extract_input_slices(ranges)
1608 lines = self.extract_input_slices(ranges)
1608 macro = Macro(lines)
1609 macro = Macro(lines)
1609 self.shell.user_ns.update({name:macro})
1610 self.shell.user_ns.update({name:macro})
1610 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1611 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1611 print 'Macro contents:'
1612 print 'Macro contents:'
1612 print macro,
1613 print macro,
1613
1614
1614 def magic_save(self,parameter_s = ''):
1615 def magic_save(self,parameter_s = ''):
1615 """Save a set of lines to a given filename.
1616 """Save a set of lines to a given filename.
1616
1617
1617 Usage:\\
1618 Usage:\\
1618 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1619 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1619
1620
1620 This function uses the same syntax as %macro for line extraction, but
1621 This function uses the same syntax as %macro for line extraction, but
1621 instead of creating a macro it saves the resulting string to the
1622 instead of creating a macro it saves the resulting string to the
1622 filename you specify.
1623 filename you specify.
1623
1624
1624 It adds a '.py' extension to the file if you don't do so yourself, and
1625 It adds a '.py' extension to the file if you don't do so yourself, and
1625 it asks for confirmation before overwriting existing files."""
1626 it asks for confirmation before overwriting existing files."""
1626
1627
1627 args = parameter_s.split()
1628 args = parameter_s.split()
1628 fname,ranges = args[0], args[1:]
1629 fname,ranges = args[0], args[1:]
1629 if not fname.endswith('.py'):
1630 if not fname.endswith('.py'):
1630 fname += '.py'
1631 fname += '.py'
1631 if os.path.isfile(fname):
1632 if os.path.isfile(fname):
1632 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1633 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1633 if ans.lower() not in ['y','yes']:
1634 if ans.lower() not in ['y','yes']:
1634 print 'Operation cancelled.'
1635 print 'Operation cancelled.'
1635 return
1636 return
1636 cmds = ''.join(self.extract_input_slices(ranges))
1637 cmds = ''.join(self.extract_input_slices(ranges))
1637 f = file(fname,'w')
1638 f = file(fname,'w')
1638 f.write(cmds)
1639 f.write(cmds)
1639 f.close()
1640 f.close()
1640 print 'The following commands were written to file `%s`:' % fname
1641 print 'The following commands were written to file `%s`:' % fname
1641 print cmds
1642 print cmds
1642
1643
1643 def _edit_macro(self,mname,macro):
1644 def _edit_macro(self,mname,macro):
1644 """open an editor with the macro data in a file"""
1645 """open an editor with the macro data in a file"""
1645 filename = self.shell.mktempfile(macro.value)
1646 filename = self.shell.mktempfile(macro.value)
1646 self.shell.hooks.editor(filename)
1647 self.shell.hooks.editor(filename)
1647
1648
1648 # and make a new macro object, to replace the old one
1649 # and make a new macro object, to replace the old one
1649 mfile = open(filename)
1650 mfile = open(filename)
1650 mvalue = mfile.read()
1651 mvalue = mfile.read()
1651 mfile.close()
1652 mfile.close()
1652 self.shell.user_ns[mname] = Macro(mvalue)
1653 self.shell.user_ns[mname] = Macro(mvalue)
1653
1654
1654 def magic_ed(self,parameter_s=''):
1655 def magic_ed(self,parameter_s=''):
1655 """Alias to %edit."""
1656 """Alias to %edit."""
1656 return self.magic_edit(parameter_s)
1657 return self.magic_edit(parameter_s)
1657
1658
1658 def magic_edit(self,parameter_s='',last_call=['','']):
1659 def magic_edit(self,parameter_s='',last_call=['','']):
1659 """Bring up an editor and execute the resulting code.
1660 """Bring up an editor and execute the resulting code.
1660
1661
1661 Usage:
1662 Usage:
1662 %edit [options] [args]
1663 %edit [options] [args]
1663
1664
1664 %edit runs IPython's editor hook. The default version of this hook is
1665 %edit runs IPython's editor hook. The default version of this hook is
1665 set to call the __IPYTHON__.rc.editor command. This is read from your
1666 set to call the __IPYTHON__.rc.editor command. This is read from your
1666 environment variable $EDITOR. If this isn't found, it will default to
1667 environment variable $EDITOR. If this isn't found, it will default to
1667 vi under Linux/Unix and to notepad under Windows. See the end of this
1668 vi under Linux/Unix and to notepad under Windows. See the end of this
1668 docstring for how to change the editor hook.
1669 docstring for how to change the editor hook.
1669
1670
1670 You can also set the value of this editor via the command line option
1671 You can also set the value of this editor via the command line option
1671 '-editor' or in your ipythonrc file. This is useful if you wish to use
1672 '-editor' or in your ipythonrc file. This is useful if you wish to use
1672 specifically for IPython an editor different from your typical default
1673 specifically for IPython an editor different from your typical default
1673 (and for Windows users who typically don't set environment variables).
1674 (and for Windows users who typically don't set environment variables).
1674
1675
1675 This command allows you to conveniently edit multi-line code right in
1676 This command allows you to conveniently edit multi-line code right in
1676 your IPython session.
1677 your IPython session.
1677
1678
1678 If called without arguments, %edit opens up an empty editor with a
1679 If called without arguments, %edit opens up an empty editor with a
1679 temporary file and will execute the contents of this file when you
1680 temporary file and will execute the contents of this file when you
1680 close it (don't forget to save it!).
1681 close it (don't forget to save it!).
1681
1682
1682 Options:
1683 Options:
1683
1684
1684 -p: this will call the editor with the same data as the previous time
1685 -p: this will call the editor with the same data as the previous time
1685 it was used, regardless of how long ago (in your current session) it
1686 it was used, regardless of how long ago (in your current session) it
1686 was.
1687 was.
1687
1688
1688 -x: do not execute the edited code immediately upon exit. This is
1689 -x: do not execute the edited code immediately upon exit. This is
1689 mainly useful if you are editing programs which need to be called with
1690 mainly useful if you are editing programs which need to be called with
1690 command line arguments, which you can then do using %run.
1691 command line arguments, which you can then do using %run.
1691
1692
1692 Arguments:
1693 Arguments:
1693
1694
1694 If arguments are given, the following possibilites exist:
1695 If arguments are given, the following possibilites exist:
1695
1696
1696 - The arguments are numbers or pairs of colon-separated numbers (like
1697 - The arguments are numbers or pairs of colon-separated numbers (like
1697 1 4:8 9). These are interpreted as lines of previous input to be
1698 1 4:8 9). These are interpreted as lines of previous input to be
1698 loaded into the editor. The syntax is the same of the %macro command.
1699 loaded into the editor. The syntax is the same of the %macro command.
1699
1700
1700 - If the argument doesn't start with a number, it is evaluated as a
1701 - If the argument doesn't start with a number, it is evaluated as a
1701 variable and its contents loaded into the editor. You can thus edit
1702 variable and its contents loaded into the editor. You can thus edit
1702 any string which contains python code (including the result of
1703 any string which contains python code (including the result of
1703 previous edits).
1704 previous edits).
1704
1705
1705 - If the argument is the name of an object (other than a string),
1706 - If the argument is the name of an object (other than a string),
1706 IPython will try to locate the file where it was defined and open the
1707 IPython will try to locate the file where it was defined and open the
1707 editor at the point where it is defined. You can use `%edit function`
1708 editor at the point where it is defined. You can use `%edit function`
1708 to load an editor exactly at the point where 'function' is defined,
1709 to load an editor exactly at the point where 'function' is defined,
1709 edit it and have the file be executed automatically.
1710 edit it and have the file be executed automatically.
1710
1711
1711 If the object is a macro (see %macro for details), this opens up your
1712 If the object is a macro (see %macro for details), this opens up your
1712 specified editor with a temporary file containing the macro's data.
1713 specified editor with a temporary file containing the macro's data.
1713 Upon exit, the macro is reloaded with the contents of the file.
1714 Upon exit, the macro is reloaded with the contents of the file.
1714
1715
1715 Note: opening at an exact line is only supported under Unix, and some
1716 Note: opening at an exact line is only supported under Unix, and some
1716 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1717 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1717 '+NUMBER' parameter necessary for this feature. Good editors like
1718 '+NUMBER' parameter necessary for this feature. Good editors like
1718 (X)Emacs, vi, jed, pico and joe all do.
1719 (X)Emacs, vi, jed, pico and joe all do.
1719
1720
1720 - If the argument is not found as a variable, IPython will look for a
1721 - If the argument is not found as a variable, IPython will look for a
1721 file with that name (adding .py if necessary) and load it into the
1722 file with that name (adding .py if necessary) and load it into the
1722 editor. It will execute its contents with execfile() when you exit,
1723 editor. It will execute its contents with execfile() when you exit,
1723 loading any code in the file into your interactive namespace.
1724 loading any code in the file into your interactive namespace.
1724
1725
1725 After executing your code, %edit will return as output the code you
1726 After executing your code, %edit will return as output the code you
1726 typed in the editor (except when it was an existing file). This way
1727 typed in the editor (except when it was an existing file). This way
1727 you can reload the code in further invocations of %edit as a variable,
1728 you can reload the code in further invocations of %edit as a variable,
1728 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1729 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1729 the output.
1730 the output.
1730
1731
1731 Note that %edit is also available through the alias %ed.
1732 Note that %edit is also available through the alias %ed.
1732
1733
1733 This is an example of creating a simple function inside the editor and
1734 This is an example of creating a simple function inside the editor and
1734 then modifying it. First, start up the editor:
1735 then modifying it. First, start up the editor:
1735
1736
1736 In [1]: ed\\
1737 In [1]: ed\\
1737 Editing... done. Executing edited code...\\
1738 Editing... done. Executing edited code...\\
1738 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1739 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1739
1740
1740 We can then call the function foo():
1741 We can then call the function foo():
1741
1742
1742 In [2]: foo()\\
1743 In [2]: foo()\\
1743 foo() was defined in an editing session
1744 foo() was defined in an editing session
1744
1745
1745 Now we edit foo. IPython automatically loads the editor with the
1746 Now we edit foo. IPython automatically loads the editor with the
1746 (temporary) file where foo() was previously defined:
1747 (temporary) file where foo() was previously defined:
1747
1748
1748 In [3]: ed foo\\
1749 In [3]: ed foo\\
1749 Editing... done. Executing edited code...
1750 Editing... done. Executing edited code...
1750
1751
1751 And if we call foo() again we get the modified version:
1752 And if we call foo() again we get the modified version:
1752
1753
1753 In [4]: foo()\\
1754 In [4]: foo()\\
1754 foo() has now been changed!
1755 foo() has now been changed!
1755
1756
1756 Here is an example of how to edit a code snippet successive
1757 Here is an example of how to edit a code snippet successive
1757 times. First we call the editor:
1758 times. First we call the editor:
1758
1759
1759 In [8]: ed\\
1760 In [8]: ed\\
1760 Editing... done. Executing edited code...\\
1761 Editing... done. Executing edited code...\\
1761 hello\\
1762 hello\\
1762 Out[8]: "print 'hello'\\n"
1763 Out[8]: "print 'hello'\\n"
1763
1764
1764 Now we call it again with the previous output (stored in _):
1765 Now we call it again with the previous output (stored in _):
1765
1766
1766 In [9]: ed _\\
1767 In [9]: ed _\\
1767 Editing... done. Executing edited code...\\
1768 Editing... done. Executing edited code...\\
1768 hello world\\
1769 hello world\\
1769 Out[9]: "print 'hello world'\\n"
1770 Out[9]: "print 'hello world'\\n"
1770
1771
1771 Now we call it with the output #8 (stored in _8, also as Out[8]):
1772 Now we call it with the output #8 (stored in _8, also as Out[8]):
1772
1773
1773 In [10]: ed _8\\
1774 In [10]: ed _8\\
1774 Editing... done. Executing edited code...\\
1775 Editing... done. Executing edited code...\\
1775 hello again\\
1776 hello again\\
1776 Out[10]: "print 'hello again'\\n"
1777 Out[10]: "print 'hello again'\\n"
1777
1778
1778
1779
1779 Changing the default editor hook:
1780 Changing the default editor hook:
1780
1781
1781 If you wish to write your own editor hook, you can put it in a
1782 If you wish to write your own editor hook, you can put it in a
1782 configuration file which you load at startup time. The default hook
1783 configuration file which you load at startup time. The default hook
1783 is defined in the IPython.hooks module, and you can use that as a
1784 is defined in the IPython.hooks module, and you can use that as a
1784 starting example for further modifications. That file also has
1785 starting example for further modifications. That file also has
1785 general instructions on how to set a new hook for use once you've
1786 general instructions on how to set a new hook for use once you've
1786 defined it."""
1787 defined it."""
1787
1788
1788 # FIXME: This function has become a convoluted mess. It needs a
1789 # FIXME: This function has become a convoluted mess. It needs a
1789 # ground-up rewrite with clean, simple logic.
1790 # ground-up rewrite with clean, simple logic.
1790
1791
1791 def make_filename(arg):
1792 def make_filename(arg):
1792 "Make a filename from the given args"
1793 "Make a filename from the given args"
1793 try:
1794 try:
1794 filename = get_py_filename(arg)
1795 filename = get_py_filename(arg)
1795 except IOError:
1796 except IOError:
1796 if args.endswith('.py'):
1797 if args.endswith('.py'):
1797 filename = arg
1798 filename = arg
1798 else:
1799 else:
1799 filename = None
1800 filename = None
1800 return filename
1801 return filename
1801
1802
1802 # custom exceptions
1803 # custom exceptions
1803 class DataIsObject(Exception): pass
1804 class DataIsObject(Exception): pass
1804
1805
1805 opts,args = self.parse_options(parameter_s,'px')
1806 opts,args = self.parse_options(parameter_s,'px')
1806
1807
1807 # Default line number value
1808 # Default line number value
1808 lineno = None
1809 lineno = None
1809 if opts.has_key('p'):
1810 if opts.has_key('p'):
1810 args = '_%s' % last_call[0]
1811 args = '_%s' % last_call[0]
1811 if not self.shell.user_ns.has_key(args):
1812 if not self.shell.user_ns.has_key(args):
1812 args = last_call[1]
1813 args = last_call[1]
1813
1814
1814 # use last_call to remember the state of the previous call, but don't
1815 # use last_call to remember the state of the previous call, but don't
1815 # let it be clobbered by successive '-p' calls.
1816 # let it be clobbered by successive '-p' calls.
1816 try:
1817 try:
1817 last_call[0] = self.shell.outputcache.prompt_count
1818 last_call[0] = self.shell.outputcache.prompt_count
1818 if not opts.has_key('p'):
1819 if not opts.has_key('p'):
1819 last_call[1] = parameter_s
1820 last_call[1] = parameter_s
1820 except:
1821 except:
1821 pass
1822 pass
1822
1823
1823 # by default this is done with temp files, except when the given
1824 # by default this is done with temp files, except when the given
1824 # arg is a filename
1825 # arg is a filename
1825 use_temp = 1
1826 use_temp = 1
1826
1827
1827 if re.match(r'\d',args):
1828 if re.match(r'\d',args):
1828 # Mode where user specifies ranges of lines, like in %macro.
1829 # Mode where user specifies ranges of lines, like in %macro.
1829 # This means that you can't edit files whose names begin with
1830 # This means that you can't edit files whose names begin with
1830 # numbers this way. Tough.
1831 # numbers this way. Tough.
1831 ranges = args.split()
1832 ranges = args.split()
1832 data = ''.join(self.extract_input_slices(ranges))
1833 data = ''.join(self.extract_input_slices(ranges))
1833 elif args.endswith('.py'):
1834 elif args.endswith('.py'):
1834 filename = make_filename(args)
1835 filename = make_filename(args)
1835 data = ''
1836 data = ''
1836 use_temp = 0
1837 use_temp = 0
1837 elif args:
1838 elif args:
1838 try:
1839 try:
1839 # Load the parameter given as a variable. If not a string,
1840 # Load the parameter given as a variable. If not a string,
1840 # process it as an object instead (below)
1841 # process it as an object instead (below)
1841
1842
1842 #print '*** args',args,'type',type(args) # dbg
1843 #print '*** args',args,'type',type(args) # dbg
1843 data = eval(args,self.shell.user_ns)
1844 data = eval(args,self.shell.user_ns)
1844 if not type(data) in StringTypes:
1845 if not type(data) in StringTypes:
1845 raise DataIsObject
1846 raise DataIsObject
1846
1847
1847 except (NameError,SyntaxError):
1848 except (NameError,SyntaxError):
1848 # given argument is not a variable, try as a filename
1849 # given argument is not a variable, try as a filename
1849 filename = make_filename(args)
1850 filename = make_filename(args)
1850 if filename is None:
1851 if filename is None:
1851 warn("Argument given (%s) can't be found as a variable "
1852 warn("Argument given (%s) can't be found as a variable "
1852 "or as a filename." % args)
1853 "or as a filename." % args)
1853 return
1854 return
1854
1855
1855 data = ''
1856 data = ''
1856 use_temp = 0
1857 use_temp = 0
1857 except DataIsObject:
1858 except DataIsObject:
1858
1859
1859 # macros have a special edit function
1860 # macros have a special edit function
1860 if isinstance(data,Macro):
1861 if isinstance(data,Macro):
1861 self._edit_macro(args,data)
1862 self._edit_macro(args,data)
1862 return
1863 return
1863
1864
1864 # For objects, try to edit the file where they are defined
1865 # For objects, try to edit the file where they are defined
1865 try:
1866 try:
1866 filename = inspect.getabsfile(data)
1867 filename = inspect.getabsfile(data)
1867 datafile = 1
1868 datafile = 1
1868 except TypeError:
1869 except TypeError:
1869 filename = make_filename(args)
1870 filename = make_filename(args)
1870 datafile = 1
1871 datafile = 1
1871 warn('Could not find file where `%s` is defined.\n'
1872 warn('Could not find file where `%s` is defined.\n'
1872 'Opening a file named `%s`' % (args,filename))
1873 'Opening a file named `%s`' % (args,filename))
1873 # Now, make sure we can actually read the source (if it was in
1874 # Now, make sure we can actually read the source (if it was in
1874 # a temp file it's gone by now).
1875 # a temp file it's gone by now).
1875 if datafile:
1876 if datafile:
1876 try:
1877 try:
1877 lineno = inspect.getsourcelines(data)[1]
1878 lineno = inspect.getsourcelines(data)[1]
1878 except IOError:
1879 except IOError:
1879 filename = make_filename(args)
1880 filename = make_filename(args)
1880 if filename is None:
1881 if filename is None:
1881 warn('The file `%s` where `%s` was defined cannot '
1882 warn('The file `%s` where `%s` was defined cannot '
1882 'be read.' % (filename,data))
1883 'be read.' % (filename,data))
1883 return
1884 return
1884 use_temp = 0
1885 use_temp = 0
1885 else:
1886 else:
1886 data = ''
1887 data = ''
1887
1888
1888 if use_temp:
1889 if use_temp:
1889 filename = self.shell.mktempfile(data)
1890 filename = self.shell.mktempfile(data)
1890
1891
1891 # do actual editing here
1892 # do actual editing here
1892 print 'Editing...',
1893 print 'Editing...',
1893 sys.stdout.flush()
1894 sys.stdout.flush()
1894 self.shell.hooks.editor(filename,lineno)
1895 self.shell.hooks.editor(filename,lineno)
1895 if opts.has_key('x'): # -x prevents actual execution
1896 if opts.has_key('x'): # -x prevents actual execution
1896 print
1897 print
1897 else:
1898 else:
1898 print 'done. Executing edited code...'
1899 print 'done. Executing edited code...'
1899 try:
1900 try:
1900 self.shell.safe_execfile(filename,self.shell.user_ns)
1901 self.shell.safe_execfile(filename,self.shell.user_ns)
1901 except IOError,msg:
1902 except IOError,msg:
1902 if msg.filename == filename:
1903 if msg.filename == filename:
1903 warn('File not found. Did you forget to save?')
1904 warn('File not found. Did you forget to save?')
1904 return
1905 return
1905 else:
1906 else:
1906 self.shell.showtraceback()
1907 self.shell.showtraceback()
1907 except:
1908 except:
1908 self.shell.showtraceback()
1909 self.shell.showtraceback()
1909
1910
1910 def magic_xmode(self,parameter_s = ''):
1911 def magic_xmode(self,parameter_s = ''):
1911 """Switch modes for the exception handlers.
1912 """Switch modes for the exception handlers.
1912
1913
1913 Valid modes: Plain, Context and Verbose.
1914 Valid modes: Plain, Context and Verbose.
1914
1915
1915 If called without arguments, acts as a toggle."""
1916 If called without arguments, acts as a toggle."""
1916
1917
1917 def xmode_switch_err(name):
1918 def xmode_switch_err(name):
1918 warn('Error changing %s exception modes.\n%s' %
1919 warn('Error changing %s exception modes.\n%s' %
1919 (name,sys.exc_info()[1]))
1920 (name,sys.exc_info()[1]))
1920
1921
1921 shell = self.shell
1922 shell = self.shell
1922 new_mode = parameter_s.strip().capitalize()
1923 new_mode = parameter_s.strip().capitalize()
1923 try:
1924 try:
1924 shell.InteractiveTB.set_mode(mode=new_mode)
1925 shell.InteractiveTB.set_mode(mode=new_mode)
1925 print 'Exception reporting mode:',shell.InteractiveTB.mode
1926 print 'Exception reporting mode:',shell.InteractiveTB.mode
1926 except:
1927 except:
1927 xmode_switch_err('user')
1928 xmode_switch_err('user')
1928
1929
1929 # threaded shells use a special handler in sys.excepthook
1930 # threaded shells use a special handler in sys.excepthook
1930 if shell.isthreaded:
1931 if shell.isthreaded:
1931 try:
1932 try:
1932 shell.sys_excepthook.set_mode(mode=new_mode)
1933 shell.sys_excepthook.set_mode(mode=new_mode)
1933 except:
1934 except:
1934 xmode_switch_err('threaded')
1935 xmode_switch_err('threaded')
1935
1936
1936 def magic_colors(self,parameter_s = ''):
1937 def magic_colors(self,parameter_s = ''):
1937 """Switch color scheme for prompts, info system and exception handlers.
1938 """Switch color scheme for prompts, info system and exception handlers.
1938
1939
1939 Currently implemented schemes: NoColor, Linux, LightBG.
1940 Currently implemented schemes: NoColor, Linux, LightBG.
1940
1941
1941 Color scheme names are not case-sensitive."""
1942 Color scheme names are not case-sensitive."""
1942
1943
1943 def color_switch_err(name):
1944 def color_switch_err(name):
1944 warn('Error changing %s color schemes.\n%s' %
1945 warn('Error changing %s color schemes.\n%s' %
1945 (name,sys.exc_info()[1]))
1946 (name,sys.exc_info()[1]))
1946
1947
1947
1948
1948 new_scheme = parameter_s.strip()
1949 new_scheme = parameter_s.strip()
1949 if not new_scheme:
1950 if not new_scheme:
1950 print 'You must specify a color scheme.'
1951 print 'You must specify a color scheme.'
1951 return
1952 return
1952 # Under Windows, check for Gary Bishop's readline, which is necessary
1953 # Under Windows, check for Gary Bishop's readline, which is necessary
1953 # for ANSI coloring
1954 # for ANSI coloring
1954 if os.name in ['nt','dos']:
1955 if os.name in ['nt','dos']:
1955 try:
1956 try:
1956 import readline
1957 import readline
1957 except ImportError:
1958 except ImportError:
1958 has_readline = 0
1959 has_readline = 0
1959 else:
1960 else:
1960 try:
1961 try:
1961 readline.GetOutputFile()
1962 readline.GetOutputFile()
1962 except AttributeError:
1963 except AttributeError:
1963 has_readline = 0
1964 has_readline = 0
1964 else:
1965 else:
1965 has_readline = 1
1966 has_readline = 1
1966 if not has_readline:
1967 if not has_readline:
1967 msg = """\
1968 msg = """\
1968 Proper color support under MS Windows requires Gary Bishop's readline library.
1969 Proper color support under MS Windows requires Gary Bishop's readline library.
1969 You can find it at:
1970 You can find it at:
1970 http://sourceforge.net/projects/uncpythontools
1971 http://sourceforge.net/projects/uncpythontools
1971 Gary's readline needs the ctypes module, from:
1972 Gary's readline needs the ctypes module, from:
1972 http://starship.python.net/crew/theller/ctypes
1973 http://starship.python.net/crew/theller/ctypes
1973
1974
1974 Defaulting color scheme to 'NoColor'"""
1975 Defaulting color scheme to 'NoColor'"""
1975 new_scheme = 'NoColor'
1976 new_scheme = 'NoColor'
1976 warn(msg)
1977 warn(msg)
1977 # local shortcut
1978 # local shortcut
1978 shell = self.shell
1979 shell = self.shell
1979
1980
1980 # Set prompt colors
1981 # Set prompt colors
1981 try:
1982 try:
1982 shell.outputcache.set_colors(new_scheme)
1983 shell.outputcache.set_colors(new_scheme)
1983 except:
1984 except:
1984 color_switch_err('prompt')
1985 color_switch_err('prompt')
1985 else:
1986 else:
1986 shell.rc.colors = \
1987 shell.rc.colors = \
1987 shell.outputcache.color_table.active_scheme_name
1988 shell.outputcache.color_table.active_scheme_name
1988 # Set exception colors
1989 # Set exception colors
1989 try:
1990 try:
1990 shell.InteractiveTB.set_colors(scheme = new_scheme)
1991 shell.InteractiveTB.set_colors(scheme = new_scheme)
1991 shell.SyntaxTB.set_colors(scheme = new_scheme)
1992 shell.SyntaxTB.set_colors(scheme = new_scheme)
1992 except:
1993 except:
1993 color_switch_err('exception')
1994 color_switch_err('exception')
1994
1995
1995 # threaded shells use a verbose traceback in sys.excepthook
1996 # threaded shells use a verbose traceback in sys.excepthook
1996 if shell.isthreaded:
1997 if shell.isthreaded:
1997 try:
1998 try:
1998 shell.sys_excepthook.set_colors(scheme=new_scheme)
1999 shell.sys_excepthook.set_colors(scheme=new_scheme)
1999 except:
2000 except:
2000 color_switch_err('system exception handler')
2001 color_switch_err('system exception handler')
2001
2002
2002 # Set info (for 'object?') colors
2003 # Set info (for 'object?') colors
2003 if shell.rc.color_info:
2004 if shell.rc.color_info:
2004 try:
2005 try:
2005 shell.inspector.set_active_scheme(new_scheme)
2006 shell.inspector.set_active_scheme(new_scheme)
2006 except:
2007 except:
2007 color_switch_err('object inspector')
2008 color_switch_err('object inspector')
2008 else:
2009 else:
2009 shell.inspector.set_active_scheme('NoColor')
2010 shell.inspector.set_active_scheme('NoColor')
2010
2011
2011 def magic_color_info(self,parameter_s = ''):
2012 def magic_color_info(self,parameter_s = ''):
2012 """Toggle color_info.
2013 """Toggle color_info.
2013
2014
2014 The color_info configuration parameter controls whether colors are
2015 The color_info configuration parameter controls whether colors are
2015 used for displaying object details (by things like %psource, %pfile or
2016 used for displaying object details (by things like %psource, %pfile or
2016 the '?' system). This function toggles this value with each call.
2017 the '?' system). This function toggles this value with each call.
2017
2018
2018 Note that unless you have a fairly recent pager (less works better
2019 Note that unless you have a fairly recent pager (less works better
2019 than more) in your system, using colored object information displays
2020 than more) in your system, using colored object information displays
2020 will not work properly. Test it and see."""
2021 will not work properly. Test it and see."""
2021
2022
2022 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2023 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2023 self.magic_colors(self.shell.rc.colors)
2024 self.magic_colors(self.shell.rc.colors)
2024 print 'Object introspection functions have now coloring:',
2025 print 'Object introspection functions have now coloring:',
2025 print ['OFF','ON'][self.shell.rc.color_info]
2026 print ['OFF','ON'][self.shell.rc.color_info]
2026
2027
2027 def magic_Pprint(self, parameter_s=''):
2028 def magic_Pprint(self, parameter_s=''):
2028 """Toggle pretty printing on/off."""
2029 """Toggle pretty printing on/off."""
2029
2030
2030 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2031 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2031 print 'Pretty printing has been turned', \
2032 print 'Pretty printing has been turned', \
2032 ['OFF','ON'][self.shell.outputcache.Pprint]
2033 ['OFF','ON'][self.shell.outputcache.Pprint]
2033
2034
2034 def magic_exit(self, parameter_s=''):
2035 def magic_exit(self, parameter_s=''):
2035 """Exit IPython, confirming if configured to do so.
2036 """Exit IPython, confirming if configured to do so.
2036
2037
2037 You can configure whether IPython asks for confirmation upon exit by
2038 You can configure whether IPython asks for confirmation upon exit by
2038 setting the confirm_exit flag in the ipythonrc file."""
2039 setting the confirm_exit flag in the ipythonrc file."""
2039
2040
2040 self.shell.exit()
2041 self.shell.exit()
2041
2042
2042 def magic_quit(self, parameter_s=''):
2043 def magic_quit(self, parameter_s=''):
2043 """Exit IPython, confirming if configured to do so (like %exit)"""
2044 """Exit IPython, confirming if configured to do so (like %exit)"""
2044
2045
2045 self.shell.exit()
2046 self.shell.exit()
2046
2047
2047 def magic_Exit(self, parameter_s=''):
2048 def magic_Exit(self, parameter_s=''):
2048 """Exit IPython without confirmation."""
2049 """Exit IPython without confirmation."""
2049
2050
2050 self.shell.exit_now = True
2051 self.shell.exit_now = True
2051
2052
2052 def magic_Quit(self, parameter_s=''):
2053 def magic_Quit(self, parameter_s=''):
2053 """Exit IPython without confirmation (like %Exit)."""
2054 """Exit IPython without confirmation (like %Exit)."""
2054
2055
2055 self.shell.exit_now = True
2056 self.shell.exit_now = True
2056
2057
2057 #......................................................................
2058 #......................................................................
2058 # Functions to implement unix shell-type things
2059 # Functions to implement unix shell-type things
2059
2060
2060 def magic_alias(self, parameter_s = ''):
2061 def magic_alias(self, parameter_s = ''):
2061 """Define an alias for a system command.
2062 """Define an alias for a system command.
2062
2063
2063 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2064 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2064
2065
2065 Then, typing 'alias_name params' will execute the system command 'cmd
2066 Then, typing 'alias_name params' will execute the system command 'cmd
2066 params' (from your underlying operating system).
2067 params' (from your underlying operating system).
2067
2068
2068 Aliases have lower precedence than magic functions and Python normal
2069 Aliases have lower precedence than magic functions and Python normal
2069 variables, so if 'foo' is both a Python variable and an alias, the
2070 variables, so if 'foo' is both a Python variable and an alias, the
2070 alias can not be executed until 'del foo' removes the Python variable.
2071 alias can not be executed until 'del foo' removes the Python variable.
2071
2072
2072 You can use the %l specifier in an alias definition to represent the
2073 You can use the %l specifier in an alias definition to represent the
2073 whole line when the alias is called. For example:
2074 whole line when the alias is called. For example:
2074
2075
2075 In [2]: alias all echo "Input in brackets: <%l>"\\
2076 In [2]: alias all echo "Input in brackets: <%l>"\\
2076 In [3]: all hello world\\
2077 In [3]: all hello world\\
2077 Input in brackets: <hello world>
2078 Input in brackets: <hello world>
2078
2079
2079 You can also define aliases with parameters using %s specifiers (one
2080 You can also define aliases with parameters using %s specifiers (one
2080 per parameter):
2081 per parameter):
2081
2082
2082 In [1]: alias parts echo first %s second %s\\
2083 In [1]: alias parts echo first %s second %s\\
2083 In [2]: %parts A B\\
2084 In [2]: %parts A B\\
2084 first A second B\\
2085 first A second B\\
2085 In [3]: %parts A\\
2086 In [3]: %parts A\\
2086 Incorrect number of arguments: 2 expected.\\
2087 Incorrect number of arguments: 2 expected.\\
2087 parts is an alias to: 'echo first %s second %s'
2088 parts is an alias to: 'echo first %s second %s'
2088
2089
2089 Note that %l and %s are mutually exclusive. You can only use one or
2090 Note that %l and %s are mutually exclusive. You can only use one or
2090 the other in your aliases.
2091 the other in your aliases.
2091
2092
2092 Aliases expand Python variables just like system calls using ! or !!
2093 Aliases expand Python variables just like system calls using ! or !!
2093 do: all expressions prefixed with '$' get expanded. For details of
2094 do: all expressions prefixed with '$' get expanded. For details of
2094 the semantic rules, see PEP-215:
2095 the semantic rules, see PEP-215:
2095 http://www.python.org/peps/pep-0215.html. This is the library used by
2096 http://www.python.org/peps/pep-0215.html. This is the library used by
2096 IPython for variable expansion. If you want to access a true shell
2097 IPython for variable expansion. If you want to access a true shell
2097 variable, an extra $ is necessary to prevent its expansion by IPython:
2098 variable, an extra $ is necessary to prevent its expansion by IPython:
2098
2099
2099 In [6]: alias show echo\\
2100 In [6]: alias show echo\\
2100 In [7]: PATH='A Python string'\\
2101 In [7]: PATH='A Python string'\\
2101 In [8]: show $PATH\\
2102 In [8]: show $PATH\\
2102 A Python string\\
2103 A Python string\\
2103 In [9]: show $$PATH\\
2104 In [9]: show $$PATH\\
2104 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2105 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2105
2106
2106 You can use the alias facility to acess all of $PATH. See the %rehash
2107 You can use the alias facility to acess all of $PATH. See the %rehash
2107 and %rehashx functions, which automatically create aliases for the
2108 and %rehashx functions, which automatically create aliases for the
2108 contents of your $PATH.
2109 contents of your $PATH.
2109
2110
2110 If called with no parameters, %alias prints the current alias table."""
2111 If called with no parameters, %alias prints the current alias table."""
2111
2112
2112 par = parameter_s.strip()
2113 par = parameter_s.strip()
2113 if not par:
2114 if not par:
2114 if self.shell.rc.automagic:
2115 if self.shell.rc.automagic:
2115 prechar = ''
2116 prechar = ''
2116 else:
2117 else:
2117 prechar = self.shell.ESC_MAGIC
2118 prechar = self.shell.ESC_MAGIC
2118 print 'Alias\t\tSystem Command\n'+'-'*30
2119 print 'Alias\t\tSystem Command\n'+'-'*30
2119 atab = self.shell.alias_table
2120 atab = self.shell.alias_table
2120 aliases = atab.keys()
2121 aliases = atab.keys()
2121 aliases.sort()
2122 aliases.sort()
2122 for alias in aliases:
2123 for alias in aliases:
2123 print prechar+alias+'\t\t'+atab[alias][1]
2124 print prechar+alias+'\t\t'+atab[alias][1]
2124 print '-'*30+'\nTotal number of aliases:',len(aliases)
2125 print '-'*30+'\nTotal number of aliases:',len(aliases)
2125 return
2126 return
2126 try:
2127 try:
2127 alias,cmd = par.split(None,1)
2128 alias,cmd = par.split(None,1)
2128 except:
2129 except:
2129 print OInspect.getdoc(self.magic_alias)
2130 print OInspect.getdoc(self.magic_alias)
2130 else:
2131 else:
2131 nargs = cmd.count('%s')
2132 nargs = cmd.count('%s')
2132 if nargs>0 and cmd.find('%l')>=0:
2133 if nargs>0 and cmd.find('%l')>=0:
2133 error('The %s and %l specifiers are mutually exclusive '
2134 error('The %s and %l specifiers are mutually exclusive '
2134 'in alias definitions.')
2135 'in alias definitions.')
2135 else: # all looks OK
2136 else: # all looks OK
2136 self.shell.alias_table[alias] = (nargs,cmd)
2137 self.shell.alias_table[alias] = (nargs,cmd)
2137 self.shell.alias_table_validate(verbose=1)
2138 self.shell.alias_table_validate(verbose=1)
2138 # end magic_alias
2139 # end magic_alias
2139
2140
2140 def magic_unalias(self, parameter_s = ''):
2141 def magic_unalias(self, parameter_s = ''):
2141 """Remove an alias"""
2142 """Remove an alias"""
2142
2143
2143 aname = parameter_s.strip()
2144 aname = parameter_s.strip()
2144 if aname in self.shell.alias_table:
2145 if aname in self.shell.alias_table:
2145 del self.shell.alias_table[aname]
2146 del self.shell.alias_table[aname]
2146
2147
2147 def magic_rehash(self, parameter_s = ''):
2148 def magic_rehash(self, parameter_s = ''):
2148 """Update the alias table with all entries in $PATH.
2149 """Update the alias table with all entries in $PATH.
2149
2150
2150 This version does no checks on execute permissions or whether the
2151 This version does no checks on execute permissions or whether the
2151 contents of $PATH are truly files (instead of directories or something
2152 contents of $PATH are truly files (instead of directories or something
2152 else). For such a safer (but slower) version, use %rehashx."""
2153 else). For such a safer (but slower) version, use %rehashx."""
2153
2154
2154 # This function (and rehashx) manipulate the alias_table directly
2155 # This function (and rehashx) manipulate the alias_table directly
2155 # rather than calling magic_alias, for speed reasons. A rehash on a
2156 # rather than calling magic_alias, for speed reasons. A rehash on a
2156 # typical Linux box involves several thousand entries, so efficiency
2157 # typical Linux box involves several thousand entries, so efficiency
2157 # here is a top concern.
2158 # here is a top concern.
2158
2159
2159 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2160 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2160 alias_table = self.shell.alias_table
2161 alias_table = self.shell.alias_table
2161 for pdir in path:
2162 for pdir in path:
2162 for ff in os.listdir(pdir):
2163 for ff in os.listdir(pdir):
2163 # each entry in the alias table must be (N,name), where
2164 # each entry in the alias table must be (N,name), where
2164 # N is the number of positional arguments of the alias.
2165 # N is the number of positional arguments of the alias.
2165 alias_table[ff] = (0,ff)
2166 alias_table[ff] = (0,ff)
2166 # Make sure the alias table doesn't contain keywords or builtins
2167 # Make sure the alias table doesn't contain keywords or builtins
2167 self.shell.alias_table_validate()
2168 self.shell.alias_table_validate()
2168 # Call again init_auto_alias() so we get 'rm -i' and other modified
2169 # Call again init_auto_alias() so we get 'rm -i' and other modified
2169 # aliases since %rehash will probably clobber them
2170 # aliases since %rehash will probably clobber them
2170 self.shell.init_auto_alias()
2171 self.shell.init_auto_alias()
2171
2172
2172 def magic_rehashx(self, parameter_s = ''):
2173 def magic_rehashx(self, parameter_s = ''):
2173 """Update the alias table with all executable files in $PATH.
2174 """Update the alias table with all executable files in $PATH.
2174
2175
2175 This version explicitly checks that every entry in $PATH is a file
2176 This version explicitly checks that every entry in $PATH is a file
2176 with execute access (os.X_OK), so it is much slower than %rehash.
2177 with execute access (os.X_OK), so it is much slower than %rehash.
2177
2178
2178 Under Windows, it checks executability as a match agains a
2179 Under Windows, it checks executability as a match agains a
2179 '|'-separated string of extensions, stored in the IPython config
2180 '|'-separated string of extensions, stored in the IPython config
2180 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2181 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2181
2182
2182 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2183 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2183 alias_table = self.shell.alias_table
2184 alias_table = self.shell.alias_table
2184
2185
2185 if os.name == 'posix':
2186 if os.name == 'posix':
2186 isexec = lambda fname:os.path.isfile(fname) and \
2187 isexec = lambda fname:os.path.isfile(fname) and \
2187 os.access(fname,os.X_OK)
2188 os.access(fname,os.X_OK)
2188 else:
2189 else:
2189
2190
2190 try:
2191 try:
2191 winext = os.environ['pathext'].replace(';','|').replace('.','')
2192 winext = os.environ['pathext'].replace(';','|').replace('.','')
2192 except KeyError:
2193 except KeyError:
2193 winext = 'exe|com|bat'
2194 winext = 'exe|com|bat'
2194
2195
2195 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2196 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2196 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2197 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2197 savedir = os.getcwd()
2198 savedir = os.getcwd()
2198 try:
2199 try:
2199 # write the whole loop for posix/Windows so we don't have an if in
2200 # write the whole loop for posix/Windows so we don't have an if in
2200 # the innermost part
2201 # the innermost part
2201 if os.name == 'posix':
2202 if os.name == 'posix':
2202 for pdir in path:
2203 for pdir in path:
2203 os.chdir(pdir)
2204 os.chdir(pdir)
2204 for ff in os.listdir(pdir):
2205 for ff in os.listdir(pdir):
2205 if isexec(ff):
2206 if isexec(ff):
2206 # each entry in the alias table must be (N,name),
2207 # each entry in the alias table must be (N,name),
2207 # where N is the number of positional arguments of the
2208 # where N is the number of positional arguments of the
2208 # alias.
2209 # alias.
2209 alias_table[ff] = (0,ff)
2210 alias_table[ff] = (0,ff)
2210 else:
2211 else:
2211 for pdir in path:
2212 for pdir in path:
2212 os.chdir(pdir)
2213 os.chdir(pdir)
2213 for ff in os.listdir(pdir):
2214 for ff in os.listdir(pdir):
2214 if isexec(ff):
2215 if isexec(ff):
2215 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2216 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2216 # Make sure the alias table doesn't contain keywords or builtins
2217 # Make sure the alias table doesn't contain keywords or builtins
2217 self.shell.alias_table_validate()
2218 self.shell.alias_table_validate()
2218 # Call again init_auto_alias() so we get 'rm -i' and other
2219 # Call again init_auto_alias() so we get 'rm -i' and other
2219 # modified aliases since %rehashx will probably clobber them
2220 # modified aliases since %rehashx will probably clobber them
2220 self.shell.init_auto_alias()
2221 self.shell.init_auto_alias()
2221 finally:
2222 finally:
2222 os.chdir(savedir)
2223 os.chdir(savedir)
2223
2224
2224 def magic_pwd(self, parameter_s = ''):
2225 def magic_pwd(self, parameter_s = ''):
2225 """Return the current working directory path."""
2226 """Return the current working directory path."""
2226 return os.getcwd()
2227 return os.getcwd()
2227
2228
2228 def magic_cd(self, parameter_s=''):
2229 def magic_cd(self, parameter_s=''):
2229 """Change the current working directory.
2230 """Change the current working directory.
2230
2231
2231 This command automatically maintains an internal list of directories
2232 This command automatically maintains an internal list of directories
2232 you visit during your IPython session, in the variable _dh. The
2233 you visit during your IPython session, in the variable _dh. The
2233 command %dhist shows this history nicely formatted.
2234 command %dhist shows this history nicely formatted.
2234
2235
2235 Usage:
2236 Usage:
2236
2237
2237 cd 'dir': changes to directory 'dir'.
2238 cd 'dir': changes to directory 'dir'.
2238
2239
2239 cd -: changes to the last visited directory.
2240 cd -: changes to the last visited directory.
2240
2241
2241 cd -<n>: changes to the n-th directory in the directory history.
2242 cd -<n>: changes to the n-th directory in the directory history.
2242
2243
2243 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2244 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2244 (note: cd <bookmark_name> is enough if there is no
2245 (note: cd <bookmark_name> is enough if there is no
2245 directory <bookmark_name>, but a bookmark with the name exists.)
2246 directory <bookmark_name>, but a bookmark with the name exists.)
2246
2247
2247 Options:
2248 Options:
2248
2249
2249 -q: quiet. Do not print the working directory after the cd command is
2250 -q: quiet. Do not print the working directory after the cd command is
2250 executed. By default IPython's cd command does print this directory,
2251 executed. By default IPython's cd command does print this directory,
2251 since the default prompts do not display path information.
2252 since the default prompts do not display path information.
2252
2253
2253 Note that !cd doesn't work for this purpose because the shell where
2254 Note that !cd doesn't work for this purpose because the shell where
2254 !command runs is immediately discarded after executing 'command'."""
2255 !command runs is immediately discarded after executing 'command'."""
2255
2256
2256 parameter_s = parameter_s.strip()
2257 parameter_s = parameter_s.strip()
2257 bkms = self.shell.persist.get("bookmarks",{})
2258 bkms = self.shell.persist.get("bookmarks",{})
2258
2259
2259 numcd = re.match(r'(-)(\d+)$',parameter_s)
2260 numcd = re.match(r'(-)(\d+)$',parameter_s)
2260 # jump in directory history by number
2261 # jump in directory history by number
2261 if numcd:
2262 if numcd:
2262 nn = int(numcd.group(2))
2263 nn = int(numcd.group(2))
2263 try:
2264 try:
2264 ps = self.shell.user_ns['_dh'][nn]
2265 ps = self.shell.user_ns['_dh'][nn]
2265 except IndexError:
2266 except IndexError:
2266 print 'The requested directory does not exist in history.'
2267 print 'The requested directory does not exist in history.'
2267 return
2268 return
2268 else:
2269 else:
2269 opts = {}
2270 opts = {}
2270 else:
2271 else:
2271 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2272 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2272 # jump to previous
2273 # jump to previous
2273 if ps == '-':
2274 if ps == '-':
2274 try:
2275 try:
2275 ps = self.shell.user_ns['_dh'][-2]
2276 ps = self.shell.user_ns['_dh'][-2]
2276 except IndexError:
2277 except IndexError:
2277 print 'No previous directory to change to.'
2278 print 'No previous directory to change to.'
2278 return
2279 return
2279 # jump to bookmark
2280 # jump to bookmark
2280 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2281 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2281 if bkms.has_key(ps):
2282 if bkms.has_key(ps):
2282 target = bkms[ps]
2283 target = bkms[ps]
2283 print '(bookmark:%s) -> %s' % (ps,target)
2284 print '(bookmark:%s) -> %s' % (ps,target)
2284 ps = target
2285 ps = target
2285 else:
2286 else:
2286 if bkms:
2287 if bkms:
2287 error("Bookmark '%s' not found. "
2288 error("Bookmark '%s' not found. "
2288 "Use '%bookmark -l' to see your bookmarks." % ps)
2289 "Use '%bookmark -l' to see your bookmarks." % ps)
2289 else:
2290 else:
2290 print "Bookmarks not set - use %bookmark <bookmarkname>"
2291 print "Bookmarks not set - use %bookmark <bookmarkname>"
2291 return
2292 return
2292
2293
2293 # at this point ps should point to the target dir
2294 # at this point ps should point to the target dir
2294 if ps:
2295 if ps:
2295 try:
2296 try:
2296 os.chdir(os.path.expanduser(ps))
2297 os.chdir(os.path.expanduser(ps))
2297 except OSError:
2298 except OSError:
2298 print sys.exc_info()[1]
2299 print sys.exc_info()[1]
2299 else:
2300 else:
2300 self.shell.user_ns['_dh'].append(os.getcwd())
2301 self.shell.user_ns['_dh'].append(os.getcwd())
2301 else:
2302 else:
2302 os.chdir(self.shell.home_dir)
2303 os.chdir(self.shell.home_dir)
2303 self.shell.user_ns['_dh'].append(os.getcwd())
2304 self.shell.user_ns['_dh'].append(os.getcwd())
2304 if not 'q' in opts:
2305 if not 'q' in opts:
2305 print self.shell.user_ns['_dh'][-1]
2306 print self.shell.user_ns['_dh'][-1]
2306
2307
2307 def magic_dhist(self, parameter_s=''):
2308 def magic_dhist(self, parameter_s=''):
2308 """Print your history of visited directories.
2309 """Print your history of visited directories.
2309
2310
2310 %dhist -> print full history\\
2311 %dhist -> print full history\\
2311 %dhist n -> print last n entries only\\
2312 %dhist n -> print last n entries only\\
2312 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2313 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2313
2314
2314 This history is automatically maintained by the %cd command, and
2315 This history is automatically maintained by the %cd command, and
2315 always available as the global list variable _dh. You can use %cd -<n>
2316 always available as the global list variable _dh. You can use %cd -<n>
2316 to go to directory number <n>."""
2317 to go to directory number <n>."""
2317
2318
2318 dh = self.shell.user_ns['_dh']
2319 dh = self.shell.user_ns['_dh']
2319 if parameter_s:
2320 if parameter_s:
2320 try:
2321 try:
2321 args = map(int,parameter_s.split())
2322 args = map(int,parameter_s.split())
2322 except:
2323 except:
2323 self.arg_err(Magic.magic_dhist)
2324 self.arg_err(Magic.magic_dhist)
2324 return
2325 return
2325 if len(args) == 1:
2326 if len(args) == 1:
2326 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2327 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2327 elif len(args) == 2:
2328 elif len(args) == 2:
2328 ini,fin = args
2329 ini,fin = args
2329 else:
2330 else:
2330 self.arg_err(Magic.magic_dhist)
2331 self.arg_err(Magic.magic_dhist)
2331 return
2332 return
2332 else:
2333 else:
2333 ini,fin = 0,len(dh)
2334 ini,fin = 0,len(dh)
2334 nlprint(dh,
2335 nlprint(dh,
2335 header = 'Directory history (kept in _dh)',
2336 header = 'Directory history (kept in _dh)',
2336 start=ini,stop=fin)
2337 start=ini,stop=fin)
2337
2338
2338 def magic_env(self, parameter_s=''):
2339 def magic_env(self, parameter_s=''):
2339 """List environment variables."""
2340 """List environment variables."""
2340
2341
2341 return os.environ.data
2342 return os.environ.data
2342
2343
2343 def magic_pushd(self, parameter_s=''):
2344 def magic_pushd(self, parameter_s=''):
2344 """Place the current dir on stack and change directory.
2345 """Place the current dir on stack and change directory.
2345
2346
2346 Usage:\\
2347 Usage:\\
2347 %pushd ['dirname']
2348 %pushd ['dirname']
2348
2349
2349 %pushd with no arguments does a %pushd to your home directory.
2350 %pushd with no arguments does a %pushd to your home directory.
2350 """
2351 """
2351 if parameter_s == '': parameter_s = '~'
2352 if parameter_s == '': parameter_s = '~'
2352 dir_s = self.shell.dir_stack
2353 dir_s = self.shell.dir_stack
2353 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2354 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2354 os.path.expanduser(self.shell.dir_stack[0]):
2355 os.path.expanduser(self.shell.dir_stack[0]):
2355 try:
2356 try:
2356 self.magic_cd(parameter_s)
2357 self.magic_cd(parameter_s)
2357 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2358 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2358 self.magic_dirs()
2359 self.magic_dirs()
2359 except:
2360 except:
2360 print 'Invalid directory'
2361 print 'Invalid directory'
2361 else:
2362 else:
2362 print 'You are already there!'
2363 print 'You are already there!'
2363
2364
2364 def magic_popd(self, parameter_s=''):
2365 def magic_popd(self, parameter_s=''):
2365 """Change to directory popped off the top of the stack.
2366 """Change to directory popped off the top of the stack.
2366 """
2367 """
2367 if len (self.shell.dir_stack) > 1:
2368 if len (self.shell.dir_stack) > 1:
2368 self.shell.dir_stack.pop(0)
2369 self.shell.dir_stack.pop(0)
2369 self.magic_cd(self.shell.dir_stack[0])
2370 self.magic_cd(self.shell.dir_stack[0])
2370 print self.shell.dir_stack[0]
2371 print self.shell.dir_stack[0]
2371 else:
2372 else:
2372 print "You can't remove the starting directory from the stack:",\
2373 print "You can't remove the starting directory from the stack:",\
2373 self.shell.dir_stack
2374 self.shell.dir_stack
2374
2375
2375 def magic_dirs(self, parameter_s=''):
2376 def magic_dirs(self, parameter_s=''):
2376 """Return the current directory stack."""
2377 """Return the current directory stack."""
2377
2378
2378 return self.shell.dir_stack[:]
2379 return self.shell.dir_stack[:]
2379
2380
2380 def magic_sc(self, parameter_s=''):
2381 def magic_sc(self, parameter_s=''):
2381 """Shell capture - execute a shell command and capture its output.
2382 """Shell capture - execute a shell command and capture its output.
2382
2383
2383 %sc [options] varname=command
2384 %sc [options] varname=command
2384
2385
2385 IPython will run the given command using commands.getoutput(), and
2386 IPython will run the given command using commands.getoutput(), and
2386 will then update the user's interactive namespace with a variable
2387 will then update the user's interactive namespace with a variable
2387 called varname, containing the value of the call. Your command can
2388 called varname, containing the value of the call. Your command can
2388 contain shell wildcards, pipes, etc.
2389 contain shell wildcards, pipes, etc.
2389
2390
2390 The '=' sign in the syntax is mandatory, and the variable name you
2391 The '=' sign in the syntax is mandatory, and the variable name you
2391 supply must follow Python's standard conventions for valid names.
2392 supply must follow Python's standard conventions for valid names.
2392
2393
2393 Options:
2394 Options:
2394
2395
2395 -l: list output. Split the output on newlines into a list before
2396 -l: list output. Split the output on newlines into a list before
2396 assigning it to the given variable. By default the output is stored
2397 assigning it to the given variable. By default the output is stored
2397 as a single string.
2398 as a single string.
2398
2399
2399 -v: verbose. Print the contents of the variable.
2400 -v: verbose. Print the contents of the variable.
2400
2401
2401 In most cases you should not need to split as a list, because the
2402 In most cases you should not need to split as a list, because the
2402 returned value is a special type of string which can automatically
2403 returned value is a special type of string which can automatically
2403 provide its contents either as a list (split on newlines) or as a
2404 provide its contents either as a list (split on newlines) or as a
2404 space-separated string. These are convenient, respectively, either
2405 space-separated string. These are convenient, respectively, either
2405 for sequential processing or to be passed to a shell command.
2406 for sequential processing or to be passed to a shell command.
2406
2407
2407 For example:
2408 For example:
2408
2409
2409 # Capture into variable a
2410 # Capture into variable a
2410 In [9]: sc a=ls *py
2411 In [9]: sc a=ls *py
2411
2412
2412 # a is a string with embedded newlines
2413 # a is a string with embedded newlines
2413 In [10]: a
2414 In [10]: a
2414 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2415 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2415
2416
2416 # which can be seen as a list:
2417 # which can be seen as a list:
2417 In [11]: a.l
2418 In [11]: a.l
2418 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2419 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2419
2420
2420 # or as a whitespace-separated string:
2421 # or as a whitespace-separated string:
2421 In [12]: a.s
2422 In [12]: a.s
2422 Out[12]: 'setup.py win32_manual_post_install.py'
2423 Out[12]: 'setup.py win32_manual_post_install.py'
2423
2424
2424 # a.s is useful to pass as a single command line:
2425 # a.s is useful to pass as a single command line:
2425 In [13]: !wc -l $a.s
2426 In [13]: !wc -l $a.s
2426 146 setup.py
2427 146 setup.py
2427 130 win32_manual_post_install.py
2428 130 win32_manual_post_install.py
2428 276 total
2429 276 total
2429
2430
2430 # while the list form is useful to loop over:
2431 # while the list form is useful to loop over:
2431 In [14]: for f in a.l:
2432 In [14]: for f in a.l:
2432 ....: !wc -l $f
2433 ....: !wc -l $f
2433 ....:
2434 ....:
2434 146 setup.py
2435 146 setup.py
2435 130 win32_manual_post_install.py
2436 130 win32_manual_post_install.py
2436
2437
2437 Similiarly, the lists returned by the -l option are also special, in
2438 Similiarly, the lists returned by the -l option are also special, in
2438 the sense that you can equally invoke the .s attribute on them to
2439 the sense that you can equally invoke the .s attribute on them to
2439 automatically get a whitespace-separated string from their contents:
2440 automatically get a whitespace-separated string from their contents:
2440
2441
2441 In [1]: sc -l b=ls *py
2442 In [1]: sc -l b=ls *py
2442
2443
2443 In [2]: b
2444 In [2]: b
2444 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2445 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2445
2446
2446 In [3]: b.s
2447 In [3]: b.s
2447 Out[3]: 'setup.py win32_manual_post_install.py'
2448 Out[3]: 'setup.py win32_manual_post_install.py'
2448
2449
2449 In summary, both the lists and strings used for ouptut capture have
2450 In summary, both the lists and strings used for ouptut capture have
2450 the following special attributes:
2451 the following special attributes:
2451
2452
2452 .l (or .list) : value as list.
2453 .l (or .list) : value as list.
2453 .n (or .nlstr): value as newline-separated string.
2454 .n (or .nlstr): value as newline-separated string.
2454 .s (or .spstr): value as space-separated string.
2455 .s (or .spstr): value as space-separated string.
2455 """
2456 """
2456
2457
2457 opts,args = self.parse_options(parameter_s,'lv')
2458 opts,args = self.parse_options(parameter_s,'lv')
2458 # Try to get a variable name and command to run
2459 # Try to get a variable name and command to run
2459 try:
2460 try:
2460 # the variable name must be obtained from the parse_options
2461 # the variable name must be obtained from the parse_options
2461 # output, which uses shlex.split to strip options out.
2462 # output, which uses shlex.split to strip options out.
2462 var,_ = args.split('=',1)
2463 var,_ = args.split('=',1)
2463 var = var.strip()
2464 var = var.strip()
2464 # But the the command has to be extracted from the original input
2465 # But the the command has to be extracted from the original input
2465 # parameter_s, not on what parse_options returns, to avoid the
2466 # parameter_s, not on what parse_options returns, to avoid the
2466 # quote stripping which shlex.split performs on it.
2467 # quote stripping which shlex.split performs on it.
2467 _,cmd = parameter_s.split('=',1)
2468 _,cmd = parameter_s.split('=',1)
2468 except ValueError:
2469 except ValueError:
2469 var,cmd = '',''
2470 var,cmd = '',''
2470 if not var:
2471 if not var:
2471 error('you must specify a variable to assign the command to.')
2472 error('you must specify a variable to assign the command to.')
2472 return
2473 return
2473 # If all looks ok, proceed
2474 # If all looks ok, proceed
2474 out,err = self.shell.getoutputerror(cmd)
2475 out,err = self.shell.getoutputerror(cmd)
2475 if err:
2476 if err:
2476 print >> Term.cerr,err
2477 print >> Term.cerr,err
2477 if opts.has_key('l'):
2478 if opts.has_key('l'):
2478 out = SList(out.split('\n'))
2479 out = SList(out.split('\n'))
2479 else:
2480 else:
2480 out = LSString(out)
2481 out = LSString(out)
2481 if opts.has_key('v'):
2482 if opts.has_key('v'):
2482 print '%s ==\n%s' % (var,pformat(out))
2483 print '%s ==\n%s' % (var,pformat(out))
2483 self.shell.user_ns.update({var:out})
2484 self.shell.user_ns.update({var:out})
2484
2485
2485 def magic_sx(self, parameter_s=''):
2486 def magic_sx(self, parameter_s=''):
2486 """Shell execute - run a shell command and capture its output.
2487 """Shell execute - run a shell command and capture its output.
2487
2488
2488 %sx command
2489 %sx command
2489
2490
2490 IPython will run the given command using commands.getoutput(), and
2491 IPython will run the given command using commands.getoutput(), and
2491 return the result formatted as a list (split on '\\n'). Since the
2492 return the result formatted as a list (split on '\\n'). Since the
2492 output is _returned_, it will be stored in ipython's regular output
2493 output is _returned_, it will be stored in ipython's regular output
2493 cache Out[N] and in the '_N' automatic variables.
2494 cache Out[N] and in the '_N' automatic variables.
2494
2495
2495 Notes:
2496 Notes:
2496
2497
2497 1) If an input line begins with '!!', then %sx is automatically
2498 1) If an input line begins with '!!', then %sx is automatically
2498 invoked. That is, while:
2499 invoked. That is, while:
2499 !ls
2500 !ls
2500 causes ipython to simply issue system('ls'), typing
2501 causes ipython to simply issue system('ls'), typing
2501 !!ls
2502 !!ls
2502 is a shorthand equivalent to:
2503 is a shorthand equivalent to:
2503 %sx ls
2504 %sx ls
2504
2505
2505 2) %sx differs from %sc in that %sx automatically splits into a list,
2506 2) %sx differs from %sc in that %sx automatically splits into a list,
2506 like '%sc -l'. The reason for this is to make it as easy as possible
2507 like '%sc -l'. The reason for this is to make it as easy as possible
2507 to process line-oriented shell output via further python commands.
2508 to process line-oriented shell output via further python commands.
2508 %sc is meant to provide much finer control, but requires more
2509 %sc is meant to provide much finer control, but requires more
2509 typing.
2510 typing.
2510
2511
2511 3) Just like %sc -l, this is a list with special attributes:
2512 3) Just like %sc -l, this is a list with special attributes:
2512
2513
2513 .l (or .list) : value as list.
2514 .l (or .list) : value as list.
2514 .n (or .nlstr): value as newline-separated string.
2515 .n (or .nlstr): value as newline-separated string.
2515 .s (or .spstr): value as whitespace-separated string.
2516 .s (or .spstr): value as whitespace-separated string.
2516
2517
2517 This is very useful when trying to use such lists as arguments to
2518 This is very useful when trying to use such lists as arguments to
2518 system commands."""
2519 system commands."""
2519
2520
2520 if parameter_s:
2521 if parameter_s:
2521 out,err = self.shell.getoutputerror(parameter_s)
2522 out,err = self.shell.getoutputerror(parameter_s)
2522 if err:
2523 if err:
2523 print >> Term.cerr,err
2524 print >> Term.cerr,err
2524 return SList(out.split('\n'))
2525 return SList(out.split('\n'))
2525
2526
2526 def magic_bg(self, parameter_s=''):
2527 def magic_bg(self, parameter_s=''):
2527 """Run a job in the background, in a separate thread.
2528 """Run a job in the background, in a separate thread.
2528
2529
2529 For example,
2530 For example,
2530
2531
2531 %bg myfunc(x,y,z=1)
2532 %bg myfunc(x,y,z=1)
2532
2533
2533 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2534 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2534 execution starts, a message will be printed indicating the job
2535 execution starts, a message will be printed indicating the job
2535 number. If your job number is 5, you can use
2536 number. If your job number is 5, you can use
2536
2537
2537 myvar = jobs.result(5) or myvar = jobs[5].result
2538 myvar = jobs.result(5) or myvar = jobs[5].result
2538
2539
2539 to assign this result to variable 'myvar'.
2540 to assign this result to variable 'myvar'.
2540
2541
2541 IPython has a job manager, accessible via the 'jobs' object. You can
2542 IPython has a job manager, accessible via the 'jobs' object. You can
2542 type jobs? to get more information about it, and use jobs.<TAB> to see
2543 type jobs? to get more information about it, and use jobs.<TAB> to see
2543 its attributes. All attributes not starting with an underscore are
2544 its attributes. All attributes not starting with an underscore are
2544 meant for public use.
2545 meant for public use.
2545
2546
2546 In particular, look at the jobs.new() method, which is used to create
2547 In particular, look at the jobs.new() method, which is used to create
2547 new jobs. This magic %bg function is just a convenience wrapper
2548 new jobs. This magic %bg function is just a convenience wrapper
2548 around jobs.new(), for expression-based jobs. If you want to create a
2549 around jobs.new(), for expression-based jobs. If you want to create a
2549 new job with an explicit function object and arguments, you must call
2550 new job with an explicit function object and arguments, you must call
2550 jobs.new() directly.
2551 jobs.new() directly.
2551
2552
2552 The jobs.new docstring also describes in detail several important
2553 The jobs.new docstring also describes in detail several important
2553 caveats associated with a thread-based model for background job
2554 caveats associated with a thread-based model for background job
2554 execution. Type jobs.new? for details.
2555 execution. Type jobs.new? for details.
2555
2556
2556 You can check the status of all jobs with jobs.status().
2557 You can check the status of all jobs with jobs.status().
2557
2558
2558 The jobs variable is set by IPython into the Python builtin namespace.
2559 The jobs variable is set by IPython into the Python builtin namespace.
2559 If you ever declare a variable named 'jobs', you will shadow this
2560 If you ever declare a variable named 'jobs', you will shadow this
2560 name. You can either delete your global jobs variable to regain
2561 name. You can either delete your global jobs variable to regain
2561 access to the job manager, or make a new name and assign it manually
2562 access to the job manager, or make a new name and assign it manually
2562 to the manager (stored in IPython's namespace). For example, to
2563 to the manager (stored in IPython's namespace). For example, to
2563 assign the job manager to the Jobs name, use:
2564 assign the job manager to the Jobs name, use:
2564
2565
2565 Jobs = __builtins__.jobs"""
2566 Jobs = __builtins__.jobs"""
2566
2567
2567 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2568 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2568
2569
2569 def magic_store(self, parameter_s=''):
2570 def magic_store(self, parameter_s=''):
2570 """Lightweight persistence for python variables.
2571 """Lightweight persistence for python variables.
2571
2572
2572 Example:
2573 Example:
2573
2574
2574 ville@badger[~]|1> A = ['hello',10,'world']\\
2575 ville@badger[~]|1> A = ['hello',10,'world']\\
2575 ville@badger[~]|2> %store A\\
2576 ville@badger[~]|2> %store A\\
2576 ville@badger[~]|3> Exit
2577 ville@badger[~]|3> Exit
2577
2578
2578 (IPython session is closed and started again...)
2579 (IPython session is closed and started again...)
2579
2580
2580 ville@badger:~$ ipython -p pysh\\
2581 ville@badger:~$ ipython -p pysh\\
2581 ville@badger[~]|1> print A
2582 ville@badger[~]|1> print A
2582
2583
2583 ['hello', 10, 'world']
2584 ['hello', 10, 'world']
2584
2585
2585 Usage:
2586 Usage:
2586
2587
2587 %store - Show list of all variables and their current values\\
2588 %store - Show list of all variables and their current values\\
2588 %store <var> - Store the *current* value of the variable to disk\\
2589 %store <var> - Store the *current* value of the variable to disk\\
2589 %store -d <var> - Remove the variable and its value from storage\\
2590 %store -d <var> - Remove the variable and its value from storage\\
2590 %store -r - Remove all variables from storage
2591 %store -r - Remove all variables from storage
2591
2592
2592 It should be noted that if you change the value of a variable, you
2593 It should be noted that if you change the value of a variable, you
2593 need to %store it again if you want to persist the new value.
2594 need to %store it again if you want to persist the new value.
2594
2595
2595 Note also that the variables will need to be pickleable; most basic
2596 Note also that the variables will need to be pickleable; most basic
2596 python types can be safely %stored.
2597 python types can be safely %stored.
2597 """
2598 """
2598
2599
2599 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2600 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2600 # delete
2601 # delete
2601 if opts.has_key('d'):
2602 if opts.has_key('d'):
2602 try:
2603 try:
2603 todel = args[0]
2604 todel = args[0]
2604 except IndexError:
2605 except IndexError:
2605 error('You must provide the variable to forget')
2606 error('You must provide the variable to forget')
2606 else:
2607 else:
2607 try:
2608 try:
2608 del self.shell.persist['S:' + todel]
2609 del self.shell.persist['S:' + todel]
2609 except:
2610 except:
2610 error("Can't delete variable '%s'" % todel)
2611 error("Can't delete variable '%s'" % todel)
2611 # reset
2612 # reset
2612 elif opts.has_key('r'):
2613 elif opts.has_key('r'):
2613 for k in self.shell.persist.keys():
2614 for k in self.shell.persist.keys():
2614 if k.startswith('S:'):
2615 if k.startswith('S:'):
2615 del self.shell.persist[k]
2616 del self.shell.persist[k]
2616
2617
2617 # run without arguments -> list variables & values
2618 # run without arguments -> list variables & values
2618 elif not args:
2619 elif not args:
2619 vars = [v[2:] for v in self.shell.persist.keys()
2620 vars = [v[2:] for v in self.shell.persist.keys()
2620 if v.startswith('S:')]
2621 if v.startswith('S:')]
2621 vars.sort()
2622 vars.sort()
2622 if vars:
2623 if vars:
2623 size = max(map(len,vars))
2624 size = max(map(len,vars))
2624 else:
2625 else:
2625 size = 0
2626 size = 0
2626
2627
2627 print 'Stored variables and their in-memory values:'
2628 print 'Stored variables and their in-memory values:'
2628 fmt = '%-'+str(size)+'s -> %s'
2629 fmt = '%-'+str(size)+'s -> %s'
2629 get = self.shell.user_ns.get
2630 get = self.shell.user_ns.get
2630 for var in vars:
2631 for var in vars:
2631 # print 30 first characters from every var
2632 # print 30 first characters from every var
2632 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2633 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2633
2634
2634 # default action - store the variable
2635 # default action - store the variable
2635 else:
2636 else:
2636 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2637 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2637 self.shell.persist[ 'S:' + args[0] ] = pickled
2638 self.shell.persist[ 'S:' + args[0] ] = pickled
2638 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2639 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2639
2640
2640 def magic_bookmark(self, parameter_s=''):
2641 def magic_bookmark(self, parameter_s=''):
2641 """Manage IPython's bookmark system.
2642 """Manage IPython's bookmark system.
2642
2643
2643 %bookmark <name> - set bookmark to current dir
2644 %bookmark <name> - set bookmark to current dir
2644 %bookmark <name> <dir> - set bookmark to <dir>
2645 %bookmark <name> <dir> - set bookmark to <dir>
2645 %bookmark -l - list all bookmarks
2646 %bookmark -l - list all bookmarks
2646 %bookmark -d <name> - remove bookmark
2647 %bookmark -d <name> - remove bookmark
2647 %bookmark -r - remove all bookmarks
2648 %bookmark -r - remove all bookmarks
2648
2649
2649 You can later on access a bookmarked folder with:
2650 You can later on access a bookmarked folder with:
2650 %cd -b <name>
2651 %cd -b <name>
2651 or simply '%cd <name>' if there is no directory called <name> AND
2652 or simply '%cd <name>' if there is no directory called <name> AND
2652 there is such a bookmark defined.
2653 there is such a bookmark defined.
2653
2654
2654 Your bookmarks persist through IPython sessions, but they are
2655 Your bookmarks persist through IPython sessions, but they are
2655 associated with each profile."""
2656 associated with each profile."""
2656
2657
2657 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2658 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2658 if len(args) > 2:
2659 if len(args) > 2:
2659 error('You can only give at most two arguments')
2660 error('You can only give at most two arguments')
2660 return
2661 return
2661
2662
2662 bkms = self.shell.persist.get('bookmarks',{})
2663 bkms = self.shell.persist.get('bookmarks',{})
2663
2664
2664 if opts.has_key('d'):
2665 if opts.has_key('d'):
2665 try:
2666 try:
2666 todel = args[0]
2667 todel = args[0]
2667 except IndexError:
2668 except IndexError:
2668 error('You must provide a bookmark to delete')
2669 error('You must provide a bookmark to delete')
2669 else:
2670 else:
2670 try:
2671 try:
2671 del bkms[todel]
2672 del bkms[todel]
2672 except:
2673 except:
2673 error("Can't delete bookmark '%s'" % todel)
2674 error("Can't delete bookmark '%s'" % todel)
2674 elif opts.has_key('r'):
2675 elif opts.has_key('r'):
2675 bkms = {}
2676 bkms = {}
2676 elif opts.has_key('l'):
2677 elif opts.has_key('l'):
2677 bks = bkms.keys()
2678 bks = bkms.keys()
2678 bks.sort()
2679 bks.sort()
2679 if bks:
2680 if bks:
2680 size = max(map(len,bks))
2681 size = max(map(len,bks))
2681 else:
2682 else:
2682 size = 0
2683 size = 0
2683 fmt = '%-'+str(size)+'s -> %s'
2684 fmt = '%-'+str(size)+'s -> %s'
2684 print 'Current bookmarks:'
2685 print 'Current bookmarks:'
2685 for bk in bks:
2686 for bk in bks:
2686 print fmt % (bk,bkms[bk])
2687 print fmt % (bk,bkms[bk])
2687 else:
2688 else:
2688 if not args:
2689 if not args:
2689 error("You must specify the bookmark name")
2690 error("You must specify the bookmark name")
2690 elif len(args)==1:
2691 elif len(args)==1:
2691 bkms[args[0]] = os.getcwd()
2692 bkms[args[0]] = os.getcwd()
2692 elif len(args)==2:
2693 elif len(args)==2:
2693 bkms[args[0]] = args[1]
2694 bkms[args[0]] = args[1]
2694 self.shell.persist['bookmarks'] = bkms
2695 self.shell.persist['bookmarks'] = bkms
2695
2696
2696 def magic_pycat(self, parameter_s=''):
2697 def magic_pycat(self, parameter_s=''):
2697 """Show a syntax-highlighted file through a pager.
2698 """Show a syntax-highlighted file through a pager.
2698
2699
2699 This magic is similar to the cat utility, but it will assume the file
2700 This magic is similar to the cat utility, but it will assume the file
2700 to be Python source and will show it with syntax highlighting. """
2701 to be Python source and will show it with syntax highlighting. """
2701
2702
2702 filename = get_py_filename(parameter_s)
2703 filename = get_py_filename(parameter_s)
2703 page(self.shell.colorize(file_read(filename)),
2704 page(self.shell.colorize(file_read(filename)),
2704 screen_lines=self.shell.rc.screen_length)
2705 screen_lines=self.shell.rc.screen_length)
2705
2706
2706 # end Magic
2707 # end Magic
@@ -1,565 +1,587 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 963 2005-12-28 19:21:29Z fperez $
2 # $Id: ipythonrc 990 2006-01-04 06:59:02Z fperez $
3
3
4 #***************************************************************************
4 #***************************************************************************
5 #
5 #
6 # Configuration file for IPython -- ipythonrc format
6 # Configuration file for IPython -- ipythonrc format
7 #
7 #
8 # The format of this file is simply one of 'key value' lines.
8 # The format of this file is simply one of 'key value' lines.
9 # Lines containing only whitespace at the beginning and then a # are ignored
9 # Lines containing only whitespace at the beginning and then a # are ignored
10 # as comments. But comments can NOT be put on lines with data.
10 # as comments. But comments can NOT be put on lines with data.
11
11
12 # The meaning and use of each key are explained below.
12 # The meaning and use of each key are explained below.
13
13
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15 # Section: included files
15 # Section: included files
16
16
17 # Put one or more *config* files (with the syntax of this file) you want to
17 # Put one or more *config* files (with the syntax of this file) you want to
18 # include. For keys with a unique value the outermost file has precedence. For
18 # include. For keys with a unique value the outermost file has precedence. For
19 # keys with multiple values, they all get assembled into a list which then
19 # keys with multiple values, they all get assembled into a list which then
20 # gets loaded by IPython.
20 # gets loaded by IPython.
21
21
22 # In this file, all lists of things should simply be space-separated.
22 # In this file, all lists of things should simply be space-separated.
23
23
24 # This allows you to build hierarchies of files which recursively load
24 # This allows you to build hierarchies of files which recursively load
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 # should only keep here basic things you always want available. Then you can
26 # should only keep here basic things you always want available. Then you can
27 # include it in every other special-purpose config file you create.
27 # include it in every other special-purpose config file you create.
28 include
28 include
29
29
30 #---------------------------------------------------------------------------
30 #---------------------------------------------------------------------------
31 # Section: startup setup
31 # Section: startup setup
32
32
33 # These are mostly things which parallel a command line option of the same
33 # These are mostly things which parallel a command line option of the same
34 # name.
34 # name.
35
35
36 # Keys in this section should only appear once. If any key from this section
36 # Keys in this section should only appear once. If any key from this section
37 # is encountered more than once, the last value remains, all earlier ones get
37 # is encountered more than once, the last value remains, all earlier ones get
38 # discarded.
38 # discarded.
39
39
40 # Automatic calling of callable objects. If set to true, callable objects are
40
41 # automatically called when invoked at the command line, even if you don't
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
42 # are automatically called when invoked at the command line, even if you don't
42 # type parentheses. IPython adds the parentheses for you. For example:
43 # type parentheses. IPython adds the parentheses for you. For example:
43
44
44 #In [1]: str 45
45 #In [1]: str 45
45 #------> str(45)
46 #------> str(45)
46 #Out[1]: '45'
47 #Out[1]: '45'
47
48
48 # IPython reprints your line with '---->' indicating that it added
49 # IPython reprints your line with '---->' indicating that it added
49 # parentheses. While this option is very convenient for interactive use, it
50 # parentheses. While this option is very convenient for interactive use, it
50 # may occasionally cause problems with objects which have side-effects if
51 # may occasionally cause problems with objects which have side-effects if
51 # called unexpectedly. Set it to 0 if you want to disable it.
52 # called unexpectedly.
53
54 # The valid values for autocall are:
55
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
57
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
59
60 # In this mode, you get:
61
62 #In [1]: callable
63 #Out[1]: <built-in function callable>
64
65 #In [2]: callable 'hello'
66 #------> callable('hello')
67 #Out[2]: False
68
69 # 2 -> Active always. Even if no arguments are present, the callable object
70 # is called:
71
72 #In [4]: callable
73 #------> callable()
52
74
53 # Note that even with autocall off, you can still use '/' at the start of a
75 # Note that even with autocall off, you can still use '/' at the start of a
54 # line to treat the first argument on the command line as a function and add
76 # line to treat the first argument on the command line as a function and add
55 # parentheses to it:
77 # parentheses to it:
56
78
57 #In [8]: /str 43
79 #In [8]: /str 43
58 #------> str(43)
80 #------> str(43)
59 #Out[8]: '43'
81 #Out[8]: '43'
60
82
61 autocall 1
83 autocall 1
62
84
63 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
64 # source code (see the 'editor' variable below), it is possible that you save
86 # source code (see the 'editor' variable below), it is possible that you save
65 # a file with syntax errors in it. If this variable is true, IPython will ask
87 # a file with syntax errors in it. If this variable is true, IPython will ask
66 # you whether to re-open the editor immediately to correct such an error.
88 # you whether to re-open the editor immediately to correct such an error.
67
89
68 autoedit_syntax 1
90 autoedit_syntax 1
69
91
70 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
71 # line, while also un-indenting automatically after 'raise' or 'return'.
93 # line, while also un-indenting automatically after 'raise' or 'return'.
72
94
73 # This feature uses the readline library, so it will honor your ~/.inputrc
95 # This feature uses the readline library, so it will honor your ~/.inputrc
74 # configuration (or whatever file your INPUTRC variable points to). Adding
96 # configuration (or whatever file your INPUTRC variable points to). Adding
75 # the following lines to your .inputrc file can make indent/unindenting more
97 # the following lines to your .inputrc file can make indent/unindenting more
76 # convenient (M-i indents, M-u unindents):
98 # convenient (M-i indents, M-u unindents):
77
99
78 # $if Python
100 # $if Python
79 # "\M-i": " "
101 # "\M-i": " "
80 # "\M-u": "\d\d\d\d"
102 # "\M-u": "\d\d\d\d"
81 # $endif
103 # $endif
82
104
83 # The feature is potentially a bit dangerous, because it can cause problems
105 # The feature is potentially a bit dangerous, because it can cause problems
84 # with pasting of indented code (the pasted code gets re-indented on each
106 # with pasting of indented code (the pasted code gets re-indented on each
85 # line). But it's a huge time-saver when working interactively. The magic
107 # line). But it's a huge time-saver when working interactively. The magic
86 # function @autoindent allows you to toggle it on/off at runtime.
108 # function @autoindent allows you to toggle it on/off at runtime.
87
109
88 autoindent 1
110 autoindent 1
89
111
90 # Auto-magic. This gives you access to all the magic functions without having
112 # Auto-magic. This gives you access to all the magic functions without having
91 # to prepend them with an @ sign. If you define a variable with the same name
113 # to prepend them with an @ sign. If you define a variable with the same name
92 # as a magic function (say who=1), you will need to access the magic function
114 # as a magic function (say who=1), you will need to access the magic function
93 # with @ (@who in this example). However, if later you delete your variable
115 # with @ (@who in this example). However, if later you delete your variable
94 # (del who), you'll recover the automagic calling form.
116 # (del who), you'll recover the automagic calling form.
95
117
96 # Considering that many magic functions provide a lot of shell-like
118 # Considering that many magic functions provide a lot of shell-like
97 # functionality, automagic gives you something close to a full Python+system
119 # functionality, automagic gives you something close to a full Python+system
98 # shell environment (and you can extend it further if you want).
120 # shell environment (and you can extend it further if you want).
99
121
100 automagic 1
122 automagic 1
101
123
102 # Size of the output cache. After this many entries are stored, the cache will
124 # Size of the output cache. After this many entries are stored, the cache will
103 # get flushed. Depending on the size of your intermediate calculations, you
125 # get flushed. Depending on the size of your intermediate calculations, you
104 # may have memory problems if you make it too big, since keeping things in the
126 # may have memory problems if you make it too big, since keeping things in the
105 # cache prevents Python from reclaiming the memory for old results. Experiment
127 # cache prevents Python from reclaiming the memory for old results. Experiment
106 # with a value that works well for you.
128 # with a value that works well for you.
107
129
108 # If you choose cache_size 0 IPython will revert to python's regular >>>
130 # If you choose cache_size 0 IPython will revert to python's regular >>>
109 # unnumbered prompt. You will still have _, __ and ___ for your last three
131 # unnumbered prompt. You will still have _, __ and ___ for your last three
110 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
111 # you are running on a slow machine or with very limited memory, this may
133 # you are running on a slow machine or with very limited memory, this may
112 # help.
134 # help.
113
135
114 cache_size 1000
136 cache_size 1000
115
137
116 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
117 # but that's your choice! Classic 1 -> same as IPython -classic.
139 # but that's your choice! Classic 1 -> same as IPython -classic.
118 # Note that this is _not_ the normal python interpreter, it's simply
140 # Note that this is _not_ the normal python interpreter, it's simply
119 # IPython emulating most of the classic interpreter's behavior.
141 # IPython emulating most of the classic interpreter's behavior.
120 classic 0
142 classic 0
121
143
122 # colors - Coloring option for prompts and traceback printouts.
144 # colors - Coloring option for prompts and traceback printouts.
123
145
124 # Currently available schemes: NoColor, Linux, LightBG.
146 # Currently available schemes: NoColor, Linux, LightBG.
125
147
126 # This option allows coloring the prompts and traceback printouts. This
148 # This option allows coloring the prompts and traceback printouts. This
127 # requires a terminal which can properly handle color escape sequences. If you
149 # requires a terminal which can properly handle color escape sequences. If you
128 # are having problems with this, use the NoColor scheme (uses no color escapes
150 # are having problems with this, use the NoColor scheme (uses no color escapes
129 # at all).
151 # at all).
130
152
131 # The Linux option works well in linux console type environments: dark
153 # The Linux option works well in linux console type environments: dark
132 # background with light fonts.
154 # background with light fonts.
133
155
134 # LightBG is similar to Linux but swaps dark/light colors to be more readable
156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
135 # in light background terminals.
157 # in light background terminals.
136
158
137 # keep uncommented only the one you want:
159 # keep uncommented only the one you want:
138 colors Linux
160 colors Linux
139 #colors LightBG
161 #colors LightBG
140 #colors NoColor
162 #colors NoColor
141
163
142 ########################
164 ########################
143 # Note to Windows users
165 # Note to Windows users
144 #
166 #
145 # Color and readline support is avaialble to Windows users via Gary Bishop's
167 # Color and readline support is avaialble to Windows users via Gary Bishop's
146 # readline library. You can find Gary's tools at
168 # readline library. You can find Gary's tools at
147 # http://sourceforge.net/projects/uncpythontools.
169 # http://sourceforge.net/projects/uncpythontools.
148 # Note that his readline module requires in turn the ctypes library, available
170 # Note that his readline module requires in turn the ctypes library, available
149 # at http://starship.python.net/crew/theller/ctypes.
171 # at http://starship.python.net/crew/theller/ctypes.
150 ########################
172 ########################
151
173
152 # color_info: IPython can display information about objects via a set of
174 # color_info: IPython can display information about objects via a set of
153 # functions, and optionally can use colors for this, syntax highlighting
175 # functions, and optionally can use colors for this, syntax highlighting
154 # source code and various other elements. This information is passed through a
176 # source code and various other elements. This information is passed through a
155 # pager (it defaults to 'less' if $PAGER is not set).
177 # pager (it defaults to 'less' if $PAGER is not set).
156
178
157 # If your pager has problems, try to setting it to properly handle escapes
179 # If your pager has problems, try to setting it to properly handle escapes
158 # (see the less manpage for detail), or disable this option. The magic
180 # (see the less manpage for detail), or disable this option. The magic
159 # function @color_info allows you to toggle this interactively for testing.
181 # function @color_info allows you to toggle this interactively for testing.
160
182
161 color_info 1
183 color_info 1
162
184
163 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
164 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
165 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
187 # the magic functions @Exit or @Quit you can force a direct exit, bypassing
166 # any confirmation.
188 # any confirmation.
167
189
168 confirm_exit 1
190 confirm_exit 1
169
191
170 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
171 # still available as dreload() and appears as a builtin.
193 # still available as dreload() and appears as a builtin.
172
194
173 deep_reload 0
195 deep_reload 0
174
196
175 # Which editor to use with the @edit command. If you leave this at 0, IPython
197 # Which editor to use with the @edit command. If you leave this at 0, IPython
176 # will honor your EDITOR environment variable. Since this editor is invoked on
198 # will honor your EDITOR environment variable. Since this editor is invoked on
177 # the fly by ipython and is meant for editing small code snippets, you may
199 # the fly by ipython and is meant for editing small code snippets, you may
178 # want to use a small, lightweight editor here.
200 # want to use a small, lightweight editor here.
179
201
180 # For Emacs users, setting up your Emacs server properly as described in the
202 # For Emacs users, setting up your Emacs server properly as described in the
181 # manual is a good idea. An alternative is to use jed, a very light editor
203 # manual is a good idea. An alternative is to use jed, a very light editor
182 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
183
205
184 editor 0
206 editor 0
185
207
186 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
187 log 0
209 log 0
188
210
189 # Same as ipython -Logfile YourLogfileName.
211 # Same as ipython -Logfile YourLogfileName.
190 # Don't use with log 1 (use one or the other)
212 # Don't use with log 1 (use one or the other)
191 logfile ''
213 logfile ''
192
214
193 # banner 0 -> same as ipython -nobanner
215 # banner 0 -> same as ipython -nobanner
194 banner 1
216 banner 1
195
217
196 # messages 0 -> same as ipython -nomessages
218 # messages 0 -> same as ipython -nomessages
197 messages 1
219 messages 1
198
220
199 # Automatically call the pdb debugger after every uncaught exception. If you
221 # Automatically call the pdb debugger after every uncaught exception. If you
200 # are used to debugging using pdb, this puts you automatically inside of it
222 # are used to debugging using pdb, this puts you automatically inside of it
201 # after any call (either in IPython or in code called by it) which triggers an
223 # after any call (either in IPython or in code called by it) which triggers an
202 # exception which goes uncaught.
224 # exception which goes uncaught.
203 pdb 0
225 pdb 0
204
226
205 # Enable the pprint module for printing. pprint tends to give a more readable
227 # Enable the pprint module for printing. pprint tends to give a more readable
206 # display (than print) for complex nested data structures.
228 # display (than print) for complex nested data structures.
207 pprint 1
229 pprint 1
208
230
209 # Prompt strings
231 # Prompt strings
210
232
211 # Most bash-like escapes can be used to customize IPython's prompts, as well as
233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
212 # a few additional ones which are IPython-specific. All valid prompt escapes
234 # a few additional ones which are IPython-specific. All valid prompt escapes
213 # are described in detail in the Customization section of the IPython HTML/PDF
235 # are described in detail in the Customization section of the IPython HTML/PDF
214 # manual.
236 # manual.
215
237
216 # Use \# to represent the current prompt number, and quote them to protect
238 # Use \# to represent the current prompt number, and quote them to protect
217 # spaces.
239 # spaces.
218 prompt_in1 'In [\#]: '
240 prompt_in1 'In [\#]: '
219
241
220 # \D is replaced by as many dots as there are digits in the
242 # \D is replaced by as many dots as there are digits in the
221 # current value of \#.
243 # current value of \#.
222 prompt_in2 ' .\D.: '
244 prompt_in2 ' .\D.: '
223
245
224 prompt_out 'Out[\#]: '
246 prompt_out 'Out[\#]: '
225
247
226 # Select whether to left-pad the output prompts to match the length of the
248 # Select whether to left-pad the output prompts to match the length of the
227 # input ones. This allows you for example to use a simple '>' as an output
249 # input ones. This allows you for example to use a simple '>' as an output
228 # prompt, and yet have the output line up with the input. If set to false,
250 # prompt, and yet have the output line up with the input. If set to false,
229 # the output prompts will be unpadded (flush left).
251 # the output prompts will be unpadded (flush left).
230 prompts_pad_left 1
252 prompts_pad_left 1
231
253
232 # quick 1 -> same as ipython -quick
254 # quick 1 -> same as ipython -quick
233 quick 0
255 quick 0
234
256
235 # Use the readline library (1) or not (0). Most users will want this on, but
257 # Use the readline library (1) or not (0). Most users will want this on, but
236 # if you experience strange problems with line management (mainly when using
258 # if you experience strange problems with line management (mainly when using
237 # IPython inside Emacs buffers) you may try disabling it. Not having it on
259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
238 # prevents you from getting command history with the arrow keys, searching and
260 # prevents you from getting command history with the arrow keys, searching and
239 # name completion using TAB.
261 # name completion using TAB.
240
262
241 readline 1
263 readline 1
242
264
243 # Screen Length: number of lines of your screen. This is used to control
265 # Screen Length: number of lines of your screen. This is used to control
244 # printing of very long strings. Strings longer than this number of lines will
266 # printing of very long strings. Strings longer than this number of lines will
245 # be paged with the less command instead of directly printed.
267 # be paged with the less command instead of directly printed.
246
268
247 # The default value for this is 0, which means IPython will auto-detect your
269 # The default value for this is 0, which means IPython will auto-detect your
248 # screen size every time it needs to print. If for some reason this isn't
270 # screen size every time it needs to print. If for some reason this isn't
249 # working well (it needs curses support), specify it yourself. Otherwise don't
271 # working well (it needs curses support), specify it yourself. Otherwise don't
250 # change the default.
272 # change the default.
251
273
252 screen_length 0
274 screen_length 0
253
275
254 # Prompt separators for input and output.
276 # Prompt separators for input and output.
255 # Use \n for newline explicitly, without quotes.
277 # Use \n for newline explicitly, without quotes.
256 # Use 0 (like at the cmd line) to turn off a given separator.
278 # Use 0 (like at the cmd line) to turn off a given separator.
257
279
258 # The structure of prompt printing is:
280 # The structure of prompt printing is:
259 # (SeparateIn)Input....
281 # (SeparateIn)Input....
260 # (SeparateOut)Output...
282 # (SeparateOut)Output...
261 # (SeparateOut2), # that is, no newline is printed after Out2
283 # (SeparateOut2), # that is, no newline is printed after Out2
262 # By choosing these you can organize your output any way you want.
284 # By choosing these you can organize your output any way you want.
263
285
264 separate_in \n
286 separate_in \n
265 separate_out 0
287 separate_out 0
266 separate_out2 0
288 separate_out2 0
267
289
268 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
269 # Simply removes all input/output separators, overriding the choices above.
291 # Simply removes all input/output separators, overriding the choices above.
270 nosep 0
292 nosep 0
271
293
272 # Wildcard searches - IPython has a system for searching names using
294 # Wildcard searches - IPython has a system for searching names using
273 # shell-like wildcards; type %psearch? for details. This variables sets
295 # shell-like wildcards; type %psearch? for details. This variables sets
274 # whether by default such searches should be case sensitive or not. You can
296 # whether by default such searches should be case sensitive or not. You can
275 # always override the default at the system command line or the IPython
297 # always override the default at the system command line or the IPython
276 # prompt.
298 # prompt.
277
299
278 wildcards_case_sensitive 1
300 wildcards_case_sensitive 1
279
301
280 # xmode - Exception reporting mode.
302 # xmode - Exception reporting mode.
281
303
282 # Valid modes: Plain, Context and Verbose.
304 # Valid modes: Plain, Context and Verbose.
283
305
284 # Plain: similar to python's normal traceback printing.
306 # Plain: similar to python's normal traceback printing.
285
307
286 # Context: prints 5 lines of context source code around each line in the
308 # Context: prints 5 lines of context source code around each line in the
287 # traceback.
309 # traceback.
288
310
289 # Verbose: similar to Context, but additionally prints the variables currently
311 # Verbose: similar to Context, but additionally prints the variables currently
290 # visible where the exception happened (shortening their strings if too
312 # visible where the exception happened (shortening their strings if too
291 # long). This can potentially be very slow, if you happen to have a huge data
313 # long). This can potentially be very slow, if you happen to have a huge data
292 # structure whose string representation is complex to compute. Your computer
314 # structure whose string representation is complex to compute. Your computer
293 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
315 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
294 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
316 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
295
317
296 #xmode Plain
318 #xmode Plain
297 xmode Context
319 xmode Context
298 #xmode Verbose
320 #xmode Verbose
299
321
300 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
322 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
301 # !cmd) to be used in multi-line input (like for loops). For example, if you
323 # !cmd) to be used in multi-line input (like for loops). For example, if you
302 # have this active, the following is valid in IPython:
324 # have this active, the following is valid in IPython:
303 #
325 #
304 #In [17]: for i in range(3):
326 #In [17]: for i in range(3):
305 # ....: mkdir $i
327 # ....: mkdir $i
306 # ....: !touch $i/hello
328 # ....: !touch $i/hello
307 # ....: ls -l $i
329 # ....: ls -l $i
308
330
309 multi_line_specials 1
331 multi_line_specials 1
310
332
311 #---------------------------------------------------------------------------
333 #---------------------------------------------------------------------------
312 # Section: Readline configuration (readline is not available for MS-Windows)
334 # Section: Readline configuration (readline is not available for MS-Windows)
313
335
314 # This is done via the following options:
336 # This is done via the following options:
315
337
316 # (i) readline_parse_and_bind: this option can appear as many times as you
338 # (i) readline_parse_and_bind: this option can appear as many times as you
317 # want, each time defining a string to be executed via a
339 # want, each time defining a string to be executed via a
318 # readline.parse_and_bind() command. The syntax for valid commands of this
340 # readline.parse_and_bind() command. The syntax for valid commands of this
319 # kind can be found by reading the documentation for the GNU readline library,
341 # kind can be found by reading the documentation for the GNU readline library,
320 # as these commands are of the kind which readline accepts in its
342 # as these commands are of the kind which readline accepts in its
321 # configuration file.
343 # configuration file.
322
344
323 # The TAB key can be used to complete names at the command line in one of two
345 # The TAB key can be used to complete names at the command line in one of two
324 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
346 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
325 # completes as much as possible while 'menu-complete' cycles through all
347 # completes as much as possible while 'menu-complete' cycles through all
326 # possible completions. Leave the one you prefer uncommented.
348 # possible completions. Leave the one you prefer uncommented.
327
349
328 readline_parse_and_bind tab: complete
350 readline_parse_and_bind tab: complete
329 #readline_parse_and_bind tab: menu-complete
351 #readline_parse_and_bind tab: menu-complete
330
352
331 # This binds Control-l to printing the list of all possible completions when
353 # This binds Control-l to printing the list of all possible completions when
332 # there is more than one (what 'complete' does when hitting TAB twice, or at
354 # there is more than one (what 'complete' does when hitting TAB twice, or at
333 # the first TAB if show-all-if-ambiguous is on)
355 # the first TAB if show-all-if-ambiguous is on)
334 readline_parse_and_bind "\C-l": possible-completions
356 readline_parse_and_bind "\C-l": possible-completions
335
357
336 # This forces readline to automatically print the above list when tab
358 # This forces readline to automatically print the above list when tab
337 # completion is set to 'complete'. You can still get this list manually by
359 # completion is set to 'complete'. You can still get this list manually by
338 # using the key bound to 'possible-completions' (Control-l by default) or by
360 # using the key bound to 'possible-completions' (Control-l by default) or by
339 # hitting TAB twice. Turning this on makes the printing happen at the first
361 # hitting TAB twice. Turning this on makes the printing happen at the first
340 # TAB.
362 # TAB.
341 readline_parse_and_bind set show-all-if-ambiguous on
363 readline_parse_and_bind set show-all-if-ambiguous on
342
364
343 # If you have TAB set to complete names, you can rebind any key (Control-o by
365 # If you have TAB set to complete names, you can rebind any key (Control-o by
344 # default) to insert a true TAB character.
366 # default) to insert a true TAB character.
345 readline_parse_and_bind "\C-o": tab-insert
367 readline_parse_and_bind "\C-o": tab-insert
346
368
347 # These commands allow you to indent/unindent easily, with the 4-space
369 # These commands allow you to indent/unindent easily, with the 4-space
348 # convention of the Python coding standards. Since IPython's internal
370 # convention of the Python coding standards. Since IPython's internal
349 # auto-indent system also uses 4 spaces, you should not change the number of
371 # auto-indent system also uses 4 spaces, you should not change the number of
350 # spaces in the code below.
372 # spaces in the code below.
351 readline_parse_and_bind "\M-i": " "
373 readline_parse_and_bind "\M-i": " "
352 readline_parse_and_bind "\M-o": "\d\d\d\d"
374 readline_parse_and_bind "\M-o": "\d\d\d\d"
353 readline_parse_and_bind "\M-I": "\d\d\d\d"
375 readline_parse_and_bind "\M-I": "\d\d\d\d"
354
376
355 # Bindings for incremental searches in the history. These searches use the
377 # Bindings for incremental searches in the history. These searches use the
356 # string typed so far on the command line and search anything in the previous
378 # string typed so far on the command line and search anything in the previous
357 # input history containing them.
379 # input history containing them.
358 readline_parse_and_bind "\C-r": reverse-search-history
380 readline_parse_and_bind "\C-r": reverse-search-history
359 readline_parse_and_bind "\C-s": forward-search-history
381 readline_parse_and_bind "\C-s": forward-search-history
360
382
361 # Bindings for completing the current line in the history of previous
383 # Bindings for completing the current line in the history of previous
362 # commands. This allows you to recall any previous command by typing its first
384 # commands. This allows you to recall any previous command by typing its first
363 # few letters and hitting Control-p, bypassing all intermediate commands which
385 # few letters and hitting Control-p, bypassing all intermediate commands which
364 # may be in the history (much faster than hitting up-arrow 50 times!)
386 # may be in the history (much faster than hitting up-arrow 50 times!)
365 readline_parse_and_bind "\C-p": history-search-backward
387 readline_parse_and_bind "\C-p": history-search-backward
366 readline_parse_and_bind "\C-n": history-search-forward
388 readline_parse_and_bind "\C-n": history-search-forward
367
389
368 # I also like to have the same functionality on the plain arrow keys. If you'd
390 # I also like to have the same functionality on the plain arrow keys. If you'd
369 # rather have the arrows use all the history (and not just match what you've
391 # rather have the arrows use all the history (and not just match what you've
370 # typed so far), comment out or delete the next two lines.
392 # typed so far), comment out or delete the next two lines.
371 readline_parse_and_bind "\e[A": history-search-backward
393 readline_parse_and_bind "\e[A": history-search-backward
372 readline_parse_and_bind "\e[B": history-search-forward
394 readline_parse_and_bind "\e[B": history-search-forward
373
395
374 # These are typically on by default under *nix, but not win32.
396 # These are typically on by default under *nix, but not win32.
375 readline_parse_and_bind "\C-k": kill-line
397 readline_parse_and_bind "\C-k": kill-line
376 readline_parse_and_bind "\C-u": unix-line-discard
398 readline_parse_and_bind "\C-u": unix-line-discard
377
399
378 # (ii) readline_remove_delims: a string of characters to be removed from the
400 # (ii) readline_remove_delims: a string of characters to be removed from the
379 # default word-delimiters list used by readline, so that completions may be
401 # default word-delimiters list used by readline, so that completions may be
380 # performed on strings which contain them.
402 # performed on strings which contain them.
381
403
382 readline_remove_delims -/~
404 readline_remove_delims -/~
383
405
384 # (iii) readline_merge_completions: whether to merge the result of all
406 # (iii) readline_merge_completions: whether to merge the result of all
385 # possible completions or not. If true, IPython will complete filenames,
407 # possible completions or not. If true, IPython will complete filenames,
386 # python names and aliases and return all possible completions. If you set it
408 # python names and aliases and return all possible completions. If you set it
387 # to false, each completer is used at a time, and only if it doesn't return
409 # to false, each completer is used at a time, and only if it doesn't return
388 # any completions is the next one used.
410 # any completions is the next one used.
389
411
390 # The default order is: [python_matches, file_matches, alias_matches]
412 # The default order is: [python_matches, file_matches, alias_matches]
391
413
392 readline_merge_completions 1
414 readline_merge_completions 1
393
415
394 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
416 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
395 # will complete all attributes of an object, including all the special methods
417 # will complete all attributes of an object, including all the special methods
396 # whose names start with single or double underscores (like __getitem__ or
418 # whose names start with single or double underscores (like __getitem__ or
397 # __class__).
419 # __class__).
398
420
399 # This variable allows you to control this completion behavior:
421 # This variable allows you to control this completion behavior:
400
422
401 # readline_omit__names 1 -> completion will omit showing any names starting
423 # readline_omit__names 1 -> completion will omit showing any names starting
402 # with two __, but it will still show names starting with one _.
424 # with two __, but it will still show names starting with one _.
403
425
404 # readline_omit__names 2 -> completion will omit all names beginning with one
426 # readline_omit__names 2 -> completion will omit all names beginning with one
405 # _ (which obviously means filtering out the double __ ones).
427 # _ (which obviously means filtering out the double __ ones).
406
428
407 # Even when this option is set, you can still see those names by explicitly
429 # Even when this option is set, you can still see those names by explicitly
408 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
430 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
409 # complete attribute names starting with '_'.
431 # complete attribute names starting with '_'.
410
432
411 # This option is off by default so that new users see all attributes of any
433 # This option is off by default so that new users see all attributes of any
412 # objects they are dealing with.
434 # objects they are dealing with.
413
435
414 readline_omit__names 0
436 readline_omit__names 0
415
437
416 #---------------------------------------------------------------------------
438 #---------------------------------------------------------------------------
417 # Section: modules to be loaded with 'import ...'
439 # Section: modules to be loaded with 'import ...'
418
440
419 # List, separated by spaces, the names of the modules you want to import
441 # List, separated by spaces, the names of the modules you want to import
420
442
421 # Example:
443 # Example:
422 # import_mod sys os
444 # import_mod sys os
423 # will produce internally the statements
445 # will produce internally the statements
424 # import sys
446 # import sys
425 # import os
447 # import os
426
448
427 # Each import is executed in its own try/except block, so if one module
449 # Each import is executed in its own try/except block, so if one module
428 # fails to load the others will still be ok.
450 # fails to load the others will still be ok.
429
451
430 import_mod
452 import_mod
431
453
432 #---------------------------------------------------------------------------
454 #---------------------------------------------------------------------------
433 # Section: modules to import some functions from: 'from ... import ...'
455 # Section: modules to import some functions from: 'from ... import ...'
434
456
435 # List, one per line, the modules for which you want only to import some
457 # List, one per line, the modules for which you want only to import some
436 # functions. Give the module name first and then the name of functions to be
458 # functions. Give the module name first and then the name of functions to be
437 # imported from that module.
459 # imported from that module.
438
460
439 # Example:
461 # Example:
440
462
441 # import_some IPython.genutils timing timings
463 # import_some IPython.genutils timing timings
442 # will produce internally the statement
464 # will produce internally the statement
443 # from IPython.genutils import timing, timings
465 # from IPython.genutils import timing, timings
444
466
445 # timing() and timings() are two IPython utilities for timing the execution of
467 # timing() and timings() are two IPython utilities for timing the execution of
446 # your own functions, which you may find useful. Just commment out the above
468 # your own functions, which you may find useful. Just commment out the above
447 # line if you want to test them.
469 # line if you want to test them.
448
470
449 # If you have more than one modules_some line, each gets its own try/except
471 # If you have more than one modules_some line, each gets its own try/except
450 # block (like modules, see above).
472 # block (like modules, see above).
451
473
452 import_some
474 import_some
453
475
454 #---------------------------------------------------------------------------
476 #---------------------------------------------------------------------------
455 # Section: modules to import all from : 'from ... import *'
477 # Section: modules to import all from : 'from ... import *'
456
478
457 # List (same syntax as import_mod above) those modules for which you want to
479 # List (same syntax as import_mod above) those modules for which you want to
458 # import all functions. Remember, this is a potentially dangerous thing to do,
480 # import all functions. Remember, this is a potentially dangerous thing to do,
459 # since it is very easy to overwrite names of things you need. Use with
481 # since it is very easy to overwrite names of things you need. Use with
460 # caution.
482 # caution.
461
483
462 # Example:
484 # Example:
463 # import_all sys os
485 # import_all sys os
464 # will produce internally the statements
486 # will produce internally the statements
465 # from sys import *
487 # from sys import *
466 # from os import *
488 # from os import *
467
489
468 # As before, each will be called in a separate try/except block.
490 # As before, each will be called in a separate try/except block.
469
491
470 import_all
492 import_all
471
493
472 #---------------------------------------------------------------------------
494 #---------------------------------------------------------------------------
473 # Section: Python code to execute.
495 # Section: Python code to execute.
474
496
475 # Put here code to be explicitly executed (keep it simple!)
497 # Put here code to be explicitly executed (keep it simple!)
476 # Put one line of python code per line. All whitespace is removed (this is a
498 # Put one line of python code per line. All whitespace is removed (this is a
477 # feature, not a bug), so don't get fancy building loops here.
499 # feature, not a bug), so don't get fancy building loops here.
478 # This is just for quick convenient creation of things you want available.
500 # This is just for quick convenient creation of things you want available.
479
501
480 # Example:
502 # Example:
481 # execute x = 1
503 # execute x = 1
482 # execute print 'hello world'; y = z = 'a'
504 # execute print 'hello world'; y = z = 'a'
483 # will produce internally
505 # will produce internally
484 # x = 1
506 # x = 1
485 # print 'hello world'; y = z = 'a'
507 # print 'hello world'; y = z = 'a'
486 # and each *line* (not each statement, we don't do python syntax parsing) is
508 # and each *line* (not each statement, we don't do python syntax parsing) is
487 # executed in its own try/except block.
509 # executed in its own try/except block.
488
510
489 execute
511 execute
490
512
491 # Note for the adventurous: you can use this to define your own names for the
513 # Note for the adventurous: you can use this to define your own names for the
492 # magic functions, by playing some namespace tricks:
514 # magic functions, by playing some namespace tricks:
493
515
494 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
516 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
495
517
496 # defines @pf as a new name for @profile.
518 # defines @pf as a new name for @profile.
497
519
498 #---------------------------------------------------------------------------
520 #---------------------------------------------------------------------------
499 # Section: Pyhton files to load and execute.
521 # Section: Pyhton files to load and execute.
500
522
501 # Put here the full names of files you want executed with execfile(file). If
523 # Put here the full names of files you want executed with execfile(file). If
502 # you want complicated initialization, just write whatever you want in a
524 # you want complicated initialization, just write whatever you want in a
503 # regular python file and load it from here.
525 # regular python file and load it from here.
504
526
505 # Filenames defined here (which *must* include the extension) are searched for
527 # Filenames defined here (which *must* include the extension) are searched for
506 # through all of sys.path. Since IPython adds your .ipython directory to
528 # through all of sys.path. Since IPython adds your .ipython directory to
507 # sys.path, they can also be placed in your .ipython dir and will be
529 # sys.path, they can also be placed in your .ipython dir and will be
508 # found. Otherwise (if you want to execute things not in .ipyton nor in
530 # found. Otherwise (if you want to execute things not in .ipyton nor in
509 # sys.path) give a full path (you can use ~, it gets expanded)
531 # sys.path) give a full path (you can use ~, it gets expanded)
510
532
511 # Example:
533 # Example:
512 # execfile file1.py ~/file2.py
534 # execfile file1.py ~/file2.py
513 # will generate
535 # will generate
514 # execfile('file1.py')
536 # execfile('file1.py')
515 # execfile('_path_to_your_home/file2.py')
537 # execfile('_path_to_your_home/file2.py')
516
538
517 # As before, each file gets its own try/except block.
539 # As before, each file gets its own try/except block.
518
540
519 execfile
541 execfile
520
542
521 # If you are feeling adventurous, you can even add functionality to IPython
543 # If you are feeling adventurous, you can even add functionality to IPython
522 # through here. IPython works through a global variable called __ip which
544 # through here. IPython works through a global variable called __ip which
523 # exists at the time when these files are read. If you know what you are doing
545 # exists at the time when these files are read. If you know what you are doing
524 # (read the source) you can add functions to __ip in files loaded here.
546 # (read the source) you can add functions to __ip in files loaded here.
525
547
526 # The file example-magic.py contains a simple but correct example. Try it:
548 # The file example-magic.py contains a simple but correct example. Try it:
527
549
528 # execfile example-magic.py
550 # execfile example-magic.py
529
551
530 # Look at the examples in IPython/iplib.py for more details on how these magic
552 # Look at the examples in IPython/iplib.py for more details on how these magic
531 # functions need to process their arguments.
553 # functions need to process their arguments.
532
554
533 #---------------------------------------------------------------------------
555 #---------------------------------------------------------------------------
534 # Section: aliases for system shell commands
556 # Section: aliases for system shell commands
535
557
536 # Here you can define your own names for system commands. The syntax is
558 # Here you can define your own names for system commands. The syntax is
537 # similar to that of the builtin @alias function:
559 # similar to that of the builtin @alias function:
538
560
539 # alias alias_name command_string
561 # alias alias_name command_string
540
562
541 # The resulting aliases are auto-generated magic functions (hence usable as
563 # The resulting aliases are auto-generated magic functions (hence usable as
542 # @alias_name)
564 # @alias_name)
543
565
544 # For example:
566 # For example:
545
567
546 # alias myls ls -la
568 # alias myls ls -la
547
569
548 # will define 'myls' as an alias for executing the system command 'ls -la'.
570 # will define 'myls' as an alias for executing the system command 'ls -la'.
549 # This allows you to customize IPython's environment to have the same aliases
571 # This allows you to customize IPython's environment to have the same aliases
550 # you are accustomed to from your own shell.
572 # you are accustomed to from your own shell.
551
573
552 # You can also define aliases with parameters using %s specifiers (one per
574 # You can also define aliases with parameters using %s specifiers (one per
553 # parameter):
575 # parameter):
554
576
555 # alias parts echo first %s second %s
577 # alias parts echo first %s second %s
556
578
557 # will give you in IPython:
579 # will give you in IPython:
558 # >>> @parts A B
580 # >>> @parts A B
559 # first A second B
581 # first A second B
560
582
561 # Use one 'alias' statement per alias you wish to define.
583 # Use one 'alias' statement per alias you wish to define.
562
584
563 # alias
585 # alias
564
586
565 #************************* end of file <ipythonrc> ************************
587 #************************* end of file <ipythonrc> ************************
@@ -1,539 +1,556 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 ---------------------------------------------------------------------------
9 ---------------------------------------------------------------------------
10 Original rlcompleter documentation:
10 Original rlcompleter documentation:
11
11
12 This requires the latest extension to the readline module (the
12 This requires the latest extension to the readline module (the
13 completes keywords, built-ins and globals in __main__; when completing
13 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
15 completes its attributes.
16
16
17 It's very cool to do "import string" type "string.", hit the
17 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
18 completion key (twice), and see the list of names defined by the
19 string module!
19 string module!
20
20
21 Tip: to use the tab key as the completion key, call
21 Tip: to use the tab key as the completion key, call
22
22
23 readline.parse_and_bind("tab: complete")
23 readline.parse_and_bind("tab: complete")
24
24
25 Notes:
25 Notes:
26
26
27 - Exceptions raised by the completer function are *ignored* (and
27 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
28 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
29 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
30 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
31 reset and restore the tty state.
32
32
33 - The evaluation of the NAME.NAME... form may cause arbitrary
33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
34 application defined code to be executed if an object with a
35 __getattr__ hook is found. Since it is the responsibility of the
35 __getattr__ hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
36 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
37 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
38 indexing operations) are *not* evaluated.
39
39
40 - GNU readline is also used by the built-in functions input() and
40 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
41 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
42 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
43 specifying its own completer function and using raw_input() for all
44 its input.
44 its input.
45
45
46 - When the original stdin is not a tty device, GNU readline is never
46 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
47 used, and this module (and the readline module) are silently inactive.
48
48
49 """
49 """
50
50
51 #*****************************************************************************
51 #*****************************************************************************
52 #
52 #
53 # Since this file is essentially a minimally modified copy of the rlcompleter
53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 # module which is part of the standard Python distribution, I assume that the
54 # module which is part of the standard Python distribution, I assume that the
55 # proper procedure is to maintain its copyright as belonging to the Python
55 # proper procedure is to maintain its copyright as belonging to the Python
56 # Software Foundation (in addition to my own, for all new code).
56 # Software Foundation (in addition to my own, for all new code).
57 #
57 #
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
59 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
60 #
60 #
61 # Distributed under the terms of the BSD License. The full license is in
61 # Distributed under the terms of the BSD License. The full license is in
62 # the file COPYING, distributed as part of this software.
62 # the file COPYING, distributed as part of this software.
63 #
63 #
64 #*****************************************************************************
64 #*****************************************************************************
65
65
66 import __builtin__
66 import __builtin__
67 import __main__
67 import __main__
68 import glob
68 import glob
69 import keyword
69 import keyword
70 import os
70 import os
71 import re
71 import re
72 import readline
72 import readline
73 import sys
73 import sys
74 import types
74 import types
75
75
76 # Python 2.4 offers sets as a builtin
77 try:
78 set([1,2])
79 except NameError:
80 from sets import Set as set
81
82
76 from IPython.genutils import shlex_split
83 from IPython.genutils import shlex_split
77
84
78 __all__ = ['Completer','IPCompleter']
85 __all__ = ['Completer','IPCompleter']
79
86
80 def get_class_members(cls):
87 def get_class_members(cls):
81 ret = dir(cls)
88 ret = dir(cls)
82 if hasattr(cls,'__bases__'):
89 if hasattr(cls,'__bases__'):
83 for base in cls.__bases__:
90 for base in cls.__bases__:
84 ret.extend(get_class_members(base))
91 ret.extend(get_class_members(base))
85 return ret
92 return ret
86
93
87 class Completer:
94 class Completer:
88 def __init__(self,namespace=None,global_namespace=None):
95 def __init__(self,namespace=None,global_namespace=None):
89 """Create a new completer for the command line.
96 """Create a new completer for the command line.
90
97
91 Completer([namespace,global_namespace]) -> completer instance.
98 Completer([namespace,global_namespace]) -> completer instance.
92
99
93 If unspecified, the default namespace where completions are performed
100 If unspecified, the default namespace where completions are performed
94 is __main__ (technically, __main__.__dict__). Namespaces should be
101 is __main__ (technically, __main__.__dict__). Namespaces should be
95 given as dictionaries.
102 given as dictionaries.
96
103
97 An optional second namespace can be given. This allows the completer
104 An optional second namespace can be given. This allows the completer
98 to handle cases where both the local and global scopes need to be
105 to handle cases where both the local and global scopes need to be
99 distinguished.
106 distinguished.
100
107
101 Completer instances should be used as the completion mechanism of
108 Completer instances should be used as the completion mechanism of
102 readline via the set_completer() call:
109 readline via the set_completer() call:
103
110
104 readline.set_completer(Completer(my_namespace).complete)
111 readline.set_completer(Completer(my_namespace).complete)
105 """
112 """
106
113
107 # some minimal strict typechecks. For some core data structures, I
114 # some minimal strict typechecks. For some core data structures, I
108 # want actual basic python types, not just anything that looks like
115 # want actual basic python types, not just anything that looks like
109 # one. This is especially true for namespaces.
116 # one. This is especially true for namespaces.
110 for ns in (namespace,global_namespace):
117 for ns in (namespace,global_namespace):
111 if ns is not None and type(ns) != types.DictType:
118 if ns is not None and type(ns) != types.DictType:
112 raise TypeError,'namespace must be a dictionary'
119 raise TypeError,'namespace must be a dictionary'
113
120
114 # Don't bind to namespace quite yet, but flag whether the user wants a
121 # Don't bind to namespace quite yet, but flag whether the user wants a
115 # specific namespace or to use __main__.__dict__. This will allow us
122 # specific namespace or to use __main__.__dict__. This will allow us
116 # to bind to __main__.__dict__ at completion time, not now.
123 # to bind to __main__.__dict__ at completion time, not now.
117 if namespace is None:
124 if namespace is None:
118 self.use_main_ns = 1
125 self.use_main_ns = 1
119 else:
126 else:
120 self.use_main_ns = 0
127 self.use_main_ns = 0
121 self.namespace = namespace
128 self.namespace = namespace
122
129
123 # The global namespace, if given, can be bound directly
130 # The global namespace, if given, can be bound directly
124 if global_namespace is None:
131 if global_namespace is None:
125 self.global_namespace = {}
132 self.global_namespace = {}
126 else:
133 else:
127 self.global_namespace = global_namespace
134 self.global_namespace = global_namespace
128
135
129 def complete(self, text, state):
136 def complete(self, text, state):
130 """Return the next possible completion for 'text'.
137 """Return the next possible completion for 'text'.
131
138
132 This is called successively with state == 0, 1, 2, ... until it
139 This is called successively with state == 0, 1, 2, ... until it
133 returns None. The completion should begin with 'text'.
140 returns None. The completion should begin with 'text'.
134
141
135 """
142 """
136 if self.use_main_ns:
143 if self.use_main_ns:
137 self.namespace = __main__.__dict__
144 self.namespace = __main__.__dict__
138
145
139 if state == 0:
146 if state == 0:
140 if "." in text:
147 if "." in text:
141 self.matches = self.attr_matches(text)
148 self.matches = self.attr_matches(text)
142 else:
149 else:
143 self.matches = self.global_matches(text)
150 self.matches = self.global_matches(text)
144 try:
151 try:
145 return self.matches[state]
152 return self.matches[state]
146 except IndexError:
153 except IndexError:
147 return None
154 return None
148
155
149 def global_matches(self, text):
156 def global_matches(self, text):
150 """Compute matches when text is a simple name.
157 """Compute matches when text is a simple name.
151
158
152 Return a list of all keywords, built-in functions and names currently
159 Return a list of all keywords, built-in functions and names currently
153 defined in self.namespace or self.global_namespace that match.
160 defined in self.namespace or self.global_namespace that match.
154
161
155 """
162 """
156 matches = []
163 matches = []
157 match_append = matches.append
164 match_append = matches.append
158 n = len(text)
165 n = len(text)
159 for lst in [keyword.kwlist,
166 for lst in [keyword.kwlist,
160 __builtin__.__dict__.keys(),
167 __builtin__.__dict__.keys(),
161 self.namespace.keys(),
168 self.namespace.keys(),
162 self.global_namespace.keys()]:
169 self.global_namespace.keys()]:
163 for word in lst:
170 for word in lst:
164 if word[:n] == text and word != "__builtins__":
171 if word[:n] == text and word != "__builtins__":
165 match_append(word)
172 match_append(word)
166 return matches
173 return matches
167
174
168 def attr_matches(self, text):
175 def attr_matches(self, text):
169 """Compute matches when text contains a dot.
176 """Compute matches when text contains a dot.
170
177
171 Assuming the text is of the form NAME.NAME....[NAME], and is
178 Assuming the text is of the form NAME.NAME....[NAME], and is
172 evaluatable in self.namespace or self.global_namespace, it will be
179 evaluatable in self.namespace or self.global_namespace, it will be
173 evaluated and its attributes (as revealed by dir()) are used as
180 evaluated and its attributes (as revealed by dir()) are used as
174 possible completions. (For class instances, class members are are
181 possible completions. (For class instances, class members are are
175 also considered.)
182 also considered.)
176
183
177 WARNING: this can still invoke arbitrary C code, if an object
184 WARNING: this can still invoke arbitrary C code, if an object
178 with a __getattr__ hook is evaluated.
185 with a __getattr__ hook is evaluated.
179
186
180 """
187 """
181 import re
188 import re
182
189
183 # Another option, seems to work great. Catches things like ''.<tab>
190 # Another option, seems to work great. Catches things like ''.<tab>
184 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
191 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
185
192
186 if not m:
193 if not m:
187 return []
194 return []
188
195
189 expr, attr = m.group(1, 3)
196 expr, attr = m.group(1, 3)
190 try:
197 try:
191 object = eval(expr, self.namespace)
198 object = eval(expr, self.namespace)
192 except:
199 except:
193 object = eval(expr, self.global_namespace)
200 object = eval(expr, self.global_namespace)
194
201
202 # Start building the attribute list via dir(), and then complete it
203 # with a few extra special-purpose calls.
195 words = dir(object)
204 words = dir(object)
205
196 if hasattr(object,'__class__'):
206 if hasattr(object,'__class__'):
197 words.append('__class__')
207 words.append('__class__')
198 words.extend(get_class_members(object.__class__))
208 words.extend(get_class_members(object.__class__))
199
209
210 # this is the 'dir' function for objects with Enthought's traits
211 if hasattr(object, 'trait_names'):
212 words.extend(object.trait_names())
213 # eliminate possible duplicates, as some traits may also appear as
214 # normal attributes in the dir() call.
215 words = set(words)
216
200 # filter out non-string attributes which may be stuffed by dir() calls
217 # filter out non-string attributes which may be stuffed by dir() calls
201 # and poor coding in third-party modules
218 # and poor coding in third-party modules
202 words = [w for w in words
219 words = [w for w in words
203 if isinstance(w, basestring) and w != "__builtins__"]
220 if isinstance(w, basestring) and w != "__builtins__"]
204 # Build match list to return
221 # Build match list to return
205 n = len(attr)
222 n = len(attr)
206 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
223 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
207
224
208 class IPCompleter(Completer):
225 class IPCompleter(Completer):
209 """Extension of the completer class with IPython-specific features"""
226 """Extension of the completer class with IPython-specific features"""
210
227
211 def __init__(self,shell,namespace=None,global_namespace=None,
228 def __init__(self,shell,namespace=None,global_namespace=None,
212 omit__names=0,alias_table=None):
229 omit__names=0,alias_table=None):
213 """IPCompleter() -> completer
230 """IPCompleter() -> completer
214
231
215 Return a completer object suitable for use by the readline library
232 Return a completer object suitable for use by the readline library
216 via readline.set_completer().
233 via readline.set_completer().
217
234
218 Inputs:
235 Inputs:
219
236
220 - shell: a pointer to the ipython shell itself. This is needed
237 - shell: a pointer to the ipython shell itself. This is needed
221 because this completer knows about magic functions, and those can
238 because this completer knows about magic functions, and those can
222 only be accessed via the ipython instance.
239 only be accessed via the ipython instance.
223
240
224 - namespace: an optional dict where completions are performed.
241 - namespace: an optional dict where completions are performed.
225
242
226 - global_namespace: secondary optional dict for completions, to
243 - global_namespace: secondary optional dict for completions, to
227 handle cases (such as IPython embedded inside functions) where
244 handle cases (such as IPython embedded inside functions) where
228 both Python scopes are visible.
245 both Python scopes are visible.
229
246
230 - The optional omit__names parameter sets the completer to omit the
247 - The optional omit__names parameter sets the completer to omit the
231 'magic' names (__magicname__) for python objects unless the text
248 'magic' names (__magicname__) for python objects unless the text
232 to be completed explicitly starts with one or more underscores.
249 to be completed explicitly starts with one or more underscores.
233
250
234 - If alias_table is supplied, it should be a dictionary of aliases
251 - If alias_table is supplied, it should be a dictionary of aliases
235 to complete. """
252 to complete. """
236
253
237 Completer.__init__(self,namespace,global_namespace)
254 Completer.__init__(self,namespace,global_namespace)
238 self.magic_prefix = shell.name+'.magic_'
255 self.magic_prefix = shell.name+'.magic_'
239 self.magic_escape = shell.ESC_MAGIC
256 self.magic_escape = shell.ESC_MAGIC
240 self.readline = readline
257 self.readline = readline
241 delims = self.readline.get_completer_delims()
258 delims = self.readline.get_completer_delims()
242 delims = delims.replace(self.magic_escape,'')
259 delims = delims.replace(self.magic_escape,'')
243 self.readline.set_completer_delims(delims)
260 self.readline.set_completer_delims(delims)
244 self.get_line_buffer = self.readline.get_line_buffer
261 self.get_line_buffer = self.readline.get_line_buffer
245 self.omit__names = omit__names
262 self.omit__names = omit__names
246 self.merge_completions = shell.rc.readline_merge_completions
263 self.merge_completions = shell.rc.readline_merge_completions
247
264
248 if alias_table is None:
265 if alias_table is None:
249 alias_table = {}
266 alias_table = {}
250 self.alias_table = alias_table
267 self.alias_table = alias_table
251 # Regexp to split filenames with spaces in them
268 # Regexp to split filenames with spaces in them
252 self.space_name_re = re.compile(r'([^\\] )')
269 self.space_name_re = re.compile(r'([^\\] )')
253 # Hold a local ref. to glob.glob for speed
270 # Hold a local ref. to glob.glob for speed
254 self.glob = glob.glob
271 self.glob = glob.glob
255
272
256 # Determine if we are running on 'dumb' terminals, like (X)Emacs
273 # Determine if we are running on 'dumb' terminals, like (X)Emacs
257 # buffers, to avoid completion problems.
274 # buffers, to avoid completion problems.
258 term = os.environ.get('TERM','xterm')
275 term = os.environ.get('TERM','xterm')
259 self.dumb_terminal = term in ['dumb','emacs']
276 self.dumb_terminal = term in ['dumb','emacs']
260
277
261 # Special handling of backslashes needed in win32 platforms
278 # Special handling of backslashes needed in win32 platforms
262 if sys.platform == "win32":
279 if sys.platform == "win32":
263 self.clean_glob = self._clean_glob_win32
280 self.clean_glob = self._clean_glob_win32
264 else:
281 else:
265 self.clean_glob = self._clean_glob
282 self.clean_glob = self._clean_glob
266 self.matchers = [self.python_matches,
283 self.matchers = [self.python_matches,
267 self.file_matches,
284 self.file_matches,
268 self.alias_matches,
285 self.alias_matches,
269 self.python_func_kw_matches]
286 self.python_func_kw_matches]
270
287
271 # Code contributed by Alex Schmolck, for ipython/emacs integration
288 # Code contributed by Alex Schmolck, for ipython/emacs integration
272 def all_completions(self, text):
289 def all_completions(self, text):
273 """Return all possible completions for the benefit of emacs."""
290 """Return all possible completions for the benefit of emacs."""
274
291
275 completions = []
292 completions = []
276 comp_append = completions.append
293 comp_append = completions.append
277 try:
294 try:
278 for i in xrange(sys.maxint):
295 for i in xrange(sys.maxint):
279 res = self.complete(text, i)
296 res = self.complete(text, i)
280
297
281 if not res: break
298 if not res: break
282
299
283 comp_append(res)
300 comp_append(res)
284 #XXX workaround for ``notDefined.<tab>``
301 #XXX workaround for ``notDefined.<tab>``
285 except NameError:
302 except NameError:
286 pass
303 pass
287 return completions
304 return completions
288 # /end Alex Schmolck code.
305 # /end Alex Schmolck code.
289
306
290 def _clean_glob(self,text):
307 def _clean_glob(self,text):
291 return self.glob("%s*" % text)
308 return self.glob("%s*" % text)
292
309
293 def _clean_glob_win32(self,text):
310 def _clean_glob_win32(self,text):
294 return [f.replace("\\","/")
311 return [f.replace("\\","/")
295 for f in self.glob("%s*" % text)]
312 for f in self.glob("%s*" % text)]
296
313
297 def file_matches(self, text):
314 def file_matches(self, text):
298 """Match filneames, expanding ~USER type strings.
315 """Match filneames, expanding ~USER type strings.
299
316
300 Most of the seemingly convoluted logic in this completer is an
317 Most of the seemingly convoluted logic in this completer is an
301 attempt to handle filenames with spaces in them. And yet it's not
318 attempt to handle filenames with spaces in them. And yet it's not
302 quite perfect, because Python's readline doesn't expose all of the
319 quite perfect, because Python's readline doesn't expose all of the
303 GNU readline details needed for this to be done correctly.
320 GNU readline details needed for this to be done correctly.
304
321
305 For a filename with a space in it, the printed completions will be
322 For a filename with a space in it, the printed completions will be
306 only the parts after what's already been typed (instead of the
323 only the parts after what's already been typed (instead of the
307 full completions, as is normally done). I don't think with the
324 full completions, as is normally done). I don't think with the
308 current (as of Python 2.3) Python readline it's possible to do
325 current (as of Python 2.3) Python readline it's possible to do
309 better."""
326 better."""
310
327
311 #print 'Completer->file_matches: <%s>' % text # dbg
328 #print 'Completer->file_matches: <%s>' % text # dbg
312
329
313 # chars that require escaping with backslash - i.e. chars
330 # chars that require escaping with backslash - i.e. chars
314 # that readline treats incorrectly as delimiters, but we
331 # that readline treats incorrectly as delimiters, but we
315 # don't want to treat as delimiters in filename matching
332 # don't want to treat as delimiters in filename matching
316 # when escaped with backslash
333 # when escaped with backslash
317
334
318 protectables = ' ()[]{}'
335 protectables = ' ()[]{}'
319
336
320 def protect_filename(s):
337 def protect_filename(s):
321 return "".join([(ch in protectables and '\\' + ch or ch)
338 return "".join([(ch in protectables and '\\' + ch or ch)
322 for ch in s])
339 for ch in s])
323
340
324 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
341 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
325 open_quotes = 0 # track strings with open quotes
342 open_quotes = 0 # track strings with open quotes
326 try:
343 try:
327 lsplit = shlex_split(lbuf)[-1]
344 lsplit = shlex_split(lbuf)[-1]
328 except ValueError:
345 except ValueError:
329 # typically an unmatched ", or backslash without escaped char.
346 # typically an unmatched ", or backslash without escaped char.
330 if lbuf.count('"')==1:
347 if lbuf.count('"')==1:
331 open_quotes = 1
348 open_quotes = 1
332 lsplit = lbuf.split('"')[-1]
349 lsplit = lbuf.split('"')[-1]
333 elif lbuf.count("'")==1:
350 elif lbuf.count("'")==1:
334 open_quotes = 1
351 open_quotes = 1
335 lsplit = lbuf.split("'")[-1]
352 lsplit = lbuf.split("'")[-1]
336 else:
353 else:
337 return None
354 return None
338 except IndexError:
355 except IndexError:
339 # tab pressed on empty line
356 # tab pressed on empty line
340 lsplit = ""
357 lsplit = ""
341
358
342 if lsplit != protect_filename(lsplit):
359 if lsplit != protect_filename(lsplit):
343 # if protectables are found, do matching on the whole escaped
360 # if protectables are found, do matching on the whole escaped
344 # name
361 # name
345 has_protectables = 1
362 has_protectables = 1
346 text0,text = text,lsplit
363 text0,text = text,lsplit
347 else:
364 else:
348 has_protectables = 0
365 has_protectables = 0
349 text = os.path.expanduser(text)
366 text = os.path.expanduser(text)
350
367
351 if text == "":
368 if text == "":
352 return [protect_filename(f) for f in self.glob("*")]
369 return [protect_filename(f) for f in self.glob("*")]
353
370
354 m0 = self.clean_glob(text.replace('\\',''))
371 m0 = self.clean_glob(text.replace('\\',''))
355 if has_protectables:
372 if has_protectables:
356 # If we had protectables, we need to revert our changes to the
373 # If we had protectables, we need to revert our changes to the
357 # beginning of filename so that we don't double-write the part
374 # beginning of filename so that we don't double-write the part
358 # of the filename we have so far
375 # of the filename we have so far
359 len_lsplit = len(lsplit)
376 len_lsplit = len(lsplit)
360 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
377 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
361 else:
378 else:
362 if open_quotes:
379 if open_quotes:
363 # if we have a string with an open quote, we don't need to
380 # if we have a string with an open quote, we don't need to
364 # protect the names at all (and we _shouldn't_, as it
381 # protect the names at all (and we _shouldn't_, as it
365 # would cause bugs when the filesystem call is made).
382 # would cause bugs when the filesystem call is made).
366 matches = m0
383 matches = m0
367 else:
384 else:
368 matches = [protect_filename(f) for f in m0]
385 matches = [protect_filename(f) for f in m0]
369 if len(matches) == 1 and os.path.isdir(matches[0]):
386 if len(matches) == 1 and os.path.isdir(matches[0]):
370 # Takes care of links to directories also. Use '/'
387 # Takes care of links to directories also. Use '/'
371 # explicitly, even under Windows, so that name completions
388 # explicitly, even under Windows, so that name completions
372 # don't end up escaped.
389 # don't end up escaped.
373 matches[0] += '/'
390 matches[0] += '/'
374 return matches
391 return matches
375
392
376 def alias_matches(self, text):
393 def alias_matches(self, text):
377 """Match internal system aliases"""
394 """Match internal system aliases"""
378 #print 'Completer->alias_matches:',text # dbg
395 #print 'Completer->alias_matches:',text # dbg
379 text = os.path.expanduser(text)
396 text = os.path.expanduser(text)
380 aliases = self.alias_table.keys()
397 aliases = self.alias_table.keys()
381 if text == "":
398 if text == "":
382 return aliases
399 return aliases
383 else:
400 else:
384 return [alias for alias in aliases if alias.startswith(text)]
401 return [alias for alias in aliases if alias.startswith(text)]
385
402
386 def python_matches(self,text):
403 def python_matches(self,text):
387 """Match attributes or global python names"""
404 """Match attributes or global python names"""
388 #print 'Completer->python_matches' # dbg
405 #print 'Completer->python_matches' # dbg
389 if "." in text:
406 if "." in text:
390 try:
407 try:
391 matches = self.attr_matches(text)
408 matches = self.attr_matches(text)
392 if text.endswith('.') and self.omit__names:
409 if text.endswith('.') and self.omit__names:
393 if self.omit__names == 1:
410 if self.omit__names == 1:
394 # true if txt is _not_ a __ name, false otherwise:
411 # true if txt is _not_ a __ name, false otherwise:
395 no__name = (lambda txt:
412 no__name = (lambda txt:
396 re.match(r'.*\.__.*?__',txt) is None)
413 re.match(r'.*\.__.*?__',txt) is None)
397 else:
414 else:
398 # true if txt is _not_ a _ name, false otherwise:
415 # true if txt is _not_ a _ name, false otherwise:
399 no__name = (lambda txt:
416 no__name = (lambda txt:
400 re.match(r'.*\._.*?',txt) is None)
417 re.match(r'.*\._.*?',txt) is None)
401 matches = filter(no__name, matches)
418 matches = filter(no__name, matches)
402 except NameError:
419 except NameError:
403 # catches <undefined attributes>.<tab>
420 # catches <undefined attributes>.<tab>
404 matches = []
421 matches = []
405 else:
422 else:
406 matches = self.global_matches(text)
423 matches = self.global_matches(text)
407 # this is so completion finds magics when automagic is on:
424 # this is so completion finds magics when automagic is on:
408 if matches == [] and not text.startswith(os.sep):
425 if matches == [] and not text.startswith(os.sep):
409 matches = self.attr_matches(self.magic_prefix+text)
426 matches = self.attr_matches(self.magic_prefix+text)
410 return matches
427 return matches
411
428
412 def _default_arguments(self, obj):
429 def _default_arguments(self, obj):
413 """Return the list of default arguments of obj if it is callable,
430 """Return the list of default arguments of obj if it is callable,
414 or empty list otherwise."""
431 or empty list otherwise."""
415
432
416 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
433 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
417 # for classes, check for __init__,__new__
434 # for classes, check for __init__,__new__
418 if inspect.isclass(obj):
435 if inspect.isclass(obj):
419 obj = (getattr(obj,'__init__',None) or
436 obj = (getattr(obj,'__init__',None) or
420 getattr(obj,'__new__',None))
437 getattr(obj,'__new__',None))
421 # for all others, check if they are __call__able
438 # for all others, check if they are __call__able
422 elif hasattr(obj, '__call__'):
439 elif hasattr(obj, '__call__'):
423 obj = obj.__call__
440 obj = obj.__call__
424 # XXX: is there a way to handle the builtins ?
441 # XXX: is there a way to handle the builtins ?
425 try:
442 try:
426 args,_,_1,defaults = inspect.getargspec(obj)
443 args,_,_1,defaults = inspect.getargspec(obj)
427 if defaults:
444 if defaults:
428 return args[-len(defaults):]
445 return args[-len(defaults):]
429 except TypeError: pass
446 except TypeError: pass
430 return []
447 return []
431
448
432 def python_func_kw_matches(self,text):
449 def python_func_kw_matches(self,text):
433 """Match named parameters (kwargs) of the last open function"""
450 """Match named parameters (kwargs) of the last open function"""
434
451
435 if "." in text: # a parameter cannot be dotted
452 if "." in text: # a parameter cannot be dotted
436 return []
453 return []
437 try: regexp = self.__funcParamsRegex
454 try: regexp = self.__funcParamsRegex
438 except AttributeError:
455 except AttributeError:
439 regexp = self.__funcParamsRegex = re.compile(r'''
456 regexp = self.__funcParamsRegex = re.compile(r'''
440 '.*?' | # single quoted strings or
457 '.*?' | # single quoted strings or
441 ".*?" | # double quoted strings or
458 ".*?" | # double quoted strings or
442 \w+ | # identifier
459 \w+ | # identifier
443 \S # other characters
460 \S # other characters
444 ''', re.VERBOSE | re.DOTALL)
461 ''', re.VERBOSE | re.DOTALL)
445 # 1. find the nearest identifier that comes before an unclosed
462 # 1. find the nearest identifier that comes before an unclosed
446 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
463 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
447 tokens = regexp.findall(self.get_line_buffer())
464 tokens = regexp.findall(self.get_line_buffer())
448 tokens.reverse()
465 tokens.reverse()
449 iterTokens = iter(tokens); openPar = 0
466 iterTokens = iter(tokens); openPar = 0
450 for token in iterTokens:
467 for token in iterTokens:
451 if token == ')':
468 if token == ')':
452 openPar -= 1
469 openPar -= 1
453 elif token == '(':
470 elif token == '(':
454 openPar += 1
471 openPar += 1
455 if openPar > 0:
472 if openPar > 0:
456 # found the last unclosed parenthesis
473 # found the last unclosed parenthesis
457 break
474 break
458 else:
475 else:
459 return []
476 return []
460 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
477 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
461 ids = []
478 ids = []
462 isId = re.compile(r'\w+$').match
479 isId = re.compile(r'\w+$').match
463 while True:
480 while True:
464 try:
481 try:
465 ids.append(iterTokens.next())
482 ids.append(iterTokens.next())
466 if not isId(ids[-1]):
483 if not isId(ids[-1]):
467 ids.pop(); break
484 ids.pop(); break
468 if not iterTokens.next() == '.':
485 if not iterTokens.next() == '.':
469 break
486 break
470 except StopIteration:
487 except StopIteration:
471 break
488 break
472 # lookup the candidate callable matches either using global_matches
489 # lookup the candidate callable matches either using global_matches
473 # or attr_matches for dotted names
490 # or attr_matches for dotted names
474 if len(ids) == 1:
491 if len(ids) == 1:
475 callableMatches = self.global_matches(ids[0])
492 callableMatches = self.global_matches(ids[0])
476 else:
493 else:
477 callableMatches = self.attr_matches('.'.join(ids[::-1]))
494 callableMatches = self.attr_matches('.'.join(ids[::-1]))
478 argMatches = []
495 argMatches = []
479 for callableMatch in callableMatches:
496 for callableMatch in callableMatches:
480 try: namedArgs = self._default_arguments(eval(callableMatch,
497 try: namedArgs = self._default_arguments(eval(callableMatch,
481 self.namespace))
498 self.namespace))
482 except: continue
499 except: continue
483 for namedArg in namedArgs:
500 for namedArg in namedArgs:
484 if namedArg.startswith(text):
501 if namedArg.startswith(text):
485 argMatches.append("%s=" %namedArg)
502 argMatches.append("%s=" %namedArg)
486 return argMatches
503 return argMatches
487
504
488 def complete(self, text, state):
505 def complete(self, text, state):
489 """Return the next possible completion for 'text'.
506 """Return the next possible completion for 'text'.
490
507
491 This is called successively with state == 0, 1, 2, ... until it
508 This is called successively with state == 0, 1, 2, ... until it
492 returns None. The completion should begin with 'text'. """
509 returns None. The completion should begin with 'text'. """
493
510
494 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
511 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
495
512
496 # if there is only a tab on a line with only whitespace, instead
513 # if there is only a tab on a line with only whitespace, instead
497 # of the mostly useless 'do you want to see all million
514 # of the mostly useless 'do you want to see all million
498 # completions' message, just do the right thing and give the user
515 # completions' message, just do the right thing and give the user
499 # his tab! Incidentally, this enables pasting of tabbed text from
516 # his tab! Incidentally, this enables pasting of tabbed text from
500 # an editor (as long as autoindent is off).
517 # an editor (as long as autoindent is off).
501
518
502 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
519 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
503 # don't interfere with their own tab-completion mechanism.
520 # don't interfere with their own tab-completion mechanism.
504 if not (self.dumb_terminal or self.get_line_buffer().strip()):
521 if not (self.dumb_terminal or self.get_line_buffer().strip()):
505 self.readline.insert_text('\t')
522 self.readline.insert_text('\t')
506 return None
523 return None
507
524
508 magic_escape = self.magic_escape
525 magic_escape = self.magic_escape
509 magic_prefix = self.magic_prefix
526 magic_prefix = self.magic_prefix
510
527
511 try:
528 try:
512 if text.startswith(magic_escape):
529 if text.startswith(magic_escape):
513 text = text.replace(magic_escape,magic_prefix)
530 text = text.replace(magic_escape,magic_prefix)
514 elif text.startswith('~'):
531 elif text.startswith('~'):
515 text = os.path.expanduser(text)
532 text = os.path.expanduser(text)
516 if state == 0:
533 if state == 0:
517 # Extend the list of completions with the results of each
534 # Extend the list of completions with the results of each
518 # matcher, so we return results to the user from all
535 # matcher, so we return results to the user from all
519 # namespaces.
536 # namespaces.
520 if self.merge_completions:
537 if self.merge_completions:
521 self.matches = []
538 self.matches = []
522 for matcher in self.matchers:
539 for matcher in self.matchers:
523 self.matches.extend(matcher(text))
540 self.matches.extend(matcher(text))
524 else:
541 else:
525 for matcher in self.matchers:
542 for matcher in self.matchers:
526 self.matches = matcher(text)
543 self.matches = matcher(text)
527 if self.matches:
544 if self.matches:
528 break
545 break
529
546
530 try:
547 try:
531 return self.matches[state].replace(magic_prefix,magic_escape)
548 return self.matches[state].replace(magic_prefix,magic_escape)
532 except IndexError:
549 except IndexError:
533 return None
550 return None
534 except:
551 except:
535 #from IPython.ultraTB import AutoFormattedTB; # dbg
552 #from IPython.ultraTB import AutoFormattedTB; # dbg
536 #tb=AutoFormattedTB('Verbose');tb() #dbg
553 #tb=AutoFormattedTB('Verbose');tb() #dbg
537
554
538 # If completion fails, don't annoy the user.
555 # If completion fails, don't annoy the user.
539 return None
556 return None
@@ -1,1705 +1,1717 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 980 2005-12-30 15:42:04Z fperez $"""
8 $Id: genutils.py 990 2006-01-04 06:59:02Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from __future__ import generators # 2.2 compatibility
17 from __future__ import generators # 2.2 compatibility
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 #****************************************************************************
23 #****************************************************************************
24 # required modules from the Python standard library
24 # required modules from the Python standard library
25 import __main__
25 import __main__
26 import commands
26 import commands
27 import os
27 import os
28 import re
28 import re
29 import shlex
29 import shlex
30 import shutil
30 import shutil
31 import sys
31 import sys
32 import tempfile
32 import tempfile
33 import time
33 import time
34 import types
34 import types
35
35
36 # Other IPython utilities
36 # Other IPython utilities
37 from IPython.Itpl import Itpl,itpl,printpl
37 from IPython.Itpl import Itpl,itpl,printpl
38 from IPython import DPyGetOpt
38 from IPython import DPyGetOpt
39
39
40 if os.name == "nt":
40 if os.name == "nt":
41 from IPython.winconsole import get_console_size
41 from IPython.winconsole import get_console_size
42
42
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 # 2.2-friendly
44 # 2.2-friendly
45 try:
45 try:
46 basestring
46 basestring
47 except NameError:
47 except NameError:
48 import types
48 import types
49 basestring = (types.StringType, types.UnicodeType)
49 basestring = (types.StringType, types.UnicodeType)
50 True = 1==1
50 True = 1==1
51 False = 1==0
51 False = 1==0
52
52
53 def enumerate(obj):
53 def enumerate(obj):
54 i = -1
54 i = -1
55 for item in obj:
55 for item in obj:
56 i += 1
56 i += 1
57 yield i, item
57 yield i, item
58
58
59 # add these to the builtin namespace, so that all modules find them
59 # add these to the builtin namespace, so that all modules find them
60 import __builtin__
60 import __builtin__
61 __builtin__.basestring = basestring
61 __builtin__.basestring = basestring
62 __builtin__.True = True
62 __builtin__.True = True
63 __builtin__.False = False
63 __builtin__.False = False
64 __builtin__.enumerate = enumerate
64 __builtin__.enumerate = enumerate
65
65
66 # Try to use shlex.split for converting an input string into a sys.argv-type
66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 try:
68 try:
69 shlex_split = shlex.split
69 shlex_split = shlex.split
70 except AttributeError:
70 except AttributeError:
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
76 % os.sep)
76 % os.sep)
77
77
78 def shlex_split(s):
78 def shlex_split(s):
79 """Simplified backport to Python 2.2 of shlex.split().
79 """Simplified backport to Python 2.2 of shlex.split().
80
80
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 several of the features needed to really match the functionality of
82 several of the features needed to really match the functionality of
83 shlex.split() in 2.3."""
83 shlex.split() in 2.3."""
84
84
85 lex = shlex.shlex(StringIO(s))
85 lex = shlex.shlex(StringIO(s))
86 # Try to get options, extensions and path separators as characters
86 # Try to get options, extensions and path separators as characters
87 lex.wordchars = _wordchars
87 lex.wordchars = _wordchars
88 lex.commenters = ''
88 lex.commenters = ''
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 # iterator.
90 # iterator.
91 lout = []
91 lout = []
92 while 1:
92 while 1:
93 token = lex.get_token()
93 token = lex.get_token()
94 if token == '':
94 if token == '':
95 break
95 break
96 # Try to handle quoted tokens correctly
96 # Try to handle quoted tokens correctly
97 quotes = _quotesre.match(token)
97 quotes = _quotesre.match(token)
98 if quotes:
98 if quotes:
99 token = quotes.group(1)
99 token = quotes.group(1)
100 lout.append(token)
100 lout.append(token)
101 return lout
101 return lout
102
102
103 #****************************************************************************
103 #****************************************************************************
104 # Exceptions
104 # Exceptions
105 class Error(Exception):
105 class Error(Exception):
106 """Base class for exceptions in this module."""
106 """Base class for exceptions in this module."""
107 pass
107 pass
108
108
109 #----------------------------------------------------------------------------
109 #----------------------------------------------------------------------------
110 class IOStream:
110 class IOStream:
111 def __init__(self,stream,fallback):
111 def __init__(self,stream,fallback):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 stream = fallback
113 stream = fallback
114 self.stream = stream
114 self.stream = stream
115 self._swrite = stream.write
115 self._swrite = stream.write
116 self.flush = stream.flush
116 self.flush = stream.flush
117
117
118 def write(self,data):
118 def write(self,data):
119 try:
119 try:
120 self._swrite(data)
120 self._swrite(data)
121 except:
121 except:
122 try:
122 try:
123 # print handles some unicode issues which may trip a plain
123 # print handles some unicode issues which may trip a plain
124 # write() call. Attempt to emulate write() by using a
124 # write() call. Attempt to emulate write() by using a
125 # trailing comma
125 # trailing comma
126 print >> self.stream, data,
126 print >> self.stream, data,
127 except:
127 except:
128 # if we get here, something is seriously broken.
128 # if we get here, something is seriously broken.
129 print >> sys.stderr, \
129 print >> sys.stderr, \
130 'ERROR - failed to write data to stream:', stream
130 'ERROR - failed to write data to stream:', stream
131
131
132 class IOTerm:
132 class IOTerm:
133 """ Term holds the file or file-like objects for handling I/O operations.
133 """ Term holds the file or file-like objects for handling I/O operations.
134
134
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 Windows they can can replaced to allow editing the strings before they are
136 Windows they can can replaced to allow editing the strings before they are
137 displayed."""
137 displayed."""
138
138
139 # In the future, having IPython channel all its I/O operations through
139 # In the future, having IPython channel all its I/O operations through
140 # this class will make it easier to embed it into other environments which
140 # this class will make it easier to embed it into other environments which
141 # are not a normal terminal (such as a GUI-based shell)
141 # are not a normal terminal (such as a GUI-based shell)
142 def __init__(self,cin=None,cout=None,cerr=None):
142 def __init__(self,cin=None,cout=None,cerr=None):
143 self.cin = IOStream(cin,sys.stdin)
143 self.cin = IOStream(cin,sys.stdin)
144 self.cout = IOStream(cout,sys.stdout)
144 self.cout = IOStream(cout,sys.stdout)
145 self.cerr = IOStream(cerr,sys.stderr)
145 self.cerr = IOStream(cerr,sys.stderr)
146
146
147 # Global variable to be used for all I/O
147 # Global variable to be used for all I/O
148 Term = IOTerm()
148 Term = IOTerm()
149
149
150 # Windows-specific code to load Gary Bishop's readline and configure it
150 # Windows-specific code to load Gary Bishop's readline and configure it
151 # automatically for the users
151 # automatically for the users
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
153 # windows. Cygwin returns 'cygwin' for sys.platform.
153 # windows. Cygwin returns 'cygwin' for sys.platform.
154 if os.name == 'nt':
154 if os.name == 'nt':
155 try:
155 try:
156 import readline
156 import readline
157 except ImportError:
157 except ImportError:
158 pass
158 pass
159 else:
159 else:
160 try:
160 try:
161 _out = readline.GetOutputFile()
161 _out = readline.GetOutputFile()
162 except AttributeError:
162 except AttributeError:
163 pass
163 pass
164 else:
164 else:
165 # Remake Term to use the readline i/o facilities
165 # Remake Term to use the readline i/o facilities
166 Term = IOTerm(cout=_out,cerr=_out)
166 Term = IOTerm(cout=_out,cerr=_out)
167 del _out
167 del _out
168
168
169 #****************************************************************************
169 #****************************************************************************
170 # Generic warning/error printer, used by everything else
170 # Generic warning/error printer, used by everything else
171 def warn(msg,level=2,exit_val=1):
171 def warn(msg,level=2,exit_val=1):
172 """Standard warning printer. Gives formatting consistency.
172 """Standard warning printer. Gives formatting consistency.
173
173
174 Output is sent to Term.cerr (sys.stderr by default).
174 Output is sent to Term.cerr (sys.stderr by default).
175
175
176 Options:
176 Options:
177
177
178 -level(2): allows finer control:
178 -level(2): allows finer control:
179 0 -> Do nothing, dummy function.
179 0 -> Do nothing, dummy function.
180 1 -> Print message.
180 1 -> Print message.
181 2 -> Print 'WARNING:' + message. (Default level).
181 2 -> Print 'WARNING:' + message. (Default level).
182 3 -> Print 'ERROR:' + message.
182 3 -> Print 'ERROR:' + message.
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184
184
185 -exit_val (1): exit value returned by sys.exit() for a level 4
185 -exit_val (1): exit value returned by sys.exit() for a level 4
186 warning. Ignored for all other levels."""
186 warning. Ignored for all other levels."""
187
187
188 if level>0:
188 if level>0:
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 print >> Term.cerr, '%s%s' % (header[level],msg)
190 print >> Term.cerr, '%s%s' % (header[level],msg)
191 if level == 4:
191 if level == 4:
192 print >> Term.cerr,'Exiting.\n'
192 print >> Term.cerr,'Exiting.\n'
193 sys.exit(exit_val)
193 sys.exit(exit_val)
194
194
195 def info(msg):
195 def info(msg):
196 """Equivalent to warn(msg,level=1)."""
196 """Equivalent to warn(msg,level=1)."""
197
197
198 warn(msg,level=1)
198 warn(msg,level=1)
199
199
200 def error(msg):
200 def error(msg):
201 """Equivalent to warn(msg,level=3)."""
201 """Equivalent to warn(msg,level=3)."""
202
202
203 warn(msg,level=3)
203 warn(msg,level=3)
204
204
205 def fatal(msg,exit_val=1):
205 def fatal(msg,exit_val=1):
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207
207
208 warn(msg,exit_val=exit_val,level=4)
208 warn(msg,exit_val=exit_val,level=4)
209
209
210
211 # useful for debugging
212 def debugp(expr):
213 """Print the value of an expression from the caller's frame.
214
215 Takes an expression, evaluates it in the caller's frame and prints both
216 the given expression and the resulting value. The input must be of a form
217 suitable for eval()."""
218
219 cf = sys._getframe(1)
220 print '[DBG] %s -> %r' % (expr,eval(expr,cf.f_globals,cf.f_locals))
221
210 #----------------------------------------------------------------------------
222 #----------------------------------------------------------------------------
211 StringTypes = types.StringTypes
223 StringTypes = types.StringTypes
212
224
213 # Basic timing functionality
225 # Basic timing functionality
214
226
215 # If possible (Unix), use the resource module instead of time.clock()
227 # If possible (Unix), use the resource module instead of time.clock()
216 try:
228 try:
217 import resource
229 import resource
218 def clock():
230 def clock():
219 """clock() -> floating point number
231 """clock() -> floating point number
220
232
221 Return the CPU time in seconds (user time only, system time is
233 Return the CPU time in seconds (user time only, system time is
222 ignored) since the start of the process. This is done via a call to
234 ignored) since the start of the process. This is done via a call to
223 resource.getrusage, so it avoids the wraparound problems in
235 resource.getrusage, so it avoids the wraparound problems in
224 time.clock()."""
236 time.clock()."""
225
237
226 return resource.getrusage(resource.RUSAGE_SELF)[0]
238 return resource.getrusage(resource.RUSAGE_SELF)[0]
227
239
228 def clock2():
240 def clock2():
229 """clock2() -> (t_user,t_system)
241 """clock2() -> (t_user,t_system)
230
242
231 Similar to clock(), but return a tuple of user/system times."""
243 Similar to clock(), but return a tuple of user/system times."""
232 return resource.getrusage(resource.RUSAGE_SELF)[:2]
244 return resource.getrusage(resource.RUSAGE_SELF)[:2]
233
245
234 except ImportError:
246 except ImportError:
235 clock = time.clock
247 clock = time.clock
236 def clock2():
248 def clock2():
237 """Under windows, system CPU time can't be measured.
249 """Under windows, system CPU time can't be measured.
238
250
239 This just returns clock() and zero."""
251 This just returns clock() and zero."""
240 return time.clock(),0.0
252 return time.clock(),0.0
241
253
242 def timings_out(reps,func,*args,**kw):
254 def timings_out(reps,func,*args,**kw):
243 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
255 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
244
256
245 Execute a function reps times, return a tuple with the elapsed total
257 Execute a function reps times, return a tuple with the elapsed total
246 CPU time in seconds, the time per call and the function's output.
258 CPU time in seconds, the time per call and the function's output.
247
259
248 Under Unix, the return value is the sum of user+system time consumed by
260 Under Unix, the return value is the sum of user+system time consumed by
249 the process, computed via the resource module. This prevents problems
261 the process, computed via the resource module. This prevents problems
250 related to the wraparound effect which the time.clock() function has.
262 related to the wraparound effect which the time.clock() function has.
251
263
252 Under Windows the return value is in wall clock seconds. See the
264 Under Windows the return value is in wall clock seconds. See the
253 documentation for the time module for more details."""
265 documentation for the time module for more details."""
254
266
255 reps = int(reps)
267 reps = int(reps)
256 assert reps >=1, 'reps must be >= 1'
268 assert reps >=1, 'reps must be >= 1'
257 if reps==1:
269 if reps==1:
258 start = clock()
270 start = clock()
259 out = func(*args,**kw)
271 out = func(*args,**kw)
260 tot_time = clock()-start
272 tot_time = clock()-start
261 else:
273 else:
262 rng = xrange(reps-1) # the last time is executed separately to store output
274 rng = xrange(reps-1) # the last time is executed separately to store output
263 start = clock()
275 start = clock()
264 for dummy in rng: func(*args,**kw)
276 for dummy in rng: func(*args,**kw)
265 out = func(*args,**kw) # one last time
277 out = func(*args,**kw) # one last time
266 tot_time = clock()-start
278 tot_time = clock()-start
267 av_time = tot_time / reps
279 av_time = tot_time / reps
268 return tot_time,av_time,out
280 return tot_time,av_time,out
269
281
270 def timings(reps,func,*args,**kw):
282 def timings(reps,func,*args,**kw):
271 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
283 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
272
284
273 Execute a function reps times, return a tuple with the elapsed total CPU
285 Execute a function reps times, return a tuple with the elapsed total CPU
274 time in seconds and the time per call. These are just the first two values
286 time in seconds and the time per call. These are just the first two values
275 in timings_out()."""
287 in timings_out()."""
276
288
277 return timings_out(reps,func,*args,**kw)[0:2]
289 return timings_out(reps,func,*args,**kw)[0:2]
278
290
279 def timing(func,*args,**kw):
291 def timing(func,*args,**kw):
280 """timing(func,*args,**kw) -> t_total
292 """timing(func,*args,**kw) -> t_total
281
293
282 Execute a function once, return the elapsed total CPU time in
294 Execute a function once, return the elapsed total CPU time in
283 seconds. This is just the first value in timings_out()."""
295 seconds. This is just the first value in timings_out()."""
284
296
285 return timings_out(1,func,*args,**kw)[0]
297 return timings_out(1,func,*args,**kw)[0]
286
298
287 #****************************************************************************
299 #****************************************************************************
288 # file and system
300 # file and system
289
301
290 def system(cmd,verbose=0,debug=0,header=''):
302 def system(cmd,verbose=0,debug=0,header=''):
291 """Execute a system command, return its exit status.
303 """Execute a system command, return its exit status.
292
304
293 Options:
305 Options:
294
306
295 - verbose (0): print the command to be executed.
307 - verbose (0): print the command to be executed.
296
308
297 - debug (0): only print, do not actually execute.
309 - debug (0): only print, do not actually execute.
298
310
299 - header (''): Header to print on screen prior to the executed command (it
311 - header (''): Header to print on screen prior to the executed command (it
300 is only prepended to the command, no newlines are added).
312 is only prepended to the command, no newlines are added).
301
313
302 Note: a stateful version of this function is available through the
314 Note: a stateful version of this function is available through the
303 SystemExec class."""
315 SystemExec class."""
304
316
305 stat = 0
317 stat = 0
306 if verbose or debug: print header+cmd
318 if verbose or debug: print header+cmd
307 sys.stdout.flush()
319 sys.stdout.flush()
308 if not debug: stat = os.system(cmd)
320 if not debug: stat = os.system(cmd)
309 return stat
321 return stat
310
322
311 # This function is used by ipython in a lot of places to make system calls.
323 # This function is used by ipython in a lot of places to make system calls.
312 # We need it to be slightly different under win32, due to the vagaries of
324 # We need it to be slightly different under win32, due to the vagaries of
313 # 'network shares'. A win32 override is below.
325 # 'network shares'. A win32 override is below.
314
326
315 def shell(cmd,verbose=0,debug=0,header=''):
327 def shell(cmd,verbose=0,debug=0,header=''):
316 """Execute a command in the system shell, always return None.
328 """Execute a command in the system shell, always return None.
317
329
318 Options:
330 Options:
319
331
320 - verbose (0): print the command to be executed.
332 - verbose (0): print the command to be executed.
321
333
322 - debug (0): only print, do not actually execute.
334 - debug (0): only print, do not actually execute.
323
335
324 - header (''): Header to print on screen prior to the executed command (it
336 - header (''): Header to print on screen prior to the executed command (it
325 is only prepended to the command, no newlines are added).
337 is only prepended to the command, no newlines are added).
326
338
327 Note: this is similar to genutils.system(), but it returns None so it can
339 Note: this is similar to genutils.system(), but it returns None so it can
328 be conveniently used in interactive loops without getting the return value
340 be conveniently used in interactive loops without getting the return value
329 (typically 0) printed many times."""
341 (typically 0) printed many times."""
330
342
331 stat = 0
343 stat = 0
332 if verbose or debug: print header+cmd
344 if verbose or debug: print header+cmd
333 # flush stdout so we don't mangle python's buffering
345 # flush stdout so we don't mangle python's buffering
334 sys.stdout.flush()
346 sys.stdout.flush()
335 if not debug:
347 if not debug:
336 os.system(cmd)
348 os.system(cmd)
337
349
338 # override shell() for win32 to deal with network shares
350 # override shell() for win32 to deal with network shares
339 if os.name in ('nt','dos'):
351 if os.name in ('nt','dos'):
340
352
341 shell_ori = shell
353 shell_ori = shell
342
354
343 def shell(cmd,verbose=0,debug=0,header=''):
355 def shell(cmd,verbose=0,debug=0,header=''):
344 if os.getcwd().startswith(r"\\"):
356 if os.getcwd().startswith(r"\\"):
345 path = os.getcwd()
357 path = os.getcwd()
346 # change to c drive (cannot be on UNC-share when issuing os.system,
358 # change to c drive (cannot be on UNC-share when issuing os.system,
347 # as cmd.exe cannot handle UNC addresses)
359 # as cmd.exe cannot handle UNC addresses)
348 os.chdir("c:")
360 os.chdir("c:")
349 # issue pushd to the UNC-share and then run the command
361 # issue pushd to the UNC-share and then run the command
350 try:
362 try:
351 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
363 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
352 finally:
364 finally:
353 os.chdir(path)
365 os.chdir(path)
354 else:
366 else:
355 shell_ori(cmd,verbose,debug,header)
367 shell_ori(cmd,verbose,debug,header)
356
368
357 shell.__doc__ = shell_ori.__doc__
369 shell.__doc__ = shell_ori.__doc__
358
370
359 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
371 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
360 """Dummy substitute for perl's backquotes.
372 """Dummy substitute for perl's backquotes.
361
373
362 Executes a command and returns the output.
374 Executes a command and returns the output.
363
375
364 Accepts the same arguments as system(), plus:
376 Accepts the same arguments as system(), plus:
365
377
366 - split(0): if true, the output is returned as a list split on newlines.
378 - split(0): if true, the output is returned as a list split on newlines.
367
379
368 Note: a stateful version of this function is available through the
380 Note: a stateful version of this function is available through the
369 SystemExec class."""
381 SystemExec class."""
370
382
371 if verbose or debug: print header+cmd
383 if verbose or debug: print header+cmd
372 if not debug:
384 if not debug:
373 output = commands.getoutput(cmd)
385 output = commands.getoutput(cmd)
374 if split:
386 if split:
375 return output.split('\n')
387 return output.split('\n')
376 else:
388 else:
377 return output
389 return output
378
390
379 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
391 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
380 """Return (standard output,standard error) of executing cmd in a shell.
392 """Return (standard output,standard error) of executing cmd in a shell.
381
393
382 Accepts the same arguments as system(), plus:
394 Accepts the same arguments as system(), plus:
383
395
384 - split(0): if true, each of stdout/err is returned as a list split on
396 - split(0): if true, each of stdout/err is returned as a list split on
385 newlines.
397 newlines.
386
398
387 Note: a stateful version of this function is available through the
399 Note: a stateful version of this function is available through the
388 SystemExec class."""
400 SystemExec class."""
389
401
390 if verbose or debug: print header+cmd
402 if verbose or debug: print header+cmd
391 if not cmd:
403 if not cmd:
392 if split:
404 if split:
393 return [],[]
405 return [],[]
394 else:
406 else:
395 return '',''
407 return '',''
396 if not debug:
408 if not debug:
397 pin,pout,perr = os.popen3(cmd)
409 pin,pout,perr = os.popen3(cmd)
398 tout = pout.read().rstrip()
410 tout = pout.read().rstrip()
399 terr = perr.read().rstrip()
411 terr = perr.read().rstrip()
400 pin.close()
412 pin.close()
401 pout.close()
413 pout.close()
402 perr.close()
414 perr.close()
403 if split:
415 if split:
404 return tout.split('\n'),terr.split('\n')
416 return tout.split('\n'),terr.split('\n')
405 else:
417 else:
406 return tout,terr
418 return tout,terr
407
419
408 # for compatibility with older naming conventions
420 # for compatibility with older naming conventions
409 xsys = system
421 xsys = system
410 bq = getoutput
422 bq = getoutput
411
423
412 class SystemExec:
424 class SystemExec:
413 """Access the system and getoutput functions through a stateful interface.
425 """Access the system and getoutput functions through a stateful interface.
414
426
415 Note: here we refer to the system and getoutput functions from this
427 Note: here we refer to the system and getoutput functions from this
416 library, not the ones from the standard python library.
428 library, not the ones from the standard python library.
417
429
418 This class offers the system and getoutput functions as methods, but the
430 This class offers the system and getoutput functions as methods, but the
419 verbose, debug and header parameters can be set for the instance (at
431 verbose, debug and header parameters can be set for the instance (at
420 creation time or later) so that they don't need to be specified on each
432 creation time or later) so that they don't need to be specified on each
421 call.
433 call.
422
434
423 For efficiency reasons, there's no way to override the parameters on a
435 For efficiency reasons, there's no way to override the parameters on a
424 per-call basis other than by setting instance attributes. If you need
436 per-call basis other than by setting instance attributes. If you need
425 local overrides, it's best to directly call system() or getoutput().
437 local overrides, it's best to directly call system() or getoutput().
426
438
427 The following names are provided as alternate options:
439 The following names are provided as alternate options:
428 - xsys: alias to system
440 - xsys: alias to system
429 - bq: alias to getoutput
441 - bq: alias to getoutput
430
442
431 An instance can then be created as:
443 An instance can then be created as:
432 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
444 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
433
445
434 And used as:
446 And used as:
435 >>> sysexec.xsys('pwd')
447 >>> sysexec.xsys('pwd')
436 >>> dirlist = sysexec.bq('ls -l')
448 >>> dirlist = sysexec.bq('ls -l')
437 """
449 """
438
450
439 def __init__(self,verbose=0,debug=0,header='',split=0):
451 def __init__(self,verbose=0,debug=0,header='',split=0):
440 """Specify the instance's values for verbose, debug and header."""
452 """Specify the instance's values for verbose, debug and header."""
441 setattr_list(self,'verbose debug header split')
453 setattr_list(self,'verbose debug header split')
442
454
443 def system(self,cmd):
455 def system(self,cmd):
444 """Stateful interface to system(), with the same keyword parameters."""
456 """Stateful interface to system(), with the same keyword parameters."""
445
457
446 system(cmd,self.verbose,self.debug,self.header)
458 system(cmd,self.verbose,self.debug,self.header)
447
459
448 def shell(self,cmd):
460 def shell(self,cmd):
449 """Stateful interface to shell(), with the same keyword parameters."""
461 """Stateful interface to shell(), with the same keyword parameters."""
450
462
451 shell(cmd,self.verbose,self.debug,self.header)
463 shell(cmd,self.verbose,self.debug,self.header)
452
464
453 xsys = system # alias
465 xsys = system # alias
454
466
455 def getoutput(self,cmd):
467 def getoutput(self,cmd):
456 """Stateful interface to getoutput()."""
468 """Stateful interface to getoutput()."""
457
469
458 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
470 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
459
471
460 def getoutputerror(self,cmd):
472 def getoutputerror(self,cmd):
461 """Stateful interface to getoutputerror()."""
473 """Stateful interface to getoutputerror()."""
462
474
463 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
475 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
464
476
465 bq = getoutput # alias
477 bq = getoutput # alias
466
478
467 #-----------------------------------------------------------------------------
479 #-----------------------------------------------------------------------------
468 def mutex_opts(dict,ex_op):
480 def mutex_opts(dict,ex_op):
469 """Check for presence of mutually exclusive keys in a dict.
481 """Check for presence of mutually exclusive keys in a dict.
470
482
471 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
483 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
472 for op1,op2 in ex_op:
484 for op1,op2 in ex_op:
473 if op1 in dict and op2 in dict:
485 if op1 in dict and op2 in dict:
474 raise ValueError,'\n*** ERROR in Arguments *** '\
486 raise ValueError,'\n*** ERROR in Arguments *** '\
475 'Options '+op1+' and '+op2+' are mutually exclusive.'
487 'Options '+op1+' and '+op2+' are mutually exclusive.'
476
488
477 #-----------------------------------------------------------------------------
489 #-----------------------------------------------------------------------------
478 def get_py_filename(name):
490 def get_py_filename(name):
479 """Return a valid python filename in the current directory.
491 """Return a valid python filename in the current directory.
480
492
481 If the given name is not a file, it adds '.py' and searches again.
493 If the given name is not a file, it adds '.py' and searches again.
482 Raises IOError with an informative message if the file isn't found."""
494 Raises IOError with an informative message if the file isn't found."""
483
495
484 name = os.path.expanduser(name)
496 name = os.path.expanduser(name)
485 if not os.path.isfile(name) and not name.endswith('.py'):
497 if not os.path.isfile(name) and not name.endswith('.py'):
486 name += '.py'
498 name += '.py'
487 if os.path.isfile(name):
499 if os.path.isfile(name):
488 return name
500 return name
489 else:
501 else:
490 raise IOError,'File `%s` not found.' % name
502 raise IOError,'File `%s` not found.' % name
491
503
492 #-----------------------------------------------------------------------------
504 #-----------------------------------------------------------------------------
493 def filefind(fname,alt_dirs = None):
505 def filefind(fname,alt_dirs = None):
494 """Return the given filename either in the current directory, if it
506 """Return the given filename either in the current directory, if it
495 exists, or in a specified list of directories.
507 exists, or in a specified list of directories.
496
508
497 ~ expansion is done on all file and directory names.
509 ~ expansion is done on all file and directory names.
498
510
499 Upon an unsuccessful search, raise an IOError exception."""
511 Upon an unsuccessful search, raise an IOError exception."""
500
512
501 if alt_dirs is None:
513 if alt_dirs is None:
502 try:
514 try:
503 alt_dirs = get_home_dir()
515 alt_dirs = get_home_dir()
504 except HomeDirError:
516 except HomeDirError:
505 alt_dirs = os.getcwd()
517 alt_dirs = os.getcwd()
506 search = [fname] + list_strings(alt_dirs)
518 search = [fname] + list_strings(alt_dirs)
507 search = map(os.path.expanduser,search)
519 search = map(os.path.expanduser,search)
508 #print 'search list for',fname,'list:',search # dbg
520 #print 'search list for',fname,'list:',search # dbg
509 fname = search[0]
521 fname = search[0]
510 if os.path.isfile(fname):
522 if os.path.isfile(fname):
511 return fname
523 return fname
512 for direc in search[1:]:
524 for direc in search[1:]:
513 testname = os.path.join(direc,fname)
525 testname = os.path.join(direc,fname)
514 #print 'testname',testname # dbg
526 #print 'testname',testname # dbg
515 if os.path.isfile(testname):
527 if os.path.isfile(testname):
516 return testname
528 return testname
517 raise IOError,'File' + `fname` + \
529 raise IOError,'File' + `fname` + \
518 ' not found in current or supplied directories:' + `alt_dirs`
530 ' not found in current or supplied directories:' + `alt_dirs`
519
531
520 #----------------------------------------------------------------------------
532 #----------------------------------------------------------------------------
521 def file_read(filename):
533 def file_read(filename):
522 """Read a file and close it. Returns the file source."""
534 """Read a file and close it. Returns the file source."""
523 fobj=open(filename,'r');
535 fobj=open(filename,'r');
524 source = fobj.read();
536 source = fobj.read();
525 fobj.close()
537 fobj.close()
526 return source
538 return source
527
539
528 #----------------------------------------------------------------------------
540 #----------------------------------------------------------------------------
529 def target_outdated(target,deps):
541 def target_outdated(target,deps):
530 """Determine whether a target is out of date.
542 """Determine whether a target is out of date.
531
543
532 target_outdated(target,deps) -> 1/0
544 target_outdated(target,deps) -> 1/0
533
545
534 deps: list of filenames which MUST exist.
546 deps: list of filenames which MUST exist.
535 target: single filename which may or may not exist.
547 target: single filename which may or may not exist.
536
548
537 If target doesn't exist or is older than any file listed in deps, return
549 If target doesn't exist or is older than any file listed in deps, return
538 true, otherwise return false.
550 true, otherwise return false.
539 """
551 """
540 try:
552 try:
541 target_time = os.path.getmtime(target)
553 target_time = os.path.getmtime(target)
542 except os.error:
554 except os.error:
543 return 1
555 return 1
544 for dep in deps:
556 for dep in deps:
545 dep_time = os.path.getmtime(dep)
557 dep_time = os.path.getmtime(dep)
546 if dep_time > target_time:
558 if dep_time > target_time:
547 #print "For target",target,"Dep failed:",dep # dbg
559 #print "For target",target,"Dep failed:",dep # dbg
548 #print "times (dep,tar):",dep_time,target_time # dbg
560 #print "times (dep,tar):",dep_time,target_time # dbg
549 return 1
561 return 1
550 return 0
562 return 0
551
563
552 #-----------------------------------------------------------------------------
564 #-----------------------------------------------------------------------------
553 def target_update(target,deps,cmd):
565 def target_update(target,deps,cmd):
554 """Update a target with a given command given a list of dependencies.
566 """Update a target with a given command given a list of dependencies.
555
567
556 target_update(target,deps,cmd) -> runs cmd if target is outdated.
568 target_update(target,deps,cmd) -> runs cmd if target is outdated.
557
569
558 This is just a wrapper around target_outdated() which calls the given
570 This is just a wrapper around target_outdated() which calls the given
559 command if target is outdated."""
571 command if target is outdated."""
560
572
561 if target_outdated(target,deps):
573 if target_outdated(target,deps):
562 xsys(cmd)
574 xsys(cmd)
563
575
564 #----------------------------------------------------------------------------
576 #----------------------------------------------------------------------------
565 def unquote_ends(istr):
577 def unquote_ends(istr):
566 """Remove a single pair of quotes from the endpoints of a string."""
578 """Remove a single pair of quotes from the endpoints of a string."""
567
579
568 if not istr:
580 if not istr:
569 return istr
581 return istr
570 if (istr[0]=="'" and istr[-1]=="'") or \
582 if (istr[0]=="'" and istr[-1]=="'") or \
571 (istr[0]=='"' and istr[-1]=='"'):
583 (istr[0]=='"' and istr[-1]=='"'):
572 return istr[1:-1]
584 return istr[1:-1]
573 else:
585 else:
574 return istr
586 return istr
575
587
576 #----------------------------------------------------------------------------
588 #----------------------------------------------------------------------------
577 def process_cmdline(argv,names=[],defaults={},usage=''):
589 def process_cmdline(argv,names=[],defaults={},usage=''):
578 """ Process command-line options and arguments.
590 """ Process command-line options and arguments.
579
591
580 Arguments:
592 Arguments:
581
593
582 - argv: list of arguments, typically sys.argv.
594 - argv: list of arguments, typically sys.argv.
583
595
584 - names: list of option names. See DPyGetOpt docs for details on options
596 - names: list of option names. See DPyGetOpt docs for details on options
585 syntax.
597 syntax.
586
598
587 - defaults: dict of default values.
599 - defaults: dict of default values.
588
600
589 - usage: optional usage notice to print if a wrong argument is passed.
601 - usage: optional usage notice to print if a wrong argument is passed.
590
602
591 Return a dict of options and a list of free arguments."""
603 Return a dict of options and a list of free arguments."""
592
604
593 getopt = DPyGetOpt.DPyGetOpt()
605 getopt = DPyGetOpt.DPyGetOpt()
594 getopt.setIgnoreCase(0)
606 getopt.setIgnoreCase(0)
595 getopt.parseConfiguration(names)
607 getopt.parseConfiguration(names)
596
608
597 try:
609 try:
598 getopt.processArguments(argv)
610 getopt.processArguments(argv)
599 except:
611 except:
600 print usage
612 print usage
601 warn(`sys.exc_value`,level=4)
613 warn(`sys.exc_value`,level=4)
602
614
603 defaults.update(getopt.optionValues)
615 defaults.update(getopt.optionValues)
604 args = getopt.freeValues
616 args = getopt.freeValues
605
617
606 return defaults,args
618 return defaults,args
607
619
608 #----------------------------------------------------------------------------
620 #----------------------------------------------------------------------------
609 def optstr2types(ostr):
621 def optstr2types(ostr):
610 """Convert a string of option names to a dict of type mappings.
622 """Convert a string of option names to a dict of type mappings.
611
623
612 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
624 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
613
625
614 This is used to get the types of all the options in a string formatted
626 This is used to get the types of all the options in a string formatted
615 with the conventions of DPyGetOpt. The 'type' None is used for options
627 with the conventions of DPyGetOpt. The 'type' None is used for options
616 which are strings (they need no further conversion). This function's main
628 which are strings (they need no further conversion). This function's main
617 use is to get a typemap for use with read_dict().
629 use is to get a typemap for use with read_dict().
618 """
630 """
619
631
620 typeconv = {None:'',int:'',float:''}
632 typeconv = {None:'',int:'',float:''}
621 typemap = {'s':None,'i':int,'f':float}
633 typemap = {'s':None,'i':int,'f':float}
622 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
634 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
623
635
624 for w in ostr.split():
636 for w in ostr.split():
625 oname,alias,otype = opt_re.match(w).groups()
637 oname,alias,otype = opt_re.match(w).groups()
626 if otype == '' or alias == '!': # simple switches are integers too
638 if otype == '' or alias == '!': # simple switches are integers too
627 otype = 'i'
639 otype = 'i'
628 typeconv[typemap[otype]] += oname + ' '
640 typeconv[typemap[otype]] += oname + ' '
629 return typeconv
641 return typeconv
630
642
631 #----------------------------------------------------------------------------
643 #----------------------------------------------------------------------------
632 def read_dict(filename,type_conv=None,**opt):
644 def read_dict(filename,type_conv=None,**opt):
633
645
634 """Read a dictionary of key=value pairs from an input file, optionally
646 """Read a dictionary of key=value pairs from an input file, optionally
635 performing conversions on the resulting values.
647 performing conversions on the resulting values.
636
648
637 read_dict(filename,type_conv,**opt) -> dict
649 read_dict(filename,type_conv,**opt) -> dict
638
650
639 Only one value per line is accepted, the format should be
651 Only one value per line is accepted, the format should be
640 # optional comments are ignored
652 # optional comments are ignored
641 key value\n
653 key value\n
642
654
643 Args:
655 Args:
644
656
645 - type_conv: A dictionary specifying which keys need to be converted to
657 - type_conv: A dictionary specifying which keys need to be converted to
646 which types. By default all keys are read as strings. This dictionary
658 which types. By default all keys are read as strings. This dictionary
647 should have as its keys valid conversion functions for strings
659 should have as its keys valid conversion functions for strings
648 (int,long,float,complex, or your own). The value for each key
660 (int,long,float,complex, or your own). The value for each key
649 (converter) should be a whitespace separated string containing the names
661 (converter) should be a whitespace separated string containing the names
650 of all the entries in the file to be converted using that function. For
662 of all the entries in the file to be converted using that function. For
651 keys to be left alone, use None as the conversion function (only needed
663 keys to be left alone, use None as the conversion function (only needed
652 with purge=1, see below).
664 with purge=1, see below).
653
665
654 - opt: dictionary with extra options as below (default in parens)
666 - opt: dictionary with extra options as below (default in parens)
655
667
656 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
668 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
657 of the dictionary to be returned. If purge is going to be used, the
669 of the dictionary to be returned. If purge is going to be used, the
658 set of keys to be left as strings also has to be explicitly specified
670 set of keys to be left as strings also has to be explicitly specified
659 using the (non-existent) conversion function None.
671 using the (non-existent) conversion function None.
660
672
661 fs(None): field separator. This is the key/value separator to be used
673 fs(None): field separator. This is the key/value separator to be used
662 when parsing the file. The None default means any whitespace [behavior
674 when parsing the file. The None default means any whitespace [behavior
663 of string.split()].
675 of string.split()].
664
676
665 strip(0): if 1, strip string values of leading/trailinig whitespace.
677 strip(0): if 1, strip string values of leading/trailinig whitespace.
666
678
667 warn(1): warning level if requested keys are not found in file.
679 warn(1): warning level if requested keys are not found in file.
668 - 0: silently ignore.
680 - 0: silently ignore.
669 - 1: inform but proceed.
681 - 1: inform but proceed.
670 - 2: raise KeyError exception.
682 - 2: raise KeyError exception.
671
683
672 no_empty(0): if 1, remove keys with whitespace strings as a value.
684 no_empty(0): if 1, remove keys with whitespace strings as a value.
673
685
674 unique([]): list of keys (or space separated string) which can't be
686 unique([]): list of keys (or space separated string) which can't be
675 repeated. If one such key is found in the file, each new instance
687 repeated. If one such key is found in the file, each new instance
676 overwrites the previous one. For keys not listed here, the behavior is
688 overwrites the previous one. For keys not listed here, the behavior is
677 to make a list of all appearances.
689 to make a list of all appearances.
678
690
679 Example:
691 Example:
680 If the input file test.ini has:
692 If the input file test.ini has:
681 i 3
693 i 3
682 x 4.5
694 x 4.5
683 y 5.5
695 y 5.5
684 s hi ho
696 s hi ho
685 Then:
697 Then:
686
698
687 >>> type_conv={int:'i',float:'x',None:'s'}
699 >>> type_conv={int:'i',float:'x',None:'s'}
688 >>> read_dict('test.ini')
700 >>> read_dict('test.ini')
689 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
701 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
690 >>> read_dict('test.ini',type_conv)
702 >>> read_dict('test.ini',type_conv)
691 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
703 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
692 >>> read_dict('test.ini',type_conv,purge=1)
704 >>> read_dict('test.ini',type_conv,purge=1)
693 {'i': 3, 's': 'hi ho', 'x': 4.5}
705 {'i': 3, 's': 'hi ho', 'x': 4.5}
694 """
706 """
695
707
696 # starting config
708 # starting config
697 opt.setdefault('purge',0)
709 opt.setdefault('purge',0)
698 opt.setdefault('fs',None) # field sep defaults to any whitespace
710 opt.setdefault('fs',None) # field sep defaults to any whitespace
699 opt.setdefault('strip',0)
711 opt.setdefault('strip',0)
700 opt.setdefault('warn',1)
712 opt.setdefault('warn',1)
701 opt.setdefault('no_empty',0)
713 opt.setdefault('no_empty',0)
702 opt.setdefault('unique','')
714 opt.setdefault('unique','')
703 if type(opt['unique']) in StringTypes:
715 if type(opt['unique']) in StringTypes:
704 unique_keys = qw(opt['unique'])
716 unique_keys = qw(opt['unique'])
705 elif type(opt['unique']) in (types.TupleType,types.ListType):
717 elif type(opt['unique']) in (types.TupleType,types.ListType):
706 unique_keys = opt['unique']
718 unique_keys = opt['unique']
707 else:
719 else:
708 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
720 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
709
721
710 dict = {}
722 dict = {}
711 # first read in table of values as strings
723 # first read in table of values as strings
712 file = open(filename,'r')
724 file = open(filename,'r')
713 for line in file.readlines():
725 for line in file.readlines():
714 line = line.strip()
726 line = line.strip()
715 if len(line) and line[0]=='#': continue
727 if len(line) and line[0]=='#': continue
716 if len(line)>0:
728 if len(line)>0:
717 lsplit = line.split(opt['fs'],1)
729 lsplit = line.split(opt['fs'],1)
718 try:
730 try:
719 key,val = lsplit
731 key,val = lsplit
720 except ValueError:
732 except ValueError:
721 key,val = lsplit[0],''
733 key,val = lsplit[0],''
722 key = key.strip()
734 key = key.strip()
723 if opt['strip']: val = val.strip()
735 if opt['strip']: val = val.strip()
724 if val == "''" or val == '""': val = ''
736 if val == "''" or val == '""': val = ''
725 if opt['no_empty'] and (val=='' or val.isspace()):
737 if opt['no_empty'] and (val=='' or val.isspace()):
726 continue
738 continue
727 # if a key is found more than once in the file, build a list
739 # if a key is found more than once in the file, build a list
728 # unless it's in the 'unique' list. In that case, last found in file
740 # unless it's in the 'unique' list. In that case, last found in file
729 # takes precedence. User beware.
741 # takes precedence. User beware.
730 try:
742 try:
731 if dict[key] and key in unique_keys:
743 if dict[key] and key in unique_keys:
732 dict[key] = val
744 dict[key] = val
733 elif type(dict[key]) is types.ListType:
745 elif type(dict[key]) is types.ListType:
734 dict[key].append(val)
746 dict[key].append(val)
735 else:
747 else:
736 dict[key] = [dict[key],val]
748 dict[key] = [dict[key],val]
737 except KeyError:
749 except KeyError:
738 dict[key] = val
750 dict[key] = val
739 # purge if requested
751 # purge if requested
740 if opt['purge']:
752 if opt['purge']:
741 accepted_keys = qwflat(type_conv.values())
753 accepted_keys = qwflat(type_conv.values())
742 for key in dict.keys():
754 for key in dict.keys():
743 if key in accepted_keys: continue
755 if key in accepted_keys: continue
744 del(dict[key])
756 del(dict[key])
745 # now convert if requested
757 # now convert if requested
746 if type_conv==None: return dict
758 if type_conv==None: return dict
747 conversions = type_conv.keys()
759 conversions = type_conv.keys()
748 try: conversions.remove(None)
760 try: conversions.remove(None)
749 except: pass
761 except: pass
750 for convert in conversions:
762 for convert in conversions:
751 for val in qw(type_conv[convert]):
763 for val in qw(type_conv[convert]):
752 try:
764 try:
753 dict[val] = convert(dict[val])
765 dict[val] = convert(dict[val])
754 except KeyError,e:
766 except KeyError,e:
755 if opt['warn'] == 0:
767 if opt['warn'] == 0:
756 pass
768 pass
757 elif opt['warn'] == 1:
769 elif opt['warn'] == 1:
758 print >>sys.stderr, 'Warning: key',val,\
770 print >>sys.stderr, 'Warning: key',val,\
759 'not found in file',filename
771 'not found in file',filename
760 elif opt['warn'] == 2:
772 elif opt['warn'] == 2:
761 raise KeyError,e
773 raise KeyError,e
762 else:
774 else:
763 raise ValueError,'Warning level must be 0,1 or 2'
775 raise ValueError,'Warning level must be 0,1 or 2'
764
776
765 return dict
777 return dict
766
778
767 #----------------------------------------------------------------------------
779 #----------------------------------------------------------------------------
768 def flag_calls(func):
780 def flag_calls(func):
769 """Wrap a function to detect and flag when it gets called.
781 """Wrap a function to detect and flag when it gets called.
770
782
771 This is a decorator which takes a function and wraps it in a function with
783 This is a decorator which takes a function and wraps it in a function with
772 a 'called' attribute. wrapper.called is initialized to False.
784 a 'called' attribute. wrapper.called is initialized to False.
773
785
774 The wrapper.called attribute is set to False right before each call to the
786 The wrapper.called attribute is set to False right before each call to the
775 wrapped function, so if the call fails it remains False. After the call
787 wrapped function, so if the call fails it remains False. After the call
776 completes, wrapper.called is set to True and the output is returned.
788 completes, wrapper.called is set to True and the output is returned.
777
789
778 Testing for truth in wrapper.called allows you to determine if a call to
790 Testing for truth in wrapper.called allows you to determine if a call to
779 func() was attempted and succeeded."""
791 func() was attempted and succeeded."""
780
792
781 def wrapper(*args,**kw):
793 def wrapper(*args,**kw):
782 wrapper.called = False
794 wrapper.called = False
783 out = func(*args,**kw)
795 out = func(*args,**kw)
784 wrapper.called = True
796 wrapper.called = True
785 return out
797 return out
786
798
787 wrapper.called = False
799 wrapper.called = False
788 wrapper.__doc__ = func.__doc__
800 wrapper.__doc__ = func.__doc__
789 return wrapper
801 return wrapper
790
802
791 #----------------------------------------------------------------------------
803 #----------------------------------------------------------------------------
792 class HomeDirError(Error):
804 class HomeDirError(Error):
793 pass
805 pass
794
806
795 def get_home_dir():
807 def get_home_dir():
796 """Return the closest possible equivalent to a 'home' directory.
808 """Return the closest possible equivalent to a 'home' directory.
797
809
798 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
810 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
799
811
800 Currently only Posix and NT are implemented, a HomeDirError exception is
812 Currently only Posix and NT are implemented, a HomeDirError exception is
801 raised for all other OSes. """
813 raised for all other OSes. """
802
814
803 isdir = os.path.isdir
815 isdir = os.path.isdir
804 env = os.environ
816 env = os.environ
805 try:
817 try:
806 homedir = env['HOME']
818 homedir = env['HOME']
807 if not isdir(homedir):
819 if not isdir(homedir):
808 # in case a user stuck some string which does NOT resolve to a
820 # in case a user stuck some string which does NOT resolve to a
809 # valid path, it's as good as if we hadn't foud it
821 # valid path, it's as good as if we hadn't foud it
810 raise KeyError
822 raise KeyError
811 return homedir
823 return homedir
812 except KeyError:
824 except KeyError:
813 if os.name == 'posix':
825 if os.name == 'posix':
814 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
826 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
815 elif os.name == 'nt':
827 elif os.name == 'nt':
816 # For some strange reason, win9x returns 'nt' for os.name.
828 # For some strange reason, win9x returns 'nt' for os.name.
817 try:
829 try:
818 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
830 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
819 if not isdir(homedir):
831 if not isdir(homedir):
820 homedir = os.path.join(env['USERPROFILE'])
832 homedir = os.path.join(env['USERPROFILE'])
821 if not isdir(homedir):
833 if not isdir(homedir):
822 raise HomeDirError
834 raise HomeDirError
823 return homedir
835 return homedir
824 except:
836 except:
825 try:
837 try:
826 # Use the registry to get the 'My Documents' folder.
838 # Use the registry to get the 'My Documents' folder.
827 import _winreg as wreg
839 import _winreg as wreg
828 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
840 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
829 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
841 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
830 homedir = wreg.QueryValueEx(key,'Personal')[0]
842 homedir = wreg.QueryValueEx(key,'Personal')[0]
831 key.Close()
843 key.Close()
832 if not isdir(homedir):
844 if not isdir(homedir):
833 e = ('Invalid "Personal" folder registry key '
845 e = ('Invalid "Personal" folder registry key '
834 'typically "My Documents".\n'
846 'typically "My Documents".\n'
835 'Value: %s\n'
847 'Value: %s\n'
836 'This is not a valid directory on your system.' %
848 'This is not a valid directory on your system.' %
837 homedir)
849 homedir)
838 raise HomeDirError(e)
850 raise HomeDirError(e)
839 return homedir
851 return homedir
840 except HomeDirError:
852 except HomeDirError:
841 raise
853 raise
842 except:
854 except:
843 return 'C:\\'
855 return 'C:\\'
844 elif os.name == 'dos':
856 elif os.name == 'dos':
845 # Desperate, may do absurd things in classic MacOS. May work under DOS.
857 # Desperate, may do absurd things in classic MacOS. May work under DOS.
846 return 'C:\\'
858 return 'C:\\'
847 else:
859 else:
848 raise HomeDirError,'support for your operating system not implemented.'
860 raise HomeDirError,'support for your operating system not implemented.'
849
861
850 #****************************************************************************
862 #****************************************************************************
851 # strings and text
863 # strings and text
852
864
853 class LSString(str):
865 class LSString(str):
854 """String derivative with a special access attributes.
866 """String derivative with a special access attributes.
855
867
856 These are normal strings, but with the special attributes:
868 These are normal strings, but with the special attributes:
857
869
858 .l (or .list) : value as list (split on newlines).
870 .l (or .list) : value as list (split on newlines).
859 .n (or .nlstr): original value (the string itself).
871 .n (or .nlstr): original value (the string itself).
860 .s (or .spstr): value as whitespace-separated string.
872 .s (or .spstr): value as whitespace-separated string.
861
873
862 Any values which require transformations are computed only once and
874 Any values which require transformations are computed only once and
863 cached.
875 cached.
864
876
865 Such strings are very useful to efficiently interact with the shell, which
877 Such strings are very useful to efficiently interact with the shell, which
866 typically only understands whitespace-separated options for commands."""
878 typically only understands whitespace-separated options for commands."""
867
879
868 def get_list(self):
880 def get_list(self):
869 try:
881 try:
870 return self.__list
882 return self.__list
871 except AttributeError:
883 except AttributeError:
872 self.__list = self.split('\n')
884 self.__list = self.split('\n')
873 return self.__list
885 return self.__list
874
886
875 l = list = property(get_list)
887 l = list = property(get_list)
876
888
877 def get_spstr(self):
889 def get_spstr(self):
878 try:
890 try:
879 return self.__spstr
891 return self.__spstr
880 except AttributeError:
892 except AttributeError:
881 self.__spstr = self.replace('\n',' ')
893 self.__spstr = self.replace('\n',' ')
882 return self.__spstr
894 return self.__spstr
883
895
884 s = spstr = property(get_spstr)
896 s = spstr = property(get_spstr)
885
897
886 def get_nlstr(self):
898 def get_nlstr(self):
887 return self
899 return self
888
900
889 n = nlstr = property(get_nlstr)
901 n = nlstr = property(get_nlstr)
890
902
891 #----------------------------------------------------------------------------
903 #----------------------------------------------------------------------------
892 class SList(list):
904 class SList(list):
893 """List derivative with a special access attributes.
905 """List derivative with a special access attributes.
894
906
895 These are normal lists, but with the special attributes:
907 These are normal lists, but with the special attributes:
896
908
897 .l (or .list) : value as list (the list itself).
909 .l (or .list) : value as list (the list itself).
898 .n (or .nlstr): value as a string, joined on newlines.
910 .n (or .nlstr): value as a string, joined on newlines.
899 .s (or .spstr): value as a string, joined on spaces.
911 .s (or .spstr): value as a string, joined on spaces.
900
912
901 Any values which require transformations are computed only once and
913 Any values which require transformations are computed only once and
902 cached."""
914 cached."""
903
915
904 def get_list(self):
916 def get_list(self):
905 return self
917 return self
906
918
907 l = list = property(get_list)
919 l = list = property(get_list)
908
920
909 def get_spstr(self):
921 def get_spstr(self):
910 try:
922 try:
911 return self.__spstr
923 return self.__spstr
912 except AttributeError:
924 except AttributeError:
913 self.__spstr = ' '.join(self)
925 self.__spstr = ' '.join(self)
914 return self.__spstr
926 return self.__spstr
915
927
916 s = spstr = property(get_spstr)
928 s = spstr = property(get_spstr)
917
929
918 def get_nlstr(self):
930 def get_nlstr(self):
919 try:
931 try:
920 return self.__nlstr
932 return self.__nlstr
921 except AttributeError:
933 except AttributeError:
922 self.__nlstr = '\n'.join(self)
934 self.__nlstr = '\n'.join(self)
923 return self.__nlstr
935 return self.__nlstr
924
936
925 n = nlstr = property(get_nlstr)
937 n = nlstr = property(get_nlstr)
926
938
927 #----------------------------------------------------------------------------
939 #----------------------------------------------------------------------------
928 # This can be replaced with an isspace() call once we drop 2.2 compatibility
940 # This can be replaced with an isspace() call once we drop 2.2 compatibility
929 _isspace_match = re.compile(r'^\s+$').match
941 _isspace_match = re.compile(r'^\s+$').match
930 def isspace(s):
942 def isspace(s):
931 return bool(_isspace_match(s))
943 return bool(_isspace_match(s))
932
944
933 #----------------------------------------------------------------------------
945 #----------------------------------------------------------------------------
934 def esc_quotes(strng):
946 def esc_quotes(strng):
935 """Return the input string with single and double quotes escaped out"""
947 """Return the input string with single and double quotes escaped out"""
936
948
937 return strng.replace('"','\\"').replace("'","\\'")
949 return strng.replace('"','\\"').replace("'","\\'")
938
950
939 #----------------------------------------------------------------------------
951 #----------------------------------------------------------------------------
940 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
952 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
941 """Take multiple lines of input.
953 """Take multiple lines of input.
942
954
943 A list with each line of input as a separate element is returned when a
955 A list with each line of input as a separate element is returned when a
944 termination string is entered (defaults to a single '.'). Input can also
956 termination string is entered (defaults to a single '.'). Input can also
945 terminate via EOF (^D in Unix, ^Z-RET in Windows).
957 terminate via EOF (^D in Unix, ^Z-RET in Windows).
946
958
947 Lines of input which end in \\ are joined into single entries (and a
959 Lines of input which end in \\ are joined into single entries (and a
948 secondary continuation prompt is issued as long as the user terminates
960 secondary continuation prompt is issued as long as the user terminates
949 lines with \\). This allows entering very long strings which are still
961 lines with \\). This allows entering very long strings which are still
950 meant to be treated as single entities.
962 meant to be treated as single entities.
951 """
963 """
952
964
953 try:
965 try:
954 if header:
966 if header:
955 header += '\n'
967 header += '\n'
956 lines = [raw_input(header + ps1)]
968 lines = [raw_input(header + ps1)]
957 except EOFError:
969 except EOFError:
958 return []
970 return []
959 terminate = [terminate_str]
971 terminate = [terminate_str]
960 try:
972 try:
961 while lines[-1:] != terminate:
973 while lines[-1:] != terminate:
962 new_line = raw_input(ps1)
974 new_line = raw_input(ps1)
963 while new_line.endswith('\\'):
975 while new_line.endswith('\\'):
964 new_line = new_line[:-1] + raw_input(ps2)
976 new_line = new_line[:-1] + raw_input(ps2)
965 lines.append(new_line)
977 lines.append(new_line)
966
978
967 return lines[:-1] # don't return the termination command
979 return lines[:-1] # don't return the termination command
968 except EOFError:
980 except EOFError:
969 print
981 print
970 return lines
982 return lines
971
983
972 #----------------------------------------------------------------------------
984 #----------------------------------------------------------------------------
973 def raw_input_ext(prompt='', ps2='... '):
985 def raw_input_ext(prompt='', ps2='... '):
974 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
986 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
975
987
976 line = raw_input(prompt)
988 line = raw_input(prompt)
977 while line.endswith('\\'):
989 while line.endswith('\\'):
978 line = line[:-1] + raw_input(ps2)
990 line = line[:-1] + raw_input(ps2)
979 return line
991 return line
980
992
981 #----------------------------------------------------------------------------
993 #----------------------------------------------------------------------------
982 def ask_yes_no(prompt,default=None):
994 def ask_yes_no(prompt,default=None):
983 """Asks a question and returns an integer 1/0 (y/n) answer.
995 """Asks a question and returns an integer 1/0 (y/n) answer.
984
996
985 If default is given (one of 'y','n'), it is used if the user input is
997 If default is given (one of 'y','n'), it is used if the user input is
986 empty. Otherwise the question is repeated until an answer is given.
998 empty. Otherwise the question is repeated until an answer is given.
987 If EOF occurs 20 times consecutively, the default answer is assumed,
999 If EOF occurs 20 times consecutively, the default answer is assumed,
988 or if there is no default, an exception is raised to prevent infinite
1000 or if there is no default, an exception is raised to prevent infinite
989 loops.
1001 loops.
990
1002
991 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1003 Valid answers are: y/yes/n/no (match is not case sensitive)."""
992
1004
993 answers = {'y':True,'n':False,'yes':True,'no':False}
1005 answers = {'y':True,'n':False,'yes':True,'no':False}
994 ans = None
1006 ans = None
995 eofs, max_eofs = 0, 20
1007 eofs, max_eofs = 0, 20
996 while ans not in answers.keys():
1008 while ans not in answers.keys():
997 try:
1009 try:
998 ans = raw_input(prompt+' ').lower()
1010 ans = raw_input(prompt+' ').lower()
999 if not ans: # response was an empty string
1011 if not ans: # response was an empty string
1000 ans = default
1012 ans = default
1001 eofs = 0
1013 eofs = 0
1002 except (EOFError,KeyboardInterrupt):
1014 except (EOFError,KeyboardInterrupt):
1003 eofs = eofs + 1
1015 eofs = eofs + 1
1004 if eofs >= max_eofs:
1016 if eofs >= max_eofs:
1005 if default in answers.keys():
1017 if default in answers.keys():
1006 ans = default
1018 ans = default
1007 else:
1019 else:
1008 raise
1020 raise
1009
1021
1010 return answers[ans]
1022 return answers[ans]
1011
1023
1012 #----------------------------------------------------------------------------
1024 #----------------------------------------------------------------------------
1013 def marquee(txt='',width=78,mark='*'):
1025 def marquee(txt='',width=78,mark='*'):
1014 """Return the input string centered in a 'marquee'."""
1026 """Return the input string centered in a 'marquee'."""
1015 if not txt:
1027 if not txt:
1016 return (mark*width)[:width]
1028 return (mark*width)[:width]
1017 nmark = (width-len(txt)-2)/len(mark)/2
1029 nmark = (width-len(txt)-2)/len(mark)/2
1018 if nmark < 0: nmark =0
1030 if nmark < 0: nmark =0
1019 marks = mark*nmark
1031 marks = mark*nmark
1020 return '%s %s %s' % (marks,txt,marks)
1032 return '%s %s %s' % (marks,txt,marks)
1021
1033
1022 #----------------------------------------------------------------------------
1034 #----------------------------------------------------------------------------
1023 class EvalDict:
1035 class EvalDict:
1024 """
1036 """
1025 Emulate a dict which evaluates its contents in the caller's frame.
1037 Emulate a dict which evaluates its contents in the caller's frame.
1026
1038
1027 Usage:
1039 Usage:
1028 >>>number = 19
1040 >>>number = 19
1029 >>>text = "python"
1041 >>>text = "python"
1030 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1042 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1031 """
1043 """
1032
1044
1033 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1045 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1034 # modified (shorter) version of:
1046 # modified (shorter) version of:
1035 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1047 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1036 # Skip Montanaro (skip@pobox.com).
1048 # Skip Montanaro (skip@pobox.com).
1037
1049
1038 def __getitem__(self, name):
1050 def __getitem__(self, name):
1039 frame = sys._getframe(1)
1051 frame = sys._getframe(1)
1040 return eval(name, frame.f_globals, frame.f_locals)
1052 return eval(name, frame.f_globals, frame.f_locals)
1041
1053
1042 EvalString = EvalDict # for backwards compatibility
1054 EvalString = EvalDict # for backwards compatibility
1043 #----------------------------------------------------------------------------
1055 #----------------------------------------------------------------------------
1044 def qw(words,flat=0,sep=None,maxsplit=-1):
1056 def qw(words,flat=0,sep=None,maxsplit=-1):
1045 """Similar to Perl's qw() operator, but with some more options.
1057 """Similar to Perl's qw() operator, but with some more options.
1046
1058
1047 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1059 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1048
1060
1049 words can also be a list itself, and with flat=1, the output will be
1061 words can also be a list itself, and with flat=1, the output will be
1050 recursively flattened. Examples:
1062 recursively flattened. Examples:
1051
1063
1052 >>> qw('1 2')
1064 >>> qw('1 2')
1053 ['1', '2']
1065 ['1', '2']
1054 >>> qw(['a b','1 2',['m n','p q']])
1066 >>> qw(['a b','1 2',['m n','p q']])
1055 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1067 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1056 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1068 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1057 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1069 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1058
1070
1059 if type(words) in StringTypes:
1071 if type(words) in StringTypes:
1060 return [word.strip() for word in words.split(sep,maxsplit)
1072 return [word.strip() for word in words.split(sep,maxsplit)
1061 if word and not word.isspace() ]
1073 if word and not word.isspace() ]
1062 if flat:
1074 if flat:
1063 return flatten(map(qw,words,[1]*len(words)))
1075 return flatten(map(qw,words,[1]*len(words)))
1064 return map(qw,words)
1076 return map(qw,words)
1065
1077
1066 #----------------------------------------------------------------------------
1078 #----------------------------------------------------------------------------
1067 def qwflat(words,sep=None,maxsplit=-1):
1079 def qwflat(words,sep=None,maxsplit=-1):
1068 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1080 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1069 return qw(words,1,sep,maxsplit)
1081 return qw(words,1,sep,maxsplit)
1070
1082
1071 #----------------------------------------------------------------------------
1083 #----------------------------------------------------------------------------
1072 def qw_lol(indata):
1084 def qw_lol(indata):
1073 """qw_lol('a b') -> [['a','b']],
1085 """qw_lol('a b') -> [['a','b']],
1074 otherwise it's just a call to qw().
1086 otherwise it's just a call to qw().
1075
1087
1076 We need this to make sure the modules_some keys *always* end up as a
1088 We need this to make sure the modules_some keys *always* end up as a
1077 list of lists."""
1089 list of lists."""
1078
1090
1079 if type(indata) in StringTypes:
1091 if type(indata) in StringTypes:
1080 return [qw(indata)]
1092 return [qw(indata)]
1081 else:
1093 else:
1082 return qw(indata)
1094 return qw(indata)
1083
1095
1084 #-----------------------------------------------------------------------------
1096 #-----------------------------------------------------------------------------
1085 def list_strings(arg):
1097 def list_strings(arg):
1086 """Always return a list of strings, given a string or list of strings
1098 """Always return a list of strings, given a string or list of strings
1087 as input."""
1099 as input."""
1088
1100
1089 if type(arg) in StringTypes: return [arg]
1101 if type(arg) in StringTypes: return [arg]
1090 else: return arg
1102 else: return arg
1091
1103
1092 #----------------------------------------------------------------------------
1104 #----------------------------------------------------------------------------
1093 def grep(pat,list,case=1):
1105 def grep(pat,list,case=1):
1094 """Simple minded grep-like function.
1106 """Simple minded grep-like function.
1095 grep(pat,list) returns occurrences of pat in list, None on failure.
1107 grep(pat,list) returns occurrences of pat in list, None on failure.
1096
1108
1097 It only does simple string matching, with no support for regexps. Use the
1109 It only does simple string matching, with no support for regexps. Use the
1098 option case=0 for case-insensitive matching."""
1110 option case=0 for case-insensitive matching."""
1099
1111
1100 # This is pretty crude. At least it should implement copying only references
1112 # This is pretty crude. At least it should implement copying only references
1101 # to the original data in case it's big. Now it copies the data for output.
1113 # to the original data in case it's big. Now it copies the data for output.
1102 out=[]
1114 out=[]
1103 if case:
1115 if case:
1104 for term in list:
1116 for term in list:
1105 if term.find(pat)>-1: out.append(term)
1117 if term.find(pat)>-1: out.append(term)
1106 else:
1118 else:
1107 lpat=pat.lower()
1119 lpat=pat.lower()
1108 for term in list:
1120 for term in list:
1109 if term.lower().find(lpat)>-1: out.append(term)
1121 if term.lower().find(lpat)>-1: out.append(term)
1110
1122
1111 if len(out): return out
1123 if len(out): return out
1112 else: return None
1124 else: return None
1113
1125
1114 #----------------------------------------------------------------------------
1126 #----------------------------------------------------------------------------
1115 def dgrep(pat,*opts):
1127 def dgrep(pat,*opts):
1116 """Return grep() on dir()+dir(__builtins__).
1128 """Return grep() on dir()+dir(__builtins__).
1117
1129
1118 A very common use of grep() when working interactively."""
1130 A very common use of grep() when working interactively."""
1119
1131
1120 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1132 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1121
1133
1122 #----------------------------------------------------------------------------
1134 #----------------------------------------------------------------------------
1123 def idgrep(pat):
1135 def idgrep(pat):
1124 """Case-insensitive dgrep()"""
1136 """Case-insensitive dgrep()"""
1125
1137
1126 return dgrep(pat,0)
1138 return dgrep(pat,0)
1127
1139
1128 #----------------------------------------------------------------------------
1140 #----------------------------------------------------------------------------
1129 def igrep(pat,list):
1141 def igrep(pat,list):
1130 """Synonym for case-insensitive grep."""
1142 """Synonym for case-insensitive grep."""
1131
1143
1132 return grep(pat,list,case=0)
1144 return grep(pat,list,case=0)
1133
1145
1134 #----------------------------------------------------------------------------
1146 #----------------------------------------------------------------------------
1135 def indent(str,nspaces=4,ntabs=0):
1147 def indent(str,nspaces=4,ntabs=0):
1136 """Indent a string a given number of spaces or tabstops.
1148 """Indent a string a given number of spaces or tabstops.
1137
1149
1138 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1150 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1139 """
1151 """
1140 if str is None:
1152 if str is None:
1141 return
1153 return
1142 ind = '\t'*ntabs+' '*nspaces
1154 ind = '\t'*ntabs+' '*nspaces
1143 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1155 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1144 if outstr.endswith(os.linesep+ind):
1156 if outstr.endswith(os.linesep+ind):
1145 return outstr[:-len(ind)]
1157 return outstr[:-len(ind)]
1146 else:
1158 else:
1147 return outstr
1159 return outstr
1148
1160
1149 #-----------------------------------------------------------------------------
1161 #-----------------------------------------------------------------------------
1150 def native_line_ends(filename,backup=1):
1162 def native_line_ends(filename,backup=1):
1151 """Convert (in-place) a file to line-ends native to the current OS.
1163 """Convert (in-place) a file to line-ends native to the current OS.
1152
1164
1153 If the optional backup argument is given as false, no backup of the
1165 If the optional backup argument is given as false, no backup of the
1154 original file is left. """
1166 original file is left. """
1155
1167
1156 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1168 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1157
1169
1158 bak_filename = filename + backup_suffixes[os.name]
1170 bak_filename = filename + backup_suffixes[os.name]
1159
1171
1160 original = open(filename).read()
1172 original = open(filename).read()
1161 shutil.copy2(filename,bak_filename)
1173 shutil.copy2(filename,bak_filename)
1162 try:
1174 try:
1163 new = open(filename,'wb')
1175 new = open(filename,'wb')
1164 new.write(os.linesep.join(original.splitlines()))
1176 new.write(os.linesep.join(original.splitlines()))
1165 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1177 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1166 new.close()
1178 new.close()
1167 except:
1179 except:
1168 os.rename(bak_filename,filename)
1180 os.rename(bak_filename,filename)
1169 if not backup:
1181 if not backup:
1170 try:
1182 try:
1171 os.remove(bak_filename)
1183 os.remove(bak_filename)
1172 except:
1184 except:
1173 pass
1185 pass
1174
1186
1175 #----------------------------------------------------------------------------
1187 #----------------------------------------------------------------------------
1176 def get_pager_cmd(pager_cmd = None):
1188 def get_pager_cmd(pager_cmd = None):
1177 """Return a pager command.
1189 """Return a pager command.
1178
1190
1179 Makes some attempts at finding an OS-correct one."""
1191 Makes some attempts at finding an OS-correct one."""
1180
1192
1181 if os.name == 'posix':
1193 if os.name == 'posix':
1182 default_pager_cmd = 'less -r' # -r for color control sequences
1194 default_pager_cmd = 'less -r' # -r for color control sequences
1183 elif os.name in ['nt','dos']:
1195 elif os.name in ['nt','dos']:
1184 default_pager_cmd = 'type'
1196 default_pager_cmd = 'type'
1185
1197
1186 if pager_cmd is None:
1198 if pager_cmd is None:
1187 try:
1199 try:
1188 pager_cmd = os.environ['PAGER']
1200 pager_cmd = os.environ['PAGER']
1189 except:
1201 except:
1190 pager_cmd = default_pager_cmd
1202 pager_cmd = default_pager_cmd
1191 return pager_cmd
1203 return pager_cmd
1192
1204
1193 #-----------------------------------------------------------------------------
1205 #-----------------------------------------------------------------------------
1194 def get_pager_start(pager,start):
1206 def get_pager_start(pager,start):
1195 """Return the string for paging files with an offset.
1207 """Return the string for paging files with an offset.
1196
1208
1197 This is the '+N' argument which less and more (under Unix) accept.
1209 This is the '+N' argument which less and more (under Unix) accept.
1198 """
1210 """
1199
1211
1200 if pager in ['less','more']:
1212 if pager in ['less','more']:
1201 if start:
1213 if start:
1202 start_string = '+' + str(start)
1214 start_string = '+' + str(start)
1203 else:
1215 else:
1204 start_string = ''
1216 start_string = ''
1205 else:
1217 else:
1206 start_string = ''
1218 start_string = ''
1207 return start_string
1219 return start_string
1208
1220
1209 #----------------------------------------------------------------------------
1221 #----------------------------------------------------------------------------
1210 if os.name == "nt":
1222 if os.name == "nt":
1211 import msvcrt
1223 import msvcrt
1212 def page_more():
1224 def page_more():
1213 """ Smart pausing between pages
1225 """ Smart pausing between pages
1214
1226
1215 @return: True if need print more lines, False if quit
1227 @return: True if need print more lines, False if quit
1216 """
1228 """
1217 Term.cout.write('---Return to continue, q to quit--- ')
1229 Term.cout.write('---Return to continue, q to quit--- ')
1218 ans = msvcrt.getch()
1230 ans = msvcrt.getch()
1219 if ans in ("q", "Q"):
1231 if ans in ("q", "Q"):
1220 result = False
1232 result = False
1221 else:
1233 else:
1222 result = True
1234 result = True
1223 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1235 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1224 return result
1236 return result
1225 else:
1237 else:
1226 def page_more():
1238 def page_more():
1227 ans = raw_input('---Return to continue, q to quit--- ')
1239 ans = raw_input('---Return to continue, q to quit--- ')
1228 if ans.lower().startswith('q'):
1240 if ans.lower().startswith('q'):
1229 return False
1241 return False
1230 else:
1242 else:
1231 return True
1243 return True
1232
1244
1233 esc_re = re.compile(r"(\x1b[^m]+m)")
1245 esc_re = re.compile(r"(\x1b[^m]+m)")
1234
1246
1235 def page_dumb(strng,start=0,screen_lines=25):
1247 def page_dumb(strng,start=0,screen_lines=25):
1236 """Very dumb 'pager' in Python, for when nothing else works.
1248 """Very dumb 'pager' in Python, for when nothing else works.
1237
1249
1238 Only moves forward, same interface as page(), except for pager_cmd and
1250 Only moves forward, same interface as page(), except for pager_cmd and
1239 mode."""
1251 mode."""
1240
1252
1241 out_ln = strng.splitlines()[start:]
1253 out_ln = strng.splitlines()[start:]
1242 screens = chop(out_ln,screen_lines-1)
1254 screens = chop(out_ln,screen_lines-1)
1243 if len(screens) == 1:
1255 if len(screens) == 1:
1244 print >>Term.cout, os.linesep.join(screens[0])
1256 print >>Term.cout, os.linesep.join(screens[0])
1245 else:
1257 else:
1246 last_escape = ""
1258 last_escape = ""
1247 for scr in screens[0:-1]:
1259 for scr in screens[0:-1]:
1248 hunk = os.linesep.join(scr)
1260 hunk = os.linesep.join(scr)
1249 print >>Term.cout, last_escape + hunk
1261 print >>Term.cout, last_escape + hunk
1250 if not page_more():
1262 if not page_more():
1251 return
1263 return
1252 esc_list = esc_re.findall(hunk)
1264 esc_list = esc_re.findall(hunk)
1253 if len(esc_list) > 0:
1265 if len(esc_list) > 0:
1254 last_escape = esc_list[-1]
1266 last_escape = esc_list[-1]
1255 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1267 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1256
1268
1257 #----------------------------------------------------------------------------
1269 #----------------------------------------------------------------------------
1258 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1270 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1259 """Print a string, piping through a pager after a certain length.
1271 """Print a string, piping through a pager after a certain length.
1260
1272
1261 The screen_lines parameter specifies the number of *usable* lines of your
1273 The screen_lines parameter specifies the number of *usable* lines of your
1262 terminal screen (total lines minus lines you need to reserve to show other
1274 terminal screen (total lines minus lines you need to reserve to show other
1263 information).
1275 information).
1264
1276
1265 If you set screen_lines to a number <=0, page() will try to auto-determine
1277 If you set screen_lines to a number <=0, page() will try to auto-determine
1266 your screen size and will only use up to (screen_size+screen_lines) for
1278 your screen size and will only use up to (screen_size+screen_lines) for
1267 printing, paging after that. That is, if you want auto-detection but need
1279 printing, paging after that. That is, if you want auto-detection but need
1268 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1280 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1269 auto-detection without any lines reserved simply use screen_lines = 0.
1281 auto-detection without any lines reserved simply use screen_lines = 0.
1270
1282
1271 If a string won't fit in the allowed lines, it is sent through the
1283 If a string won't fit in the allowed lines, it is sent through the
1272 specified pager command. If none given, look for PAGER in the environment,
1284 specified pager command. If none given, look for PAGER in the environment,
1273 and ultimately default to less.
1285 and ultimately default to less.
1274
1286
1275 If no system pager works, the string is sent through a 'dumb pager'
1287 If no system pager works, the string is sent through a 'dumb pager'
1276 written in python, very simplistic.
1288 written in python, very simplistic.
1277 """
1289 """
1278
1290
1279 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1291 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1280 TERM = os.environ.get('TERM','dumb')
1292 TERM = os.environ.get('TERM','dumb')
1281 if TERM in ['dumb','emacs'] and os.name != 'nt':
1293 if TERM in ['dumb','emacs'] and os.name != 'nt':
1282 print strng
1294 print strng
1283 return
1295 return
1284 # chop off the topmost part of the string we don't want to see
1296 # chop off the topmost part of the string we don't want to see
1285 str_lines = strng.split(os.linesep)[start:]
1297 str_lines = strng.split(os.linesep)[start:]
1286 str_toprint = os.linesep.join(str_lines)
1298 str_toprint = os.linesep.join(str_lines)
1287 num_newlines = len(str_lines)
1299 num_newlines = len(str_lines)
1288 len_str = len(str_toprint)
1300 len_str = len(str_toprint)
1289
1301
1290 # Dumb heuristics to guesstimate number of on-screen lines the string
1302 # Dumb heuristics to guesstimate number of on-screen lines the string
1291 # takes. Very basic, but good enough for docstrings in reasonable
1303 # takes. Very basic, but good enough for docstrings in reasonable
1292 # terminals. If someone later feels like refining it, it's not hard.
1304 # terminals. If someone later feels like refining it, it's not hard.
1293 numlines = max(num_newlines,int(len_str/80)+1)
1305 numlines = max(num_newlines,int(len_str/80)+1)
1294
1306
1295 if os.name == "nt":
1307 if os.name == "nt":
1296 screen_lines_def = get_console_size(defaulty=25)[1]
1308 screen_lines_def = get_console_size(defaulty=25)[1]
1297 else:
1309 else:
1298 screen_lines_def = 25 # default value if we can't auto-determine
1310 screen_lines_def = 25 # default value if we can't auto-determine
1299
1311
1300 # auto-determine screen size
1312 # auto-determine screen size
1301 if screen_lines <= 0:
1313 if screen_lines <= 0:
1302 if TERM=='xterm':
1314 if TERM=='xterm':
1303 try:
1315 try:
1304 import curses
1316 import curses
1305 if hasattr(curses,'initscr'):
1317 if hasattr(curses,'initscr'):
1306 use_curses = 1
1318 use_curses = 1
1307 else:
1319 else:
1308 use_curses = 0
1320 use_curses = 0
1309 except ImportError:
1321 except ImportError:
1310 use_curses = 0
1322 use_curses = 0
1311 else:
1323 else:
1312 # curses causes problems on many terminals other than xterm.
1324 # curses causes problems on many terminals other than xterm.
1313 use_curses = 0
1325 use_curses = 0
1314 if use_curses:
1326 if use_curses:
1315 scr = curses.initscr()
1327 scr = curses.initscr()
1316 screen_lines_real,screen_cols = scr.getmaxyx()
1328 screen_lines_real,screen_cols = scr.getmaxyx()
1317 curses.endwin()
1329 curses.endwin()
1318 screen_lines += screen_lines_real
1330 screen_lines += screen_lines_real
1319 #print '***Screen size:',screen_lines_real,'lines x',\
1331 #print '***Screen size:',screen_lines_real,'lines x',\
1320 #screen_cols,'columns.' # dbg
1332 #screen_cols,'columns.' # dbg
1321 else:
1333 else:
1322 screen_lines += screen_lines_def
1334 screen_lines += screen_lines_def
1323
1335
1324 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1336 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1325 if numlines <= screen_lines :
1337 if numlines <= screen_lines :
1326 #print '*** normal print' # dbg
1338 #print '*** normal print' # dbg
1327 print >>Term.cout, str_toprint
1339 print >>Term.cout, str_toprint
1328 else:
1340 else:
1329 # Try to open pager and default to internal one if that fails.
1341 # Try to open pager and default to internal one if that fails.
1330 # All failure modes are tagged as 'retval=1', to match the return
1342 # All failure modes are tagged as 'retval=1', to match the return
1331 # value of a failed system command. If any intermediate attempt
1343 # value of a failed system command. If any intermediate attempt
1332 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1344 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1333 pager_cmd = get_pager_cmd(pager_cmd)
1345 pager_cmd = get_pager_cmd(pager_cmd)
1334 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1346 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1335 if os.name == 'nt':
1347 if os.name == 'nt':
1336 if pager_cmd.startswith('type'):
1348 if pager_cmd.startswith('type'):
1337 # The default WinXP 'type' command is failing on complex strings.
1349 # The default WinXP 'type' command is failing on complex strings.
1338 retval = 1
1350 retval = 1
1339 else:
1351 else:
1340 tmpname = tempfile.mktemp('.txt')
1352 tmpname = tempfile.mktemp('.txt')
1341 tmpfile = file(tmpname,'wt')
1353 tmpfile = file(tmpname,'wt')
1342 tmpfile.write(strng)
1354 tmpfile.write(strng)
1343 tmpfile.close()
1355 tmpfile.close()
1344 cmd = "%s < %s" % (pager_cmd,tmpname)
1356 cmd = "%s < %s" % (pager_cmd,tmpname)
1345 if os.system(cmd):
1357 if os.system(cmd):
1346 retval = 1
1358 retval = 1
1347 else:
1359 else:
1348 retval = None
1360 retval = None
1349 os.remove(tmpname)
1361 os.remove(tmpname)
1350 else:
1362 else:
1351 try:
1363 try:
1352 retval = None
1364 retval = None
1353 # if I use popen4, things hang. No idea why.
1365 # if I use popen4, things hang. No idea why.
1354 #pager,shell_out = os.popen4(pager_cmd)
1366 #pager,shell_out = os.popen4(pager_cmd)
1355 pager = os.popen(pager_cmd,'w')
1367 pager = os.popen(pager_cmd,'w')
1356 pager.write(strng)
1368 pager.write(strng)
1357 pager.close()
1369 pager.close()
1358 retval = pager.close() # success returns None
1370 retval = pager.close() # success returns None
1359 except IOError,msg: # broken pipe when user quits
1371 except IOError,msg: # broken pipe when user quits
1360 if msg.args == (32,'Broken pipe'):
1372 if msg.args == (32,'Broken pipe'):
1361 retval = None
1373 retval = None
1362 else:
1374 else:
1363 retval = 1
1375 retval = 1
1364 except OSError:
1376 except OSError:
1365 # Other strange problems, sometimes seen in Win2k/cygwin
1377 # Other strange problems, sometimes seen in Win2k/cygwin
1366 retval = 1
1378 retval = 1
1367 if retval is not None:
1379 if retval is not None:
1368 page_dumb(strng,screen_lines=screen_lines)
1380 page_dumb(strng,screen_lines=screen_lines)
1369
1381
1370 #----------------------------------------------------------------------------
1382 #----------------------------------------------------------------------------
1371 def page_file(fname,start = 0, pager_cmd = None):
1383 def page_file(fname,start = 0, pager_cmd = None):
1372 """Page a file, using an optional pager command and starting line.
1384 """Page a file, using an optional pager command and starting line.
1373 """
1385 """
1374
1386
1375 pager_cmd = get_pager_cmd(pager_cmd)
1387 pager_cmd = get_pager_cmd(pager_cmd)
1376 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1388 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1377
1389
1378 try:
1390 try:
1379 if os.environ['TERM'] in ['emacs','dumb']:
1391 if os.environ['TERM'] in ['emacs','dumb']:
1380 raise EnvironmentError
1392 raise EnvironmentError
1381 xsys(pager_cmd + ' ' + fname)
1393 xsys(pager_cmd + ' ' + fname)
1382 except:
1394 except:
1383 try:
1395 try:
1384 if start > 0:
1396 if start > 0:
1385 start -= 1
1397 start -= 1
1386 page(open(fname).read(),start)
1398 page(open(fname).read(),start)
1387 except:
1399 except:
1388 print 'Unable to show file',`fname`
1400 print 'Unable to show file',`fname`
1389
1401
1390 #----------------------------------------------------------------------------
1402 #----------------------------------------------------------------------------
1391 def snip_print(str,width = 75,print_full = 0,header = ''):
1403 def snip_print(str,width = 75,print_full = 0,header = ''):
1392 """Print a string snipping the midsection to fit in width.
1404 """Print a string snipping the midsection to fit in width.
1393
1405
1394 print_full: mode control:
1406 print_full: mode control:
1395 - 0: only snip long strings
1407 - 0: only snip long strings
1396 - 1: send to page() directly.
1408 - 1: send to page() directly.
1397 - 2: snip long strings and ask for full length viewing with page()
1409 - 2: snip long strings and ask for full length viewing with page()
1398 Return 1 if snipping was necessary, 0 otherwise."""
1410 Return 1 if snipping was necessary, 0 otherwise."""
1399
1411
1400 if print_full == 1:
1412 if print_full == 1:
1401 page(header+str)
1413 page(header+str)
1402 return 0
1414 return 0
1403
1415
1404 print header,
1416 print header,
1405 if len(str) < width:
1417 if len(str) < width:
1406 print str
1418 print str
1407 snip = 0
1419 snip = 0
1408 else:
1420 else:
1409 whalf = int((width -5)/2)
1421 whalf = int((width -5)/2)
1410 print str[:whalf] + ' <...> ' + str[-whalf:]
1422 print str[:whalf] + ' <...> ' + str[-whalf:]
1411 snip = 1
1423 snip = 1
1412 if snip and print_full == 2:
1424 if snip and print_full == 2:
1413 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1425 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1414 page(str)
1426 page(str)
1415 return snip
1427 return snip
1416
1428
1417 #****************************************************************************
1429 #****************************************************************************
1418 # lists, dicts and structures
1430 # lists, dicts and structures
1419
1431
1420 def belong(candidates,checklist):
1432 def belong(candidates,checklist):
1421 """Check whether a list of items appear in a given list of options.
1433 """Check whether a list of items appear in a given list of options.
1422
1434
1423 Returns a list of 1 and 0, one for each candidate given."""
1435 Returns a list of 1 and 0, one for each candidate given."""
1424
1436
1425 return [x in checklist for x in candidates]
1437 return [x in checklist for x in candidates]
1426
1438
1427 #----------------------------------------------------------------------------
1439 #----------------------------------------------------------------------------
1428 def uniq_stable(elems):
1440 def uniq_stable(elems):
1429 """uniq_stable(elems) -> list
1441 """uniq_stable(elems) -> list
1430
1442
1431 Return from an iterable, a list of all the unique elements in the input,
1443 Return from an iterable, a list of all the unique elements in the input,
1432 but maintaining the order in which they first appear.
1444 but maintaining the order in which they first appear.
1433
1445
1434 A naive solution to this problem which just makes a dictionary with the
1446 A naive solution to this problem which just makes a dictionary with the
1435 elements as keys fails to respect the stability condition, since
1447 elements as keys fails to respect the stability condition, since
1436 dictionaries are unsorted by nature.
1448 dictionaries are unsorted by nature.
1437
1449
1438 Note: All elements in the input must be valid dictionary keys for this
1450 Note: All elements in the input must be valid dictionary keys for this
1439 routine to work, as it internally uses a dictionary for efficiency
1451 routine to work, as it internally uses a dictionary for efficiency
1440 reasons."""
1452 reasons."""
1441
1453
1442 unique = []
1454 unique = []
1443 unique_dict = {}
1455 unique_dict = {}
1444 for nn in elems:
1456 for nn in elems:
1445 if nn not in unique_dict:
1457 if nn not in unique_dict:
1446 unique.append(nn)
1458 unique.append(nn)
1447 unique_dict[nn] = None
1459 unique_dict[nn] = None
1448 return unique
1460 return unique
1449
1461
1450 #----------------------------------------------------------------------------
1462 #----------------------------------------------------------------------------
1451 class NLprinter:
1463 class NLprinter:
1452 """Print an arbitrarily nested list, indicating index numbers.
1464 """Print an arbitrarily nested list, indicating index numbers.
1453
1465
1454 An instance of this class called nlprint is available and callable as a
1466 An instance of this class called nlprint is available and callable as a
1455 function.
1467 function.
1456
1468
1457 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1469 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1458 and using 'sep' to separate the index from the value. """
1470 and using 'sep' to separate the index from the value. """
1459
1471
1460 def __init__(self):
1472 def __init__(self):
1461 self.depth = 0
1473 self.depth = 0
1462
1474
1463 def __call__(self,lst,pos='',**kw):
1475 def __call__(self,lst,pos='',**kw):
1464 """Prints the nested list numbering levels."""
1476 """Prints the nested list numbering levels."""
1465 kw.setdefault('indent',' ')
1477 kw.setdefault('indent',' ')
1466 kw.setdefault('sep',': ')
1478 kw.setdefault('sep',': ')
1467 kw.setdefault('start',0)
1479 kw.setdefault('start',0)
1468 kw.setdefault('stop',len(lst))
1480 kw.setdefault('stop',len(lst))
1469 # we need to remove start and stop from kw so they don't propagate
1481 # we need to remove start and stop from kw so they don't propagate
1470 # into a recursive call for a nested list.
1482 # into a recursive call for a nested list.
1471 start = kw['start']; del kw['start']
1483 start = kw['start']; del kw['start']
1472 stop = kw['stop']; del kw['stop']
1484 stop = kw['stop']; del kw['stop']
1473 if self.depth == 0 and 'header' in kw.keys():
1485 if self.depth == 0 and 'header' in kw.keys():
1474 print kw['header']
1486 print kw['header']
1475
1487
1476 for idx in range(start,stop):
1488 for idx in range(start,stop):
1477 elem = lst[idx]
1489 elem = lst[idx]
1478 if type(elem)==type([]):
1490 if type(elem)==type([]):
1479 self.depth += 1
1491 self.depth += 1
1480 self.__call__(elem,itpl('$pos$idx,'),**kw)
1492 self.__call__(elem,itpl('$pos$idx,'),**kw)
1481 self.depth -= 1
1493 self.depth -= 1
1482 else:
1494 else:
1483 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1495 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1484
1496
1485 nlprint = NLprinter()
1497 nlprint = NLprinter()
1486 #----------------------------------------------------------------------------
1498 #----------------------------------------------------------------------------
1487 def all_belong(candidates,checklist):
1499 def all_belong(candidates,checklist):
1488 """Check whether a list of items ALL appear in a given list of options.
1500 """Check whether a list of items ALL appear in a given list of options.
1489
1501
1490 Returns a single 1 or 0 value."""
1502 Returns a single 1 or 0 value."""
1491
1503
1492 return 1-(0 in [x in checklist for x in candidates])
1504 return 1-(0 in [x in checklist for x in candidates])
1493
1505
1494 #----------------------------------------------------------------------------
1506 #----------------------------------------------------------------------------
1495 def sort_compare(lst1,lst2,inplace = 1):
1507 def sort_compare(lst1,lst2,inplace = 1):
1496 """Sort and compare two lists.
1508 """Sort and compare two lists.
1497
1509
1498 By default it does it in place, thus modifying the lists. Use inplace = 0
1510 By default it does it in place, thus modifying the lists. Use inplace = 0
1499 to avoid that (at the cost of temporary copy creation)."""
1511 to avoid that (at the cost of temporary copy creation)."""
1500 if not inplace:
1512 if not inplace:
1501 lst1 = lst1[:]
1513 lst1 = lst1[:]
1502 lst2 = lst2[:]
1514 lst2 = lst2[:]
1503 lst1.sort(); lst2.sort()
1515 lst1.sort(); lst2.sort()
1504 return lst1 == lst2
1516 return lst1 == lst2
1505
1517
1506 #----------------------------------------------------------------------------
1518 #----------------------------------------------------------------------------
1507 def mkdict(**kwargs):
1519 def mkdict(**kwargs):
1508 """Return a dict from a keyword list.
1520 """Return a dict from a keyword list.
1509
1521
1510 It's just syntactic sugar for making ditcionary creation more convenient:
1522 It's just syntactic sugar for making ditcionary creation more convenient:
1511 # the standard way
1523 # the standard way
1512 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1524 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1513 # a cleaner way
1525 # a cleaner way
1514 >>>data = dict(red=1, green=2, blue=3)
1526 >>>data = dict(red=1, green=2, blue=3)
1515
1527
1516 If you need more than this, look at the Struct() class."""
1528 If you need more than this, look at the Struct() class."""
1517
1529
1518 return kwargs
1530 return kwargs
1519
1531
1520 #----------------------------------------------------------------------------
1532 #----------------------------------------------------------------------------
1521 def list2dict(lst):
1533 def list2dict(lst):
1522 """Takes a list of (key,value) pairs and turns it into a dict."""
1534 """Takes a list of (key,value) pairs and turns it into a dict."""
1523
1535
1524 dic = {}
1536 dic = {}
1525 for k,v in lst: dic[k] = v
1537 for k,v in lst: dic[k] = v
1526 return dic
1538 return dic
1527
1539
1528 #----------------------------------------------------------------------------
1540 #----------------------------------------------------------------------------
1529 def list2dict2(lst,default=''):
1541 def list2dict2(lst,default=''):
1530 """Takes a list and turns it into a dict.
1542 """Takes a list and turns it into a dict.
1531 Much slower than list2dict, but more versatile. This version can take
1543 Much slower than list2dict, but more versatile. This version can take
1532 lists with sublists of arbitrary length (including sclars)."""
1544 lists with sublists of arbitrary length (including sclars)."""
1533
1545
1534 dic = {}
1546 dic = {}
1535 for elem in lst:
1547 for elem in lst:
1536 if type(elem) in (types.ListType,types.TupleType):
1548 if type(elem) in (types.ListType,types.TupleType):
1537 size = len(elem)
1549 size = len(elem)
1538 if size == 0:
1550 if size == 0:
1539 pass
1551 pass
1540 elif size == 1:
1552 elif size == 1:
1541 dic[elem] = default
1553 dic[elem] = default
1542 else:
1554 else:
1543 k,v = elem[0], elem[1:]
1555 k,v = elem[0], elem[1:]
1544 if len(v) == 1: v = v[0]
1556 if len(v) == 1: v = v[0]
1545 dic[k] = v
1557 dic[k] = v
1546 else:
1558 else:
1547 dic[elem] = default
1559 dic[elem] = default
1548 return dic
1560 return dic
1549
1561
1550 #----------------------------------------------------------------------------
1562 #----------------------------------------------------------------------------
1551 def flatten(seq):
1563 def flatten(seq):
1552 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1564 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1553
1565
1554 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1566 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1555
1567
1556 # if the x=0 isn't made, a *global* variable x is left over after calling
1568 # if the x=0 isn't made, a *global* variable x is left over after calling
1557 # this function, with the value of the last element in the return
1569 # this function, with the value of the last element in the return
1558 # list. This does seem like a bug big time to me.
1570 # list. This does seem like a bug big time to me.
1559
1571
1560 # the problem is fixed with the x=0, which seems to force the creation of
1572 # the problem is fixed with the x=0, which seems to force the creation of
1561 # a local name
1573 # a local name
1562
1574
1563 x = 0
1575 x = 0
1564 return [x for subseq in seq for x in subseq]
1576 return [x for subseq in seq for x in subseq]
1565
1577
1566 #----------------------------------------------------------------------------
1578 #----------------------------------------------------------------------------
1567 def get_slice(seq,start=0,stop=None,step=1):
1579 def get_slice(seq,start=0,stop=None,step=1):
1568 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1580 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1569 if stop == None:
1581 if stop == None:
1570 stop = len(seq)
1582 stop = len(seq)
1571 item = lambda i: seq[i]
1583 item = lambda i: seq[i]
1572 return map(item,xrange(start,stop,step))
1584 return map(item,xrange(start,stop,step))
1573
1585
1574 #----------------------------------------------------------------------------
1586 #----------------------------------------------------------------------------
1575 def chop(seq,size):
1587 def chop(seq,size):
1576 """Chop a sequence into chunks of the given size."""
1588 """Chop a sequence into chunks of the given size."""
1577 chunk = lambda i: seq[i:i+size]
1589 chunk = lambda i: seq[i:i+size]
1578 return map(chunk,xrange(0,len(seq),size))
1590 return map(chunk,xrange(0,len(seq),size))
1579
1591
1580 #----------------------------------------------------------------------------
1592 #----------------------------------------------------------------------------
1581 def with(object, **args):
1593 def with(object, **args):
1582 """Set multiple attributes for an object, similar to Pascal's with.
1594 """Set multiple attributes for an object, similar to Pascal's with.
1583
1595
1584 Example:
1596 Example:
1585 with(jim,
1597 with(jim,
1586 born = 1960,
1598 born = 1960,
1587 haircolour = 'Brown',
1599 haircolour = 'Brown',
1588 eyecolour = 'Green')
1600 eyecolour = 'Green')
1589
1601
1590 Credit: Greg Ewing, in
1602 Credit: Greg Ewing, in
1591 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1603 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1592
1604
1593 object.__dict__.update(args)
1605 object.__dict__.update(args)
1594
1606
1595 #----------------------------------------------------------------------------
1607 #----------------------------------------------------------------------------
1596 def setattr_list(obj,alist,nspace = None):
1608 def setattr_list(obj,alist,nspace = None):
1597 """Set a list of attributes for an object taken from a namespace.
1609 """Set a list of attributes for an object taken from a namespace.
1598
1610
1599 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1611 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1600 alist with their values taken from nspace, which must be a dict (something
1612 alist with their values taken from nspace, which must be a dict (something
1601 like locals() will often do) If nspace isn't given, locals() of the
1613 like locals() will often do) If nspace isn't given, locals() of the
1602 *caller* is used, so in most cases you can omit it.
1614 *caller* is used, so in most cases you can omit it.
1603
1615
1604 Note that alist can be given as a string, which will be automatically
1616 Note that alist can be given as a string, which will be automatically
1605 split into a list on whitespace. If given as a list, it must be a list of
1617 split into a list on whitespace. If given as a list, it must be a list of
1606 *strings* (the variable names themselves), not of variables."""
1618 *strings* (the variable names themselves), not of variables."""
1607
1619
1608 # this grabs the local variables from the *previous* call frame -- that is
1620 # this grabs the local variables from the *previous* call frame -- that is
1609 # the locals from the function that called setattr_list().
1621 # the locals from the function that called setattr_list().
1610 # - snipped from weave.inline()
1622 # - snipped from weave.inline()
1611 if nspace is None:
1623 if nspace is None:
1612 call_frame = sys._getframe().f_back
1624 call_frame = sys._getframe().f_back
1613 nspace = call_frame.f_locals
1625 nspace = call_frame.f_locals
1614
1626
1615 if type(alist) in StringTypes:
1627 if type(alist) in StringTypes:
1616 alist = alist.split()
1628 alist = alist.split()
1617 for attr in alist:
1629 for attr in alist:
1618 val = eval(attr,nspace)
1630 val = eval(attr,nspace)
1619 setattr(obj,attr,val)
1631 setattr(obj,attr,val)
1620
1632
1621 #----------------------------------------------------------------------------
1633 #----------------------------------------------------------------------------
1622 def getattr_list(obj,alist,*args):
1634 def getattr_list(obj,alist,*args):
1623 """getattr_list(obj,alist[, default]) -> attribute list.
1635 """getattr_list(obj,alist[, default]) -> attribute list.
1624
1636
1625 Get a list of named attributes for an object. When a default argument is
1637 Get a list of named attributes for an object. When a default argument is
1626 given, it is returned when the attribute doesn't exist; without it, an
1638 given, it is returned when the attribute doesn't exist; without it, an
1627 exception is raised in that case.
1639 exception is raised in that case.
1628
1640
1629 Note that alist can be given as a string, which will be automatically
1641 Note that alist can be given as a string, which will be automatically
1630 split into a list on whitespace. If given as a list, it must be a list of
1642 split into a list on whitespace. If given as a list, it must be a list of
1631 *strings* (the variable names themselves), not of variables."""
1643 *strings* (the variable names themselves), not of variables."""
1632
1644
1633 if type(alist) in StringTypes:
1645 if type(alist) in StringTypes:
1634 alist = alist.split()
1646 alist = alist.split()
1635 if args:
1647 if args:
1636 if len(args)==1:
1648 if len(args)==1:
1637 default = args[0]
1649 default = args[0]
1638 return map(lambda attr: getattr(obj,attr,default),alist)
1650 return map(lambda attr: getattr(obj,attr,default),alist)
1639 else:
1651 else:
1640 raise ValueError,'getattr_list() takes only one optional argument'
1652 raise ValueError,'getattr_list() takes only one optional argument'
1641 else:
1653 else:
1642 return map(lambda attr: getattr(obj,attr),alist)
1654 return map(lambda attr: getattr(obj,attr),alist)
1643
1655
1644 #----------------------------------------------------------------------------
1656 #----------------------------------------------------------------------------
1645 def map_method(method,object_list,*argseq,**kw):
1657 def map_method(method,object_list,*argseq,**kw):
1646 """map_method(method,object_list,*args,**kw) -> list
1658 """map_method(method,object_list,*args,**kw) -> list
1647
1659
1648 Return a list of the results of applying the methods to the items of the
1660 Return a list of the results of applying the methods to the items of the
1649 argument sequence(s). If more than one sequence is given, the method is
1661 argument sequence(s). If more than one sequence is given, the method is
1650 called with an argument list consisting of the corresponding item of each
1662 called with an argument list consisting of the corresponding item of each
1651 sequence. All sequences must be of the same length.
1663 sequence. All sequences must be of the same length.
1652
1664
1653 Keyword arguments are passed verbatim to all objects called.
1665 Keyword arguments are passed verbatim to all objects called.
1654
1666
1655 This is Python code, so it's not nearly as fast as the builtin map()."""
1667 This is Python code, so it's not nearly as fast as the builtin map()."""
1656
1668
1657 out_list = []
1669 out_list = []
1658 idx = 0
1670 idx = 0
1659 for object in object_list:
1671 for object in object_list:
1660 try:
1672 try:
1661 handler = getattr(object, method)
1673 handler = getattr(object, method)
1662 except AttributeError:
1674 except AttributeError:
1663 out_list.append(None)
1675 out_list.append(None)
1664 else:
1676 else:
1665 if argseq:
1677 if argseq:
1666 args = map(lambda lst:lst[idx],argseq)
1678 args = map(lambda lst:lst[idx],argseq)
1667 #print 'ob',object,'hand',handler,'ar',args # dbg
1679 #print 'ob',object,'hand',handler,'ar',args # dbg
1668 out_list.append(handler(args,**kw))
1680 out_list.append(handler(args,**kw))
1669 else:
1681 else:
1670 out_list.append(handler(**kw))
1682 out_list.append(handler(**kw))
1671 idx += 1
1683 idx += 1
1672 return out_list
1684 return out_list
1673
1685
1674 #----------------------------------------------------------------------------
1686 #----------------------------------------------------------------------------
1675 def import_fail_info(mod_name,fns=None):
1687 def import_fail_info(mod_name,fns=None):
1676 """Inform load failure for a module."""
1688 """Inform load failure for a module."""
1677
1689
1678 if fns == None:
1690 if fns == None:
1679 warn("Loading of %s failed.\n" % (mod_name,))
1691 warn("Loading of %s failed.\n" % (mod_name,))
1680 else:
1692 else:
1681 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1693 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1682
1694
1683 #----------------------------------------------------------------------------
1695 #----------------------------------------------------------------------------
1684 # Proposed popitem() extension, written as a method
1696 # Proposed popitem() extension, written as a method
1685
1697
1686 class NotGiven: pass
1698 class NotGiven: pass
1687
1699
1688 def popkey(dct,key,default=NotGiven):
1700 def popkey(dct,key,default=NotGiven):
1689 """Return dct[key] and delete dct[key].
1701 """Return dct[key] and delete dct[key].
1690
1702
1691 If default is given, return it if dct[key] doesn't exist, otherwise raise
1703 If default is given, return it if dct[key] doesn't exist, otherwise raise
1692 KeyError. """
1704 KeyError. """
1693
1705
1694 try:
1706 try:
1695 val = dct[key]
1707 val = dct[key]
1696 except KeyError:
1708 except KeyError:
1697 if default is NotGiven:
1709 if default is NotGiven:
1698 raise
1710 raise
1699 else:
1711 else:
1700 return default
1712 return default
1701 else:
1713 else:
1702 del dct[key]
1714 del dct[key]
1703 return val
1715 return val
1704 #*************************** end of file <genutils.py> **********************
1716 #*************************** end of file <genutils.py> **********************
1705
1717
@@ -1,2138 +1,2153 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 988 2006-01-02 21:21:47Z fperez $
9 $Id: iplib.py 990 2006-01-04 06:59:02Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import tempfile
58 import tempfile
59 import traceback
59 import traceback
60 import types
60 import types
61
61
62 from pprint import pprint, pformat
62 from pprint import pprint, pformat
63
63
64 # IPython's own modules
64 # IPython's own modules
65 import IPython
65 import IPython
66 from IPython import OInspect,PyColorize,ultraTB
66 from IPython import OInspect,PyColorize,ultraTB
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 from IPython.FakeModule import FakeModule
68 from IPython.FakeModule import FakeModule
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 from IPython.Logger import Logger
70 from IPython.Logger import Logger
71 from IPython.Magic import Magic
71 from IPython.Magic import Magic
72 from IPython.Prompts import CachedOutput
72 from IPython.Prompts import CachedOutput
73 from IPython.Struct import Struct
73 from IPython.Struct import Struct
74 from IPython.background_jobs import BackgroundJobManager
74 from IPython.background_jobs import BackgroundJobManager
75 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.usage import cmd_line_usage,interactive_usage
76 from IPython.genutils import *
76 from IPython.genutils import *
77
77
78 # store the builtin raw_input globally, and use this always, in case user code
78 # store the builtin raw_input globally, and use this always, in case user code
79 # overwrites it (like wx.py.PyShell does)
79 # overwrites it (like wx.py.PyShell does)
80 raw_input_original = raw_input
80 raw_input_original = raw_input
81
81
82 # compiled regexps for autoindent management
82 # compiled regexps for autoindent management
83 ini_spaces_re = re.compile(r'^(\s+)')
83 ini_spaces_re = re.compile(r'^(\s+)')
84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85
85
86 #****************************************************************************
86 #****************************************************************************
87 # Some utility function definitions
87 # Some utility function definitions
88
88
89 def softspace(file, newvalue):
89 def softspace(file, newvalue):
90 """Copied from code.py, to remove the dependency"""
90 """Copied from code.py, to remove the dependency"""
91 oldvalue = 0
91 oldvalue = 0
92 try:
92 try:
93 oldvalue = file.softspace
93 oldvalue = file.softspace
94 except AttributeError:
94 except AttributeError:
95 pass
95 pass
96 try:
96 try:
97 file.softspace = newvalue
97 file.softspace = newvalue
98 except (AttributeError, TypeError):
98 except (AttributeError, TypeError):
99 # "attribute-less object" or "read-only attributes"
99 # "attribute-less object" or "read-only attributes"
100 pass
100 pass
101 return oldvalue
101 return oldvalue
102
102
103 #****************************************************************************
103 #****************************************************************************
104
104
105
105
106 #****************************************************************************
106 #****************************************************************************
107 # Local use exceptions
107 # Local use exceptions
108 class SpaceInInput(exceptions.Exception): pass
108 class SpaceInInput(exceptions.Exception): pass
109
109
110 #****************************************************************************
110 #****************************************************************************
111 # Local use classes
111 # Local use classes
112 class Bunch: pass
112 class Bunch: pass
113
113
114 class Undefined: pass
114 class Undefined: pass
115
115
116 class InputList(list):
116 class InputList(list):
117 """Class to store user input.
117 """Class to store user input.
118
118
119 It's basically a list, but slices return a string instead of a list, thus
119 It's basically a list, but slices return a string instead of a list, thus
120 allowing things like (assuming 'In' is an instance):
120 allowing things like (assuming 'In' is an instance):
121
121
122 exec In[4:7]
122 exec In[4:7]
123
123
124 or
124 or
125
125
126 exec In[5:9] + In[14] + In[21:25]"""
126 exec In[5:9] + In[14] + In[21:25]"""
127
127
128 def __getslice__(self,i,j):
128 def __getslice__(self,i,j):
129 return ''.join(list.__getslice__(self,i,j))
129 return ''.join(list.__getslice__(self,i,j))
130
130
131 class SyntaxTB(ultraTB.ListTB):
131 class SyntaxTB(ultraTB.ListTB):
132 """Extension which holds some state: the last exception value"""
132 """Extension which holds some state: the last exception value"""
133
133
134 def __init__(self,color_scheme = 'NoColor'):
134 def __init__(self,color_scheme = 'NoColor'):
135 ultraTB.ListTB.__init__(self,color_scheme)
135 ultraTB.ListTB.__init__(self,color_scheme)
136 self.last_syntax_error = None
136 self.last_syntax_error = None
137
137
138 def __call__(self, etype, value, elist):
138 def __call__(self, etype, value, elist):
139 self.last_syntax_error = value
139 self.last_syntax_error = value
140 ultraTB.ListTB.__call__(self,etype,value,elist)
140 ultraTB.ListTB.__call__(self,etype,value,elist)
141
141
142 def clear_err_state(self):
142 def clear_err_state(self):
143 """Return the current error state and clear it"""
143 """Return the current error state and clear it"""
144 e = self.last_syntax_error
144 e = self.last_syntax_error
145 self.last_syntax_error = None
145 self.last_syntax_error = None
146 return e
146 return e
147
147
148 #****************************************************************************
148 #****************************************************************************
149 # Main IPython class
149 # Main IPython class
150
150
151 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
151 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
152 # until a full rewrite is made. I've cleaned all cross-class uses of
152 # until a full rewrite is made. I've cleaned all cross-class uses of
153 # attributes and methods, but too much user code out there relies on the
153 # attributes and methods, but too much user code out there relies on the
154 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
154 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
155 #
155 #
156 # But at least now, all the pieces have been separated and we could, in
156 # But at least now, all the pieces have been separated and we could, in
157 # principle, stop using the mixin. This will ease the transition to the
157 # principle, stop using the mixin. This will ease the transition to the
158 # chainsaw branch.
158 # chainsaw branch.
159
159
160 # For reference, the following is the list of 'self.foo' uses in the Magic
160 # For reference, the following is the list of 'self.foo' uses in the Magic
161 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
161 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
162 # class, to prevent clashes.
162 # class, to prevent clashes.
163
163
164 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
164 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
165 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
165 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
166 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
166 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
167 # 'self.value']
167 # 'self.value']
168
168
169 class InteractiveShell(object,Magic):
169 class InteractiveShell(object,Magic):
170 """An enhanced console for Python."""
170 """An enhanced console for Python."""
171
171
172 # class attribute to indicate whether the class supports threads or not.
172 # class attribute to indicate whether the class supports threads or not.
173 # Subclasses with thread support should override this as needed.
173 # Subclasses with thread support should override this as needed.
174 isthreaded = False
174 isthreaded = False
175
175
176 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
176 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
177 user_ns = None,user_global_ns=None,banner2='',
177 user_ns = None,user_global_ns=None,banner2='',
178 custom_exceptions=((),None),embedded=False):
178 custom_exceptions=((),None),embedded=False):
179
179
180 # some minimal strict typechecks. For some core data structures, I
180 # some minimal strict typechecks. For some core data structures, I
181 # want actual basic python types, not just anything that looks like
181 # want actual basic python types, not just anything that looks like
182 # one. This is especially true for namespaces.
182 # one. This is especially true for namespaces.
183 for ns in (user_ns,user_global_ns):
183 for ns in (user_ns,user_global_ns):
184 if ns is not None and type(ns) != types.DictType:
184 if ns is not None and type(ns) != types.DictType:
185 raise TypeError,'namespace must be a dictionary'
185 raise TypeError,'namespace must be a dictionary'
186
186
187 # Job manager (for jobs run as background threads)
187 # Job manager (for jobs run as background threads)
188 self.jobs = BackgroundJobManager()
188 self.jobs = BackgroundJobManager()
189
189
190 # track which builtins we add, so we can clean up later
190 # track which builtins we add, so we can clean up later
191 self.builtins_added = {}
191 self.builtins_added = {}
192 # This method will add the necessary builtins for operation, but
192 # This method will add the necessary builtins for operation, but
193 # tracking what it did via the builtins_added dict.
193 # tracking what it did via the builtins_added dict.
194 self.add_builtins()
194 self.add_builtins()
195
195
196 # Do the intuitively correct thing for quit/exit: we remove the
196 # Do the intuitively correct thing for quit/exit: we remove the
197 # builtins if they exist, and our own magics will deal with this
197 # builtins if they exist, and our own magics will deal with this
198 try:
198 try:
199 del __builtin__.exit, __builtin__.quit
199 del __builtin__.exit, __builtin__.quit
200 except AttributeError:
200 except AttributeError:
201 pass
201 pass
202
202
203 # Store the actual shell's name
203 # Store the actual shell's name
204 self.name = name
204 self.name = name
205
205
206 # We need to know whether the instance is meant for embedding, since
206 # We need to know whether the instance is meant for embedding, since
207 # global/local namespaces need to be handled differently in that case
207 # global/local namespaces need to be handled differently in that case
208 self.embedded = embedded
208 self.embedded = embedded
209
209
210 # command compiler
210 # command compiler
211 self.compile = codeop.CommandCompiler()
211 self.compile = codeop.CommandCompiler()
212
212
213 # User input buffer
213 # User input buffer
214 self.buffer = []
214 self.buffer = []
215
215
216 # Default name given in compilation of code
216 # Default name given in compilation of code
217 self.filename = '<ipython console>'
217 self.filename = '<ipython console>'
218
218
219 # Make an empty namespace, which extension writers can rely on both
219 # Make an empty namespace, which extension writers can rely on both
220 # existing and NEVER being used by ipython itself. This gives them a
220 # existing and NEVER being used by ipython itself. This gives them a
221 # convenient location for storing additional information and state
221 # convenient location for storing additional information and state
222 # their extensions may require, without fear of collisions with other
222 # their extensions may require, without fear of collisions with other
223 # ipython names that may develop later.
223 # ipython names that may develop later.
224 self.meta = Bunch()
224 self.meta = Bunch()
225
225
226 # Create the namespace where the user will operate. user_ns is
226 # Create the namespace where the user will operate. user_ns is
227 # normally the only one used, and it is passed to the exec calls as
227 # normally the only one used, and it is passed to the exec calls as
228 # the locals argument. But we do carry a user_global_ns namespace
228 # the locals argument. But we do carry a user_global_ns namespace
229 # given as the exec 'globals' argument, This is useful in embedding
229 # given as the exec 'globals' argument, This is useful in embedding
230 # situations where the ipython shell opens in a context where the
230 # situations where the ipython shell opens in a context where the
231 # distinction between locals and globals is meaningful.
231 # distinction between locals and globals is meaningful.
232
232
233 # FIXME. For some strange reason, __builtins__ is showing up at user
233 # FIXME. For some strange reason, __builtins__ is showing up at user
234 # level as a dict instead of a module. This is a manual fix, but I
234 # level as a dict instead of a module. This is a manual fix, but I
235 # should really track down where the problem is coming from. Alex
235 # should really track down where the problem is coming from. Alex
236 # Schmolck reported this problem first.
236 # Schmolck reported this problem first.
237
237
238 # A useful post by Alex Martelli on this topic:
238 # A useful post by Alex Martelli on this topic:
239 # Re: inconsistent value from __builtins__
239 # Re: inconsistent value from __builtins__
240 # Von: Alex Martelli <aleaxit@yahoo.com>
240 # Von: Alex Martelli <aleaxit@yahoo.com>
241 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
241 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
242 # Gruppen: comp.lang.python
242 # Gruppen: comp.lang.python
243
243
244 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
244 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
245 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
245 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
246 # > <type 'dict'>
246 # > <type 'dict'>
247 # > >>> print type(__builtins__)
247 # > >>> print type(__builtins__)
248 # > <type 'module'>
248 # > <type 'module'>
249 # > Is this difference in return value intentional?
249 # > Is this difference in return value intentional?
250
250
251 # Well, it's documented that '__builtins__' can be either a dictionary
251 # Well, it's documented that '__builtins__' can be either a dictionary
252 # or a module, and it's been that way for a long time. Whether it's
252 # or a module, and it's been that way for a long time. Whether it's
253 # intentional (or sensible), I don't know. In any case, the idea is
253 # intentional (or sensible), I don't know. In any case, the idea is
254 # that if you need to access the built-in namespace directly, you
254 # that if you need to access the built-in namespace directly, you
255 # should start with "import __builtin__" (note, no 's') which will
255 # should start with "import __builtin__" (note, no 's') which will
256 # definitely give you a module. Yeah, it's somewhat confusing:-(.
256 # definitely give you a module. Yeah, it's somewhat confusing:-(.
257
257
258 if user_ns is None:
258 if user_ns is None:
259 # Set __name__ to __main__ to better match the behavior of the
259 # Set __name__ to __main__ to better match the behavior of the
260 # normal interpreter.
260 # normal interpreter.
261 user_ns = {'__name__' :'__main__',
261 user_ns = {'__name__' :'__main__',
262 '__builtins__' : __builtin__,
262 '__builtins__' : __builtin__,
263 }
263 }
264
264
265 if user_global_ns is None:
265 if user_global_ns is None:
266 user_global_ns = {}
266 user_global_ns = {}
267
267
268 # Assign namespaces
268 # Assign namespaces
269 # This is the namespace where all normal user variables live
269 # This is the namespace where all normal user variables live
270 self.user_ns = user_ns
270 self.user_ns = user_ns
271 # Embedded instances require a separate namespace for globals.
271 # Embedded instances require a separate namespace for globals.
272 # Normally this one is unused by non-embedded instances.
272 # Normally this one is unused by non-embedded instances.
273 self.user_global_ns = user_global_ns
273 self.user_global_ns = user_global_ns
274 # A namespace to keep track of internal data structures to prevent
274 # A namespace to keep track of internal data structures to prevent
275 # them from cluttering user-visible stuff. Will be updated later
275 # them from cluttering user-visible stuff. Will be updated later
276 self.internal_ns = {}
276 self.internal_ns = {}
277
277
278 # Namespace of system aliases. Each entry in the alias
278 # Namespace of system aliases. Each entry in the alias
279 # table must be a 2-tuple of the form (N,name), where N is the number
279 # table must be a 2-tuple of the form (N,name), where N is the number
280 # of positional arguments of the alias.
280 # of positional arguments of the alias.
281 self.alias_table = {}
281 self.alias_table = {}
282
282
283 # A table holding all the namespaces IPython deals with, so that
283 # A table holding all the namespaces IPython deals with, so that
284 # introspection facilities can search easily.
284 # introspection facilities can search easily.
285 self.ns_table = {'user':user_ns,
285 self.ns_table = {'user':user_ns,
286 'user_global':user_global_ns,
286 'user_global':user_global_ns,
287 'alias':self.alias_table,
287 'alias':self.alias_table,
288 'internal':self.internal_ns,
288 'internal':self.internal_ns,
289 'builtin':__builtin__.__dict__
289 'builtin':__builtin__.__dict__
290 }
290 }
291
291
292 # The user namespace MUST have a pointer to the shell itself.
292 # The user namespace MUST have a pointer to the shell itself.
293 self.user_ns[name] = self
293 self.user_ns[name] = self
294
294
295 # We need to insert into sys.modules something that looks like a
295 # We need to insert into sys.modules something that looks like a
296 # module but which accesses the IPython namespace, for shelve and
296 # module but which accesses the IPython namespace, for shelve and
297 # pickle to work interactively. Normally they rely on getting
297 # pickle to work interactively. Normally they rely on getting
298 # everything out of __main__, but for embedding purposes each IPython
298 # everything out of __main__, but for embedding purposes each IPython
299 # instance has its own private namespace, so we can't go shoving
299 # instance has its own private namespace, so we can't go shoving
300 # everything into __main__.
300 # everything into __main__.
301
301
302 # note, however, that we should only do this for non-embedded
302 # note, however, that we should only do this for non-embedded
303 # ipythons, which really mimic the __main__.__dict__ with their own
303 # ipythons, which really mimic the __main__.__dict__ with their own
304 # namespace. Embedded instances, on the other hand, should not do
304 # namespace. Embedded instances, on the other hand, should not do
305 # this because they need to manage the user local/global namespaces
305 # this because they need to manage the user local/global namespaces
306 # only, but they live within a 'normal' __main__ (meaning, they
306 # only, but they live within a 'normal' __main__ (meaning, they
307 # shouldn't overtake the execution environment of the script they're
307 # shouldn't overtake the execution environment of the script they're
308 # embedded in).
308 # embedded in).
309
309
310 if not embedded:
310 if not embedded:
311 try:
311 try:
312 main_name = self.user_ns['__name__']
312 main_name = self.user_ns['__name__']
313 except KeyError:
313 except KeyError:
314 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
314 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
315 else:
315 else:
316 #print "pickle hack in place" # dbg
316 #print "pickle hack in place" # dbg
317 #print 'main_name:',main_name # dbg
317 #print 'main_name:',main_name # dbg
318 sys.modules[main_name] = FakeModule(self.user_ns)
318 sys.modules[main_name] = FakeModule(self.user_ns)
319
319
320 # List of input with multi-line handling.
320 # List of input with multi-line handling.
321 # Fill its zero entry, user counter starts at 1
321 # Fill its zero entry, user counter starts at 1
322 self.input_hist = InputList(['\n'])
322 self.input_hist = InputList(['\n'])
323
323
324 # list of visited directories
324 # list of visited directories
325 try:
325 try:
326 self.dir_hist = [os.getcwd()]
326 self.dir_hist = [os.getcwd()]
327 except IOError, e:
327 except IOError, e:
328 self.dir_hist = []
328 self.dir_hist = []
329
329
330 # dict of output history
330 # dict of output history
331 self.output_hist = {}
331 self.output_hist = {}
332
332
333 # dict of things NOT to alias (keywords, builtins and some magics)
333 # dict of things NOT to alias (keywords, builtins and some magics)
334 no_alias = {}
334 no_alias = {}
335 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
335 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
336 for key in keyword.kwlist + no_alias_magics:
336 for key in keyword.kwlist + no_alias_magics:
337 no_alias[key] = 1
337 no_alias[key] = 1
338 no_alias.update(__builtin__.__dict__)
338 no_alias.update(__builtin__.__dict__)
339 self.no_alias = no_alias
339 self.no_alias = no_alias
340
340
341 # make global variables for user access to these
341 # make global variables for user access to these
342 self.user_ns['_ih'] = self.input_hist
342 self.user_ns['_ih'] = self.input_hist
343 self.user_ns['_oh'] = self.output_hist
343 self.user_ns['_oh'] = self.output_hist
344 self.user_ns['_dh'] = self.dir_hist
344 self.user_ns['_dh'] = self.dir_hist
345
345
346 # user aliases to input and output histories
346 # user aliases to input and output histories
347 self.user_ns['In'] = self.input_hist
347 self.user_ns['In'] = self.input_hist
348 self.user_ns['Out'] = self.output_hist
348 self.user_ns['Out'] = self.output_hist
349
349
350 # Object variable to store code object waiting execution. This is
350 # Object variable to store code object waiting execution. This is
351 # used mainly by the multithreaded shells, but it can come in handy in
351 # used mainly by the multithreaded shells, but it can come in handy in
352 # other situations. No need to use a Queue here, since it's a single
352 # other situations. No need to use a Queue here, since it's a single
353 # item which gets cleared once run.
353 # item which gets cleared once run.
354 self.code_to_run = None
354 self.code_to_run = None
355
355
356 # escapes for automatic behavior on the command line
356 # escapes for automatic behavior on the command line
357 self.ESC_SHELL = '!'
357 self.ESC_SHELL = '!'
358 self.ESC_HELP = '?'
358 self.ESC_HELP = '?'
359 self.ESC_MAGIC = '%'
359 self.ESC_MAGIC = '%'
360 self.ESC_QUOTE = ','
360 self.ESC_QUOTE = ','
361 self.ESC_QUOTE2 = ';'
361 self.ESC_QUOTE2 = ';'
362 self.ESC_PAREN = '/'
362 self.ESC_PAREN = '/'
363
363
364 # And their associated handlers
364 # And their associated handlers
365 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
365 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
366 self.ESC_QUOTE : self.handle_auto,
366 self.ESC_QUOTE : self.handle_auto,
367 self.ESC_QUOTE2 : self.handle_auto,
367 self.ESC_QUOTE2 : self.handle_auto,
368 self.ESC_MAGIC : self.handle_magic,
368 self.ESC_MAGIC : self.handle_magic,
369 self.ESC_HELP : self.handle_help,
369 self.ESC_HELP : self.handle_help,
370 self.ESC_SHELL : self.handle_shell_escape,
370 self.ESC_SHELL : self.handle_shell_escape,
371 }
371 }
372
372
373 # class initializations
373 # class initializations
374 Magic.__init__(self,self)
374 Magic.__init__(self,self)
375
375
376 # Python source parser/formatter for syntax highlighting
376 # Python source parser/formatter for syntax highlighting
377 pyformat = PyColorize.Parser().format
377 pyformat = PyColorize.Parser().format
378 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
378 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
379
379
380 # hooks holds pointers used for user-side customizations
380 # hooks holds pointers used for user-side customizations
381 self.hooks = Struct()
381 self.hooks = Struct()
382
382
383 # Set all default hooks, defined in the IPython.hooks module.
383 # Set all default hooks, defined in the IPython.hooks module.
384 hooks = IPython.hooks
384 hooks = IPython.hooks
385 for hook_name in hooks.__all__:
385 for hook_name in hooks.__all__:
386 self.set_hook(hook_name,getattr(hooks,hook_name))
386 self.set_hook(hook_name,getattr(hooks,hook_name))
387
387
388 # Flag to mark unconditional exit
388 # Flag to mark unconditional exit
389 self.exit_now = False
389 self.exit_now = False
390
390
391 self.usage_min = """\
391 self.usage_min = """\
392 An enhanced console for Python.
392 An enhanced console for Python.
393 Some of its features are:
393 Some of its features are:
394 - Readline support if the readline library is present.
394 - Readline support if the readline library is present.
395 - Tab completion in the local namespace.
395 - Tab completion in the local namespace.
396 - Logging of input, see command-line options.
396 - Logging of input, see command-line options.
397 - System shell escape via ! , eg !ls.
397 - System shell escape via ! , eg !ls.
398 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
398 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
399 - Keeps track of locally defined variables via %who, %whos.
399 - Keeps track of locally defined variables via %who, %whos.
400 - Show object information with a ? eg ?x or x? (use ?? for more info).
400 - Show object information with a ? eg ?x or x? (use ?? for more info).
401 """
401 """
402 if usage: self.usage = usage
402 if usage: self.usage = usage
403 else: self.usage = self.usage_min
403 else: self.usage = self.usage_min
404
404
405 # Storage
405 # Storage
406 self.rc = rc # This will hold all configuration information
406 self.rc = rc # This will hold all configuration information
407 self.pager = 'less'
407 self.pager = 'less'
408 # temporary files used for various purposes. Deleted at exit.
408 # temporary files used for various purposes. Deleted at exit.
409 self.tempfiles = []
409 self.tempfiles = []
410
410
411 # Keep track of readline usage (later set by init_readline)
411 # Keep track of readline usage (later set by init_readline)
412 self.has_readline = False
412 self.has_readline = False
413
413
414 # template for logfile headers. It gets resolved at runtime by the
414 # template for logfile headers. It gets resolved at runtime by the
415 # logstart method.
415 # logstart method.
416 self.loghead_tpl = \
416 self.loghead_tpl = \
417 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
417 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
418 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
418 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
419 #log# opts = %s
419 #log# opts = %s
420 #log# args = %s
420 #log# args = %s
421 #log# It is safe to make manual edits below here.
421 #log# It is safe to make manual edits below here.
422 #log#-----------------------------------------------------------------------
422 #log#-----------------------------------------------------------------------
423 """
423 """
424 # for pushd/popd management
424 # for pushd/popd management
425 try:
425 try:
426 self.home_dir = get_home_dir()
426 self.home_dir = get_home_dir()
427 except HomeDirError,msg:
427 except HomeDirError,msg:
428 fatal(msg)
428 fatal(msg)
429
429
430 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
430 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
431
431
432 # Functions to call the underlying shell.
432 # Functions to call the underlying shell.
433
433
434 # utility to expand user variables via Itpl
434 # utility to expand user variables via Itpl
435 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
435 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
436 self.user_ns))
436 self.user_ns))
437 # The first is similar to os.system, but it doesn't return a value,
437 # The first is similar to os.system, but it doesn't return a value,
438 # and it allows interpolation of variables in the user's namespace.
438 # and it allows interpolation of variables in the user's namespace.
439 self.system = lambda cmd: shell(self.var_expand(cmd),
439 self.system = lambda cmd: shell(self.var_expand(cmd),
440 header='IPython system call: ',
440 header='IPython system call: ',
441 verbose=self.rc.system_verbose)
441 verbose=self.rc.system_verbose)
442 # These are for getoutput and getoutputerror:
442 # These are for getoutput and getoutputerror:
443 self.getoutput = lambda cmd: \
443 self.getoutput = lambda cmd: \
444 getoutput(self.var_expand(cmd),
444 getoutput(self.var_expand(cmd),
445 header='IPython system call: ',
445 header='IPython system call: ',
446 verbose=self.rc.system_verbose)
446 verbose=self.rc.system_verbose)
447 self.getoutputerror = lambda cmd: \
447 self.getoutputerror = lambda cmd: \
448 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
448 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
449 self.user_ns)),
449 self.user_ns)),
450 header='IPython system call: ',
450 header='IPython system call: ',
451 verbose=self.rc.system_verbose)
451 verbose=self.rc.system_verbose)
452
452
453 # RegExp for splitting line contents into pre-char//first
453 # RegExp for splitting line contents into pre-char//first
454 # word-method//rest. For clarity, each group in on one line.
454 # word-method//rest. For clarity, each group in on one line.
455
455
456 # WARNING: update the regexp if the above escapes are changed, as they
456 # WARNING: update the regexp if the above escapes are changed, as they
457 # are hardwired in.
457 # are hardwired in.
458
458
459 # Don't get carried away with trying to make the autocalling catch too
459 # Don't get carried away with trying to make the autocalling catch too
460 # much: it's better to be conservative rather than to trigger hidden
460 # much: it's better to be conservative rather than to trigger hidden
461 # evals() somewhere and end up causing side effects.
461 # evals() somewhere and end up causing side effects.
462
462
463 self.line_split = re.compile(r'^([\s*,;/])'
463 self.line_split = re.compile(r'^([\s*,;/])'
464 r'([\?\w\.]+\w*\s*)'
464 r'([\?\w\.]+\w*\s*)'
465 r'(\(?.*$)')
465 r'(\(?.*$)')
466
466
467 # Original re, keep around for a while in case changes break something
467 # Original re, keep around for a while in case changes break something
468 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
468 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
469 # r'(\s*[\?\w\.]+\w*\s*)'
469 # r'(\s*[\?\w\.]+\w*\s*)'
470 # r'(\(?.*$)')
470 # r'(\(?.*$)')
471
471
472 # RegExp to identify potential function names
472 # RegExp to identify potential function names
473 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
473 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
474 # RegExp to exclude strings with this start from autocalling
474 # RegExp to exclude strings with this start from autocalling
475 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
475 self.re_exclude_auto = re.compile('^[!=()\[\]<>,\*/\+-]|^is ')
476
476
477 # try to catch also methods for stuff in lists/tuples/dicts: off
477 # try to catch also methods for stuff in lists/tuples/dicts: off
478 # (experimental). For this to work, the line_split regexp would need
478 # (experimental). For this to work, the line_split regexp would need
479 # to be modified so it wouldn't break things at '['. That line is
479 # to be modified so it wouldn't break things at '['. That line is
480 # nasty enough that I shouldn't change it until I can test it _well_.
480 # nasty enough that I shouldn't change it until I can test it _well_.
481 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
481 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
482
482
483 # keep track of where we started running (mainly for crash post-mortem)
483 # keep track of where we started running (mainly for crash post-mortem)
484 self.starting_dir = os.getcwd()
484 self.starting_dir = os.getcwd()
485
485
486 # Various switches which can be set
486 # Various switches which can be set
487 self.CACHELENGTH = 5000 # this is cheap, it's just text
487 self.CACHELENGTH = 5000 # this is cheap, it's just text
488 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
488 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
489 self.banner2 = banner2
489 self.banner2 = banner2
490
490
491 # TraceBack handlers:
491 # TraceBack handlers:
492
492
493 # Syntax error handler.
493 # Syntax error handler.
494 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
494 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
495
495
496 # The interactive one is initialized with an offset, meaning we always
496 # The interactive one is initialized with an offset, meaning we always
497 # want to remove the topmost item in the traceback, which is our own
497 # want to remove the topmost item in the traceback, which is our own
498 # internal code. Valid modes: ['Plain','Context','Verbose']
498 # internal code. Valid modes: ['Plain','Context','Verbose']
499 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
499 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
500 color_scheme='NoColor',
500 color_scheme='NoColor',
501 tb_offset = 1)
501 tb_offset = 1)
502
502
503 # IPython itself shouldn't crash. This will produce a detailed
503 # IPython itself shouldn't crash. This will produce a detailed
504 # post-mortem if it does. But we only install the crash handler for
504 # post-mortem if it does. But we only install the crash handler for
505 # non-threaded shells, the threaded ones use a normal verbose reporter
505 # non-threaded shells, the threaded ones use a normal verbose reporter
506 # and lose the crash handler. This is because exceptions in the main
506 # and lose the crash handler. This is because exceptions in the main
507 # thread (such as in GUI code) propagate directly to sys.excepthook,
507 # thread (such as in GUI code) propagate directly to sys.excepthook,
508 # and there's no point in printing crash dumps for every user exception.
508 # and there's no point in printing crash dumps for every user exception.
509 if self.isthreaded:
509 if self.isthreaded:
510 sys.excepthook = ultraTB.FormattedTB()
510 sys.excepthook = ultraTB.FormattedTB()
511 else:
511 else:
512 from IPython import CrashHandler
512 from IPython import CrashHandler
513 sys.excepthook = CrashHandler.CrashHandler(self)
513 sys.excepthook = CrashHandler.CrashHandler(self)
514
514
515 # The instance will store a pointer to this, so that runtime code
515 # The instance will store a pointer to this, so that runtime code
516 # (such as magics) can access it. This is because during the
516 # (such as magics) can access it. This is because during the
517 # read-eval loop, it gets temporarily overwritten (to deal with GUI
517 # read-eval loop, it gets temporarily overwritten (to deal with GUI
518 # frameworks).
518 # frameworks).
519 self.sys_excepthook = sys.excepthook
519 self.sys_excepthook = sys.excepthook
520
520
521 # and add any custom exception handlers the user may have specified
521 # and add any custom exception handlers the user may have specified
522 self.set_custom_exc(*custom_exceptions)
522 self.set_custom_exc(*custom_exceptions)
523
523
524 # Object inspector
524 # Object inspector
525 self.inspector = OInspect.Inspector(OInspect.InspectColors,
525 self.inspector = OInspect.Inspector(OInspect.InspectColors,
526 PyColorize.ANSICodeColors,
526 PyColorize.ANSICodeColors,
527 'NoColor')
527 'NoColor')
528 # indentation management
528 # indentation management
529 self.autoindent = False
529 self.autoindent = False
530 self.indent_current_nsp = 0
530 self.indent_current_nsp = 0
531 self.indent_current = '' # actual indent string
531 self.indent_current = '' # actual indent string
532
532
533 # Make some aliases automatically
533 # Make some aliases automatically
534 # Prepare list of shell aliases to auto-define
534 # Prepare list of shell aliases to auto-define
535 if os.name == 'posix':
535 if os.name == 'posix':
536 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
536 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
537 'mv mv -i','rm rm -i','cp cp -i',
537 'mv mv -i','rm rm -i','cp cp -i',
538 'cat cat','less less','clear clear',
538 'cat cat','less less','clear clear',
539 # a better ls
539 # a better ls
540 'ls ls -F',
540 'ls ls -F',
541 # long ls
541 # long ls
542 'll ls -lF',
542 'll ls -lF',
543 # color ls
543 # color ls
544 'lc ls -F -o --color',
544 'lc ls -F -o --color',
545 # ls normal files only
545 # ls normal files only
546 'lf ls -F -o --color %l | grep ^-',
546 'lf ls -F -o --color %l | grep ^-',
547 # ls symbolic links
547 # ls symbolic links
548 'lk ls -F -o --color %l | grep ^l',
548 'lk ls -F -o --color %l | grep ^l',
549 # directories or links to directories,
549 # directories or links to directories,
550 'ldir ls -F -o --color %l | grep /$',
550 'ldir ls -F -o --color %l | grep /$',
551 # things which are executable
551 # things which are executable
552 'lx ls -F -o --color %l | grep ^-..x',
552 'lx ls -F -o --color %l | grep ^-..x',
553 )
553 )
554 elif os.name in ['nt','dos']:
554 elif os.name in ['nt','dos']:
555 auto_alias = ('dir dir /on', 'ls dir /on',
555 auto_alias = ('dir dir /on', 'ls dir /on',
556 'ddir dir /ad /on', 'ldir dir /ad /on',
556 'ddir dir /ad /on', 'ldir dir /ad /on',
557 'mkdir mkdir','rmdir rmdir','echo echo',
557 'mkdir mkdir','rmdir rmdir','echo echo',
558 'ren ren','cls cls','copy copy')
558 'ren ren','cls cls','copy copy')
559 else:
559 else:
560 auto_alias = ()
560 auto_alias = ()
561 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
561 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
562 # Call the actual (public) initializer
562 # Call the actual (public) initializer
563 self.init_auto_alias()
563 self.init_auto_alias()
564 # end __init__
564 # end __init__
565
565
566 def post_config_initialization(self):
566 def post_config_initialization(self):
567 """Post configuration init method
567 """Post configuration init method
568
568
569 This is called after the configuration files have been processed to
569 This is called after the configuration files have been processed to
570 'finalize' the initialization."""
570 'finalize' the initialization."""
571
571
572 rc = self.rc
572 rc = self.rc
573
573
574 # Load readline proper
574 # Load readline proper
575 if rc.readline:
575 if rc.readline:
576 self.init_readline()
576 self.init_readline()
577
577
578 # log system
578 # log system
579 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
579 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
580 # local shortcut, this is used a LOT
580 # local shortcut, this is used a LOT
581 self.log = self.logger.log
581 self.log = self.logger.log
582
582
583 # Initialize cache, set in/out prompts and printing system
583 # Initialize cache, set in/out prompts and printing system
584 self.outputcache = CachedOutput(self,
584 self.outputcache = CachedOutput(self,
585 rc.cache_size,
585 rc.cache_size,
586 rc.pprint,
586 rc.pprint,
587 input_sep = rc.separate_in,
587 input_sep = rc.separate_in,
588 output_sep = rc.separate_out,
588 output_sep = rc.separate_out,
589 output_sep2 = rc.separate_out2,
589 output_sep2 = rc.separate_out2,
590 ps1 = rc.prompt_in1,
590 ps1 = rc.prompt_in1,
591 ps2 = rc.prompt_in2,
591 ps2 = rc.prompt_in2,
592 ps_out = rc.prompt_out,
592 ps_out = rc.prompt_out,
593 pad_left = rc.prompts_pad_left)
593 pad_left = rc.prompts_pad_left)
594
594
595 # user may have over-ridden the default print hook:
595 # user may have over-ridden the default print hook:
596 try:
596 try:
597 self.outputcache.__class__.display = self.hooks.display
597 self.outputcache.__class__.display = self.hooks.display
598 except AttributeError:
598 except AttributeError:
599 pass
599 pass
600
600
601 # I don't like assigning globally to sys, because it means when embedding
601 # I don't like assigning globally to sys, because it means when embedding
602 # instances, each embedded instance overrides the previous choice. But
602 # instances, each embedded instance overrides the previous choice. But
603 # sys.displayhook seems to be called internally by exec, so I don't see a
603 # sys.displayhook seems to be called internally by exec, so I don't see a
604 # way around it.
604 # way around it.
605 sys.displayhook = self.outputcache
605 sys.displayhook = self.outputcache
606
606
607 # Set user colors (don't do it in the constructor above so that it
607 # Set user colors (don't do it in the constructor above so that it
608 # doesn't crash if colors option is invalid)
608 # doesn't crash if colors option is invalid)
609 self.magic_colors(rc.colors)
609 self.magic_colors(rc.colors)
610
610
611 # Set calling of pdb on exceptions
611 # Set calling of pdb on exceptions
612 self.call_pdb = rc.pdb
612 self.call_pdb = rc.pdb
613
613
614 # Load user aliases
614 # Load user aliases
615 for alias in rc.alias:
615 for alias in rc.alias:
616 self.magic_alias(alias)
616 self.magic_alias(alias)
617
617
618 # dynamic data that survives through sessions
618 # dynamic data that survives through sessions
619 # XXX make the filename a config option?
619 # XXX make the filename a config option?
620 persist_base = 'persist'
620 persist_base = 'persist'
621 if rc.profile:
621 if rc.profile:
622 persist_base += '_%s' % rc.profile
622 persist_base += '_%s' % rc.profile
623 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
623 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
624
624
625 try:
625 try:
626 self.persist = pickle.load(file(self.persist_fname))
626 self.persist = pickle.load(file(self.persist_fname))
627 except:
627 except:
628 self.persist = {}
628 self.persist = {}
629
629
630
630
631 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
631 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
632 try:
632 try:
633 obj = pickle.loads(value)
633 obj = pickle.loads(value)
634 except:
634 except:
635
635
636 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
636 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
637 print "The error was:",sys.exc_info()[0]
637 print "The error was:",sys.exc_info()[0]
638 continue
638 continue
639
639
640
640
641 self.user_ns[key] = obj
641 self.user_ns[key] = obj
642
642
643 def add_builtins(self):
643 def add_builtins(self):
644 """Store ipython references into the builtin namespace.
644 """Store ipython references into the builtin namespace.
645
645
646 Some parts of ipython operate via builtins injected here, which hold a
646 Some parts of ipython operate via builtins injected here, which hold a
647 reference to IPython itself."""
647 reference to IPython itself."""
648
648
649 builtins_new = dict(__IPYTHON__ = self,
649 builtins_new = dict(__IPYTHON__ = self,
650 ip_set_hook = self.set_hook,
650 ip_set_hook = self.set_hook,
651 jobs = self.jobs,
651 jobs = self.jobs,
652 ipmagic = self.ipmagic,
652 ipmagic = self.ipmagic,
653 ipalias = self.ipalias,
653 ipalias = self.ipalias,
654 ipsystem = self.ipsystem,
654 ipsystem = self.ipsystem,
655 )
655 )
656 for biname,bival in builtins_new.items():
656 for biname,bival in builtins_new.items():
657 try:
657 try:
658 # store the orignal value so we can restore it
658 # store the orignal value so we can restore it
659 self.builtins_added[biname] = __builtin__.__dict__[biname]
659 self.builtins_added[biname] = __builtin__.__dict__[biname]
660 except KeyError:
660 except KeyError:
661 # or mark that it wasn't defined, and we'll just delete it at
661 # or mark that it wasn't defined, and we'll just delete it at
662 # cleanup
662 # cleanup
663 self.builtins_added[biname] = Undefined
663 self.builtins_added[biname] = Undefined
664 __builtin__.__dict__[biname] = bival
664 __builtin__.__dict__[biname] = bival
665
665
666 # Keep in the builtins a flag for when IPython is active. We set it
666 # Keep in the builtins a flag for when IPython is active. We set it
667 # with setdefault so that multiple nested IPythons don't clobber one
667 # with setdefault so that multiple nested IPythons don't clobber one
668 # another. Each will increase its value by one upon being activated,
668 # another. Each will increase its value by one upon being activated,
669 # which also gives us a way to determine the nesting level.
669 # which also gives us a way to determine the nesting level.
670 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
670 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
671
671
672 def clean_builtins(self):
672 def clean_builtins(self):
673 """Remove any builtins which might have been added by add_builtins, or
673 """Remove any builtins which might have been added by add_builtins, or
674 restore overwritten ones to their previous values."""
674 restore overwritten ones to their previous values."""
675 for biname,bival in self.builtins_added.items():
675 for biname,bival in self.builtins_added.items():
676 if bival is Undefined:
676 if bival is Undefined:
677 del __builtin__.__dict__[biname]
677 del __builtin__.__dict__[biname]
678 else:
678 else:
679 __builtin__.__dict__[biname] = bival
679 __builtin__.__dict__[biname] = bival
680 self.builtins_added.clear()
680 self.builtins_added.clear()
681
681
682 def set_hook(self,name,hook):
682 def set_hook(self,name,hook):
683 """set_hook(name,hook) -> sets an internal IPython hook.
683 """set_hook(name,hook) -> sets an internal IPython hook.
684
684
685 IPython exposes some of its internal API as user-modifiable hooks. By
685 IPython exposes some of its internal API as user-modifiable hooks. By
686 resetting one of these hooks, you can modify IPython's behavior to
686 resetting one of these hooks, you can modify IPython's behavior to
687 call at runtime your own routines."""
687 call at runtime your own routines."""
688
688
689 # At some point in the future, this should validate the hook before it
689 # At some point in the future, this should validate the hook before it
690 # accepts it. Probably at least check that the hook takes the number
690 # accepts it. Probably at least check that the hook takes the number
691 # of args it's supposed to.
691 # of args it's supposed to.
692 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
692 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
693
693
694 def set_custom_exc(self,exc_tuple,handler):
694 def set_custom_exc(self,exc_tuple,handler):
695 """set_custom_exc(exc_tuple,handler)
695 """set_custom_exc(exc_tuple,handler)
696
696
697 Set a custom exception handler, which will be called if any of the
697 Set a custom exception handler, which will be called if any of the
698 exceptions in exc_tuple occur in the mainloop (specifically, in the
698 exceptions in exc_tuple occur in the mainloop (specifically, in the
699 runcode() method.
699 runcode() method.
700
700
701 Inputs:
701 Inputs:
702
702
703 - exc_tuple: a *tuple* of valid exceptions to call the defined
703 - exc_tuple: a *tuple* of valid exceptions to call the defined
704 handler for. It is very important that you use a tuple, and NOT A
704 handler for. It is very important that you use a tuple, and NOT A
705 LIST here, because of the way Python's except statement works. If
705 LIST here, because of the way Python's except statement works. If
706 you only want to trap a single exception, use a singleton tuple:
706 you only want to trap a single exception, use a singleton tuple:
707
707
708 exc_tuple == (MyCustomException,)
708 exc_tuple == (MyCustomException,)
709
709
710 - handler: this must be defined as a function with the following
710 - handler: this must be defined as a function with the following
711 basic interface: def my_handler(self,etype,value,tb).
711 basic interface: def my_handler(self,etype,value,tb).
712
712
713 This will be made into an instance method (via new.instancemethod)
713 This will be made into an instance method (via new.instancemethod)
714 of IPython itself, and it will be called if any of the exceptions
714 of IPython itself, and it will be called if any of the exceptions
715 listed in the exc_tuple are caught. If the handler is None, an
715 listed in the exc_tuple are caught. If the handler is None, an
716 internal basic one is used, which just prints basic info.
716 internal basic one is used, which just prints basic info.
717
717
718 WARNING: by putting in your own exception handler into IPython's main
718 WARNING: by putting in your own exception handler into IPython's main
719 execution loop, you run a very good chance of nasty crashes. This
719 execution loop, you run a very good chance of nasty crashes. This
720 facility should only be used if you really know what you are doing."""
720 facility should only be used if you really know what you are doing."""
721
721
722 assert type(exc_tuple)==type(()) , \
722 assert type(exc_tuple)==type(()) , \
723 "The custom exceptions must be given AS A TUPLE."
723 "The custom exceptions must be given AS A TUPLE."
724
724
725 def dummy_handler(self,etype,value,tb):
725 def dummy_handler(self,etype,value,tb):
726 print '*** Simple custom exception handler ***'
726 print '*** Simple custom exception handler ***'
727 print 'Exception type :',etype
727 print 'Exception type :',etype
728 print 'Exception value:',value
728 print 'Exception value:',value
729 print 'Traceback :',tb
729 print 'Traceback :',tb
730 print 'Source code :','\n'.join(self.buffer)
730 print 'Source code :','\n'.join(self.buffer)
731
731
732 if handler is None: handler = dummy_handler
732 if handler is None: handler = dummy_handler
733
733
734 self.CustomTB = new.instancemethod(handler,self,self.__class__)
734 self.CustomTB = new.instancemethod(handler,self,self.__class__)
735 self.custom_exceptions = exc_tuple
735 self.custom_exceptions = exc_tuple
736
736
737 def set_custom_completer(self,completer,pos=0):
737 def set_custom_completer(self,completer,pos=0):
738 """set_custom_completer(completer,pos=0)
738 """set_custom_completer(completer,pos=0)
739
739
740 Adds a new custom completer function.
740 Adds a new custom completer function.
741
741
742 The position argument (defaults to 0) is the index in the completers
742 The position argument (defaults to 0) is the index in the completers
743 list where you want the completer to be inserted."""
743 list where you want the completer to be inserted."""
744
744
745 newcomp = new.instancemethod(completer,self.Completer,
745 newcomp = new.instancemethod(completer,self.Completer,
746 self.Completer.__class__)
746 self.Completer.__class__)
747 self.Completer.matchers.insert(pos,newcomp)
747 self.Completer.matchers.insert(pos,newcomp)
748
748
749 def _get_call_pdb(self):
749 def _get_call_pdb(self):
750 return self._call_pdb
750 return self._call_pdb
751
751
752 def _set_call_pdb(self,val):
752 def _set_call_pdb(self,val):
753
753
754 if val not in (0,1,False,True):
754 if val not in (0,1,False,True):
755 raise ValueError,'new call_pdb value must be boolean'
755 raise ValueError,'new call_pdb value must be boolean'
756
756
757 # store value in instance
757 # store value in instance
758 self._call_pdb = val
758 self._call_pdb = val
759
759
760 # notify the actual exception handlers
760 # notify the actual exception handlers
761 self.InteractiveTB.call_pdb = val
761 self.InteractiveTB.call_pdb = val
762 if self.isthreaded:
762 if self.isthreaded:
763 try:
763 try:
764 self.sys_excepthook.call_pdb = val
764 self.sys_excepthook.call_pdb = val
765 except:
765 except:
766 warn('Failed to activate pdb for threaded exception handler')
766 warn('Failed to activate pdb for threaded exception handler')
767
767
768 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
768 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
769 'Control auto-activation of pdb at exceptions')
769 'Control auto-activation of pdb at exceptions')
770
770
771
771
772 # These special functions get installed in the builtin namespace, to
772 # These special functions get installed in the builtin namespace, to
773 # provide programmatic (pure python) access to magics, aliases and system
773 # provide programmatic (pure python) access to magics, aliases and system
774 # calls. This is important for logging, user scripting, and more.
774 # calls. This is important for logging, user scripting, and more.
775
775
776 # We are basically exposing, via normal python functions, the three
776 # We are basically exposing, via normal python functions, the three
777 # mechanisms in which ipython offers special call modes (magics for
777 # mechanisms in which ipython offers special call modes (magics for
778 # internal control, aliases for direct system access via pre-selected
778 # internal control, aliases for direct system access via pre-selected
779 # names, and !cmd for calling arbitrary system commands).
779 # names, and !cmd for calling arbitrary system commands).
780
780
781 def ipmagic(self,arg_s):
781 def ipmagic(self,arg_s):
782 """Call a magic function by name.
782 """Call a magic function by name.
783
783
784 Input: a string containing the name of the magic function to call and any
784 Input: a string containing the name of the magic function to call and any
785 additional arguments to be passed to the magic.
785 additional arguments to be passed to the magic.
786
786
787 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
787 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
788 prompt:
788 prompt:
789
789
790 In[1]: %name -opt foo bar
790 In[1]: %name -opt foo bar
791
791
792 To call a magic without arguments, simply use ipmagic('name').
792 To call a magic without arguments, simply use ipmagic('name').
793
793
794 This provides a proper Python function to call IPython's magics in any
794 This provides a proper Python function to call IPython's magics in any
795 valid Python code you can type at the interpreter, including loops and
795 valid Python code you can type at the interpreter, including loops and
796 compound statements. It is added by IPython to the Python builtin
796 compound statements. It is added by IPython to the Python builtin
797 namespace upon initialization."""
797 namespace upon initialization."""
798
798
799 args = arg_s.split(' ',1)
799 args = arg_s.split(' ',1)
800 magic_name = args[0]
800 magic_name = args[0]
801 if magic_name.startswith(self.ESC_MAGIC):
801 if magic_name.startswith(self.ESC_MAGIC):
802 magic_name = magic_name[1:]
802 magic_name = magic_name[1:]
803 try:
803 try:
804 magic_args = args[1]
804 magic_args = args[1]
805 except IndexError:
805 except IndexError:
806 magic_args = ''
806 magic_args = ''
807 fn = getattr(self,'magic_'+magic_name,None)
807 fn = getattr(self,'magic_'+magic_name,None)
808 if fn is None:
808 if fn is None:
809 error("Magic function `%s` not found." % magic_name)
809 error("Magic function `%s` not found." % magic_name)
810 else:
810 else:
811 magic_args = self.var_expand(magic_args)
811 magic_args = self.var_expand(magic_args)
812 return fn(magic_args)
812 return fn(magic_args)
813
813
814 def ipalias(self,arg_s):
814 def ipalias(self,arg_s):
815 """Call an alias by name.
815 """Call an alias by name.
816
816
817 Input: a string containing the name of the alias to call and any
817 Input: a string containing the name of the alias to call and any
818 additional arguments to be passed to the magic.
818 additional arguments to be passed to the magic.
819
819
820 ipalias('name -opt foo bar') is equivalent to typing at the ipython
820 ipalias('name -opt foo bar') is equivalent to typing at the ipython
821 prompt:
821 prompt:
822
822
823 In[1]: name -opt foo bar
823 In[1]: name -opt foo bar
824
824
825 To call an alias without arguments, simply use ipalias('name').
825 To call an alias without arguments, simply use ipalias('name').
826
826
827 This provides a proper Python function to call IPython's aliases in any
827 This provides a proper Python function to call IPython's aliases in any
828 valid Python code you can type at the interpreter, including loops and
828 valid Python code you can type at the interpreter, including loops and
829 compound statements. It is added by IPython to the Python builtin
829 compound statements. It is added by IPython to the Python builtin
830 namespace upon initialization."""
830 namespace upon initialization."""
831
831
832 args = arg_s.split(' ',1)
832 args = arg_s.split(' ',1)
833 alias_name = args[0]
833 alias_name = args[0]
834 try:
834 try:
835 alias_args = args[1]
835 alias_args = args[1]
836 except IndexError:
836 except IndexError:
837 alias_args = ''
837 alias_args = ''
838 if alias_name in self.alias_table:
838 if alias_name in self.alias_table:
839 self.call_alias(alias_name,alias_args)
839 self.call_alias(alias_name,alias_args)
840 else:
840 else:
841 error("Alias `%s` not found." % alias_name)
841 error("Alias `%s` not found." % alias_name)
842
842
843 def ipsystem(self,arg_s):
843 def ipsystem(self,arg_s):
844 """Make a system call, using IPython."""
844 """Make a system call, using IPython."""
845 self.system(arg_s)
845 self.system(arg_s)
846
846
847 def complete(self,text):
847 def complete(self,text):
848 """Return a sorted list of all possible completions on text.
848 """Return a sorted list of all possible completions on text.
849
849
850 Inputs:
850 Inputs:
851
851
852 - text: a string of text to be completed on.
852 - text: a string of text to be completed on.
853
853
854 This is a wrapper around the completion mechanism, similar to what
854 This is a wrapper around the completion mechanism, similar to what
855 readline does at the command line when the TAB key is hit. By
855 readline does at the command line when the TAB key is hit. By
856 exposing it as a method, it can be used by other non-readline
856 exposing it as a method, it can be used by other non-readline
857 environments (such as GUIs) for text completion.
857 environments (such as GUIs) for text completion.
858
858
859 Simple usage example:
859 Simple usage example:
860
860
861 In [1]: x = 'hello'
861 In [1]: x = 'hello'
862
862
863 In [2]: __IP.complete('x.l')
863 In [2]: __IP.complete('x.l')
864 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
864 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
865
865
866 complete = self.Completer.complete
866 complete = self.Completer.complete
867 state = 0
867 state = 0
868 # use a dict so we get unique keys, since ipyhton's multiple
868 # use a dict so we get unique keys, since ipyhton's multiple
869 # completers can return duplicates.
869 # completers can return duplicates.
870 comps = {}
870 comps = {}
871 while True:
871 while True:
872 newcomp = complete(text,state)
872 newcomp = complete(text,state)
873 if newcomp is None:
873 if newcomp is None:
874 break
874 break
875 comps[newcomp] = 1
875 comps[newcomp] = 1
876 state += 1
876 state += 1
877 outcomps = comps.keys()
877 outcomps = comps.keys()
878 outcomps.sort()
878 outcomps.sort()
879 return outcomps
879 return outcomps
880
880
881 def set_completer_frame(self, frame):
881 def set_completer_frame(self, frame):
882 if frame:
882 if frame:
883 self.Completer.namespace = frame.f_locals
883 self.Completer.namespace = frame.f_locals
884 self.Completer.global_namespace = frame.f_globals
884 self.Completer.global_namespace = frame.f_globals
885 else:
885 else:
886 self.Completer.namespace = self.user_ns
886 self.Completer.namespace = self.user_ns
887 self.Completer.global_namespace = self.user_global_ns
887 self.Completer.global_namespace = self.user_global_ns
888
888
889 def init_auto_alias(self):
889 def init_auto_alias(self):
890 """Define some aliases automatically.
890 """Define some aliases automatically.
891
891
892 These are ALL parameter-less aliases"""
892 These are ALL parameter-less aliases"""
893 for alias,cmd in self.auto_alias:
893 for alias,cmd in self.auto_alias:
894 self.alias_table[alias] = (0,cmd)
894 self.alias_table[alias] = (0,cmd)
895
895
896 def alias_table_validate(self,verbose=0):
896 def alias_table_validate(self,verbose=0):
897 """Update information about the alias table.
897 """Update information about the alias table.
898
898
899 In particular, make sure no Python keywords/builtins are in it."""
899 In particular, make sure no Python keywords/builtins are in it."""
900
900
901 no_alias = self.no_alias
901 no_alias = self.no_alias
902 for k in self.alias_table.keys():
902 for k in self.alias_table.keys():
903 if k in no_alias:
903 if k in no_alias:
904 del self.alias_table[k]
904 del self.alias_table[k]
905 if verbose:
905 if verbose:
906 print ("Deleting alias <%s>, it's a Python "
906 print ("Deleting alias <%s>, it's a Python "
907 "keyword or builtin." % k)
907 "keyword or builtin." % k)
908
908
909 def set_autoindent(self,value=None):
909 def set_autoindent(self,value=None):
910 """Set the autoindent flag, checking for readline support.
910 """Set the autoindent flag, checking for readline support.
911
911
912 If called with no arguments, it acts as a toggle."""
912 If called with no arguments, it acts as a toggle."""
913
913
914 if not self.has_readline:
914 if not self.has_readline:
915 if os.name == 'posix':
915 if os.name == 'posix':
916 warn("The auto-indent feature requires the readline library")
916 warn("The auto-indent feature requires the readline library")
917 self.autoindent = 0
917 self.autoindent = 0
918 return
918 return
919 if value is None:
919 if value is None:
920 self.autoindent = not self.autoindent
920 self.autoindent = not self.autoindent
921 else:
921 else:
922 self.autoindent = value
922 self.autoindent = value
923
923
924 def rc_set_toggle(self,rc_field,value=None):
924 def rc_set_toggle(self,rc_field,value=None):
925 """Set or toggle a field in IPython's rc config. structure.
925 """Set or toggle a field in IPython's rc config. structure.
926
926
927 If called with no arguments, it acts as a toggle.
927 If called with no arguments, it acts as a toggle.
928
928
929 If called with a non-existent field, the resulting AttributeError
929 If called with a non-existent field, the resulting AttributeError
930 exception will propagate out."""
930 exception will propagate out."""
931
931
932 rc_val = getattr(self.rc,rc_field)
932 rc_val = getattr(self.rc,rc_field)
933 if value is None:
933 if value is None:
934 value = not rc_val
934 value = not rc_val
935 setattr(self.rc,rc_field,value)
935 setattr(self.rc,rc_field,value)
936
936
937 def user_setup(self,ipythondir,rc_suffix,mode='install'):
937 def user_setup(self,ipythondir,rc_suffix,mode='install'):
938 """Install the user configuration directory.
938 """Install the user configuration directory.
939
939
940 Can be called when running for the first time or to upgrade the user's
940 Can be called when running for the first time or to upgrade the user's
941 .ipython/ directory with the mode parameter. Valid modes are 'install'
941 .ipython/ directory with the mode parameter. Valid modes are 'install'
942 and 'upgrade'."""
942 and 'upgrade'."""
943
943
944 def wait():
944 def wait():
945 try:
945 try:
946 raw_input("Please press <RETURN> to start IPython.")
946 raw_input("Please press <RETURN> to start IPython.")
947 except EOFError:
947 except EOFError:
948 print >> Term.cout
948 print >> Term.cout
949 print '*'*70
949 print '*'*70
950
950
951 cwd = os.getcwd() # remember where we started
951 cwd = os.getcwd() # remember where we started
952 glb = glob.glob
952 glb = glob.glob
953 print '*'*70
953 print '*'*70
954 if mode == 'install':
954 if mode == 'install':
955 print \
955 print \
956 """Welcome to IPython. I will try to create a personal configuration directory
956 """Welcome to IPython. I will try to create a personal configuration directory
957 where you can customize many aspects of IPython's functionality in:\n"""
957 where you can customize many aspects of IPython's functionality in:\n"""
958 else:
958 else:
959 print 'I am going to upgrade your configuration in:'
959 print 'I am going to upgrade your configuration in:'
960
960
961 print ipythondir
961 print ipythondir
962
962
963 rcdirend = os.path.join('IPython','UserConfig')
963 rcdirend = os.path.join('IPython','UserConfig')
964 cfg = lambda d: os.path.join(d,rcdirend)
964 cfg = lambda d: os.path.join(d,rcdirend)
965 try:
965 try:
966 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
966 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
967 except IOError:
967 except IOError:
968 warning = """
968 warning = """
969 Installation error. IPython's directory was not found.
969 Installation error. IPython's directory was not found.
970
970
971 Check the following:
971 Check the following:
972
972
973 The ipython/IPython directory should be in a directory belonging to your
973 The ipython/IPython directory should be in a directory belonging to your
974 PYTHONPATH environment variable (that is, it should be in a directory
974 PYTHONPATH environment variable (that is, it should be in a directory
975 belonging to sys.path). You can copy it explicitly there or just link to it.
975 belonging to sys.path). You can copy it explicitly there or just link to it.
976
976
977 IPython will proceed with builtin defaults.
977 IPython will proceed with builtin defaults.
978 """
978 """
979 warn(warning)
979 warn(warning)
980 wait()
980 wait()
981 return
981 return
982
982
983 if mode == 'install':
983 if mode == 'install':
984 try:
984 try:
985 shutil.copytree(rcdir,ipythondir)
985 shutil.copytree(rcdir,ipythondir)
986 os.chdir(ipythondir)
986 os.chdir(ipythondir)
987 rc_files = glb("ipythonrc*")
987 rc_files = glb("ipythonrc*")
988 for rc_file in rc_files:
988 for rc_file in rc_files:
989 os.rename(rc_file,rc_file+rc_suffix)
989 os.rename(rc_file,rc_file+rc_suffix)
990 except:
990 except:
991 warning = """
991 warning = """
992
992
993 There was a problem with the installation:
993 There was a problem with the installation:
994 %s
994 %s
995 Try to correct it or contact the developers if you think it's a bug.
995 Try to correct it or contact the developers if you think it's a bug.
996 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
996 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
997 warn(warning)
997 warn(warning)
998 wait()
998 wait()
999 return
999 return
1000
1000
1001 elif mode == 'upgrade':
1001 elif mode == 'upgrade':
1002 try:
1002 try:
1003 os.chdir(ipythondir)
1003 os.chdir(ipythondir)
1004 except:
1004 except:
1005 print """
1005 print """
1006 Can not upgrade: changing to directory %s failed. Details:
1006 Can not upgrade: changing to directory %s failed. Details:
1007 %s
1007 %s
1008 """ % (ipythondir,sys.exc_info()[1])
1008 """ % (ipythondir,sys.exc_info()[1])
1009 wait()
1009 wait()
1010 return
1010 return
1011 else:
1011 else:
1012 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1012 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1013 for new_full_path in sources:
1013 for new_full_path in sources:
1014 new_filename = os.path.basename(new_full_path)
1014 new_filename = os.path.basename(new_full_path)
1015 if new_filename.startswith('ipythonrc'):
1015 if new_filename.startswith('ipythonrc'):
1016 new_filename = new_filename + rc_suffix
1016 new_filename = new_filename + rc_suffix
1017 # The config directory should only contain files, skip any
1017 # The config directory should only contain files, skip any
1018 # directories which may be there (like CVS)
1018 # directories which may be there (like CVS)
1019 if os.path.isdir(new_full_path):
1019 if os.path.isdir(new_full_path):
1020 continue
1020 continue
1021 if os.path.exists(new_filename):
1021 if os.path.exists(new_filename):
1022 old_file = new_filename+'.old'
1022 old_file = new_filename+'.old'
1023 if os.path.exists(old_file):
1023 if os.path.exists(old_file):
1024 os.remove(old_file)
1024 os.remove(old_file)
1025 os.rename(new_filename,old_file)
1025 os.rename(new_filename,old_file)
1026 shutil.copy(new_full_path,new_filename)
1026 shutil.copy(new_full_path,new_filename)
1027 else:
1027 else:
1028 raise ValueError,'unrecognized mode for install:',`mode`
1028 raise ValueError,'unrecognized mode for install:',`mode`
1029
1029
1030 # Fix line-endings to those native to each platform in the config
1030 # Fix line-endings to those native to each platform in the config
1031 # directory.
1031 # directory.
1032 try:
1032 try:
1033 os.chdir(ipythondir)
1033 os.chdir(ipythondir)
1034 except:
1034 except:
1035 print """
1035 print """
1036 Problem: changing to directory %s failed.
1036 Problem: changing to directory %s failed.
1037 Details:
1037 Details:
1038 %s
1038 %s
1039
1039
1040 Some configuration files may have incorrect line endings. This should not
1040 Some configuration files may have incorrect line endings. This should not
1041 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1041 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1042 wait()
1042 wait()
1043 else:
1043 else:
1044 for fname in glb('ipythonrc*'):
1044 for fname in glb('ipythonrc*'):
1045 try:
1045 try:
1046 native_line_ends(fname,backup=0)
1046 native_line_ends(fname,backup=0)
1047 except IOError:
1047 except IOError:
1048 pass
1048 pass
1049
1049
1050 if mode == 'install':
1050 if mode == 'install':
1051 print """
1051 print """
1052 Successful installation!
1052 Successful installation!
1053
1053
1054 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1054 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1055 IPython manual (there are both HTML and PDF versions supplied with the
1055 IPython manual (there are both HTML and PDF versions supplied with the
1056 distribution) to make sure that your system environment is properly configured
1056 distribution) to make sure that your system environment is properly configured
1057 to take advantage of IPython's features."""
1057 to take advantage of IPython's features."""
1058 else:
1058 else:
1059 print """
1059 print """
1060 Successful upgrade!
1060 Successful upgrade!
1061
1061
1062 All files in your directory:
1062 All files in your directory:
1063 %(ipythondir)s
1063 %(ipythondir)s
1064 which would have been overwritten by the upgrade were backed up with a .old
1064 which would have been overwritten by the upgrade were backed up with a .old
1065 extension. If you had made particular customizations in those files you may
1065 extension. If you had made particular customizations in those files you may
1066 want to merge them back into the new files.""" % locals()
1066 want to merge them back into the new files.""" % locals()
1067 wait()
1067 wait()
1068 os.chdir(cwd)
1068 os.chdir(cwd)
1069 # end user_setup()
1069 # end user_setup()
1070
1070
1071 def atexit_operations(self):
1071 def atexit_operations(self):
1072 """This will be executed at the time of exit.
1072 """This will be executed at the time of exit.
1073
1073
1074 Saving of persistent data should be performed here. """
1074 Saving of persistent data should be performed here. """
1075
1075
1076 # input history
1076 # input history
1077 self.savehist()
1077 self.savehist()
1078
1078
1079 # Cleanup all tempfiles left around
1079 # Cleanup all tempfiles left around
1080 for tfile in self.tempfiles:
1080 for tfile in self.tempfiles:
1081 try:
1081 try:
1082 os.unlink(tfile)
1082 os.unlink(tfile)
1083 except OSError:
1083 except OSError:
1084 pass
1084 pass
1085
1085
1086 # save the "persistent data" catch-all dictionary
1086 # save the "persistent data" catch-all dictionary
1087 try:
1087 try:
1088 pickle.dump(self.persist, open(self.persist_fname,"w"))
1088 pickle.dump(self.persist, open(self.persist_fname,"w"))
1089 except:
1089 except:
1090 print "*** ERROR *** persistent data saving failed."
1090 print "*** ERROR *** persistent data saving failed."
1091
1091
1092 def savehist(self):
1092 def savehist(self):
1093 """Save input history to a file (via readline library)."""
1093 """Save input history to a file (via readline library)."""
1094 try:
1094 try:
1095 self.readline.write_history_file(self.histfile)
1095 self.readline.write_history_file(self.histfile)
1096 except:
1096 except:
1097 print 'Unable to save IPython command history to file: ' + \
1097 print 'Unable to save IPython command history to file: ' + \
1098 `self.histfile`
1098 `self.histfile`
1099
1099
1100 def pre_readline(self):
1100 def pre_readline(self):
1101 """readline hook to be used at the start of each line.
1101 """readline hook to be used at the start of each line.
1102
1102
1103 Currently it handles auto-indent only."""
1103 Currently it handles auto-indent only."""
1104
1104
1105 self.readline.insert_text(self.indent_current)
1105 self.readline.insert_text(self.indent_current)
1106
1106
1107 def init_readline(self):
1107 def init_readline(self):
1108 """Command history completion/saving/reloading."""
1108 """Command history completion/saving/reloading."""
1109 try:
1109 try:
1110 import readline
1110 import readline
1111 except ImportError:
1111 except ImportError:
1112 self.has_readline = 0
1112 self.has_readline = 0
1113 self.readline = None
1113 self.readline = None
1114 # no point in bugging windows users with this every time:
1114 # no point in bugging windows users with this every time:
1115 if os.name == 'posix':
1115 if os.name == 'posix':
1116 warn('Readline services not available on this platform.')
1116 warn('Readline services not available on this platform.')
1117 else:
1117 else:
1118 import atexit
1118 import atexit
1119 from IPython.completer import IPCompleter
1119 from IPython.completer import IPCompleter
1120 self.Completer = IPCompleter(self,
1120 self.Completer = IPCompleter(self,
1121 self.user_ns,
1121 self.user_ns,
1122 self.user_global_ns,
1122 self.user_global_ns,
1123 self.rc.readline_omit__names,
1123 self.rc.readline_omit__names,
1124 self.alias_table)
1124 self.alias_table)
1125
1125
1126 # Platform-specific configuration
1126 # Platform-specific configuration
1127 if os.name == 'nt':
1127 if os.name == 'nt':
1128 self.readline_startup_hook = readline.set_pre_input_hook
1128 self.readline_startup_hook = readline.set_pre_input_hook
1129 else:
1129 else:
1130 self.readline_startup_hook = readline.set_startup_hook
1130 self.readline_startup_hook = readline.set_startup_hook
1131
1131
1132 # Load user's initrc file (readline config)
1132 # Load user's initrc file (readline config)
1133 inputrc_name = os.environ.get('INPUTRC')
1133 inputrc_name = os.environ.get('INPUTRC')
1134 if inputrc_name is None:
1134 if inputrc_name is None:
1135 home_dir = get_home_dir()
1135 home_dir = get_home_dir()
1136 if home_dir is not None:
1136 if home_dir is not None:
1137 inputrc_name = os.path.join(home_dir,'.inputrc')
1137 inputrc_name = os.path.join(home_dir,'.inputrc')
1138 if os.path.isfile(inputrc_name):
1138 if os.path.isfile(inputrc_name):
1139 try:
1139 try:
1140 readline.read_init_file(inputrc_name)
1140 readline.read_init_file(inputrc_name)
1141 except:
1141 except:
1142 warn('Problems reading readline initialization file <%s>'
1142 warn('Problems reading readline initialization file <%s>'
1143 % inputrc_name)
1143 % inputrc_name)
1144
1144
1145 self.has_readline = 1
1145 self.has_readline = 1
1146 self.readline = readline
1146 self.readline = readline
1147 # save this in sys so embedded copies can restore it properly
1147 # save this in sys so embedded copies can restore it properly
1148 sys.ipcompleter = self.Completer.complete
1148 sys.ipcompleter = self.Completer.complete
1149 readline.set_completer(self.Completer.complete)
1149 readline.set_completer(self.Completer.complete)
1150
1150
1151 # Configure readline according to user's prefs
1151 # Configure readline according to user's prefs
1152 for rlcommand in self.rc.readline_parse_and_bind:
1152 for rlcommand in self.rc.readline_parse_and_bind:
1153 readline.parse_and_bind(rlcommand)
1153 readline.parse_and_bind(rlcommand)
1154
1154
1155 # remove some chars from the delimiters list
1155 # remove some chars from the delimiters list
1156 delims = readline.get_completer_delims()
1156 delims = readline.get_completer_delims()
1157 delims = delims.translate(string._idmap,
1157 delims = delims.translate(string._idmap,
1158 self.rc.readline_remove_delims)
1158 self.rc.readline_remove_delims)
1159 readline.set_completer_delims(delims)
1159 readline.set_completer_delims(delims)
1160 # otherwise we end up with a monster history after a while:
1160 # otherwise we end up with a monster history after a while:
1161 readline.set_history_length(1000)
1161 readline.set_history_length(1000)
1162 try:
1162 try:
1163 #print '*** Reading readline history' # dbg
1163 #print '*** Reading readline history' # dbg
1164 readline.read_history_file(self.histfile)
1164 readline.read_history_file(self.histfile)
1165 except IOError:
1165 except IOError:
1166 pass # It doesn't exist yet.
1166 pass # It doesn't exist yet.
1167
1167
1168 atexit.register(self.atexit_operations)
1168 atexit.register(self.atexit_operations)
1169 del atexit
1169 del atexit
1170
1170
1171 # Configure auto-indent for all platforms
1171 # Configure auto-indent for all platforms
1172 self.set_autoindent(self.rc.autoindent)
1172 self.set_autoindent(self.rc.autoindent)
1173
1173
1174 def _should_recompile(self,e):
1174 def _should_recompile(self,e):
1175 """Utility routine for edit_syntax_error"""
1175 """Utility routine for edit_syntax_error"""
1176
1176
1177 if e.filename in ('<ipython console>','<input>','<string>',
1177 if e.filename in ('<ipython console>','<input>','<string>',
1178 '<console>'):
1178 '<console>'):
1179 return False
1179 return False
1180 try:
1180 try:
1181 if not ask_yes_no('Return to editor to correct syntax error? '
1181 if not ask_yes_no('Return to editor to correct syntax error? '
1182 '[Y/n] ','y'):
1182 '[Y/n] ','y'):
1183 return False
1183 return False
1184 except EOFError:
1184 except EOFError:
1185 return False
1185 return False
1186 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1186 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1187 return True
1187 return True
1188
1188
1189 def edit_syntax_error(self):
1189 def edit_syntax_error(self):
1190 """The bottom half of the syntax error handler called in the main loop.
1190 """The bottom half of the syntax error handler called in the main loop.
1191
1191
1192 Loop until syntax error is fixed or user cancels.
1192 Loop until syntax error is fixed or user cancels.
1193 """
1193 """
1194
1194
1195 while self.SyntaxTB.last_syntax_error:
1195 while self.SyntaxTB.last_syntax_error:
1196 # copy and clear last_syntax_error
1196 # copy and clear last_syntax_error
1197 err = self.SyntaxTB.clear_err_state()
1197 err = self.SyntaxTB.clear_err_state()
1198 if not self._should_recompile(err):
1198 if not self._should_recompile(err):
1199 return
1199 return
1200 try:
1200 try:
1201 # may set last_syntax_error again if a SyntaxError is raised
1201 # may set last_syntax_error again if a SyntaxError is raised
1202 self.safe_execfile(err.filename,self.shell.user_ns)
1202 self.safe_execfile(err.filename,self.shell.user_ns)
1203 except:
1203 except:
1204 self.showtraceback()
1204 self.showtraceback()
1205 else:
1205 else:
1206 f = file(err.filename)
1206 f = file(err.filename)
1207 try:
1207 try:
1208 sys.displayhook(f.read())
1208 sys.displayhook(f.read())
1209 finally:
1209 finally:
1210 f.close()
1210 f.close()
1211
1211
1212 def showsyntaxerror(self, filename=None):
1212 def showsyntaxerror(self, filename=None):
1213 """Display the syntax error that just occurred.
1213 """Display the syntax error that just occurred.
1214
1214
1215 This doesn't display a stack trace because there isn't one.
1215 This doesn't display a stack trace because there isn't one.
1216
1216
1217 If a filename is given, it is stuffed in the exception instead
1217 If a filename is given, it is stuffed in the exception instead
1218 of what was there before (because Python's parser always uses
1218 of what was there before (because Python's parser always uses
1219 "<string>" when reading from a string).
1219 "<string>" when reading from a string).
1220 """
1220 """
1221 etype, value, last_traceback = sys.exc_info()
1221 etype, value, last_traceback = sys.exc_info()
1222 if filename and etype is SyntaxError:
1222 if filename and etype is SyntaxError:
1223 # Work hard to stuff the correct filename in the exception
1223 # Work hard to stuff the correct filename in the exception
1224 try:
1224 try:
1225 msg, (dummy_filename, lineno, offset, line) = value
1225 msg, (dummy_filename, lineno, offset, line) = value
1226 except:
1226 except:
1227 # Not the format we expect; leave it alone
1227 # Not the format we expect; leave it alone
1228 pass
1228 pass
1229 else:
1229 else:
1230 # Stuff in the right filename
1230 # Stuff in the right filename
1231 try:
1231 try:
1232 # Assume SyntaxError is a class exception
1232 # Assume SyntaxError is a class exception
1233 value = SyntaxError(msg, (filename, lineno, offset, line))
1233 value = SyntaxError(msg, (filename, lineno, offset, line))
1234 except:
1234 except:
1235 # If that failed, assume SyntaxError is a string
1235 # If that failed, assume SyntaxError is a string
1236 value = msg, (filename, lineno, offset, line)
1236 value = msg, (filename, lineno, offset, line)
1237 self.SyntaxTB(etype,value,[])
1237 self.SyntaxTB(etype,value,[])
1238
1238
1239 def debugger(self):
1239 def debugger(self):
1240 """Call the pdb debugger."""
1240 """Call the pdb debugger."""
1241
1241
1242 if not self.rc.pdb:
1242 if not self.rc.pdb:
1243 return
1243 return
1244 pdb.pm()
1244 pdb.pm()
1245
1245
1246 def showtraceback(self,exc_tuple = None,filename=None):
1246 def showtraceback(self,exc_tuple = None,filename=None):
1247 """Display the exception that just occurred."""
1247 """Display the exception that just occurred."""
1248
1248
1249 # Though this won't be called by syntax errors in the input line,
1249 # Though this won't be called by syntax errors in the input line,
1250 # there may be SyntaxError cases whith imported code.
1250 # there may be SyntaxError cases whith imported code.
1251 if exc_tuple is None:
1251 if exc_tuple is None:
1252 type, value, tb = sys.exc_info()
1252 type, value, tb = sys.exc_info()
1253 else:
1253 else:
1254 type, value, tb = exc_tuple
1254 type, value, tb = exc_tuple
1255 if type is SyntaxError:
1255 if type is SyntaxError:
1256 self.showsyntaxerror(filename)
1256 self.showsyntaxerror(filename)
1257 else:
1257 else:
1258 self.InteractiveTB()
1258 self.InteractiveTB()
1259 if self.InteractiveTB.call_pdb and self.has_readline:
1259 if self.InteractiveTB.call_pdb and self.has_readline:
1260 # pdb mucks up readline, fix it back
1260 # pdb mucks up readline, fix it back
1261 self.readline.set_completer(self.Completer.complete)
1261 self.readline.set_completer(self.Completer.complete)
1262
1262
1263 def mainloop(self,banner=None):
1263 def mainloop(self,banner=None):
1264 """Creates the local namespace and starts the mainloop.
1264 """Creates the local namespace and starts the mainloop.
1265
1265
1266 If an optional banner argument is given, it will override the
1266 If an optional banner argument is given, it will override the
1267 internally created default banner."""
1267 internally created default banner."""
1268
1268
1269 if self.rc.c: # Emulate Python's -c option
1269 if self.rc.c: # Emulate Python's -c option
1270 self.exec_init_cmd()
1270 self.exec_init_cmd()
1271 if banner is None:
1271 if banner is None:
1272 if self.rc.banner:
1272 if self.rc.banner:
1273 banner = self.BANNER+self.banner2
1273 banner = self.BANNER+self.banner2
1274 else:
1274 else:
1275 banner = ''
1275 banner = ''
1276 self.interact(banner)
1276 self.interact(banner)
1277
1277
1278 def exec_init_cmd(self):
1278 def exec_init_cmd(self):
1279 """Execute a command given at the command line.
1279 """Execute a command given at the command line.
1280
1280
1281 This emulates Python's -c option."""
1281 This emulates Python's -c option."""
1282
1282
1283 sys.argv = ['-c']
1283 sys.argv = ['-c']
1284 self.push(self.rc.c)
1284 self.push(self.rc.c)
1285
1285
1286 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1286 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1287 """Embeds IPython into a running python program.
1287 """Embeds IPython into a running python program.
1288
1288
1289 Input:
1289 Input:
1290
1290
1291 - header: An optional header message can be specified.
1291 - header: An optional header message can be specified.
1292
1292
1293 - local_ns, global_ns: working namespaces. If given as None, the
1293 - local_ns, global_ns: working namespaces. If given as None, the
1294 IPython-initialized one is updated with __main__.__dict__, so that
1294 IPython-initialized one is updated with __main__.__dict__, so that
1295 program variables become visible but user-specific configuration
1295 program variables become visible but user-specific configuration
1296 remains possible.
1296 remains possible.
1297
1297
1298 - stack_depth: specifies how many levels in the stack to go to
1298 - stack_depth: specifies how many levels in the stack to go to
1299 looking for namespaces (when local_ns and global_ns are None). This
1299 looking for namespaces (when local_ns and global_ns are None). This
1300 allows an intermediate caller to make sure that this function gets
1300 allows an intermediate caller to make sure that this function gets
1301 the namespace from the intended level in the stack. By default (0)
1301 the namespace from the intended level in the stack. By default (0)
1302 it will get its locals and globals from the immediate caller.
1302 it will get its locals and globals from the immediate caller.
1303
1303
1304 Warning: it's possible to use this in a program which is being run by
1304 Warning: it's possible to use this in a program which is being run by
1305 IPython itself (via %run), but some funny things will happen (a few
1305 IPython itself (via %run), but some funny things will happen (a few
1306 globals get overwritten). In the future this will be cleaned up, as
1306 globals get overwritten). In the future this will be cleaned up, as
1307 there is no fundamental reason why it can't work perfectly."""
1307 there is no fundamental reason why it can't work perfectly."""
1308
1308
1309 # Get locals and globals from caller
1309 # Get locals and globals from caller
1310 if local_ns is None or global_ns is None:
1310 if local_ns is None or global_ns is None:
1311 call_frame = sys._getframe(stack_depth).f_back
1311 call_frame = sys._getframe(stack_depth).f_back
1312
1312
1313 if local_ns is None:
1313 if local_ns is None:
1314 local_ns = call_frame.f_locals
1314 local_ns = call_frame.f_locals
1315 if global_ns is None:
1315 if global_ns is None:
1316 global_ns = call_frame.f_globals
1316 global_ns = call_frame.f_globals
1317
1317
1318 # Update namespaces and fire up interpreter
1318 # Update namespaces and fire up interpreter
1319
1319
1320 # The global one is easy, we can just throw it in
1320 # The global one is easy, we can just throw it in
1321 self.user_global_ns = global_ns
1321 self.user_global_ns = global_ns
1322
1322
1323 # but the user/local one is tricky: ipython needs it to store internal
1323 # but the user/local one is tricky: ipython needs it to store internal
1324 # data, but we also need the locals. We'll copy locals in the user
1324 # data, but we also need the locals. We'll copy locals in the user
1325 # one, but will track what got copied so we can delete them at exit.
1325 # one, but will track what got copied so we can delete them at exit.
1326 # This is so that a later embedded call doesn't see locals from a
1326 # This is so that a later embedded call doesn't see locals from a
1327 # previous call (which most likely existed in a separate scope).
1327 # previous call (which most likely existed in a separate scope).
1328 local_varnames = local_ns.keys()
1328 local_varnames = local_ns.keys()
1329 self.user_ns.update(local_ns)
1329 self.user_ns.update(local_ns)
1330
1330
1331 # Patch for global embedding to make sure that things don't overwrite
1331 # Patch for global embedding to make sure that things don't overwrite
1332 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1332 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1333 # FIXME. Test this a bit more carefully (the if.. is new)
1333 # FIXME. Test this a bit more carefully (the if.. is new)
1334 if local_ns is None and global_ns is None:
1334 if local_ns is None and global_ns is None:
1335 self.user_global_ns.update(__main__.__dict__)
1335 self.user_global_ns.update(__main__.__dict__)
1336
1336
1337 # make sure the tab-completer has the correct frame information, so it
1337 # make sure the tab-completer has the correct frame information, so it
1338 # actually completes using the frame's locals/globals
1338 # actually completes using the frame's locals/globals
1339 self.set_completer_frame(call_frame)
1339 self.set_completer_frame(call_frame)
1340
1340
1341 # before activating the interactive mode, we need to make sure that
1341 # before activating the interactive mode, we need to make sure that
1342 # all names in the builtin namespace needed by ipython point to
1342 # all names in the builtin namespace needed by ipython point to
1343 # ourselves, and not to other instances.
1343 # ourselves, and not to other instances.
1344 self.add_builtins()
1344 self.add_builtins()
1345
1345
1346 self.interact(header)
1346 self.interact(header)
1347
1347
1348 # now, purge out the user namespace from anything we might have added
1348 # now, purge out the user namespace from anything we might have added
1349 # from the caller's local namespace
1349 # from the caller's local namespace
1350 delvar = self.user_ns.pop
1350 delvar = self.user_ns.pop
1351 for var in local_varnames:
1351 for var in local_varnames:
1352 delvar(var,None)
1352 delvar(var,None)
1353 # and clean builtins we may have overridden
1353 # and clean builtins we may have overridden
1354 self.clean_builtins()
1354 self.clean_builtins()
1355
1355
1356 def interact(self, banner=None):
1356 def interact(self, banner=None):
1357 """Closely emulate the interactive Python console.
1357 """Closely emulate the interactive Python console.
1358
1358
1359 The optional banner argument specify the banner to print
1359 The optional banner argument specify the banner to print
1360 before the first interaction; by default it prints a banner
1360 before the first interaction; by default it prints a banner
1361 similar to the one printed by the real Python interpreter,
1361 similar to the one printed by the real Python interpreter,
1362 followed by the current class name in parentheses (so as not
1362 followed by the current class name in parentheses (so as not
1363 to confuse this with the real interpreter -- since it's so
1363 to confuse this with the real interpreter -- since it's so
1364 close!).
1364 close!).
1365
1365
1366 """
1366 """
1367 cprt = 'Type "copyright", "credits" or "license" for more information.'
1367 cprt = 'Type "copyright", "credits" or "license" for more information.'
1368 if banner is None:
1368 if banner is None:
1369 self.write("Python %s on %s\n%s\n(%s)\n" %
1369 self.write("Python %s on %s\n%s\n(%s)\n" %
1370 (sys.version, sys.platform, cprt,
1370 (sys.version, sys.platform, cprt,
1371 self.__class__.__name__))
1371 self.__class__.__name__))
1372 else:
1372 else:
1373 self.write(banner)
1373 self.write(banner)
1374
1374
1375 more = 0
1375 more = 0
1376
1376
1377 # Mark activity in the builtins
1377 # Mark activity in the builtins
1378 __builtin__.__dict__['__IPYTHON__active'] += 1
1378 __builtin__.__dict__['__IPYTHON__active'] += 1
1379
1379
1380 # exit_now is set by a call to %Exit or %Quit
1380 # exit_now is set by a call to %Exit or %Quit
1381 self.exit_now = False
1381 self.exit_now = False
1382 while not self.exit_now:
1382 while not self.exit_now:
1383
1383
1384 try:
1384 try:
1385 if more:
1385 if more:
1386 prompt = self.outputcache.prompt2
1386 prompt = self.outputcache.prompt2
1387 if self.autoindent:
1387 if self.autoindent:
1388 self.readline_startup_hook(self.pre_readline)
1388 self.readline_startup_hook(self.pre_readline)
1389 else:
1389 else:
1390 prompt = self.outputcache.prompt1
1390 prompt = self.outputcache.prompt1
1391 try:
1391 try:
1392 line = self.raw_input(prompt,more)
1392 line = self.raw_input(prompt,more)
1393 if self.autoindent:
1393 if self.autoindent:
1394 self.readline_startup_hook(None)
1394 self.readline_startup_hook(None)
1395 except EOFError:
1395 except EOFError:
1396 if self.autoindent:
1396 if self.autoindent:
1397 self.readline_startup_hook(None)
1397 self.readline_startup_hook(None)
1398 self.write("\n")
1398 self.write("\n")
1399 self.exit()
1399 self.exit()
1400 else:
1400 else:
1401 more = self.push(line)
1401 more = self.push(line)
1402
1402
1403 if (self.SyntaxTB.last_syntax_error and
1403 if (self.SyntaxTB.last_syntax_error and
1404 self.rc.autoedit_syntax):
1404 self.rc.autoedit_syntax):
1405 self.edit_syntax_error()
1405 self.edit_syntax_error()
1406
1406
1407 except KeyboardInterrupt:
1407 except KeyboardInterrupt:
1408 self.write("\nKeyboardInterrupt\n")
1408 self.write("\nKeyboardInterrupt\n")
1409 self.resetbuffer()
1409 self.resetbuffer()
1410 more = 0
1410 more = 0
1411 # keep cache in sync with the prompt counter:
1411 # keep cache in sync with the prompt counter:
1412 self.outputcache.prompt_count -= 1
1412 self.outputcache.prompt_count -= 1
1413
1413
1414 if self.autoindent:
1414 if self.autoindent:
1415 self.indent_current_nsp = 0
1415 self.indent_current_nsp = 0
1416 self.indent_current = ' '* self.indent_current_nsp
1416 self.indent_current = ' '* self.indent_current_nsp
1417
1417
1418 except bdb.BdbQuit:
1418 except bdb.BdbQuit:
1419 warn("The Python debugger has exited with a BdbQuit exception.\n"
1419 warn("The Python debugger has exited with a BdbQuit exception.\n"
1420 "Because of how pdb handles the stack, it is impossible\n"
1420 "Because of how pdb handles the stack, it is impossible\n"
1421 "for IPython to properly format this particular exception.\n"
1421 "for IPython to properly format this particular exception.\n"
1422 "IPython will resume normal operation.")
1422 "IPython will resume normal operation.")
1423
1423
1424 # We are off again...
1424 # We are off again...
1425 __builtin__.__dict__['__IPYTHON__active'] -= 1
1425 __builtin__.__dict__['__IPYTHON__active'] -= 1
1426
1426
1427 def excepthook(self, type, value, tb):
1427 def excepthook(self, type, value, tb):
1428 """One more defense for GUI apps that call sys.excepthook.
1428 """One more defense for GUI apps that call sys.excepthook.
1429
1429
1430 GUI frameworks like wxPython trap exceptions and call
1430 GUI frameworks like wxPython trap exceptions and call
1431 sys.excepthook themselves. I guess this is a feature that
1431 sys.excepthook themselves. I guess this is a feature that
1432 enables them to keep running after exceptions that would
1432 enables them to keep running after exceptions that would
1433 otherwise kill their mainloop. This is a bother for IPython
1433 otherwise kill their mainloop. This is a bother for IPython
1434 which excepts to catch all of the program exceptions with a try:
1434 which excepts to catch all of the program exceptions with a try:
1435 except: statement.
1435 except: statement.
1436
1436
1437 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1437 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1438 any app directly invokes sys.excepthook, it will look to the user like
1438 any app directly invokes sys.excepthook, it will look to the user like
1439 IPython crashed. In order to work around this, we can disable the
1439 IPython crashed. In order to work around this, we can disable the
1440 CrashHandler and replace it with this excepthook instead, which prints a
1440 CrashHandler and replace it with this excepthook instead, which prints a
1441 regular traceback using our InteractiveTB. In this fashion, apps which
1441 regular traceback using our InteractiveTB. In this fashion, apps which
1442 call sys.excepthook will generate a regular-looking exception from
1442 call sys.excepthook will generate a regular-looking exception from
1443 IPython, and the CrashHandler will only be triggered by real IPython
1443 IPython, and the CrashHandler will only be triggered by real IPython
1444 crashes.
1444 crashes.
1445
1445
1446 This hook should be used sparingly, only in places which are not likely
1446 This hook should be used sparingly, only in places which are not likely
1447 to be true IPython errors.
1447 to be true IPython errors.
1448 """
1448 """
1449
1449
1450 self.InteractiveTB(type, value, tb, tb_offset=0)
1450 self.InteractiveTB(type, value, tb, tb_offset=0)
1451 if self.InteractiveTB.call_pdb and self.has_readline:
1451 if self.InteractiveTB.call_pdb and self.has_readline:
1452 self.readline.set_completer(self.Completer.complete)
1452 self.readline.set_completer(self.Completer.complete)
1453
1453
1454 def call_alias(self,alias,rest=''):
1454 def call_alias(self,alias,rest=''):
1455 """Call an alias given its name and the rest of the line.
1455 """Call an alias given its name and the rest of the line.
1456
1456
1457 This function MUST be given a proper alias, because it doesn't make
1457 This function MUST be given a proper alias, because it doesn't make
1458 any checks when looking up into the alias table. The caller is
1458 any checks when looking up into the alias table. The caller is
1459 responsible for invoking it only with a valid alias."""
1459 responsible for invoking it only with a valid alias."""
1460
1460
1461 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1461 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1462 nargs,cmd = self.alias_table[alias]
1462 nargs,cmd = self.alias_table[alias]
1463 # Expand the %l special to be the user's input line
1463 # Expand the %l special to be the user's input line
1464 if cmd.find('%l') >= 0:
1464 if cmd.find('%l') >= 0:
1465 cmd = cmd.replace('%l',rest)
1465 cmd = cmd.replace('%l',rest)
1466 rest = ''
1466 rest = ''
1467 if nargs==0:
1467 if nargs==0:
1468 # Simple, argument-less aliases
1468 # Simple, argument-less aliases
1469 cmd = '%s %s' % (cmd,rest)
1469 cmd = '%s %s' % (cmd,rest)
1470 else:
1470 else:
1471 # Handle aliases with positional arguments
1471 # Handle aliases with positional arguments
1472 args = rest.split(None,nargs)
1472 args = rest.split(None,nargs)
1473 if len(args)< nargs:
1473 if len(args)< nargs:
1474 error('Alias <%s> requires %s arguments, %s given.' %
1474 error('Alias <%s> requires %s arguments, %s given.' %
1475 (alias,nargs,len(args)))
1475 (alias,nargs,len(args)))
1476 return
1476 return
1477 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1477 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1478 # Now call the macro, evaluating in the user's namespace
1478 # Now call the macro, evaluating in the user's namespace
1479 try:
1479 try:
1480 self.system(cmd)
1480 self.system(cmd)
1481 except:
1481 except:
1482 self.showtraceback()
1482 self.showtraceback()
1483
1483
1484 def autoindent_update(self,line):
1484 def autoindent_update(self,line):
1485 """Keep track of the indent level."""
1485 """Keep track of the indent level."""
1486 if self.autoindent:
1486 if self.autoindent:
1487 if line:
1487 if line:
1488 ini_spaces = ini_spaces_re.match(line)
1488 ini_spaces = ini_spaces_re.match(line)
1489 if ini_spaces:
1489 if ini_spaces:
1490 nspaces = ini_spaces.end()
1490 nspaces = ini_spaces.end()
1491 else:
1491 else:
1492 nspaces = 0
1492 nspaces = 0
1493 self.indent_current_nsp = nspaces
1493 self.indent_current_nsp = nspaces
1494
1494
1495 if line[-1] == ':':
1495 if line[-1] == ':':
1496 self.indent_current_nsp += 4
1496 self.indent_current_nsp += 4
1497 elif dedent_re.match(line):
1497 elif dedent_re.match(line):
1498 self.indent_current_nsp -= 4
1498 self.indent_current_nsp -= 4
1499 else:
1499 else:
1500 self.indent_current_nsp = 0
1500 self.indent_current_nsp = 0
1501
1501
1502 # indent_current is the actual string to be inserted
1502 # indent_current is the actual string to be inserted
1503 # by the readline hooks for indentation
1503 # by the readline hooks for indentation
1504 self.indent_current = ' '* self.indent_current_nsp
1504 self.indent_current = ' '* self.indent_current_nsp
1505
1505
1506 def runlines(self,lines):
1506 def runlines(self,lines):
1507 """Run a string of one or more lines of source.
1507 """Run a string of one or more lines of source.
1508
1508
1509 This method is capable of running a string containing multiple source
1509 This method is capable of running a string containing multiple source
1510 lines, as if they had been entered at the IPython prompt. Since it
1510 lines, as if they had been entered at the IPython prompt. Since it
1511 exposes IPython's processing machinery, the given strings can contain
1511 exposes IPython's processing machinery, the given strings can contain
1512 magic calls (%magic), special shell access (!cmd), etc."""
1512 magic calls (%magic), special shell access (!cmd), etc."""
1513
1513
1514 # We must start with a clean buffer, in case this is run from an
1514 # We must start with a clean buffer, in case this is run from an
1515 # interactive IPython session (via a magic, for example).
1515 # interactive IPython session (via a magic, for example).
1516 self.resetbuffer()
1516 self.resetbuffer()
1517 lines = lines.split('\n')
1517 lines = lines.split('\n')
1518 more = 0
1518 more = 0
1519 for line in lines:
1519 for line in lines:
1520 # skip blank lines so we don't mess up the prompt counter, but do
1520 # skip blank lines so we don't mess up the prompt counter, but do
1521 # NOT skip even a blank line if we are in a code block (more is
1521 # NOT skip even a blank line if we are in a code block (more is
1522 # true)
1522 # true)
1523 if line or more:
1523 if line or more:
1524 more = self.push(self.prefilter(line,more))
1524 more = self.push(self.prefilter(line,more))
1525 # IPython's runsource returns None if there was an error
1525 # IPython's runsource returns None if there was an error
1526 # compiling the code. This allows us to stop processing right
1526 # compiling the code. This allows us to stop processing right
1527 # away, so the user gets the error message at the right place.
1527 # away, so the user gets the error message at the right place.
1528 if more is None:
1528 if more is None:
1529 break
1529 break
1530 # final newline in case the input didn't have it, so that the code
1530 # final newline in case the input didn't have it, so that the code
1531 # actually does get executed
1531 # actually does get executed
1532 if more:
1532 if more:
1533 self.push('\n')
1533 self.push('\n')
1534
1534
1535 def runsource(self, source, filename='<input>', symbol='single'):
1535 def runsource(self, source, filename='<input>', symbol='single'):
1536 """Compile and run some source in the interpreter.
1536 """Compile and run some source in the interpreter.
1537
1537
1538 Arguments are as for compile_command().
1538 Arguments are as for compile_command().
1539
1539
1540 One several things can happen:
1540 One several things can happen:
1541
1541
1542 1) The input is incorrect; compile_command() raised an
1542 1) The input is incorrect; compile_command() raised an
1543 exception (SyntaxError or OverflowError). A syntax traceback
1543 exception (SyntaxError or OverflowError). A syntax traceback
1544 will be printed by calling the showsyntaxerror() method.
1544 will be printed by calling the showsyntaxerror() method.
1545
1545
1546 2) The input is incomplete, and more input is required;
1546 2) The input is incomplete, and more input is required;
1547 compile_command() returned None. Nothing happens.
1547 compile_command() returned None. Nothing happens.
1548
1548
1549 3) The input is complete; compile_command() returned a code
1549 3) The input is complete; compile_command() returned a code
1550 object. The code is executed by calling self.runcode() (which
1550 object. The code is executed by calling self.runcode() (which
1551 also handles run-time exceptions, except for SystemExit).
1551 also handles run-time exceptions, except for SystemExit).
1552
1552
1553 The return value is:
1553 The return value is:
1554
1554
1555 - True in case 2
1555 - True in case 2
1556
1556
1557 - False in the other cases, unless an exception is raised, where
1557 - False in the other cases, unless an exception is raised, where
1558 None is returned instead. This can be used by external callers to
1558 None is returned instead. This can be used by external callers to
1559 know whether to continue feeding input or not.
1559 know whether to continue feeding input or not.
1560
1560
1561 The return value can be used to decide whether to use sys.ps1 or
1561 The return value can be used to decide whether to use sys.ps1 or
1562 sys.ps2 to prompt the next line."""
1562 sys.ps2 to prompt the next line."""
1563
1563
1564 try:
1564 try:
1565 code = self.compile(source,filename,symbol)
1565 code = self.compile(source,filename,symbol)
1566 except (OverflowError, SyntaxError, ValueError):
1566 except (OverflowError, SyntaxError, ValueError):
1567 # Case 1
1567 # Case 1
1568 self.showsyntaxerror(filename)
1568 self.showsyntaxerror(filename)
1569 return None
1569 return None
1570
1570
1571 if code is None:
1571 if code is None:
1572 # Case 2
1572 # Case 2
1573 return True
1573 return True
1574
1574
1575 # Case 3
1575 # Case 3
1576 # We store the code object so that threaded shells and
1576 # We store the code object so that threaded shells and
1577 # custom exception handlers can access all this info if needed.
1577 # custom exception handlers can access all this info if needed.
1578 # The source corresponding to this can be obtained from the
1578 # The source corresponding to this can be obtained from the
1579 # buffer attribute as '\n'.join(self.buffer).
1579 # buffer attribute as '\n'.join(self.buffer).
1580 self.code_to_run = code
1580 self.code_to_run = code
1581 # now actually execute the code object
1581 # now actually execute the code object
1582 if self.runcode(code) == 0:
1582 if self.runcode(code) == 0:
1583 return False
1583 return False
1584 else:
1584 else:
1585 return None
1585 return None
1586
1586
1587 def runcode(self,code_obj):
1587 def runcode(self,code_obj):
1588 """Execute a code object.
1588 """Execute a code object.
1589
1589
1590 When an exception occurs, self.showtraceback() is called to display a
1590 When an exception occurs, self.showtraceback() is called to display a
1591 traceback.
1591 traceback.
1592
1592
1593 Return value: a flag indicating whether the code to be run completed
1593 Return value: a flag indicating whether the code to be run completed
1594 successfully:
1594 successfully:
1595
1595
1596 - 0: successful execution.
1596 - 0: successful execution.
1597 - 1: an error occurred.
1597 - 1: an error occurred.
1598 """
1598 """
1599
1599
1600 # Set our own excepthook in case the user code tries to call it
1600 # Set our own excepthook in case the user code tries to call it
1601 # directly, so that the IPython crash handler doesn't get triggered
1601 # directly, so that the IPython crash handler doesn't get triggered
1602 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1602 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1603
1603
1604 # we save the original sys.excepthook in the instance, in case config
1604 # we save the original sys.excepthook in the instance, in case config
1605 # code (such as magics) needs access to it.
1605 # code (such as magics) needs access to it.
1606 self.sys_excepthook = old_excepthook
1606 self.sys_excepthook = old_excepthook
1607 outflag = 1 # happens in more places, so it's easier as default
1607 outflag = 1 # happens in more places, so it's easier as default
1608 try:
1608 try:
1609 try:
1609 try:
1610 # Embedded instances require separate global/local namespaces
1610 # Embedded instances require separate global/local namespaces
1611 # so they can see both the surrounding (local) namespace and
1611 # so they can see both the surrounding (local) namespace and
1612 # the module-level globals when called inside another function.
1612 # the module-level globals when called inside another function.
1613 if self.embedded:
1613 if self.embedded:
1614 exec code_obj in self.user_global_ns, self.user_ns
1614 exec code_obj in self.user_global_ns, self.user_ns
1615 # Normal (non-embedded) instances should only have a single
1615 # Normal (non-embedded) instances should only have a single
1616 # namespace for user code execution, otherwise functions won't
1616 # namespace for user code execution, otherwise functions won't
1617 # see interactive top-level globals.
1617 # see interactive top-level globals.
1618 else:
1618 else:
1619 exec code_obj in self.user_ns
1619 exec code_obj in self.user_ns
1620 finally:
1620 finally:
1621 # Reset our crash handler in place
1621 # Reset our crash handler in place
1622 sys.excepthook = old_excepthook
1622 sys.excepthook = old_excepthook
1623 except SystemExit:
1623 except SystemExit:
1624 self.resetbuffer()
1624 self.resetbuffer()
1625 self.showtraceback()
1625 self.showtraceback()
1626 warn("Type exit or quit to exit IPython "
1626 warn("Type exit or quit to exit IPython "
1627 "(%Exit or %Quit do so unconditionally).",level=1)
1627 "(%Exit or %Quit do so unconditionally).",level=1)
1628 except self.custom_exceptions:
1628 except self.custom_exceptions:
1629 etype,value,tb = sys.exc_info()
1629 etype,value,tb = sys.exc_info()
1630 self.CustomTB(etype,value,tb)
1630 self.CustomTB(etype,value,tb)
1631 except:
1631 except:
1632 self.showtraceback()
1632 self.showtraceback()
1633 else:
1633 else:
1634 outflag = 0
1634 outflag = 0
1635 if softspace(sys.stdout, 0):
1635 if softspace(sys.stdout, 0):
1636 print
1636 print
1637 # Flush out code object which has been run (and source)
1637 # Flush out code object which has been run (and source)
1638 self.code_to_run = None
1638 self.code_to_run = None
1639 return outflag
1639 return outflag
1640
1640
1641 def push(self, line):
1641 def push(self, line):
1642 """Push a line to the interpreter.
1642 """Push a line to the interpreter.
1643
1643
1644 The line should not have a trailing newline; it may have
1644 The line should not have a trailing newline; it may have
1645 internal newlines. The line is appended to a buffer and the
1645 internal newlines. The line is appended to a buffer and the
1646 interpreter's runsource() method is called with the
1646 interpreter's runsource() method is called with the
1647 concatenated contents of the buffer as source. If this
1647 concatenated contents of the buffer as source. If this
1648 indicates that the command was executed or invalid, the buffer
1648 indicates that the command was executed or invalid, the buffer
1649 is reset; otherwise, the command is incomplete, and the buffer
1649 is reset; otherwise, the command is incomplete, and the buffer
1650 is left as it was after the line was appended. The return
1650 is left as it was after the line was appended. The return
1651 value is 1 if more input is required, 0 if the line was dealt
1651 value is 1 if more input is required, 0 if the line was dealt
1652 with in some way (this is the same as runsource()).
1652 with in some way (this is the same as runsource()).
1653 """
1653 """
1654
1654
1655 # autoindent management should be done here, and not in the
1655 # autoindent management should be done here, and not in the
1656 # interactive loop, since that one is only seen by keyboard input. We
1656 # interactive loop, since that one is only seen by keyboard input. We
1657 # need this done correctly even for code run via runlines (which uses
1657 # need this done correctly even for code run via runlines (which uses
1658 # push).
1658 # push).
1659
1659
1660 #print 'push line: <%s>' % line # dbg
1660 #print 'push line: <%s>' % line # dbg
1661 self.autoindent_update(line)
1661 self.autoindent_update(line)
1662
1662
1663 self.buffer.append(line)
1663 self.buffer.append(line)
1664 more = self.runsource('\n'.join(self.buffer), self.filename)
1664 more = self.runsource('\n'.join(self.buffer), self.filename)
1665 if not more:
1665 if not more:
1666 self.resetbuffer()
1666 self.resetbuffer()
1667 return more
1667 return more
1668
1668
1669 def resetbuffer(self):
1669 def resetbuffer(self):
1670 """Reset the input buffer."""
1670 """Reset the input buffer."""
1671 self.buffer[:] = []
1671 self.buffer[:] = []
1672
1672
1673 def raw_input(self,prompt='',continue_prompt=False):
1673 def raw_input(self,prompt='',continue_prompt=False):
1674 """Write a prompt and read a line.
1674 """Write a prompt and read a line.
1675
1675
1676 The returned line does not include the trailing newline.
1676 The returned line does not include the trailing newline.
1677 When the user enters the EOF key sequence, EOFError is raised.
1677 When the user enters the EOF key sequence, EOFError is raised.
1678
1678
1679 Optional inputs:
1679 Optional inputs:
1680
1680
1681 - prompt(''): a string to be printed to prompt the user.
1681 - prompt(''): a string to be printed to prompt the user.
1682
1682
1683 - continue_prompt(False): whether this line is the first one or a
1683 - continue_prompt(False): whether this line is the first one or a
1684 continuation in a sequence of inputs.
1684 continuation in a sequence of inputs.
1685 """
1685 """
1686
1686
1687 line = raw_input_original(prompt)
1687 line = raw_input_original(prompt)
1688 # Try to be reasonably smart about not re-indenting pasted input more
1688 # Try to be reasonably smart about not re-indenting pasted input more
1689 # than necessary. We do this by trimming out the auto-indent initial
1689 # than necessary. We do this by trimming out the auto-indent initial
1690 # spaces, if the user's actual input started itself with whitespace.
1690 # spaces, if the user's actual input started itself with whitespace.
1691 if self.autoindent:
1691 if self.autoindent:
1692 line2 = line[self.indent_current_nsp:]
1692 line2 = line[self.indent_current_nsp:]
1693 if line2[0:1] in (' ','\t'):
1693 if line2[0:1] in (' ','\t'):
1694 line = line2
1694 line = line2
1695 return self.prefilter(line,continue_prompt)
1695 return self.prefilter(line,continue_prompt)
1696
1696
1697 def split_user_input(self,line):
1697 def split_user_input(self,line):
1698 """Split user input into pre-char, function part and rest."""
1698 """Split user input into pre-char, function part and rest."""
1699
1699
1700 lsplit = self.line_split.match(line)
1700 lsplit = self.line_split.match(line)
1701 if lsplit is None: # no regexp match returns None
1701 if lsplit is None: # no regexp match returns None
1702 try:
1702 try:
1703 iFun,theRest = line.split(None,1)
1703 iFun,theRest = line.split(None,1)
1704 except ValueError:
1704 except ValueError:
1705 iFun,theRest = line,''
1705 iFun,theRest = line,''
1706 pre = re.match('^(\s*)(.*)',line).groups()[0]
1706 pre = re.match('^(\s*)(.*)',line).groups()[0]
1707 else:
1707 else:
1708 pre,iFun,theRest = lsplit.groups()
1708 pre,iFun,theRest = lsplit.groups()
1709
1709
1710 #print 'line:<%s>' % line # dbg
1710 #print 'line:<%s>' % line # dbg
1711 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1711 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1712 return pre,iFun.strip(),theRest
1712 return pre,iFun.strip(),theRest
1713
1713
1714 def _prefilter(self, line, continue_prompt):
1714 def _prefilter(self, line, continue_prompt):
1715 """Calls different preprocessors, depending on the form of line."""
1715 """Calls different preprocessors, depending on the form of line."""
1716
1716
1717 # All handlers *must* return a value, even if it's blank ('').
1717 # All handlers *must* return a value, even if it's blank ('').
1718
1718
1719 # Lines are NOT logged here. Handlers should process the line as
1719 # Lines are NOT logged here. Handlers should process the line as
1720 # needed, update the cache AND log it (so that the input cache array
1720 # needed, update the cache AND log it (so that the input cache array
1721 # stays synced).
1721 # stays synced).
1722
1722
1723 # This function is _very_ delicate, and since it's also the one which
1723 # This function is _very_ delicate, and since it's also the one which
1724 # determines IPython's response to user input, it must be as efficient
1724 # determines IPython's response to user input, it must be as efficient
1725 # as possible. For this reason it has _many_ returns in it, trying
1725 # as possible. For this reason it has _many_ returns in it, trying
1726 # always to exit as quickly as it can figure out what it needs to do.
1726 # always to exit as quickly as it can figure out what it needs to do.
1727
1727
1728 # This function is the main responsible for maintaining IPython's
1728 # This function is the main responsible for maintaining IPython's
1729 # behavior respectful of Python's semantics. So be _very_ careful if
1729 # behavior respectful of Python's semantics. So be _very_ careful if
1730 # making changes to anything here.
1730 # making changes to anything here.
1731
1731
1732 #.....................................................................
1732 #.....................................................................
1733 # Code begins
1733 # Code begins
1734
1734
1735 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1735 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1736
1736
1737 # save the line away in case we crash, so the post-mortem handler can
1737 # save the line away in case we crash, so the post-mortem handler can
1738 # record it
1738 # record it
1739 self._last_input_line = line
1739 self._last_input_line = line
1740
1740
1741 #print '***line: <%s>' % line # dbg
1741 #print '***line: <%s>' % line # dbg
1742
1742
1743 # the input history needs to track even empty lines
1743 # the input history needs to track even empty lines
1744 if not line.strip():
1744 if not line.strip():
1745 if not continue_prompt:
1745 if not continue_prompt:
1746 self.outputcache.prompt_count -= 1
1746 self.outputcache.prompt_count -= 1
1747 return self.handle_normal(line,continue_prompt)
1747 return self.handle_normal(line,continue_prompt)
1748 #return self.handle_normal('',continue_prompt)
1748 #return self.handle_normal('',continue_prompt)
1749
1749
1750 # print '***cont',continue_prompt # dbg
1750 # print '***cont',continue_prompt # dbg
1751 # special handlers are only allowed for single line statements
1751 # special handlers are only allowed for single line statements
1752 if continue_prompt and not self.rc.multi_line_specials:
1752 if continue_prompt and not self.rc.multi_line_specials:
1753 return self.handle_normal(line,continue_prompt)
1753 return self.handle_normal(line,continue_prompt)
1754
1754
1755 # For the rest, we need the structure of the input
1755 # For the rest, we need the structure of the input
1756 pre,iFun,theRest = self.split_user_input(line)
1756 pre,iFun,theRest = self.split_user_input(line)
1757 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1757 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1758
1758
1759 # First check for explicit escapes in the last/first character
1759 # First check for explicit escapes in the last/first character
1760 handler = None
1760 handler = None
1761 if line[-1] == self.ESC_HELP:
1761 if line[-1] == self.ESC_HELP:
1762 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1762 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1763 if handler is None:
1763 if handler is None:
1764 # look at the first character of iFun, NOT of line, so we skip
1764 # look at the first character of iFun, NOT of line, so we skip
1765 # leading whitespace in multiline input
1765 # leading whitespace in multiline input
1766 handler = self.esc_handlers.get(iFun[0:1])
1766 handler = self.esc_handlers.get(iFun[0:1])
1767 if handler is not None:
1767 if handler is not None:
1768 return handler(line,continue_prompt,pre,iFun,theRest)
1768 return handler(line,continue_prompt,pre,iFun,theRest)
1769 # Emacs ipython-mode tags certain input lines
1769 # Emacs ipython-mode tags certain input lines
1770 if line.endswith('# PYTHON-MODE'):
1770 if line.endswith('# PYTHON-MODE'):
1771 return self.handle_emacs(line,continue_prompt)
1771 return self.handle_emacs(line,continue_prompt)
1772
1772
1773 # Next, check if we can automatically execute this thing
1773 # Next, check if we can automatically execute this thing
1774
1774
1775 # Allow ! in multi-line statements if multi_line_specials is on:
1775 # Allow ! in multi-line statements if multi_line_specials is on:
1776 if continue_prompt and self.rc.multi_line_specials and \
1776 if continue_prompt and self.rc.multi_line_specials and \
1777 iFun.startswith(self.ESC_SHELL):
1777 iFun.startswith(self.ESC_SHELL):
1778 return self.handle_shell_escape(line,continue_prompt,
1778 return self.handle_shell_escape(line,continue_prompt,
1779 pre=pre,iFun=iFun,
1779 pre=pre,iFun=iFun,
1780 theRest=theRest)
1780 theRest=theRest)
1781
1781
1782 # Let's try to find if the input line is a magic fn
1782 # Let's try to find if the input line is a magic fn
1783 oinfo = None
1783 oinfo = None
1784 if hasattr(self,'magic_'+iFun):
1784 if hasattr(self,'magic_'+iFun):
1785 # WARNING: _ofind uses getattr(), so it can consume generators and
1785 # WARNING: _ofind uses getattr(), so it can consume generators and
1786 # cause other side effects.
1786 # cause other side effects.
1787 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1787 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1788 if oinfo['ismagic']:
1788 if oinfo['ismagic']:
1789 # Be careful not to call magics when a variable assignment is
1789 # Be careful not to call magics when a variable assignment is
1790 # being made (ls='hi', for example)
1790 # being made (ls='hi', for example)
1791 if self.rc.automagic and \
1791 if self.rc.automagic and \
1792 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1792 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1793 (self.rc.multi_line_specials or not continue_prompt):
1793 (self.rc.multi_line_specials or not continue_prompt):
1794 return self.handle_magic(line,continue_prompt,
1794 return self.handle_magic(line,continue_prompt,
1795 pre,iFun,theRest)
1795 pre,iFun,theRest)
1796 else:
1796 else:
1797 return self.handle_normal(line,continue_prompt)
1797 return self.handle_normal(line,continue_prompt)
1798
1798
1799 # If the rest of the line begins with an (in)equality, assginment or
1799 # If the rest of the line begins with an (in)equality, assginment or
1800 # function call, we should not call _ofind but simply execute it.
1800 # function call, we should not call _ofind but simply execute it.
1801 # This avoids spurious geattr() accesses on objects upon assignment.
1801 # This avoids spurious geattr() accesses on objects upon assignment.
1802 #
1802 #
1803 # It also allows users to assign to either alias or magic names true
1803 # It also allows users to assign to either alias or magic names true
1804 # python variables (the magic/alias systems always take second seat to
1804 # python variables (the magic/alias systems always take second seat to
1805 # true python code).
1805 # true python code).
1806 if theRest and theRest[0] in '!=()':
1806 if theRest and theRest[0] in '!=()':
1807 return self.handle_normal(line,continue_prompt)
1807 return self.handle_normal(line,continue_prompt)
1808
1808
1809 if oinfo is None:
1809 if oinfo is None:
1810 # let's try to ensure that _oinfo is ONLY called when autocall is
1810 # let's try to ensure that _oinfo is ONLY called when autocall is
1811 # on. Since it has inevitable potential side effects, at least
1811 # on. Since it has inevitable potential side effects, at least
1812 # having autocall off should be a guarantee to the user that no
1812 # having autocall off should be a guarantee to the user that no
1813 # weird things will happen.
1813 # weird things will happen.
1814
1814
1815 if self.rc.autocall:
1815 if self.rc.autocall:
1816 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1816 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1817 else:
1817 else:
1818 # in this case, all that's left is either an alias or
1818 # in this case, all that's left is either an alias or
1819 # processing the line normally.
1819 # processing the line normally.
1820 if iFun in self.alias_table:
1820 if iFun in self.alias_table:
1821 return self.handle_alias(line,continue_prompt,
1821 return self.handle_alias(line,continue_prompt,
1822 pre,iFun,theRest)
1822 pre,iFun,theRest)
1823 else:
1823 else:
1824 return self.handle_normal(line,continue_prompt)
1824 return self.handle_normal(line,continue_prompt)
1825
1825
1826 if not oinfo['found']:
1826 if not oinfo['found']:
1827 return self.handle_normal(line,continue_prompt)
1827 return self.handle_normal(line,continue_prompt)
1828 else:
1828 else:
1829 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1829 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1830 if oinfo['isalias']:
1830 if oinfo['isalias']:
1831 return self.handle_alias(line,continue_prompt,
1831 return self.handle_alias(line,continue_prompt,
1832 pre,iFun,theRest)
1832 pre,iFun,theRest)
1833
1833
1834 if self.rc.autocall and \
1834 if self.rc.autocall and \
1835 not self.re_exclude_auto.match(theRest) and \
1835 not self.re_exclude_auto.match(theRest) and \
1836 self.re_fun_name.match(iFun) and \
1836 self.re_fun_name.match(iFun) and \
1837 callable(oinfo['obj']) :
1837 callable(oinfo['obj']) :
1838 #print 'going auto' # dbg
1838 #print 'going auto' # dbg
1839 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1839 return self.handle_auto(line,continue_prompt,
1840 pre,iFun,theRest,oinfo['obj'])
1840 else:
1841 else:
1841 #print 'was callable?', callable(oinfo['obj']) # dbg
1842 #print 'was callable?', callable(oinfo['obj']) # dbg
1842 return self.handle_normal(line,continue_prompt)
1843 return self.handle_normal(line,continue_prompt)
1843
1844
1844 # If we get here, we have a normal Python line. Log and return.
1845 # If we get here, we have a normal Python line. Log and return.
1845 return self.handle_normal(line,continue_prompt)
1846 return self.handle_normal(line,continue_prompt)
1846
1847
1847 def _prefilter_dumb(self, line, continue_prompt):
1848 def _prefilter_dumb(self, line, continue_prompt):
1848 """simple prefilter function, for debugging"""
1849 """simple prefilter function, for debugging"""
1849 return self.handle_normal(line,continue_prompt)
1850 return self.handle_normal(line,continue_prompt)
1850
1851
1851 # Set the default prefilter() function (this can be user-overridden)
1852 # Set the default prefilter() function (this can be user-overridden)
1852 prefilter = _prefilter
1853 prefilter = _prefilter
1853
1854
1854 def handle_normal(self,line,continue_prompt=None,
1855 def handle_normal(self,line,continue_prompt=None,
1855 pre=None,iFun=None,theRest=None):
1856 pre=None,iFun=None,theRest=None):
1856 """Handle normal input lines. Use as a template for handlers."""
1857 """Handle normal input lines. Use as a template for handlers."""
1857
1858
1858 # With autoindent on, we need some way to exit the input loop, and I
1859 # With autoindent on, we need some way to exit the input loop, and I
1859 # don't want to force the user to have to backspace all the way to
1860 # don't want to force the user to have to backspace all the way to
1860 # clear the line. The rule will be in this case, that either two
1861 # clear the line. The rule will be in this case, that either two
1861 # lines of pure whitespace in a row, or a line of pure whitespace but
1862 # lines of pure whitespace in a row, or a line of pure whitespace but
1862 # of a size different to the indent level, will exit the input loop.
1863 # of a size different to the indent level, will exit the input loop.
1863
1864
1864 if (continue_prompt and self.autoindent and isspace(line) and
1865 if (continue_prompt and self.autoindent and isspace(line) and
1865 (line != self.indent_current or isspace(self.buffer[-1]))):
1866 (line != self.indent_current or isspace(self.buffer[-1]))):
1866 line = ''
1867 line = ''
1867
1868
1868 self.log(line,continue_prompt)
1869 self.log(line,continue_prompt)
1869 return line
1870 return line
1870
1871
1871 def handle_alias(self,line,continue_prompt=None,
1872 def handle_alias(self,line,continue_prompt=None,
1872 pre=None,iFun=None,theRest=None):
1873 pre=None,iFun=None,theRest=None):
1873 """Handle alias input lines. """
1874 """Handle alias input lines. """
1874
1875
1875 # pre is needed, because it carries the leading whitespace. Otherwise
1876 # pre is needed, because it carries the leading whitespace. Otherwise
1876 # aliases won't work in indented sections.
1877 # aliases won't work in indented sections.
1877 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1878 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1878 self.log(line_out,continue_prompt)
1879 self.log(line_out,continue_prompt)
1879 return line_out
1880 return line_out
1880
1881
1881 def handle_shell_escape(self, line, continue_prompt=None,
1882 def handle_shell_escape(self, line, continue_prompt=None,
1882 pre=None,iFun=None,theRest=None):
1883 pre=None,iFun=None,theRest=None):
1883 """Execute the line in a shell, empty return value"""
1884 """Execute the line in a shell, empty return value"""
1884
1885
1885 #print 'line in :', `line` # dbg
1886 #print 'line in :', `line` # dbg
1886 # Example of a special handler. Others follow a similar pattern.
1887 # Example of a special handler. Others follow a similar pattern.
1887 if continue_prompt: # multi-line statements
1888 if continue_prompt: # multi-line statements
1888 if iFun.startswith('!!'):
1889 if iFun.startswith('!!'):
1889 print 'SyntaxError: !! is not allowed in multiline statements'
1890 print 'SyntaxError: !! is not allowed in multiline statements'
1890 return pre
1891 return pre
1891 else:
1892 else:
1892 cmd = ("%s %s" % (iFun[1:],theRest))
1893 cmd = ("%s %s" % (iFun[1:],theRest))
1893 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1894 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1894 else: # single-line input
1895 else: # single-line input
1895 if line.startswith('!!'):
1896 if line.startswith('!!'):
1896 # rewrite iFun/theRest to properly hold the call to %sx and
1897 # rewrite iFun/theRest to properly hold the call to %sx and
1897 # the actual command to be executed, so handle_magic can work
1898 # the actual command to be executed, so handle_magic can work
1898 # correctly
1899 # correctly
1899 theRest = '%s %s' % (iFun[2:],theRest)
1900 theRest = '%s %s' % (iFun[2:],theRest)
1900 iFun = 'sx'
1901 iFun = 'sx'
1901 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1902 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1902 continue_prompt,pre,iFun,theRest)
1903 continue_prompt,pre,iFun,theRest)
1903 else:
1904 else:
1904 cmd=line[1:]
1905 cmd=line[1:]
1905 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1906 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1906 # update cache/log and return
1907 # update cache/log and return
1907 self.log(line_out,continue_prompt)
1908 self.log(line_out,continue_prompt)
1908 return line_out
1909 return line_out
1909
1910
1910 def handle_magic(self, line, continue_prompt=None,
1911 def handle_magic(self, line, continue_prompt=None,
1911 pre=None,iFun=None,theRest=None):
1912 pre=None,iFun=None,theRest=None):
1912 """Execute magic functions.
1913 """Execute magic functions.
1913
1914
1914 Also log them with a prepended # so the log is clean Python."""
1915 Also log them with a prepended # so the log is clean Python."""
1915
1916
1916 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1917 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1917 self.log(cmd,continue_prompt)
1918 self.log(cmd,continue_prompt)
1918 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1919 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1919 return cmd
1920 return cmd
1920
1921
1921 def handle_auto(self, line, continue_prompt=None,
1922 def handle_auto(self, line, continue_prompt=None,
1922 pre=None,iFun=None,theRest=None):
1923 pre=None,iFun=None,theRest=None,obj=None):
1923 """Hande lines which can be auto-executed, quoting if requested."""
1924 """Hande lines which can be auto-executed, quoting if requested."""
1924
1925
1925 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1926 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1926
1927
1927 # This should only be active for single-line input!
1928 # This should only be active for single-line input!
1928 if continue_prompt:
1929 if continue_prompt:
1930 self.log(line,continue_prompt)
1929 return line
1931 return line
1930
1932
1933 auto_rewrite = True
1931 if pre == self.ESC_QUOTE:
1934 if pre == self.ESC_QUOTE:
1932 # Auto-quote splitting on whitespace
1935 # Auto-quote splitting on whitespace
1933 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1936 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1934 elif pre == self.ESC_QUOTE2:
1937 elif pre == self.ESC_QUOTE2:
1935 # Auto-quote whole string
1938 # Auto-quote whole string
1936 newcmd = '%s("%s")' % (iFun,theRest)
1939 newcmd = '%s("%s")' % (iFun,theRest)
1937 else:
1940 else:
1938 # Auto-paren
1941 # Auto-paren.
1939 if theRest[0:1] in ('=','['):
1942 # We only apply it to argument-less calls if the autocall
1940 # Don't autocall in these cases. They can be either
1943 # parameter is set to 2. We only need to check that autocall is <
1941 # rebindings of an existing callable's name, or item access
1944 # 2, since this function isn't called unless it's at least 1.
1942 # for an object which is BOTH callable and implements
1945 if not theRest and self.rc.autocall < 2:
1943 # __getitem__.
1946 newcmd = '%s %s' % (iFun,theRest)
1944 return '%s %s' % (iFun,theRest)
1947 auto_rewrite = False
1945 if theRest.endswith(';'):
1946 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1947 else:
1948 else:
1948 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1949 if theRest.startswith('['):
1950 if hasattr(obj,'__getitem__'):
1951 # Don't autocall in this case: item access for an object
1952 # which is BOTH callable and implements __getitem__.
1953 newcmd = '%s %s' % (iFun,theRest)
1954 auto_rewrite = False
1955 else:
1956 # if the object doesn't support [] access, go ahead and
1957 # autocall
1958 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1959 elif theRest.endswith(';'):
1960 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1961 else:
1962 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1949
1963
1950 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1964 if auto_rewrite:
1965 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1951 # log what is now valid Python, not the actual user input (without the
1966 # log what is now valid Python, not the actual user input (without the
1952 # final newline)
1967 # final newline)
1953 self.log(newcmd,continue_prompt)
1968 self.log(newcmd,continue_prompt)
1954 return newcmd
1969 return newcmd
1955
1970
1956 def handle_help(self, line, continue_prompt=None,
1971 def handle_help(self, line, continue_prompt=None,
1957 pre=None,iFun=None,theRest=None):
1972 pre=None,iFun=None,theRest=None):
1958 """Try to get some help for the object.
1973 """Try to get some help for the object.
1959
1974
1960 obj? or ?obj -> basic information.
1975 obj? or ?obj -> basic information.
1961 obj?? or ??obj -> more details.
1976 obj?? or ??obj -> more details.
1962 """
1977 """
1963
1978
1964 # We need to make sure that we don't process lines which would be
1979 # We need to make sure that we don't process lines which would be
1965 # otherwise valid python, such as "x=1 # what?"
1980 # otherwise valid python, such as "x=1 # what?"
1966 try:
1981 try:
1967 codeop.compile_command(line)
1982 codeop.compile_command(line)
1968 except SyntaxError:
1983 except SyntaxError:
1969 # We should only handle as help stuff which is NOT valid syntax
1984 # We should only handle as help stuff which is NOT valid syntax
1970 if line[0]==self.ESC_HELP:
1985 if line[0]==self.ESC_HELP:
1971 line = line[1:]
1986 line = line[1:]
1972 elif line[-1]==self.ESC_HELP:
1987 elif line[-1]==self.ESC_HELP:
1973 line = line[:-1]
1988 line = line[:-1]
1974 self.log('#?'+line)
1989 self.log('#?'+line)
1975 if line:
1990 if line:
1976 self.magic_pinfo(line)
1991 self.magic_pinfo(line)
1977 else:
1992 else:
1978 page(self.usage,screen_lines=self.rc.screen_length)
1993 page(self.usage,screen_lines=self.rc.screen_length)
1979 return '' # Empty string is needed here!
1994 return '' # Empty string is needed here!
1980 except:
1995 except:
1981 # Pass any other exceptions through to the normal handler
1996 # Pass any other exceptions through to the normal handler
1982 return self.handle_normal(line,continue_prompt)
1997 return self.handle_normal(line,continue_prompt)
1983 else:
1998 else:
1984 # If the code compiles ok, we should handle it normally
1999 # If the code compiles ok, we should handle it normally
1985 return self.handle_normal(line,continue_prompt)
2000 return self.handle_normal(line,continue_prompt)
1986
2001
1987 def handle_emacs(self,line,continue_prompt=None,
2002 def handle_emacs(self,line,continue_prompt=None,
1988 pre=None,iFun=None,theRest=None):
2003 pre=None,iFun=None,theRest=None):
1989 """Handle input lines marked by python-mode."""
2004 """Handle input lines marked by python-mode."""
1990
2005
1991 # Currently, nothing is done. Later more functionality can be added
2006 # Currently, nothing is done. Later more functionality can be added
1992 # here if needed.
2007 # here if needed.
1993
2008
1994 # The input cache shouldn't be updated
2009 # The input cache shouldn't be updated
1995
2010
1996 return line
2011 return line
1997
2012
1998 def mktempfile(self,data=None):
2013 def mktempfile(self,data=None):
1999 """Make a new tempfile and return its filename.
2014 """Make a new tempfile and return its filename.
2000
2015
2001 This makes a call to tempfile.mktemp, but it registers the created
2016 This makes a call to tempfile.mktemp, but it registers the created
2002 filename internally so ipython cleans it up at exit time.
2017 filename internally so ipython cleans it up at exit time.
2003
2018
2004 Optional inputs:
2019 Optional inputs:
2005
2020
2006 - data(None): if data is given, it gets written out to the temp file
2021 - data(None): if data is given, it gets written out to the temp file
2007 immediately, and the file is closed again."""
2022 immediately, and the file is closed again."""
2008
2023
2009 filename = tempfile.mktemp('.py')
2024 filename = tempfile.mktemp('.py')
2010 self.tempfiles.append(filename)
2025 self.tempfiles.append(filename)
2011
2026
2012 if data:
2027 if data:
2013 tmp_file = open(filename,'w')
2028 tmp_file = open(filename,'w')
2014 tmp_file.write(data)
2029 tmp_file.write(data)
2015 tmp_file.close()
2030 tmp_file.close()
2016 return filename
2031 return filename
2017
2032
2018 def write(self,data):
2033 def write(self,data):
2019 """Write a string to the default output"""
2034 """Write a string to the default output"""
2020 Term.cout.write(data)
2035 Term.cout.write(data)
2021
2036
2022 def write_err(self,data):
2037 def write_err(self,data):
2023 """Write a string to the default error output"""
2038 """Write a string to the default error output"""
2024 Term.cerr.write(data)
2039 Term.cerr.write(data)
2025
2040
2026 def exit(self):
2041 def exit(self):
2027 """Handle interactive exit.
2042 """Handle interactive exit.
2028
2043
2029 This method sets the exit_now attribute."""
2044 This method sets the exit_now attribute."""
2030
2045
2031 if self.rc.confirm_exit:
2046 if self.rc.confirm_exit:
2032 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2047 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2033 self.exit_now = True
2048 self.exit_now = True
2034 else:
2049 else:
2035 self.exit_now = True
2050 self.exit_now = True
2036 return self.exit_now
2051 return self.exit_now
2037
2052
2038 def safe_execfile(self,fname,*where,**kw):
2053 def safe_execfile(self,fname,*where,**kw):
2039 fname = os.path.expanduser(fname)
2054 fname = os.path.expanduser(fname)
2040
2055
2041 # find things also in current directory
2056 # find things also in current directory
2042 dname = os.path.dirname(fname)
2057 dname = os.path.dirname(fname)
2043 if not sys.path.count(dname):
2058 if not sys.path.count(dname):
2044 sys.path.append(dname)
2059 sys.path.append(dname)
2045
2060
2046 try:
2061 try:
2047 xfile = open(fname)
2062 xfile = open(fname)
2048 except:
2063 except:
2049 print >> Term.cerr, \
2064 print >> Term.cerr, \
2050 'Could not open file <%s> for safe execution.' % fname
2065 'Could not open file <%s> for safe execution.' % fname
2051 return None
2066 return None
2052
2067
2053 kw.setdefault('islog',0)
2068 kw.setdefault('islog',0)
2054 kw.setdefault('quiet',1)
2069 kw.setdefault('quiet',1)
2055 kw.setdefault('exit_ignore',0)
2070 kw.setdefault('exit_ignore',0)
2056 first = xfile.readline()
2071 first = xfile.readline()
2057 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2072 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2058 xfile.close()
2073 xfile.close()
2059 # line by line execution
2074 # line by line execution
2060 if first.startswith(loghead) or kw['islog']:
2075 if first.startswith(loghead) or kw['islog']:
2061 print 'Loading log file <%s> one line at a time...' % fname
2076 print 'Loading log file <%s> one line at a time...' % fname
2062 if kw['quiet']:
2077 if kw['quiet']:
2063 stdout_save = sys.stdout
2078 stdout_save = sys.stdout
2064 sys.stdout = StringIO.StringIO()
2079 sys.stdout = StringIO.StringIO()
2065 try:
2080 try:
2066 globs,locs = where[0:2]
2081 globs,locs = where[0:2]
2067 except:
2082 except:
2068 try:
2083 try:
2069 globs = locs = where[0]
2084 globs = locs = where[0]
2070 except:
2085 except:
2071 globs = locs = globals()
2086 globs = locs = globals()
2072 badblocks = []
2087 badblocks = []
2073
2088
2074 # we also need to identify indented blocks of code when replaying
2089 # we also need to identify indented blocks of code when replaying
2075 # logs and put them together before passing them to an exec
2090 # logs and put them together before passing them to an exec
2076 # statement. This takes a bit of regexp and look-ahead work in the
2091 # statement. This takes a bit of regexp and look-ahead work in the
2077 # file. It's easiest if we swallow the whole thing in memory
2092 # file. It's easiest if we swallow the whole thing in memory
2078 # first, and manually walk through the lines list moving the
2093 # first, and manually walk through the lines list moving the
2079 # counter ourselves.
2094 # counter ourselves.
2080 indent_re = re.compile('\s+\S')
2095 indent_re = re.compile('\s+\S')
2081 xfile = open(fname)
2096 xfile = open(fname)
2082 filelines = xfile.readlines()
2097 filelines = xfile.readlines()
2083 xfile.close()
2098 xfile.close()
2084 nlines = len(filelines)
2099 nlines = len(filelines)
2085 lnum = 0
2100 lnum = 0
2086 while lnum < nlines:
2101 while lnum < nlines:
2087 line = filelines[lnum]
2102 line = filelines[lnum]
2088 lnum += 1
2103 lnum += 1
2089 # don't re-insert logger status info into cache
2104 # don't re-insert logger status info into cache
2090 if line.startswith('#log#'):
2105 if line.startswith('#log#'):
2091 continue
2106 continue
2092 else:
2107 else:
2093 # build a block of code (maybe a single line) for execution
2108 # build a block of code (maybe a single line) for execution
2094 block = line
2109 block = line
2095 try:
2110 try:
2096 next = filelines[lnum] # lnum has already incremented
2111 next = filelines[lnum] # lnum has already incremented
2097 except:
2112 except:
2098 next = None
2113 next = None
2099 while next and indent_re.match(next):
2114 while next and indent_re.match(next):
2100 block += next
2115 block += next
2101 lnum += 1
2116 lnum += 1
2102 try:
2117 try:
2103 next = filelines[lnum]
2118 next = filelines[lnum]
2104 except:
2119 except:
2105 next = None
2120 next = None
2106 # now execute the block of one or more lines
2121 # now execute the block of one or more lines
2107 try:
2122 try:
2108 exec block in globs,locs
2123 exec block in globs,locs
2109 except SystemExit:
2124 except SystemExit:
2110 pass
2125 pass
2111 except:
2126 except:
2112 badblocks.append(block.rstrip())
2127 badblocks.append(block.rstrip())
2113 if kw['quiet']: # restore stdout
2128 if kw['quiet']: # restore stdout
2114 sys.stdout.close()
2129 sys.stdout.close()
2115 sys.stdout = stdout_save
2130 sys.stdout = stdout_save
2116 print 'Finished replaying log file <%s>' % fname
2131 print 'Finished replaying log file <%s>' % fname
2117 if badblocks:
2132 if badblocks:
2118 print >> sys.stderr, ('\nThe following lines/blocks in file '
2133 print >> sys.stderr, ('\nThe following lines/blocks in file '
2119 '<%s> reported errors:' % fname)
2134 '<%s> reported errors:' % fname)
2120
2135
2121 for badline in badblocks:
2136 for badline in badblocks:
2122 print >> sys.stderr, badline
2137 print >> sys.stderr, badline
2123 else: # regular file execution
2138 else: # regular file execution
2124 try:
2139 try:
2125 execfile(fname,*where)
2140 execfile(fname,*where)
2126 except SyntaxError:
2141 except SyntaxError:
2127 etype,evalue = sys.exc_info()[:2]
2142 etype,evalue = sys.exc_info()[:2]
2128 self.SyntaxTB(etype,evalue,[])
2143 self.SyntaxTB(etype,evalue,[])
2129 warn('Failure executing file: <%s>' % fname)
2144 warn('Failure executing file: <%s>' % fname)
2130 except SystemExit,status:
2145 except SystemExit,status:
2131 if not kw['exit_ignore']:
2146 if not kw['exit_ignore']:
2132 self.InteractiveTB()
2147 self.InteractiveTB()
2133 warn('Failure executing file: <%s>' % fname)
2148 warn('Failure executing file: <%s>' % fname)
2134 except:
2149 except:
2135 self.InteractiveTB()
2150 self.InteractiveTB()
2136 warn('Failure executing file: <%s>' % fname)
2151 warn('Failure executing file: <%s>' % fname)
2137
2152
2138 #************************* end of file <iplib.py> *****************************
2153 #************************* end of file <iplib.py> *****************************
@@ -1,701 +1,701 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 967 2005-12-29 09:02:13Z fperez $"""
9 $Id: ipmaker.py 990 2006-01-04 06:59:02Z fperez $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 from IPython import Release
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
20 __license__ = Release.license
21 __version__ = Release.version
21 __version__ = Release.version
22
22
23 credits._Printer__data = """
23 credits._Printer__data = """
24 Python: %s
24 Python: %s
25
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
28 % credits._Printer__data
29
29
30 copyright._Printer__data += """
30 copyright._Printer__data += """
31
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
33 All Rights Reserved."""
34
34
35 #****************************************************************************
35 #****************************************************************************
36 # Required modules
36 # Required modules
37
37
38 # From the standard library
38 # From the standard library
39 import __main__
39 import __main__
40 import __builtin__
40 import __builtin__
41 import os
41 import os
42 import re
42 import re
43 import sys
43 import sys
44 import types
44 import types
45 from pprint import pprint,pformat
45 from pprint import pprint,pformat
46
46
47 # Our own
47 # Our own
48 from IPython import DPyGetOpt
48 from IPython import DPyGetOpt
49 from IPython.Struct import Struct
49 from IPython.Struct import Struct
50 from IPython.OutputTrap import OutputTrap
50 from IPython.OutputTrap import OutputTrap
51 from IPython.ConfigLoader import ConfigLoader
51 from IPython.ConfigLoader import ConfigLoader
52 from IPython.iplib import InteractiveShell
52 from IPython.iplib import InteractiveShell
53 from IPython.usage import cmd_line_usage,interactive_usage
53 from IPython.usage import cmd_line_usage,interactive_usage
54 from IPython.genutils import *
54 from IPython.genutils import *
55
55
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 rc_override=None,shell_class=InteractiveShell,
58 rc_override=None,shell_class=InteractiveShell,
59 embedded=False,**kw):
59 embedded=False,**kw):
60 """This is a dump of IPython into a single function.
60 """This is a dump of IPython into a single function.
61
61
62 Later it will have to be broken up in a sensible manner.
62 Later it will have to be broken up in a sensible manner.
63
63
64 Arguments:
64 Arguments:
65
65
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 script name, b/c DPyGetOpt strips the first argument only for the real
67 script name, b/c DPyGetOpt strips the first argument only for the real
68 sys.argv.
68 sys.argv.
69
69
70 - user_ns: a dict to be used as the user's namespace."""
70 - user_ns: a dict to be used as the user's namespace."""
71
71
72 #----------------------------------------------------------------------
72 #----------------------------------------------------------------------
73 # Defaults and initialization
73 # Defaults and initialization
74
74
75 # For developer debugging, deactivates crash handler and uses pdb.
75 # For developer debugging, deactivates crash handler and uses pdb.
76 DEVDEBUG = False
76 DEVDEBUG = False
77
77
78 if argv is None:
78 if argv is None:
79 argv = sys.argv
79 argv = sys.argv
80
80
81 # __IP is the main global that lives throughout and represents the whole
81 # __IP is the main global that lives throughout and represents the whole
82 # application. If the user redefines it, all bets are off as to what
82 # application. If the user redefines it, all bets are off as to what
83 # happens.
83 # happens.
84
84
85 # __IP is the name of he global which the caller will have accessible as
85 # __IP is the name of he global which the caller will have accessible as
86 # __IP.name. We set its name via the first parameter passed to
86 # __IP.name. We set its name via the first parameter passed to
87 # InteractiveShell:
87 # InteractiveShell:
88
88
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 embedded=embedded,**kw)
90 embedded=embedded,**kw)
91
91
92 # Put 'help' in the user namespace
92 # Put 'help' in the user namespace
93 from site import _Helper
93 from site import _Helper
94 IP.user_ns['help'] = _Helper()
94 IP.user_ns['help'] = _Helper()
95
95
96
96
97 if DEVDEBUG:
97 if DEVDEBUG:
98 # For developer debugging only (global flag)
98 # For developer debugging only (global flag)
99 from IPython import ultraTB
99 from IPython import ultraTB
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101
101
102 IP.BANNER_PARTS = ['Python %s\n'
102 IP.BANNER_PARTS = ['Python %s\n'
103 'Type "copyright", "credits" or "license" '
103 'Type "copyright", "credits" or "license" '
104 'for more information.\n'
104 'for more information.\n'
105 % (sys.version.split('\n')[0],),
105 % (sys.version.split('\n')[0],),
106 "IPython %s -- An enhanced Interactive Python."
106 "IPython %s -- An enhanced Interactive Python."
107 % (__version__,),
107 % (__version__,),
108 """? -> Introduction to IPython's features.
108 """? -> Introduction to IPython's features.
109 %magic -> Information about IPython's 'magic' % functions.
109 %magic -> Information about IPython's 'magic' % functions.
110 help -> Python's own help system.
110 help -> Python's own help system.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 """ ]
112 """ ]
113
113
114 IP.usage = interactive_usage
114 IP.usage = interactive_usage
115
115
116 # Platform-dependent suffix and directory names. We use _ipython instead
116 # Platform-dependent suffix and directory names. We use _ipython instead
117 # of .ipython under win32 b/c there's software that breaks with .named
117 # of .ipython under win32 b/c there's software that breaks with .named
118 # directories on that platform.
118 # directories on that platform.
119 if os.name == 'posix':
119 if os.name == 'posix':
120 rc_suffix = ''
120 rc_suffix = ''
121 ipdir_def = '.ipython'
121 ipdir_def = '.ipython'
122 else:
122 else:
123 rc_suffix = '.ini'
123 rc_suffix = '.ini'
124 ipdir_def = '_ipython'
124 ipdir_def = '_ipython'
125
125
126 # default directory for configuration
126 # default directory for configuration
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
128 os.path.join(IP.home_dir,ipdir_def)))
128 os.path.join(IP.home_dir,ipdir_def)))
129
129
130 # we need the directory where IPython itself is installed
130 # we need the directory where IPython itself is installed
131 import IPython
131 import IPython
132 IPython_dir = os.path.dirname(IPython.__file__)
132 IPython_dir = os.path.dirname(IPython.__file__)
133 del IPython
133 del IPython
134
134
135 #-------------------------------------------------------------------------
135 #-------------------------------------------------------------------------
136 # Command line handling
136 # Command line handling
137
137
138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
138 # Valid command line options (uses DPyGetOpt syntax, like Perl's
139 # GetOpt::Long)
139 # GetOpt::Long)
140
140
141 # Any key not listed here gets deleted even if in the file (like session
141 # Any key not listed here gets deleted even if in the file (like session
142 # or profile). That's deliberate, to maintain the rc namespace clean.
142 # or profile). That's deliberate, to maintain the rc namespace clean.
143
143
144 # Each set of options appears twice: under _conv only the names are
144 # Each set of options appears twice: under _conv only the names are
145 # listed, indicating which type they must be converted to when reading the
145 # listed, indicating which type they must be converted to when reading the
146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
146 # ipythonrc file. And under DPyGetOpt they are listed with the regular
147 # DPyGetOpt syntax (=s,=i,:f,etc).
147 # DPyGetOpt syntax (=s,=i,:f,etc).
148
148
149 # Make sure there's a space before each end of line (they get auto-joined!)
149 # Make sure there's a space before each end of line (they get auto-joined!)
150 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
150 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
151 'c=s classic|cl color_info! colors=s confirm_exit! '
151 'c=s classic|cl color_info! colors=s confirm_exit! '
152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
152 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
153 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
154 'quick screen_length|sl=i prompts_pad_left=i '
154 'quick screen_length|sl=i prompts_pad_left=i '
155 'logfile|lf=s logplay|lp=s profile|p=s '
155 'logfile|lf=s logplay|lp=s profile|p=s '
156 'readline! readline_merge_completions! '
156 'readline! readline_merge_completions! '
157 'readline_omit__names! '
157 'readline_omit__names! '
158 'rcfile=s separate_in|si=s separate_out|so=s '
158 'rcfile=s separate_in|si=s separate_out|so=s '
159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
159 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
160 'magic_docstrings system_verbose! '
160 'magic_docstrings system_verbose! '
161 'multi_line_specials! '
161 'multi_line_specials! '
162 'autoedit_syntax!')
162 'autoedit_syntax!')
163
163
164 # Options that can *only* appear at the cmd line (not in rcfiles).
164 # Options that can *only* appear at the cmd line (not in rcfiles).
165
165
166 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
166 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
167 # the 'C-c !' command in emacs automatically appends a -i option at the end.
167 # the 'C-c !' command in emacs automatically appends a -i option at the end.
168 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
168 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
169 'gthread! qthread! wthread! pylab! tk!')
169 'gthread! qthread! wthread! pylab! tk!')
170
170
171 # Build the actual name list to be used by DPyGetOpt
171 # Build the actual name list to be used by DPyGetOpt
172 opts_names = qw(cmdline_opts) + qw(cmdline_only)
172 opts_names = qw(cmdline_opts) + qw(cmdline_only)
173
173
174 # Set sensible command line defaults.
174 # Set sensible command line defaults.
175 # This should have everything from cmdline_opts and cmdline_only
175 # This should have everything from cmdline_opts and cmdline_only
176 opts_def = Struct(autocall = 1,
176 opts_def = Struct(autocall = 1,
177 autoedit_syntax = 1,
177 autoedit_syntax = 1,
178 autoindent=0,
178 autoindent=0,
179 automagic = 1,
179 automagic = 1,
180 banner = 1,
180 banner = 1,
181 cache_size = 1000,
181 cache_size = 1000,
182 c = '',
182 c = '',
183 classic = 0,
183 classic = 0,
184 colors = 'NoColor',
184 colors = 'NoColor',
185 color_info = 0,
185 color_info = 0,
186 confirm_exit = 1,
186 confirm_exit = 1,
187 debug = 0,
187 debug = 0,
188 deep_reload = 0,
188 deep_reload = 0,
189 editor = '0',
189 editor = '0',
190 help = 0,
190 help = 0,
191 ignore = 0,
191 ignore = 0,
192 ipythondir = ipythondir,
192 ipythondir = ipythondir,
193 log = 0,
193 log = 0,
194 logfile = '',
194 logfile = '',
195 logplay = '',
195 logplay = '',
196 multi_line_specials = 1,
196 multi_line_specials = 1,
197 messages = 1,
197 messages = 1,
198 nosep = 0,
198 nosep = 0,
199 pdb = 0,
199 pdb = 0,
200 pprint = 0,
200 pprint = 0,
201 profile = '',
201 profile = '',
202 prompt_in1 = 'In [\\#]: ',
202 prompt_in1 = 'In [\\#]: ',
203 prompt_in2 = ' .\\D.: ',
203 prompt_in2 = ' .\\D.: ',
204 prompt_out = 'Out[\\#]: ',
204 prompt_out = 'Out[\\#]: ',
205 prompts_pad_left = 1,
205 prompts_pad_left = 1,
206 quick = 0,
206 quick = 0,
207 readline = 1,
207 readline = 1,
208 readline_merge_completions = 1,
208 readline_merge_completions = 1,
209 readline_omit__names = 0,
209 readline_omit__names = 0,
210 rcfile = 'ipythonrc' + rc_suffix,
210 rcfile = 'ipythonrc' + rc_suffix,
211 screen_length = 0,
211 screen_length = 0,
212 separate_in = '\n',
212 separate_in = '\n',
213 separate_out = '\n',
213 separate_out = '\n',
214 separate_out2 = '',
214 separate_out2 = '',
215 system_verbose = 0,
215 system_verbose = 0,
216 gthread = 0,
216 gthread = 0,
217 qthread = 0,
217 qthread = 0,
218 wthread = 0,
218 wthread = 0,
219 pylab = 0,
219 pylab = 0,
220 tk = 0,
220 tk = 0,
221 upgrade = 0,
221 upgrade = 0,
222 Version = 0,
222 Version = 0,
223 xmode = 'Verbose',
223 xmode = 'Verbose',
224 wildcards_case_sensitive = 1,
224 wildcards_case_sensitive = 1,
225 magic_docstrings = 0, # undocumented, for doc generation
225 magic_docstrings = 0, # undocumented, for doc generation
226 )
226 )
227
227
228 # Things that will *only* appear in rcfiles (not at the command line).
228 # Things that will *only* appear in rcfiles (not at the command line).
229 # Make sure there's a space before each end of line (they get auto-joined!)
229 # Make sure there's a space before each end of line (they get auto-joined!)
230 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
230 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
231 qw_lol: 'import_some ',
231 qw_lol: 'import_some ',
232 # for things with embedded whitespace:
232 # for things with embedded whitespace:
233 list_strings:'execute alias readline_parse_and_bind ',
233 list_strings:'execute alias readline_parse_and_bind ',
234 # Regular strings need no conversion:
234 # Regular strings need no conversion:
235 None:'readline_remove_delims ',
235 None:'readline_remove_delims ',
236 }
236 }
237 # Default values for these
237 # Default values for these
238 rc_def = Struct(include = [],
238 rc_def = Struct(include = [],
239 import_mod = [],
239 import_mod = [],
240 import_all = [],
240 import_all = [],
241 import_some = [[]],
241 import_some = [[]],
242 execute = [],
242 execute = [],
243 execfile = [],
243 execfile = [],
244 alias = [],
244 alias = [],
245 readline_parse_and_bind = [],
245 readline_parse_and_bind = [],
246 readline_remove_delims = '',
246 readline_remove_delims = '',
247 )
247 )
248
248
249 # Build the type conversion dictionary from the above tables:
249 # Build the type conversion dictionary from the above tables:
250 typeconv = rcfile_opts.copy()
250 typeconv = rcfile_opts.copy()
251 typeconv.update(optstr2types(cmdline_opts))
251 typeconv.update(optstr2types(cmdline_opts))
252
252
253 # FIXME: the None key appears in both, put that back together by hand. Ugly!
253 # FIXME: the None key appears in both, put that back together by hand. Ugly!
254 typeconv[None] += ' ' + rcfile_opts[None]
254 typeconv[None] += ' ' + rcfile_opts[None]
255
255
256 # Remove quotes at ends of all strings (used to protect spaces)
256 # Remove quotes at ends of all strings (used to protect spaces)
257 typeconv[unquote_ends] = typeconv[None]
257 typeconv[unquote_ends] = typeconv[None]
258 del typeconv[None]
258 del typeconv[None]
259
259
260 # Build the list we'll use to make all config decisions with defaults:
260 # Build the list we'll use to make all config decisions with defaults:
261 opts_all = opts_def.copy()
261 opts_all = opts_def.copy()
262 opts_all.update(rc_def)
262 opts_all.update(rc_def)
263
263
264 # Build conflict resolver for recursive loading of config files:
264 # Build conflict resolver for recursive loading of config files:
265 # - preserve means the outermost file maintains the value, it is not
265 # - preserve means the outermost file maintains the value, it is not
266 # overwritten if an included file has the same key.
266 # overwritten if an included file has the same key.
267 # - add_flip applies + to the two values, so it better make sense to add
267 # - add_flip applies + to the two values, so it better make sense to add
268 # those types of keys. But it flips them first so that things loaded
268 # those types of keys. But it flips them first so that things loaded
269 # deeper in the inclusion chain have lower precedence.
269 # deeper in the inclusion chain have lower precedence.
270 conflict = {'preserve': ' '.join([ typeconv[int],
270 conflict = {'preserve': ' '.join([ typeconv[int],
271 typeconv[unquote_ends] ]),
271 typeconv[unquote_ends] ]),
272 'add_flip': ' '.join([ typeconv[qwflat],
272 'add_flip': ' '.join([ typeconv[qwflat],
273 typeconv[qw_lol],
273 typeconv[qw_lol],
274 typeconv[list_strings] ])
274 typeconv[list_strings] ])
275 }
275 }
276
276
277 # Now actually process the command line
277 # Now actually process the command line
278 getopt = DPyGetOpt.DPyGetOpt()
278 getopt = DPyGetOpt.DPyGetOpt()
279 getopt.setIgnoreCase(0)
279 getopt.setIgnoreCase(0)
280
280
281 getopt.parseConfiguration(opts_names)
281 getopt.parseConfiguration(opts_names)
282
282
283 try:
283 try:
284 getopt.processArguments(argv)
284 getopt.processArguments(argv)
285 except:
285 except:
286 print cmd_line_usage
286 print cmd_line_usage
287 warn('\nError in Arguments: ' + `sys.exc_value`)
287 warn('\nError in Arguments: ' + `sys.exc_value`)
288 sys.exit(1)
288 sys.exit(1)
289
289
290 # convert the options dict to a struct for much lighter syntax later
290 # convert the options dict to a struct for much lighter syntax later
291 opts = Struct(getopt.optionValues)
291 opts = Struct(getopt.optionValues)
292 args = getopt.freeValues
292 args = getopt.freeValues
293
293
294 # this is the struct (which has default values at this point) with which
294 # this is the struct (which has default values at this point) with which
295 # we make all decisions:
295 # we make all decisions:
296 opts_all.update(opts)
296 opts_all.update(opts)
297
297
298 # Options that force an immediate exit
298 # Options that force an immediate exit
299 if opts_all.help:
299 if opts_all.help:
300 page(cmd_line_usage)
300 page(cmd_line_usage)
301 sys.exit()
301 sys.exit()
302
302
303 if opts_all.Version:
303 if opts_all.Version:
304 print __version__
304 print __version__
305 sys.exit()
305 sys.exit()
306
306
307 if opts_all.magic_docstrings:
307 if opts_all.magic_docstrings:
308 IP.magic_magic('-latex')
308 IP.magic_magic('-latex')
309 sys.exit()
309 sys.exit()
310
310
311 # Create user config directory if it doesn't exist. This must be done
311 # Create user config directory if it doesn't exist. This must be done
312 # *after* getting the cmd line options.
312 # *after* getting the cmd line options.
313 if not os.path.isdir(opts_all.ipythondir):
313 if not os.path.isdir(opts_all.ipythondir):
314 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
314 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
315
315
316 # upgrade user config files while preserving a copy of the originals
316 # upgrade user config files while preserving a copy of the originals
317 if opts_all.upgrade:
317 if opts_all.upgrade:
318 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
318 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
319
319
320 # check mutually exclusive options in the *original* command line
320 # check mutually exclusive options in the *original* command line
321 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
321 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
322 qw('classic profile'),qw('classic rcfile')])
322 qw('classic profile'),qw('classic rcfile')])
323
323
324 #---------------------------------------------------------------------------
324 #---------------------------------------------------------------------------
325 # Log replay
325 # Log replay
326
326
327 # if -logplay, we need to 'become' the other session. That basically means
327 # if -logplay, we need to 'become' the other session. That basically means
328 # replacing the current command line environment with that of the old
328 # replacing the current command line environment with that of the old
329 # session and moving on.
329 # session and moving on.
330
330
331 # this is needed so that later we know we're in session reload mode, as
331 # this is needed so that later we know we're in session reload mode, as
332 # opts_all will get overwritten:
332 # opts_all will get overwritten:
333 load_logplay = 0
333 load_logplay = 0
334
334
335 if opts_all.logplay:
335 if opts_all.logplay:
336 load_logplay = opts_all.logplay
336 load_logplay = opts_all.logplay
337 opts_debug_save = opts_all.debug
337 opts_debug_save = opts_all.debug
338 try:
338 try:
339 logplay = open(opts_all.logplay)
339 logplay = open(opts_all.logplay)
340 except IOError:
340 except IOError:
341 if opts_all.debug: IP.InteractiveTB()
341 if opts_all.debug: IP.InteractiveTB()
342 warn('Could not open logplay file '+`opts_all.logplay`)
342 warn('Could not open logplay file '+`opts_all.logplay`)
343 # restore state as if nothing had happened and move on, but make
343 # restore state as if nothing had happened and move on, but make
344 # sure that later we don't try to actually load the session file
344 # sure that later we don't try to actually load the session file
345 logplay = None
345 logplay = None
346 load_logplay = 0
346 load_logplay = 0
347 del opts_all.logplay
347 del opts_all.logplay
348 else:
348 else:
349 try:
349 try:
350 logplay.readline()
350 logplay.readline()
351 logplay.readline();
351 logplay.readline();
352 # this reloads that session's command line
352 # this reloads that session's command line
353 cmd = logplay.readline()[6:]
353 cmd = logplay.readline()[6:]
354 exec cmd
354 exec cmd
355 # restore the true debug flag given so that the process of
355 # restore the true debug flag given so that the process of
356 # session loading itself can be monitored.
356 # session loading itself can be monitored.
357 opts.debug = opts_debug_save
357 opts.debug = opts_debug_save
358 # save the logplay flag so later we don't overwrite the log
358 # save the logplay flag so later we don't overwrite the log
359 opts.logplay = load_logplay
359 opts.logplay = load_logplay
360 # now we must update our own structure with defaults
360 # now we must update our own structure with defaults
361 opts_all.update(opts)
361 opts_all.update(opts)
362 # now load args
362 # now load args
363 cmd = logplay.readline()[6:]
363 cmd = logplay.readline()[6:]
364 exec cmd
364 exec cmd
365 logplay.close()
365 logplay.close()
366 except:
366 except:
367 logplay.close()
367 logplay.close()
368 if opts_all.debug: IP.InteractiveTB()
368 if opts_all.debug: IP.InteractiveTB()
369 warn("Logplay file lacking full configuration information.\n"
369 warn("Logplay file lacking full configuration information.\n"
370 "I'll try to read it, but some things may not work.")
370 "I'll try to read it, but some things may not work.")
371
371
372 #-------------------------------------------------------------------------
372 #-------------------------------------------------------------------------
373 # set up output traps: catch all output from files, being run, modules
373 # set up output traps: catch all output from files, being run, modules
374 # loaded, etc. Then give it to the user in a clean form at the end.
374 # loaded, etc. Then give it to the user in a clean form at the end.
375
375
376 msg_out = 'Output messages. '
376 msg_out = 'Output messages. '
377 msg_err = 'Error messages. '
377 msg_err = 'Error messages. '
378 msg_sep = '\n'
378 msg_sep = '\n'
379 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
379 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
380 msg_err,msg_sep,debug,
380 msg_err,msg_sep,debug,
381 quiet_out=1),
381 quiet_out=1),
382 user_exec = OutputTrap('User File Execution',msg_out,
382 user_exec = OutputTrap('User File Execution',msg_out,
383 msg_err,msg_sep,debug),
383 msg_err,msg_sep,debug),
384 logplay = OutputTrap('Log Loader',msg_out,
384 logplay = OutputTrap('Log Loader',msg_out,
385 msg_err,msg_sep,debug),
385 msg_err,msg_sep,debug),
386 summary = ''
386 summary = ''
387 )
387 )
388
388
389 #-------------------------------------------------------------------------
389 #-------------------------------------------------------------------------
390 # Process user ipythonrc-type configuration files
390 # Process user ipythonrc-type configuration files
391
391
392 # turn on output trapping and log to msg.config
392 # turn on output trapping and log to msg.config
393 # remember that with debug on, trapping is actually disabled
393 # remember that with debug on, trapping is actually disabled
394 msg.config.trap_all()
394 msg.config.trap_all()
395
395
396 # look for rcfile in current or default directory
396 # look for rcfile in current or default directory
397 try:
397 try:
398 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
398 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
399 except IOError:
399 except IOError:
400 if opts_all.debug: IP.InteractiveTB()
400 if opts_all.debug: IP.InteractiveTB()
401 warn('Configuration file %s not found. Ignoring request.'
401 warn('Configuration file %s not found. Ignoring request.'
402 % (opts_all.rcfile) )
402 % (opts_all.rcfile) )
403
403
404 # 'profiles' are a shorthand notation for config filenames
404 # 'profiles' are a shorthand notation for config filenames
405 if opts_all.profile:
405 if opts_all.profile:
406 try:
406 try:
407 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
407 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
408 + rc_suffix,
408 + rc_suffix,
409 opts_all.ipythondir)
409 opts_all.ipythondir)
410 except IOError:
410 except IOError:
411 if opts_all.debug: IP.InteractiveTB()
411 if opts_all.debug: IP.InteractiveTB()
412 opts.profile = '' # remove profile from options if invalid
412 opts.profile = '' # remove profile from options if invalid
413 warn('Profile configuration file %s not found. Ignoring request.'
413 warn('Profile configuration file %s not found. Ignoring request.'
414 % (opts_all.profile) )
414 % (opts_all.profile) )
415
415
416 # load the config file
416 # load the config file
417 rcfiledata = None
417 rcfiledata = None
418 if opts_all.quick:
418 if opts_all.quick:
419 print 'Launching IPython in quick mode. No config file read.'
419 print 'Launching IPython in quick mode. No config file read.'
420 elif opts_all.classic:
420 elif opts_all.classic:
421 print 'Launching IPython in classic mode. No config file read.'
421 print 'Launching IPython in classic mode. No config file read.'
422 elif opts_all.rcfile:
422 elif opts_all.rcfile:
423 try:
423 try:
424 cfg_loader = ConfigLoader(conflict)
424 cfg_loader = ConfigLoader(conflict)
425 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
425 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
426 'include',opts_all.ipythondir,
426 'include',opts_all.ipythondir,
427 purge = 1,
427 purge = 1,
428 unique = conflict['preserve'])
428 unique = conflict['preserve'])
429 except:
429 except:
430 IP.InteractiveTB()
430 IP.InteractiveTB()
431 warn('Problems loading configuration file '+
431 warn('Problems loading configuration file '+
432 `opts_all.rcfile`+
432 `opts_all.rcfile`+
433 '\nStarting with default -bare bones- configuration.')
433 '\nStarting with default -bare bones- configuration.')
434 else:
434 else:
435 warn('No valid configuration file found in either currrent directory\n'+
435 warn('No valid configuration file found in either currrent directory\n'+
436 'or in the IPython config. directory: '+`opts_all.ipythondir`+
436 'or in the IPython config. directory: '+`opts_all.ipythondir`+
437 '\nProceeding with internal defaults.')
437 '\nProceeding with internal defaults.')
438
438
439 #------------------------------------------------------------------------
439 #------------------------------------------------------------------------
440 # Set exception handlers in mode requested by user.
440 # Set exception handlers in mode requested by user.
441 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
441 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
442 IP.magic_xmode(opts_all.xmode)
442 IP.magic_xmode(opts_all.xmode)
443 otrap.release_out()
443 otrap.release_out()
444
444
445 #------------------------------------------------------------------------
445 #------------------------------------------------------------------------
446 # Execute user config
446 # Execute user config
447
447
448 # Create a valid config structure with the right precedence order:
448 # Create a valid config structure with the right precedence order:
449 # defaults < rcfile < command line. This needs to be in the instance, so
449 # defaults < rcfile < command line. This needs to be in the instance, so
450 # that method calls below that rely on it find it.
450 # that method calls below that rely on it find it.
451 IP.rc = rc_def.copy()
451 IP.rc = rc_def.copy()
452
452
453 # Work with a local alias inside this routine to avoid unnecessary
453 # Work with a local alias inside this routine to avoid unnecessary
454 # attribute lookups.
454 # attribute lookups.
455 IP_rc = IP.rc
455 IP_rc = IP.rc
456
456
457 IP_rc.update(opts_def)
457 IP_rc.update(opts_def)
458 if rcfiledata:
458 if rcfiledata:
459 # now we can update
459 # now we can update
460 IP_rc.update(rcfiledata)
460 IP_rc.update(rcfiledata)
461 IP_rc.update(opts)
461 IP_rc.update(opts)
462 IP_rc.update(rc_override)
462 IP_rc.update(rc_override)
463
463
464 # Store the original cmd line for reference:
464 # Store the original cmd line for reference:
465 IP_rc.opts = opts
465 IP_rc.opts = opts
466 IP_rc.args = args
466 IP_rc.args = args
467
467
468 # create a *runtime* Struct like rc for holding parameters which may be
468 # create a *runtime* Struct like rc for holding parameters which may be
469 # created and/or modified by runtime user extensions.
469 # created and/or modified by runtime user extensions.
470 IP.runtime_rc = Struct()
470 IP.runtime_rc = Struct()
471
471
472 # from this point on, all config should be handled through IP_rc,
472 # from this point on, all config should be handled through IP_rc,
473 # opts* shouldn't be used anymore.
473 # opts* shouldn't be used anymore.
474
474
475 # add personal .ipython dir to sys.path so that users can put things in
475 # add personal .ipython dir to sys.path so that users can put things in
476 # there for customization
476 # there for customization
477 sys.path.append(IP_rc.ipythondir)
477 sys.path.append(IP_rc.ipythondir)
478 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
478 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
479
479
480 # update IP_rc with some special things that need manual
480 # update IP_rc with some special things that need manual
481 # tweaks. Basically options which affect other options. I guess this
481 # tweaks. Basically options which affect other options. I guess this
482 # should just be written so that options are fully orthogonal and we
482 # should just be written so that options are fully orthogonal and we
483 # wouldn't worry about this stuff!
483 # wouldn't worry about this stuff!
484
484
485 if IP_rc.classic:
485 if IP_rc.classic:
486 IP_rc.quick = 1
486 IP_rc.quick = 1
487 IP_rc.cache_size = 0
487 IP_rc.cache_size = 0
488 IP_rc.pprint = 0
488 IP_rc.pprint = 0
489 IP_rc.prompt_in1 = '>>> '
489 IP_rc.prompt_in1 = '>>> '
490 IP_rc.prompt_in2 = '... '
490 IP_rc.prompt_in2 = '... '
491 IP_rc.prompt_out = ''
491 IP_rc.prompt_out = ''
492 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
492 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
493 IP_rc.colors = 'NoColor'
493 IP_rc.colors = 'NoColor'
494 IP_rc.xmode = 'Plain'
494 IP_rc.xmode = 'Plain'
495
495
496 # configure readline
496 # configure readline
497 # Define the history file for saving commands in between sessions
497 # Define the history file for saving commands in between sessions
498 if IP_rc.profile:
498 if IP_rc.profile:
499 histfname = 'history-%s' % IP_rc.profile
499 histfname = 'history-%s' % IP_rc.profile
500 else:
500 else:
501 histfname = 'history'
501 histfname = 'history'
502 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
502 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
503
503
504 # update exception handlers with rc file status
504 # update exception handlers with rc file status
505 otrap.trap_out() # I don't want these messages ever.
505 otrap.trap_out() # I don't want these messages ever.
506 IP.magic_xmode(IP_rc.xmode)
506 IP.magic_xmode(IP_rc.xmode)
507 otrap.release_out()
507 otrap.release_out()
508
508
509 # activate logging if requested and not reloading a log
509 # activate logging if requested and not reloading a log
510 if IP_rc.logplay:
510 if IP_rc.logplay:
511 IP.magic_logstart(IP_rc.logplay + ' append')
511 IP.magic_logstart(IP_rc.logplay + ' append')
512 elif IP_rc.logfile:
512 elif IP_rc.logfile:
513 IP.magic_logstart(IP_rc.logfile)
513 IP.magic_logstart(IP_rc.logfile)
514 elif IP_rc.log:
514 elif IP_rc.log:
515 IP.magic_logstart()
515 IP.magic_logstart()
516
516
517 # find user editor so that it we don't have to look it up constantly
517 # find user editor so that it we don't have to look it up constantly
518 if IP_rc.editor.strip()=='0':
518 if IP_rc.editor.strip()=='0':
519 try:
519 try:
520 ed = os.environ['EDITOR']
520 ed = os.environ['EDITOR']
521 except KeyError:
521 except KeyError:
522 if os.name == 'posix':
522 if os.name == 'posix':
523 ed = 'vi' # the only one guaranteed to be there!
523 ed = 'vi' # the only one guaranteed to be there!
524 else:
524 else:
525 ed = 'notepad' # same in Windows!
525 ed = 'notepad' # same in Windows!
526 IP_rc.editor = ed
526 IP_rc.editor = ed
527
527
528 # Keep track of whether this is an embedded instance or not (useful for
528 # Keep track of whether this is an embedded instance or not (useful for
529 # post-mortems).
529 # post-mortems).
530 IP_rc.embedded = IP.embedded
530 IP_rc.embedded = IP.embedded
531
531
532 # Recursive reload
532 # Recursive reload
533 try:
533 try:
534 from IPython import deep_reload
534 from IPython import deep_reload
535 if IP_rc.deep_reload:
535 if IP_rc.deep_reload:
536 __builtin__.reload = deep_reload.reload
536 __builtin__.reload = deep_reload.reload
537 else:
537 else:
538 __builtin__.dreload = deep_reload.reload
538 __builtin__.dreload = deep_reload.reload
539 del deep_reload
539 del deep_reload
540 except ImportError:
540 except ImportError:
541 pass
541 pass
542
542
543 # Save the current state of our namespace so that the interactive shell
543 # Save the current state of our namespace so that the interactive shell
544 # can later know which variables have been created by us from config files
544 # can later know which variables have been created by us from config files
545 # and loading. This way, loading a file (in any way) is treated just like
545 # and loading. This way, loading a file (in any way) is treated just like
546 # defining things on the command line, and %who works as expected.
546 # defining things on the command line, and %who works as expected.
547
547
548 # DON'T do anything that affects the namespace beyond this point!
548 # DON'T do anything that affects the namespace beyond this point!
549 IP.internal_ns.update(__main__.__dict__)
549 IP.internal_ns.update(__main__.__dict__)
550
550
551 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
551 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
552
552
553 # Now run through the different sections of the users's config
553 # Now run through the different sections of the users's config
554 if IP_rc.debug:
554 if IP_rc.debug:
555 print 'Trying to execute the following configuration structure:'
555 print 'Trying to execute the following configuration structure:'
556 print '(Things listed first are deeper in the inclusion tree and get'
556 print '(Things listed first are deeper in the inclusion tree and get'
557 print 'loaded first).\n'
557 print 'loaded first).\n'
558 pprint(IP_rc.__dict__)
558 pprint(IP_rc.__dict__)
559
559
560 for mod in IP_rc.import_mod:
560 for mod in IP_rc.import_mod:
561 try:
561 try:
562 exec 'import '+mod in IP.user_ns
562 exec 'import '+mod in IP.user_ns
563 except :
563 except :
564 IP.InteractiveTB()
564 IP.InteractiveTB()
565 import_fail_info(mod)
565 import_fail_info(mod)
566
566
567 for mod_fn in IP_rc.import_some:
567 for mod_fn in IP_rc.import_some:
568 if mod_fn == []: break
568 if mod_fn == []: break
569 mod,fn = mod_fn[0],','.join(mod_fn[1:])
569 mod,fn = mod_fn[0],','.join(mod_fn[1:])
570 try:
570 try:
571 exec 'from '+mod+' import '+fn in IP.user_ns
571 exec 'from '+mod+' import '+fn in IP.user_ns
572 except :
572 except :
573 IP.InteractiveTB()
573 IP.InteractiveTB()
574 import_fail_info(mod,fn)
574 import_fail_info(mod,fn)
575
575
576 for mod in IP_rc.import_all:
576 for mod in IP_rc.import_all:
577 try:
577 try:
578 exec 'from '+mod+' import *' in IP.user_ns
578 exec 'from '+mod+' import *' in IP.user_ns
579 except :
579 except :
580 IP.InteractiveTB()
580 IP.InteractiveTB()
581 import_fail_info(mod)
581 import_fail_info(mod)
582
582
583 for code in IP_rc.execute:
583 for code in IP_rc.execute:
584 try:
584 try:
585 exec code in IP.user_ns
585 exec code in IP.user_ns
586 except:
586 except:
587 IP.InteractiveTB()
587 IP.InteractiveTB()
588 warn('Failure executing code: ' + `code`)
588 warn('Failure executing code: ' + `code`)
589
589
590 # Execute the files the user wants in ipythonrc
590 # Execute the files the user wants in ipythonrc
591 for file in IP_rc.execfile:
591 for file in IP_rc.execfile:
592 try:
592 try:
593 file = filefind(file,sys.path+[IPython_dir])
593 file = filefind(file,sys.path+[IPython_dir])
594 except IOError:
594 except IOError:
595 warn(itpl('File $file not found. Skipping it.'))
595 warn(itpl('File $file not found. Skipping it.'))
596 else:
596 else:
597 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
597 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
598
598
599 # release stdout and stderr and save config log into a global summary
599 # release stdout and stderr and save config log into a global summary
600 msg.config.release_all()
600 msg.config.release_all()
601 if IP_rc.messages:
601 if IP_rc.messages:
602 msg.summary += msg.config.summary_all()
602 msg.summary += msg.config.summary_all()
603
603
604 #------------------------------------------------------------------------
604 #------------------------------------------------------------------------
605 # Setup interactive session
605 # Setup interactive session
606
606
607 # Now we should be fully configured. We can then execute files or load
607 # Now we should be fully configured. We can then execute files or load
608 # things only needed for interactive use. Then we'll open the shell.
608 # things only needed for interactive use. Then we'll open the shell.
609
609
610 # Take a snapshot of the user namespace before opening the shell. That way
610 # Take a snapshot of the user namespace before opening the shell. That way
611 # we'll be able to identify which things were interactively defined and
611 # we'll be able to identify which things were interactively defined and
612 # which were defined through config files.
612 # which were defined through config files.
613 IP.user_config_ns = IP.user_ns.copy()
613 IP.user_config_ns = IP.user_ns.copy()
614
614
615 # Force reading a file as if it were a session log. Slower but safer.
615 # Force reading a file as if it were a session log. Slower but safer.
616 if load_logplay:
616 if load_logplay:
617 print 'Replaying log...'
617 print 'Replaying log...'
618 try:
618 try:
619 if IP_rc.debug:
619 if IP_rc.debug:
620 logplay_quiet = 0
620 logplay_quiet = 0
621 else:
621 else:
622 logplay_quiet = 1
622 logplay_quiet = 1
623
623
624 msg.logplay.trap_all()
624 msg.logplay.trap_all()
625 IP.safe_execfile(load_logplay,IP.user_ns,
625 IP.safe_execfile(load_logplay,IP.user_ns,
626 islog = 1, quiet = logplay_quiet)
626 islog = 1, quiet = logplay_quiet)
627 msg.logplay.release_all()
627 msg.logplay.release_all()
628 if IP_rc.messages:
628 if IP_rc.messages:
629 msg.summary += msg.logplay.summary_all()
629 msg.summary += msg.logplay.summary_all()
630 except:
630 except:
631 warn('Problems replaying logfile %s.' % load_logplay)
631 warn('Problems replaying logfile %s.' % load_logplay)
632 IP.InteractiveTB()
632 IP.InteractiveTB()
633
633
634 # Load remaining files in command line
634 # Load remaining files in command line
635 msg.user_exec.trap_all()
635 msg.user_exec.trap_all()
636
636
637 # Do NOT execute files named in the command line as scripts to be loaded
637 # Do NOT execute files named in the command line as scripts to be loaded
638 # by embedded instances. Doing so has the potential for an infinite
638 # by embedded instances. Doing so has the potential for an infinite
639 # recursion if there are exceptions thrown in the process.
639 # recursion if there are exceptions thrown in the process.
640
640
641 # XXX FIXME: the execution of user files should be moved out to after
641 # XXX FIXME: the execution of user files should be moved out to after
642 # ipython is fully initialized, just as if they were run via %run at the
642 # ipython is fully initialized, just as if they were run via %run at the
643 # ipython prompt. This would also give them the benefit of ipython's
643 # ipython prompt. This would also give them the benefit of ipython's
644 # nice tracebacks.
644 # nice tracebacks.
645
645
646 if not embedded and IP_rc.args:
646 if not embedded and IP_rc.args:
647 name_save = IP.user_ns['__name__']
647 name_save = IP.user_ns['__name__']
648 IP.user_ns['__name__'] = '__main__'
648 IP.user_ns['__name__'] = '__main__'
649 try:
649 try:
650 # Set our own excepthook in case the user code tries to call it
650 # Set our own excepthook in case the user code tries to call it
651 # directly. This prevents triggering the IPython crash handler.
651 # directly. This prevents triggering the IPython crash handler.
652 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
652 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
653 for run in args:
653 for run in args:
654 IP.safe_execfile(run,IP.user_ns)
654 IP.safe_execfile(run,IP.user_ns)
655 finally:
655 finally:
656 # Reset our crash handler in place
656 # Reset our crash handler in place
657 sys.excepthook = old_excepthook
657 sys.excepthook = old_excepthook
658
658
659 IP.user_ns['__name__'] = name_save
659 IP.user_ns['__name__'] = name_save
660
660
661 msg.user_exec.release_all()
661 msg.user_exec.release_all()
662 if IP_rc.messages:
662 if IP_rc.messages:
663 msg.summary += msg.user_exec.summary_all()
663 msg.summary += msg.user_exec.summary_all()
664
664
665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
666 if IP_rc.nosep:
666 if IP_rc.nosep:
667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
674
674
675 # Determine how many lines at the bottom of the screen are needed for
675 # Determine how many lines at the bottom of the screen are needed for
676 # showing prompts, so we can know wheter long strings are to be printed or
676 # showing prompts, so we can know wheter long strings are to be printed or
677 # paged:
677 # paged:
678 num_lines_bot = IP_rc.separate_in.count('\n')+1
678 num_lines_bot = IP_rc.separate_in.count('\n')+1
679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
680
680
681 # configure startup banner
681 # configure startup banner
682 if IP_rc.c: # regular python doesn't print the banner with -c
682 if IP_rc.c: # regular python doesn't print the banner with -c
683 IP_rc.banner = 0
683 IP_rc.banner = 0
684 if IP_rc.banner:
684 if IP_rc.banner:
685 BANN_P = IP.BANNER_PARTS
685 BANN_P = IP.BANNER_PARTS
686 else:
686 else:
687 BANN_P = []
687 BANN_P = []
688
688
689 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
689 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
690
690
691 # add message log (possibly empty)
691 # add message log (possibly empty)
692 if msg.summary: BANN_P.append(msg.summary)
692 if msg.summary: BANN_P.append(msg.summary)
693 # Final banner is a string
693 # Final banner is a string
694 IP.BANNER = '\n'.join(BANN_P)
694 IP.BANNER = '\n'.join(BANN_P)
695
695
696 # Finalize the IPython instance. This assumes the rc structure is fully
696 # Finalize the IPython instance. This assumes the rc structure is fully
697 # in place.
697 # in place.
698 IP.post_config_initialization()
698 IP.post_config_initialization()
699
699
700 return IP
700 return IP
701 #************************ end of file <ipmaker.py> **************************
701 #************************ end of file <ipmaker.py> **************************
@@ -1,585 +1,589 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #*****************************************************************************
2 #*****************************************************************************
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 #
4 #
5 # Distributed under the terms of the BSD License. The full license is in
5 # Distributed under the terms of the BSD License. The full license is in
6 # the file COPYING, distributed as part of this software.
6 # the file COPYING, distributed as part of this software.
7 #*****************************************************************************
7 #*****************************************************************************
8
8
9 # $Id: usage.py 966 2005-12-29 08:34:07Z fperez $
9 # $Id: usage.py 990 2006-01-04 06:59:02Z fperez $
10
10
11 from IPython import Release
11 from IPython import Release
12 __author__ = '%s <%s>' % Release.authors['Fernando']
12 __author__ = '%s <%s>' % Release.authors['Fernando']
13 __license__ = Release.license
13 __license__ = Release.license
14 __version__ = Release.version
14 __version__ = Release.version
15
15
16 __doc__ = """
16 __doc__ = """
17 IPython -- An enhanced Interactive Python
17 IPython -- An enhanced Interactive Python
18 =========================================
18 =========================================
19
19
20 A Python shell with automatic history (input and output), dynamic object
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the system
21 introspection, easier configuration, command completion, access to the system
22 shell and more.
22 shell and more.
23
23
24 IPython can also be embedded in running programs. See EMBEDDING below.
24 IPython can also be embedded in running programs. See EMBEDDING below.
25
25
26
26
27 USAGE
27 USAGE
28 ipython [options] files
28 ipython [options] files
29
29
30 If invoked with no options, it executes all the files listed in
30 If invoked with no options, it executes all the files listed in
31 sequence and drops you into the interpreter while still acknowledging
31 sequence and drops you into the interpreter while still acknowledging
32 any options you may have set in your ipythonrc file. This behavior is
32 any options you may have set in your ipythonrc file. This behavior is
33 different from standard Python, which when called as python -i will
33 different from standard Python, which when called as python -i will
34 only execute one file and will ignore your configuration setup.
34 only execute one file and will ignore your configuration setup.
35
35
36 Please note that some of the configuration options are not available at
36 Please note that some of the configuration options are not available at
37 the command line, simply because they are not practical here. Look into
37 the command line, simply because they are not practical here. Look into
38 your ipythonrc configuration file for details on those. This file
38 your ipythonrc configuration file for details on those. This file
39 typically installed in the $HOME/.ipython directory.
39 typically installed in the $HOME/.ipython directory.
40
40
41 For Windows users, $HOME resolves to C:\\Documents and
41 For Windows users, $HOME resolves to C:\\Documents and
42 Settings\\YourUserName in most instances, and _ipython is used instead
42 Settings\\YourUserName in most instances, and _ipython is used instead
43 of .ipython, since some Win32 programs have problems with dotted names
43 of .ipython, since some Win32 programs have problems with dotted names
44 in directories.
44 in directories.
45
45
46 In the rest of this text, we will refer to this directory as
46 In the rest of this text, we will refer to this directory as
47 IPYTHONDIR.
47 IPYTHONDIR.
48
48
49
49
50 SPECIAL THREADING OPTIONS
50 SPECIAL THREADING OPTIONS
51 The following special options are ONLY valid at the beginning of the
51 The following special options are ONLY valid at the beginning of the
52 command line, and not later. This is because they control the initial-
52 command line, and not later. This is because they control the initial-
53 ization of ipython itself, before the normal option-handling mechanism
53 ization of ipython itself, before the normal option-handling mechanism
54 is active.
54 is active.
55
55
56 -gthread, -qthread, -wthread, -pylab
56 -gthread, -qthread, -wthread, -pylab
57
57
58 Only ONE of these can be given, and it can only be given as the
58 Only ONE of these can be given, and it can only be given as the
59 first option passed to IPython (it will have no effect in any
59 first option passed to IPython (it will have no effect in any
60 other position). They provide threading support for the GTK, QT
60 other position). They provide threading support for the GTK, QT
61 and WXWidgets toolkits, and for the matplotlib library.
61 and WXWidgets toolkits, and for the matplotlib library.
62
62
63 With any of the first three options, IPython starts running a
63 With any of the first three options, IPython starts running a
64 separate thread for the graphical toolkit's operation, so that
64 separate thread for the graphical toolkit's operation, so that
65 you can open and control graphical elements from within an
65 you can open and control graphical elements from within an
66 IPython command line, without blocking. All three provide
66 IPython command line, without blocking. All three provide
67 essentially the same functionality, respectively for GTK, QT and
67 essentially the same functionality, respectively for GTK, QT and
68 WXWidgets (via their Python interfaces).
68 WXWidgets (via their Python interfaces).
69
69
70 If -pylab is given, IPython loads special support for the mat-
70 If -pylab is given, IPython loads special support for the mat-
71 plotlib library (http://matplotlib.sourceforge.net), allowing
71 plotlib library (http://matplotlib.sourceforge.net), allowing
72 interactive usage of any of its backends as defined in the
72 interactive usage of any of its backends as defined in the
73 user's .matplotlibrc file. It automatically activates GTK, QT
73 user's .matplotlibrc file. It automatically activates GTK, QT
74 or WX threading for IPyhton if the choice of matplotlib backend
74 or WX threading for IPyhton if the choice of matplotlib backend
75 requires it. It also modifies the %run command to correctly
75 requires it. It also modifies the %run command to correctly
76 execute (without blocking) any matplotlib-based script which
76 execute (without blocking) any matplotlib-based script which
77 calls show() at the end.
77 calls show() at the end.
78
78
79 -tk The -g/q/wthread options, and -pylab (if matplotlib is
79 -tk The -g/q/wthread options, and -pylab (if matplotlib is
80 configured to use GTK, QT or WX), will normally block Tk
80 configured to use GTK, QT or WX), will normally block Tk
81 graphical interfaces. This means that when GTK, QT or WX
81 graphical interfaces. This means that when GTK, QT or WX
82 threading is active, any attempt to open a Tk GUI will result in
82 threading is active, any attempt to open a Tk GUI will result in
83 a dead window, and possibly cause the Python interpreter to
83 a dead window, and possibly cause the Python interpreter to
84 crash. An extra option, -tk, is available to address this
84 crash. An extra option, -tk, is available to address this
85 issue. It can ONLY be given as a SECOND option after any of the
85 issue. It can ONLY be given as a SECOND option after any of the
86 above (-gthread, -qthread, -wthread or -pylab).
86 above (-gthread, -qthread, -wthread or -pylab).
87
87
88 If -tk is given, IPython will try to coordinate Tk threading
88 If -tk is given, IPython will try to coordinate Tk threading
89 with GTK, QT or WX. This is however potentially unreliable, and
89 with GTK, QT or WX. This is however potentially unreliable, and
90 you will have to test on your platform and Python configuration
90 you will have to test on your platform and Python configuration
91 to determine whether it works for you. Debian users have
91 to determine whether it works for you. Debian users have
92 reported success, apparently due to the fact that Debian builds
92 reported success, apparently due to the fact that Debian builds
93 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
93 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
94 other Linux environments (such as Fedora Core 2/3), this option
94 other Linux environments (such as Fedora Core 2/3), this option
95 has caused random crashes and lockups of the Python interpreter.
95 has caused random crashes and lockups of the Python interpreter.
96 Under other operating systems (Mac OSX and Windows), you'll need
96 Under other operating systems (Mac OSX and Windows), you'll need
97 to try it to find out, since currently no user reports are
97 to try it to find out, since currently no user reports are
98 available.
98 available.
99
99
100 There is unfortunately no way for IPython to determine at run-
100 There is unfortunately no way for IPython to determine at run-
101 time whether -tk will work reliably or not, so you will need to
101 time whether -tk will work reliably or not, so you will need to
102 do some experiments before relying on it for regular work.
102 do some experiments before relying on it for regular work.
103
103
104 A WARNING ABOUT SIGNALS AND THREADS
104 A WARNING ABOUT SIGNALS AND THREADS
105
105
106 When any of the thread systems (GTK, QT or WX) are active, either
106 When any of the thread systems (GTK, QT or WX) are active, either
107 directly or via -pylab with a threaded backend, it is impossible to
107 directly or via -pylab with a threaded backend, it is impossible to
108 interrupt long-running Python code via Ctrl-C. IPython can not pass
108 interrupt long-running Python code via Ctrl-C. IPython can not pass
109 the KeyboardInterrupt exception (or the underlying SIGINT) across
109 the KeyboardInterrupt exception (or the underlying SIGINT) across
110 threads, so any long-running process started from IPython will run to
110 threads, so any long-running process started from IPython will run to
111 completion, or will have to be killed via an external (OS-based)
111 completion, or will have to be killed via an external (OS-based)
112 mechanism.
112 mechanism.
113
113
114 To the best of my knowledge, this limitation is imposed by the Python
114 To the best of my knowledge, this limitation is imposed by the Python
115 interpreter itself, and it comes from the difficulty of writing
115 interpreter itself, and it comes from the difficulty of writing
116 portable signal/threaded code. If any user is an expert on this topic
116 portable signal/threaded code. If any user is an expert on this topic
117 and can suggest a better solution, I would love to hear about it. In
117 and can suggest a better solution, I would love to hear about it. In
118 the IPython sources, look at the Shell.py module, and in particular at
118 the IPython sources, look at the Shell.py module, and in particular at
119 the runcode() method.
119 the runcode() method.
120
120
121 REGULAR OPTIONS
121 REGULAR OPTIONS
122 After the above threading options have been given, regular options can
122 After the above threading options have been given, regular options can
123 follow in any order. All options can be abbreviated to their shortest
123 follow in any order. All options can be abbreviated to their shortest
124 non-ambiguous form and are case-sensitive. One or two dashes can be
124 non-ambiguous form and are case-sensitive. One or two dashes can be
125 used. Some options have an alternate short form, indicated after a |.
125 used. Some options have an alternate short form, indicated after a |.
126
126
127 Most options can also be set from your ipythonrc configuration file.
127 Most options can also be set from your ipythonrc configuration file.
128 See the provided examples for assistance. Options given on the comman-
128 See the provided examples for assistance. Options given on the comman-
129 dline override the values set in the ipythonrc file.
129 dline override the values set in the ipythonrc file.
130
130
131 All options with a [no] prepended can be specified in negated form
131 All options with a [no] prepended can be specified in negated form
132 (using -nooption instead of -option) to turn the feature off.
132 (using -nooption instead of -option) to turn the feature off.
133
133
134 -h, --help
134 -h, --help
135 Show summary of options.
135 Show summary of options.
136
136
137 -pylab This can only be given as the first option passed to IPython (it
137 -pylab This can only be given as the first option passed to IPython (it
138 will have no effect in any other position). It adds special sup-
138 will have no effect in any other position). It adds special sup-
139 port for the matplotlib library (http://matplotlib.source-
139 port for the matplotlib library (http://matplotlib.source-
140 forge.net), allowing interactive usage of any of its backends as
140 forge.net), allowing interactive usage of any of its backends as
141 defined in the user’s .matplotlibrc file. It automatically
141 defined in the user’s .matplotlibrc file. It automatically
142 activates GTK or WX threading for IPyhton if the choice of mat-
142 activates GTK or WX threading for IPyhton if the choice of mat-
143 plotlib backend requires it. It also modifies the @run command
143 plotlib backend requires it. It also modifies the @run command
144 to correctly execute (without blocking) any matplotlib-based
144 to correctly execute (without blocking) any matplotlib-based
145 script which calls show() at the end.
145 script which calls show() at the end.
146
146
147 -[no]autocall
147 -autocall <val>
148 Make IPython automatically call any callable object even if you
148 Make IPython automatically call any callable object even if you
149 didnt type explicit parentheses. For example, ’str 43’ becomes
149 didn't type explicit parentheses. For example, 'str 43' becomes
150 ’str(43)’ automatically.
150 'str(43)' automatically. The value can be '0' to disable the
151 feature, '1' for 'smart' autocall, where it is not applied if
152 there are no more arguments on the line, and '2' for 'full'
153 autocall, where all callable objects are automatically called
154 (even if no arguments are present). The default is '1'.
151
155
152 -[no]autoindent
156 -[no]autoindent
153 Turn automatic indentation on/off.
157 Turn automatic indentation on/off.
154
158
155 -[no]automagic
159 -[no]automagic
156 Make magic commands automatic (without needing their first char-
160 Make magic commands automatic (without needing their first char-
157 acter to be %). Type %magic at the IPython prompt for more
161 acter to be %). Type %magic at the IPython prompt for more
158 information.
162 information.
159
163
160 -[no]autoedit_syntax
164 -[no]autoedit_syntax
161 When a syntax error occurs after editing a file, automatically
165 When a syntax error occurs after editing a file, automatically
162 open the file to the trouble causing line for convenient fixing.
166 open the file to the trouble causing line for convenient fixing.
163
167
164 -[no]banner
168 -[no]banner
165 Print the intial information banner (default on).
169 Print the intial information banner (default on).
166
170
167 -c <command>
171 -c <command>
168 Execute the given command string, and set sys.argv to [’c’].
172 Execute the given command string, and set sys.argv to [’c’].
169 This is similar to the -c option in the normal Python inter-
173 This is similar to the -c option in the normal Python inter-
170 preter.
174 preter.
171
175
172 -cache_size|cs <n>
176 -cache_size|cs <n>
173 Size of the output cache (maximum number of entries to hold in
177 Size of the output cache (maximum number of entries to hold in
174 memory). The default is 1000, you can change it permanently in
178 memory). The default is 1000, you can change it permanently in
175 your config file. Setting it to 0 completely disables the
179 your config file. Setting it to 0 completely disables the
176 caching system, and the minimum value accepted is 20 (if you
180 caching system, and the minimum value accepted is 20 (if you
177 provide a value less than 20, it is reset to 0 and a warning is
181 provide a value less than 20, it is reset to 0 and a warning is
178 issued). This limit is defined because otherwise you’ll spend
182 issued). This limit is defined because otherwise you’ll spend
179 more time re-flushing a too small cache than working.
183 more time re-flushing a too small cache than working.
180
184
181 -classic|cl
185 -classic|cl
182 Gives IPython a similar feel to the classic Python prompt.
186 Gives IPython a similar feel to the classic Python prompt.
183
187
184 -colors <scheme>
188 -colors <scheme>
185 Color scheme for prompts and exception reporting. Currently
189 Color scheme for prompts and exception reporting. Currently
186 implemented: NoColor, Linux, and LightBG.
190 implemented: NoColor, Linux, and LightBG.
187
191
188 -[no]color_info
192 -[no]color_info
189 IPython can display information about objects via a set of func-
193 IPython can display information about objects via a set of func-
190 tions, and optionally can use colors for this, syntax highlight-
194 tions, and optionally can use colors for this, syntax highlight-
191 ing source code and various other elements. However, because
195 ing source code and various other elements. However, because
192 this information is passed through a pager (like ’less’) and
196 this information is passed through a pager (like ’less’) and
193 many pagers get confused with color codes, this option is off by
197 many pagers get confused with color codes, this option is off by
194 default. You can test it and turn it on permanently in your
198 default. You can test it and turn it on permanently in your
195 ipythonrc file if it works for you. As a reference, the ’less’
199 ipythonrc file if it works for you. As a reference, the ’less’
196 pager supplied with Mandrake 8.2 works ok, but that in RedHat
200 pager supplied with Mandrake 8.2 works ok, but that in RedHat
197 7.2 doesn’t.
201 7.2 doesn’t.
198
202
199 Test it and turn it on permanently if it works with your system.
203 Test it and turn it on permanently if it works with your system.
200 The magic function @color_info allows you to toggle this inter-
204 The magic function @color_info allows you to toggle this inter-
201 actively for testing.
205 actively for testing.
202
206
203 -[no]confirm_exit
207 -[no]confirm_exit
204 Set to confirm when you try to exit IPython with an EOF (Con-
208 Set to confirm when you try to exit IPython with an EOF (Con-
205 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
209 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
206 magic functions @Exit or @Quit you can force a direct exit,
210 magic functions @Exit or @Quit you can force a direct exit,
207 bypassing any confirmation.
211 bypassing any confirmation.
208
212
209 -[no]debug
213 -[no]debug
210 Show information about the loading process. Very useful to pin
214 Show information about the loading process. Very useful to pin
211 down problems with your configuration files or to get details
215 down problems with your configuration files or to get details
212 about session restores.
216 about session restores.
213
217
214 -[no]deep_reload
218 -[no]deep_reload
215 IPython can use the deep_reload module which reloads changes in
219 IPython can use the deep_reload module which reloads changes in
216 modules recursively (it replaces the reload() function, so you
220 modules recursively (it replaces the reload() function, so you
217 don’t need to change anything to use it). deep_reload() forces a
221 don’t need to change anything to use it). deep_reload() forces a
218 full reload of modules whose code may have changed, which the
222 full reload of modules whose code may have changed, which the
219 default reload() function does not.
223 default reload() function does not.
220
224
221 When deep_reload is off, IPython will use the normal reload(),
225 When deep_reload is off, IPython will use the normal reload(),
222 but deep_reload will still be available as dreload(). This fea-
226 but deep_reload will still be available as dreload(). This fea-
223 ture is off by default [which means that you have both normal
227 ture is off by default [which means that you have both normal
224 reload() and dreload()].
228 reload() and dreload()].
225
229
226 -editor <name>
230 -editor <name>
227 Which editor to use with the @edit command. By default, IPython
231 Which editor to use with the @edit command. By default, IPython
228 will honor your EDITOR environment variable (if not set, vi is
232 will honor your EDITOR environment variable (if not set, vi is
229 the Unix default and notepad the Windows one). Since this editor
233 the Unix default and notepad the Windows one). Since this editor
230 is invoked on the fly by IPython and is meant for editing small
234 is invoked on the fly by IPython and is meant for editing small
231 code snippets, you may want to use a small, lightweight editor
235 code snippets, you may want to use a small, lightweight editor
232 here (in case your default EDITOR is something like Emacs).
236 here (in case your default EDITOR is something like Emacs).
233
237
234 -ipythondir <name>
238 -ipythondir <name>
235 The name of your IPython configuration directory IPYTHONDIR.
239 The name of your IPython configuration directory IPYTHONDIR.
236 This can also be specified through the environment variable
240 This can also be specified through the environment variable
237 IPYTHONDIR.
241 IPYTHONDIR.
238
242
239 -log|l Generate a log file of all input. The file is named
243 -log|l Generate a log file of all input. The file is named
240 ipython_log.py in your current directory (which prevents logs
244 ipython_log.py in your current directory (which prevents logs
241 from multiple IPython sessions from trampling each other). You
245 from multiple IPython sessions from trampling each other). You
242 can use this to later restore a session by loading your logfile
246 can use this to later restore a session by loading your logfile
243 as a file to be executed with option -logplay (see below).
247 as a file to be executed with option -logplay (see below).
244
248
245 -logfile|lf
249 -logfile|lf
246 Specify the name of your logfile.
250 Specify the name of your logfile.
247
251
248 -logplay|lp
252 -logplay|lp
249 Replay a previous log. For restoring a session as close as pos-
253 Replay a previous log. For restoring a session as close as pos-
250 sible to the state you left it in, use this option (don’t just
254 sible to the state you left it in, use this option (don’t just
251 run the logfile). With -logplay, IPython will try to reconstruct
255 run the logfile). With -logplay, IPython will try to reconstruct
252 the previous working environment in full, not just execute the
256 the previous working environment in full, not just execute the
253 commands in the logfile.
257 commands in the logfile.
254 When a session is restored, logging is automatically turned on
258 When a session is restored, logging is automatically turned on
255 again with the name of the logfile it was invoked with (it is
259 again with the name of the logfile it was invoked with (it is
256 read from the log header). So once you’ve turned logging on for
260 read from the log header). So once you’ve turned logging on for
257 a session, you can quit IPython and reload it as many times as
261 a session, you can quit IPython and reload it as many times as
258 you want and it will continue to log its history and restore
262 you want and it will continue to log its history and restore
259 from the beginning every time.
263 from the beginning every time.
260
264
261 Caveats: there are limitations in this option. The history vari-
265 Caveats: there are limitations in this option. The history vari-
262 ables _i*,_* and _dh don’t get restored properly. In the future
266 ables _i*,_* and _dh don’t get restored properly. In the future
263 we will try to implement full session saving by writing and
267 we will try to implement full session saving by writing and
264 retrieving a failed because of inherent limitations of Python’s
268 retrieving a failed because of inherent limitations of Python’s
265 Pickle module, so this may have to wait.
269 Pickle module, so this may have to wait.
266
270
267 -[no]messages
271 -[no]messages
268 Print messages which IPython collects about its startup process
272 Print messages which IPython collects about its startup process
269 (default on).
273 (default on).
270
274
271 -[no]pdb
275 -[no]pdb
272 Automatically call the pdb debugger after every uncaught excep-
276 Automatically call the pdb debugger after every uncaught excep-
273 tion. If you are used to debugging using pdb, this puts you
277 tion. If you are used to debugging using pdb, this puts you
274 automatically inside of it after any call (either in IPython or
278 automatically inside of it after any call (either in IPython or
275 in code called by it) which triggers an exception which goes
279 in code called by it) which triggers an exception which goes
276 uncaught.
280 uncaught.
277
281
278 -[no]pprint
282 -[no]pprint
279 IPython can optionally use the pprint (pretty printer) module
283 IPython can optionally use the pprint (pretty printer) module
280 for displaying results. pprint tends to give a nicer display of
284 for displaying results. pprint tends to give a nicer display of
281 nested data structures. If you like it, you can turn it on per-
285 nested data structures. If you like it, you can turn it on per-
282 manently in your config file (default off).
286 manently in your config file (default off).
283
287
284 -profile|p <name>
288 -profile|p <name>
285 Assume that your config file is ipythonrc-<name> (looks in cur-
289 Assume that your config file is ipythonrc-<name> (looks in cur-
286 rent dir first, then in IPYTHONDIR). This is a quick way to keep
290 rent dir first, then in IPYTHONDIR). This is a quick way to keep
287 and load multiple config files for different tasks, especially
291 and load multiple config files for different tasks, especially
288 if you use the include option of config files. You can keep a
292 if you use the include option of config files. You can keep a
289 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
293 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
290 which include this one and load extra things for particular
294 which include this one and load extra things for particular
291 tasks. For example:
295 tasks. For example:
292
296
293 1) $HOME/.ipython/ipythonrc : load basic things you always want.
297 1) $HOME/.ipython/ipythonrc : load basic things you always want.
294 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
298 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
295 related modules.
299 related modules.
296 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
300 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
297 plotting modules.
301 plotting modules.
298
302
299 Since it is possible to create an endless loop by having circu-
303 Since it is possible to create an endless loop by having circu-
300 lar file inclusions, IPython will stop if it reaches 15 recur-
304 lar file inclusions, IPython will stop if it reaches 15 recur-
301 sive inclusions.
305 sive inclusions.
302
306
303 -prompt_in1|pi1 <string>
307 -prompt_in1|pi1 <string>
304 Specify the string used for input prompts. Note that if you are
308 Specify the string used for input prompts. Note that if you are
305 using numbered prompts, the number is represented with a ’\#’ in
309 using numbered prompts, the number is represented with a ’\#’ in
306 the string. Don’t forget to quote strings with spaces embedded
310 the string. Don’t forget to quote strings with spaces embedded
307 in them. Default: ’In [\#]:’.
311 in them. Default: ’In [\#]:’.
308
312
309 Most bash-like escapes can be used to customize IPython’s
313 Most bash-like escapes can be used to customize IPython’s
310 prompts, as well as a few additional ones which are IPython-spe-
314 prompts, as well as a few additional ones which are IPython-spe-
311 cific. All valid prompt escapes are described in detail in the
315 cific. All valid prompt escapes are described in detail in the
312 Customization section of the IPython HTML/PDF manual.
316 Customization section of the IPython HTML/PDF manual.
313
317
314 -prompt_in2|pi2 <string>
318 -prompt_in2|pi2 <string>
315 Similar to the previous option, but used for the continuation
319 Similar to the previous option, but used for the continuation
316 prompts. The special sequence ’\D’ is similar to ’\#’, but with
320 prompts. The special sequence ’\D’ is similar to ’\#’, but with
317 all digits replaced dots (so you can have your continuation
321 all digits replaced dots (so you can have your continuation
318 prompt aligned with your input prompt). Default: ’ .\D.:’
322 prompt aligned with your input prompt). Default: ’ .\D.:’
319 (note three spaces at the start for alignment with ’In [\#]’).
323 (note three spaces at the start for alignment with ’In [\#]’).
320
324
321 -prompt_out|po <string>
325 -prompt_out|po <string>
322 String used for output prompts, also uses numbers like
326 String used for output prompts, also uses numbers like
323 prompt_in1. Default: ’Out[\#]:’.
327 prompt_in1. Default: ’Out[\#]:’.
324
328
325 -quick Start in bare bones mode (no config file loaded).
329 -quick Start in bare bones mode (no config file loaded).
326
330
327 -rcfile <name>
331 -rcfile <name>
328 Name of your IPython resource configuration file. normally
332 Name of your IPython resource configuration file. normally
329 IPython loads ipythonrc (from current directory) or
333 IPython loads ipythonrc (from current directory) or
330 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
334 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
331 IPython starts with a bare bones configuration (no modules
335 IPython starts with a bare bones configuration (no modules
332 loaded at all).
336 loaded at all).
333
337
334 -[no]readline
338 -[no]readline
335 Use the readline library, which is needed to support name com-
339 Use the readline library, which is needed to support name com-
336 pletion and command history, among other things. It is enabled
340 pletion and command history, among other things. It is enabled
337 by default, but may cause problems for users of X/Emacs in
341 by default, but may cause problems for users of X/Emacs in
338 Python comint or shell buffers.
342 Python comint or shell buffers.
339
343
340 Note that emacs ’eterm’ buffers (opened with M-x term) support
344 Note that emacs ’eterm’ buffers (opened with M-x term) support
341 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
345 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
342 shell and C-c !) buffers do not.
346 shell and C-c !) buffers do not.
343
347
344 -screen_length|sl <n>
348 -screen_length|sl <n>
345 Number of lines of your screen. This is used to control print-
349 Number of lines of your screen. This is used to control print-
346 ing of very long strings. Strings longer than this number of
350 ing of very long strings. Strings longer than this number of
347 lines will be sent through a pager instead of directly printed.
351 lines will be sent through a pager instead of directly printed.
348
352
349 The default value for this is 0, which means IPython will auto-
353 The default value for this is 0, which means IPython will auto-
350 detect your screen size every time it needs to print certain
354 detect your screen size every time it needs to print certain
351 potentially long strings (this doesn’t change the behavior of
355 potentially long strings (this doesn’t change the behavior of
352 the ’print’ keyword, it’s only triggered internally). If for
356 the ’print’ keyword, it’s only triggered internally). If for
353 some reason this isn’t working well (it needs curses support),
357 some reason this isn’t working well (it needs curses support),
354 specify it yourself. Otherwise don’t change the default.
358 specify it yourself. Otherwise don’t change the default.
355
359
356 -separate_in|si <string>
360 -separate_in|si <string>
357 Separator before input prompts. Default ’0.
361 Separator before input prompts. Default ’0.
358
362
359 -separate_out|so <string>
363 -separate_out|so <string>
360 Separator before output prompts. Default: 0 (nothing).
364 Separator before output prompts. Default: 0 (nothing).
361
365
362 -separate_out2|so2 <string>
366 -separate_out2|so2 <string>
363 Separator after output prompts. Default: 0 (nothing).
367 Separator after output prompts. Default: 0 (nothing).
364
368
365 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
369 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
366 Simply removes all input/output separators.
370 Simply removes all input/output separators.
367
371
368 -upgrade
372 -upgrade
369 Allows you to upgrade your IPYTHONDIR configuration when you
373 Allows you to upgrade your IPYTHONDIR configuration when you
370 install a new version of IPython. Since new versions may
374 install a new version of IPython. Since new versions may
371 include new command lines options or example files, this copies
375 include new command lines options or example files, this copies
372 updated ipythonrc-type files. However, it backs up (with a .old
376 updated ipythonrc-type files. However, it backs up (with a .old
373 extension) all files which it overwrites so that you can merge
377 extension) all files which it overwrites so that you can merge
374 back any custimizations you might have in your personal files.
378 back any custimizations you might have in your personal files.
375
379
376 -Version
380 -Version
377 Print version information and exit.
381 Print version information and exit.
378
382
379 -xmode <modename>
383 -xmode <modename>
380 Mode for exception reporting. The valid modes are Plain, Con-
384 Mode for exception reporting. The valid modes are Plain, Con-
381 text, and Verbose.
385 text, and Verbose.
382
386
383 - Plain: similar to python’s normal traceback printing.
387 - Plain: similar to python’s normal traceback printing.
384
388
385 - Context: prints 5 lines of context source code around each
389 - Context: prints 5 lines of context source code around each
386 line in the traceback.
390 line in the traceback.
387
391
388 - Verbose: similar to Context, but additionally prints the vari-
392 - Verbose: similar to Context, but additionally prints the vari-
389 ables currently visible where the exception happened (shortening
393 ables currently visible where the exception happened (shortening
390 their strings if too long). This can potentially be very slow,
394 their strings if too long). This can potentially be very slow,
391 if you happen to have a huge data structure whose string repre-
395 if you happen to have a huge data structure whose string repre-
392 sentation is complex to compute. Your computer may appear to
396 sentation is complex to compute. Your computer may appear to
393 freeze for a while with cpu usage at 100%. If this occurs, you
397 freeze for a while with cpu usage at 100%. If this occurs, you
394 can cancel the traceback with Ctrl-C (maybe hitting it more than
398 can cancel the traceback with Ctrl-C (maybe hitting it more than
395 once).
399 once).
396
400
397
401
398 EMBEDDING
402 EMBEDDING
399 It is possible to start an IPython instance inside your own Python pro-
403 It is possible to start an IPython instance inside your own Python pro-
400 grams. In the documentation example files there are some illustrations
404 grams. In the documentation example files there are some illustrations
401 on how to do this.
405 on how to do this.
402
406
403 This feature allows you to evalutate dynamically the state of your
407 This feature allows you to evalutate dynamically the state of your
404 code, operate with your variables, analyze them, etc. Note however
408 code, operate with your variables, analyze them, etc. Note however
405 that any changes you make to values while in the shell do NOT propagate
409 that any changes you make to values while in the shell do NOT propagate
406 back to the running code, so it is safe to modify your values because
410 back to the running code, so it is safe to modify your values because
407 you won’t break your code in bizarre ways by doing so.
411 you won’t break your code in bizarre ways by doing so.
408 """
412 """
409
413
410 cmd_line_usage = __doc__
414 cmd_line_usage = __doc__
411
415
412 #---------------------------------------------------------------------------
416 #---------------------------------------------------------------------------
413 interactive_usage = """
417 interactive_usage = """
414 IPython -- An enhanced Interactive Python
418 IPython -- An enhanced Interactive Python
415 =========================================
419 =========================================
416
420
417 IPython offers a combination of convenient shell features, special commands
421 IPython offers a combination of convenient shell features, special commands
418 and a history mechanism for both input (command history) and output (results
422 and a history mechanism for both input (command history) and output (results
419 caching, similar to Mathematica). It is intended to be a fully compatible
423 caching, similar to Mathematica). It is intended to be a fully compatible
420 replacement for the standard Python interpreter, while offering vastly
424 replacement for the standard Python interpreter, while offering vastly
421 improved functionality and flexibility.
425 improved functionality and flexibility.
422
426
423 At your system command line, type 'ipython -help' to see the command line
427 At your system command line, type 'ipython -help' to see the command line
424 options available. This document only describes interactive features.
428 options available. This document only describes interactive features.
425
429
426 Warning: IPython relies on the existence of a global variable called __IP which
430 Warning: IPython relies on the existence of a global variable called __IP which
427 controls the shell itself. If you redefine __IP to anything, bizarre behavior
431 controls the shell itself. If you redefine __IP to anything, bizarre behavior
428 will quickly occur.
432 will quickly occur.
429
433
430 MAIN FEATURES
434 MAIN FEATURES
431
435
432 * Access to the standard Python help. As of Python 2.1, a help system is
436 * Access to the standard Python help. As of Python 2.1, a help system is
433 available with access to object docstrings and the Python manuals. Simply
437 available with access to object docstrings and the Python manuals. Simply
434 type 'help' (no quotes) to access it.
438 type 'help' (no quotes) to access it.
435
439
436 * Magic commands: type %magic for information on the magic subsystem.
440 * Magic commands: type %magic for information on the magic subsystem.
437
441
438 * System command aliases, via the %alias command or the ipythonrc config file.
442 * System command aliases, via the %alias command or the ipythonrc config file.
439
443
440 * Dynamic object information:
444 * Dynamic object information:
441
445
442 Typing ?word or word? prints detailed information about an object. If
446 Typing ?word or word? prints detailed information about an object. If
443 certain strings in the object are too long (docstrings, code, etc.) they get
447 certain strings in the object are too long (docstrings, code, etc.) they get
444 snipped in the center for brevity.
448 snipped in the center for brevity.
445
449
446 Typing ??word or word?? gives access to the full information without
450 Typing ??word or word?? gives access to the full information without
447 snipping long strings. Long strings are sent to the screen through the less
451 snipping long strings. Long strings are sent to the screen through the less
448 pager if longer than the screen, printed otherwise.
452 pager if longer than the screen, printed otherwise.
449
453
450 The ?/?? system gives access to the full source code for any object (if
454 The ?/?? system gives access to the full source code for any object (if
451 available), shows function prototypes and other useful information.
455 available), shows function prototypes and other useful information.
452
456
453 If you just want to see an object's docstring, type '%pdoc object' (without
457 If you just want to see an object's docstring, type '%pdoc object' (without
454 quotes, and without % if you have automagic on).
458 quotes, and without % if you have automagic on).
455
459
456 Both %pdoc and ?/?? give you access to documentation even on things which are
460 Both %pdoc and ?/?? give you access to documentation even on things which are
457 not explicitely defined. Try for example typing {}.get? or after import os,
461 not explicitely defined. Try for example typing {}.get? or after import os,
458 type os.path.abspath??. The magic functions %pdef, %source and %file operate
462 type os.path.abspath??. The magic functions %pdef, %source and %file operate
459 similarly.
463 similarly.
460
464
461 * Completion in the local namespace, by typing TAB at the prompt.
465 * Completion in the local namespace, by typing TAB at the prompt.
462
466
463 At any time, hitting tab will complete any available python commands or
467 At any time, hitting tab will complete any available python commands or
464 variable names, and show you a list of the possible completions if there's
468 variable names, and show you a list of the possible completions if there's
465 no unambiguous one. It will also complete filenames in the current directory.
469 no unambiguous one. It will also complete filenames in the current directory.
466
470
467 This feature requires the readline and rlcomplete modules, so it won't work
471 This feature requires the readline and rlcomplete modules, so it won't work
468 if your Python lacks readline support (such as under Windows).
472 if your Python lacks readline support (such as under Windows).
469
473
470 * Search previous command history in two ways (also requires readline):
474 * Search previous command history in two ways (also requires readline):
471
475
472 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
476 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
473 search through only the history items that match what you've typed so
477 search through only the history items that match what you've typed so
474 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
478 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
475 normal arrow keys.
479 normal arrow keys.
476
480
477 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
481 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
478 your history for lines that match what you've typed so far, completing as
482 your history for lines that match what you've typed so far, completing as
479 much as it can.
483 much as it can.
480
484
481 * Persistent command history across sessions (readline required).
485 * Persistent command history across sessions (readline required).
482
486
483 * Logging of input with the ability to save and restore a working session.
487 * Logging of input with the ability to save and restore a working session.
484
488
485 * System escape with !. Typing !ls will run 'ls' in the current directory.
489 * System escape with !. Typing !ls will run 'ls' in the current directory.
486
490
487 * The reload command does a 'deep' reload of a module: changes made to the
491 * The reload command does a 'deep' reload of a module: changes made to the
488 module since you imported will actually be available without having to exit.
492 module since you imported will actually be available without having to exit.
489
493
490 * Verbose and colored exception traceback printouts. See the magic xmode and
494 * Verbose and colored exception traceback printouts. See the magic xmode and
491 xcolor functions for details (just type %magic).
495 xcolor functions for details (just type %magic).
492
496
493 * Input caching system:
497 * Input caching system:
494
498
495 IPython offers numbered prompts (In/Out) with input and output caching. All
499 IPython offers numbered prompts (In/Out) with input and output caching. All
496 input is saved and can be retrieved as variables (besides the usual arrow
500 input is saved and can be retrieved as variables (besides the usual arrow
497 key recall).
501 key recall).
498
502
499 The following GLOBAL variables always exist (so don't overwrite them!):
503 The following GLOBAL variables always exist (so don't overwrite them!):
500 _i: stores previous input.
504 _i: stores previous input.
501 _ii: next previous.
505 _ii: next previous.
502 _iii: next-next previous.
506 _iii: next-next previous.
503 _ih : a list of all input _ih[n] is the input from line n.
507 _ih : a list of all input _ih[n] is the input from line n.
504
508
505 Additionally, global variables named _i<n> are dynamically created (<n>
509 Additionally, global variables named _i<n> are dynamically created (<n>
506 being the prompt counter), such that _i<n> == _ih[<n>]
510 being the prompt counter), such that _i<n> == _ih[<n>]
507
511
508 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
512 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
509
513
510 You can create macros which contain multiple input lines from this history,
514 You can create macros which contain multiple input lines from this history,
511 for later re-execution, with the %macro function.
515 for later re-execution, with the %macro function.
512
516
513 The history function %hist allows you to see any part of your input history
517 The history function %hist allows you to see any part of your input history
514 by printing a range of the _i variables. Note that inputs which contain
518 by printing a range of the _i variables. Note that inputs which contain
515 magic functions (%) appear in the history with a prepended comment. This is
519 magic functions (%) appear in the history with a prepended comment. This is
516 because they aren't really valid Python code, so you can't exec them.
520 because they aren't really valid Python code, so you can't exec them.
517
521
518 * Output caching system:
522 * Output caching system:
519
523
520 For output that is returned from actions, a system similar to the input
524 For output that is returned from actions, a system similar to the input
521 cache exists but using _ instead of _i. Only actions that produce a result
525 cache exists but using _ instead of _i. Only actions that produce a result
522 (NOT assignments, for example) are cached. If you are familiar with
526 (NOT assignments, for example) are cached. If you are familiar with
523 Mathematica, IPython's _ variables behave exactly like Mathematica's %
527 Mathematica, IPython's _ variables behave exactly like Mathematica's %
524 variables.
528 variables.
525
529
526 The following GLOBAL variables always exist (so don't overwrite them!):
530 The following GLOBAL variables always exist (so don't overwrite them!):
527 _ (one underscore): previous output.
531 _ (one underscore): previous output.
528 __ (two underscores): next previous.
532 __ (two underscores): next previous.
529 ___ (three underscores): next-next previous.
533 ___ (three underscores): next-next previous.
530
534
531 Global variables named _<n> are dynamically created (<n> being the prompt
535 Global variables named _<n> are dynamically created (<n> being the prompt
532 counter), such that the result of output <n> is always available as _<n>.
536 counter), such that the result of output <n> is always available as _<n>.
533
537
534 Finally, a global dictionary named _oh exists with entries for all lines
538 Finally, a global dictionary named _oh exists with entries for all lines
535 which generated output.
539 which generated output.
536
540
537 * Directory history:
541 * Directory history:
538
542
539 Your history of visited directories is kept in the global list _dh, and the
543 Your history of visited directories is kept in the global list _dh, and the
540 magic %cd command can be used to go to any entry in that list.
544 magic %cd command can be used to go to any entry in that list.
541
545
542 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
546 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
543
547
544 1. Auto-parentheses
548 1. Auto-parentheses
545 Callable objects (i.e. functions, methods, etc) can be invoked like
549 Callable objects (i.e. functions, methods, etc) can be invoked like
546 this (notice the commas between the arguments):
550 this (notice the commas between the arguments):
547 >>> callable_ob arg1, arg2, arg3
551 >>> callable_ob arg1, arg2, arg3
548 and the input will be translated to this:
552 and the input will be translated to this:
549 --> callable_ob(arg1, arg2, arg3)
553 --> callable_ob(arg1, arg2, arg3)
550 You can force auto-parentheses by using '/' as the first character
554 You can force auto-parentheses by using '/' as the first character
551 of a line. For example:
555 of a line. For example:
552 >>> /globals # becomes 'globals()'
556 >>> /globals # becomes 'globals()'
553 Note that the '/' MUST be the first character on the line! This
557 Note that the '/' MUST be the first character on the line! This
554 won't work:
558 won't work:
555 >>> print /globals # syntax error
559 >>> print /globals # syntax error
556
560
557 In most cases the automatic algorithm should work, so you should
561 In most cases the automatic algorithm should work, so you should
558 rarely need to explicitly invoke /. One notable exception is if you
562 rarely need to explicitly invoke /. One notable exception is if you
559 are trying to call a function with a list of tuples as arguments (the
563 are trying to call a function with a list of tuples as arguments (the
560 parenthesis will confuse IPython):
564 parenthesis will confuse IPython):
561 In [1]: zip (1,2,3),(4,5,6) # won't work
565 In [1]: zip (1,2,3),(4,5,6) # won't work
562 but this will work:
566 but this will work:
563 In [2]: /zip (1,2,3),(4,5,6)
567 In [2]: /zip (1,2,3),(4,5,6)
564 ------> zip ((1,2,3),(4,5,6))
568 ------> zip ((1,2,3),(4,5,6))
565 Out[2]= [(1, 4), (2, 5), (3, 6)]
569 Out[2]= [(1, 4), (2, 5), (3, 6)]
566
570
567 IPython tells you that it has altered your command line by
571 IPython tells you that it has altered your command line by
568 displaying the new command line preceded by -->. e.g.:
572 displaying the new command line preceded by -->. e.g.:
569 In [18]: callable list
573 In [18]: callable list
570 -------> callable (list)
574 -------> callable (list)
571
575
572 2. Auto-Quoting
576 2. Auto-Quoting
573 You can force auto-quoting of a function's arguments by using ',' as
577 You can force auto-quoting of a function's arguments by using ',' as
574 the first character of a line. For example:
578 the first character of a line. For example:
575 >>> ,my_function /home/me # becomes my_function("/home/me")
579 >>> ,my_function /home/me # becomes my_function("/home/me")
576
580
577 If you use ';' instead, the whole argument is quoted as a single
581 If you use ';' instead, the whole argument is quoted as a single
578 string (while ',' splits on whitespace):
582 string (while ',' splits on whitespace):
579 >>> ,my_function a b c # becomes my_function("a","b","c")
583 >>> ,my_function a b c # becomes my_function("a","b","c")
580 >>> ;my_function a b c # becomes my_function("a b c")
584 >>> ;my_function a b c # becomes my_function("a b c")
581
585
582 Note that the ',' MUST be the first character on the line! This
586 Note that the ',' MUST be the first character on the line! This
583 won't work:
587 won't work:
584 >>> x = ,my_function /home/me # syntax error
588 >>> x = ,my_function /home/me # syntax error
585 """
589 """
@@ -1,4749 +1,4763 b''
1 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/iplib.py (handle_auto): changed autocall semantics to
4 include 'smart' mode, where the autocall transformation is NOT
5 applied if there are no arguments on the line. This allows you to
6 just type 'foo' if foo is a callable to see its internal form,
7 instead of having it called with no arguments (typically a
8 mistake). The old 'full' autocall still exists: for that, you
9 need to set the 'autocall' parameter to 2 in your ipythonrc file.
10
11 * IPython/completer.py (Completer.attr_matches): add
12 tab-completion support for Enthoughts' traits. After a report by
13 Arnd and a patch by Prabhu.
14
1 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
15 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
2
16
3 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
17 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
4 Schmolck's patch to fix inspect.getinnerframes().
18 Schmolck's patch to fix inspect.getinnerframes().
5
19
6 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
20 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
7 for embedded instances, regarding handling of namespaces and items
21 for embedded instances, regarding handling of namespaces and items
8 added to the __builtin__ one. Multiple embedded instances and
22 added to the __builtin__ one. Multiple embedded instances and
9 recursive embeddings should work better now (though I'm not sure
23 recursive embeddings should work better now (though I'm not sure
10 I've got all the corner cases fixed, that code is a bit of a brain
24 I've got all the corner cases fixed, that code is a bit of a brain
11 twister).
25 twister).
12
26
13 * IPython/Magic.py (magic_edit): added support to edit in-memory
27 * IPython/Magic.py (magic_edit): added support to edit in-memory
14 macros (automatically creates the necessary temp files). %edit
28 macros (automatically creates the necessary temp files). %edit
15 also doesn't return the file contents anymore, it's just noise.
29 also doesn't return the file contents anymore, it's just noise.
16
30
17 * IPython/completer.py (Completer.attr_matches): revert change to
31 * IPython/completer.py (Completer.attr_matches): revert change to
18 complete only on attributes listed in __all__. I realized it
32 complete only on attributes listed in __all__. I realized it
19 cripples the tab-completion system as a tool for exploring the
33 cripples the tab-completion system as a tool for exploring the
20 internals of unknown libraries (it renders any non-__all__
34 internals of unknown libraries (it renders any non-__all__
21 attribute off-limits). I got bit by this when trying to see
35 attribute off-limits). I got bit by this when trying to see
22 something inside the dis module.
36 something inside the dis module.
23
37
24 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
38 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
25
39
26 * IPython/iplib.py (InteractiveShell.__init__): add .meta
40 * IPython/iplib.py (InteractiveShell.__init__): add .meta
27 namespace for users and extension writers to hold data in. This
41 namespace for users and extension writers to hold data in. This
28 follows the discussion in
42 follows the discussion in
29 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
43 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
30
44
31 * IPython/completer.py (IPCompleter.complete): small patch to help
45 * IPython/completer.py (IPCompleter.complete): small patch to help
32 tab-completion under Emacs, after a suggestion by John Barnard
46 tab-completion under Emacs, after a suggestion by John Barnard
33 <barnarj-AT-ccf.org>.
47 <barnarj-AT-ccf.org>.
34
48
35 * IPython/Magic.py (Magic.extract_input_slices): added support for
49 * IPython/Magic.py (Magic.extract_input_slices): added support for
36 the slice notation in magics to use N-M to represent numbers N...M
50 the slice notation in magics to use N-M to represent numbers N...M
37 (closed endpoints). This is used by %macro and %save.
51 (closed endpoints). This is used by %macro and %save.
38
52
39 * IPython/completer.py (Completer.attr_matches): for modules which
53 * IPython/completer.py (Completer.attr_matches): for modules which
40 define __all__, complete only on those. After a patch by Jeffrey
54 define __all__, complete only on those. After a patch by Jeffrey
41 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
55 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
42 speed up this routine.
56 speed up this routine.
43
57
44 * IPython/Logger.py (Logger.log): fix a history handling bug. I
58 * IPython/Logger.py (Logger.log): fix a history handling bug. I
45 don't know if this is the end of it, but the behavior now is
59 don't know if this is the end of it, but the behavior now is
46 certainly much more correct. Note that coupled with macros,
60 certainly much more correct. Note that coupled with macros,
47 slightly surprising (at first) behavior may occur: a macro will in
61 slightly surprising (at first) behavior may occur: a macro will in
48 general expand to multiple lines of input, so upon exiting, the
62 general expand to multiple lines of input, so upon exiting, the
49 in/out counters will both be bumped by the corresponding amount
63 in/out counters will both be bumped by the corresponding amount
50 (as if the macro's contents had been typed interactively). Typing
64 (as if the macro's contents had been typed interactively). Typing
51 %hist will reveal the intermediate (silently processed) lines.
65 %hist will reveal the intermediate (silently processed) lines.
52
66
53 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
67 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
54 pickle to fail (%run was overwriting __main__ and not restoring
68 pickle to fail (%run was overwriting __main__ and not restoring
55 it, but pickle relies on __main__ to operate).
69 it, but pickle relies on __main__ to operate).
56
70
57 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
71 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
58 using properties, but forgot to make the main InteractiveShell
72 using properties, but forgot to make the main InteractiveShell
59 class a new-style class. Properties fail silently, and
73 class a new-style class. Properties fail silently, and
60 misteriously, with old-style class (getters work, but
74 misteriously, with old-style class (getters work, but
61 setters don't do anything).
75 setters don't do anything).
62
76
63 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
77 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
64
78
65 * IPython/Magic.py (magic_history): fix history reporting bug (I
79 * IPython/Magic.py (magic_history): fix history reporting bug (I
66 know some nasties are still there, I just can't seem to find a
80 know some nasties are still there, I just can't seem to find a
67 reproducible test case to track them down; the input history is
81 reproducible test case to track them down; the input history is
68 falling out of sync...)
82 falling out of sync...)
69
83
70 * IPython/iplib.py (handle_shell_escape): fix bug where both
84 * IPython/iplib.py (handle_shell_escape): fix bug where both
71 aliases and system accesses where broken for indented code (such
85 aliases and system accesses where broken for indented code (such
72 as loops).
86 as loops).
73
87
74 * IPython/genutils.py (shell): fix small but critical bug for
88 * IPython/genutils.py (shell): fix small but critical bug for
75 win32 system access.
89 win32 system access.
76
90
77 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
91 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
78
92
79 * IPython/iplib.py (showtraceback): remove use of the
93 * IPython/iplib.py (showtraceback): remove use of the
80 sys.last_{type/value/traceback} structures, which are non
94 sys.last_{type/value/traceback} structures, which are non
81 thread-safe.
95 thread-safe.
82 (_prefilter): change control flow to ensure that we NEVER
96 (_prefilter): change control flow to ensure that we NEVER
83 introspect objects when autocall is off. This will guarantee that
97 introspect objects when autocall is off. This will guarantee that
84 having an input line of the form 'x.y', where access to attribute
98 having an input line of the form 'x.y', where access to attribute
85 'y' has side effects, doesn't trigger the side effect TWICE. It
99 'y' has side effects, doesn't trigger the side effect TWICE. It
86 is important to note that, with autocall on, these side effects
100 is important to note that, with autocall on, these side effects
87 can still happen.
101 can still happen.
88 (ipsystem): new builtin, to complete the ip{magic/alias/system}
102 (ipsystem): new builtin, to complete the ip{magic/alias/system}
89 trio. IPython offers these three kinds of special calls which are
103 trio. IPython offers these three kinds of special calls which are
90 not python code, and it's a good thing to have their call method
104 not python code, and it's a good thing to have their call method
91 be accessible as pure python functions (not just special syntax at
105 be accessible as pure python functions (not just special syntax at
92 the command line). It gives us a better internal implementation
106 the command line). It gives us a better internal implementation
93 structure, as well as exposing these for user scripting more
107 structure, as well as exposing these for user scripting more
94 cleanly.
108 cleanly.
95
109
96 * IPython/macro.py (Macro.__init__): moved macros to a standalone
110 * IPython/macro.py (Macro.__init__): moved macros to a standalone
97 file. Now that they'll be more likely to be used with the
111 file. Now that they'll be more likely to be used with the
98 persistance system (%store), I want to make sure their module path
112 persistance system (%store), I want to make sure their module path
99 doesn't change in the future, so that we don't break things for
113 doesn't change in the future, so that we don't break things for
100 users' persisted data.
114 users' persisted data.
101
115
102 * IPython/iplib.py (autoindent_update): move indentation
116 * IPython/iplib.py (autoindent_update): move indentation
103 management into the _text_ processing loop, not the keyboard
117 management into the _text_ processing loop, not the keyboard
104 interactive one. This is necessary to correctly process non-typed
118 interactive one. This is necessary to correctly process non-typed
105 multiline input (such as macros).
119 multiline input (such as macros).
106
120
107 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
121 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
108 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
122 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
109 which was producing problems in the resulting manual.
123 which was producing problems in the resulting manual.
110 (magic_whos): improve reporting of instances (show their class,
124 (magic_whos): improve reporting of instances (show their class,
111 instead of simply printing 'instance' which isn't terribly
125 instead of simply printing 'instance' which isn't terribly
112 informative).
126 informative).
113
127
114 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
128 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
115 (minor mods) to support network shares under win32.
129 (minor mods) to support network shares under win32.
116
130
117 * IPython/winconsole.py (get_console_size): add new winconsole
131 * IPython/winconsole.py (get_console_size): add new winconsole
118 module and fixes to page_dumb() to improve its behavior under
132 module and fixes to page_dumb() to improve its behavior under
119 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
133 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
120
134
121 * IPython/Magic.py (Macro): simplified Macro class to just
135 * IPython/Magic.py (Macro): simplified Macro class to just
122 subclass list. We've had only 2.2 compatibility for a very long
136 subclass list. We've had only 2.2 compatibility for a very long
123 time, yet I was still avoiding subclassing the builtin types. No
137 time, yet I was still avoiding subclassing the builtin types. No
124 more (I'm also starting to use properties, though I won't shift to
138 more (I'm also starting to use properties, though I won't shift to
125 2.3-specific features quite yet).
139 2.3-specific features quite yet).
126 (magic_store): added Ville's patch for lightweight variable
140 (magic_store): added Ville's patch for lightweight variable
127 persistence, after a request on the user list by Matt Wilkie
141 persistence, after a request on the user list by Matt Wilkie
128 <maphew-AT-gmail.com>. The new %store magic's docstring has full
142 <maphew-AT-gmail.com>. The new %store magic's docstring has full
129 details.
143 details.
130
144
131 * IPython/iplib.py (InteractiveShell.post_config_initialization):
145 * IPython/iplib.py (InteractiveShell.post_config_initialization):
132 changed the default logfile name from 'ipython.log' to
146 changed the default logfile name from 'ipython.log' to
133 'ipython_log.py'. These logs are real python files, and now that
147 'ipython_log.py'. These logs are real python files, and now that
134 we have much better multiline support, people are more likely to
148 we have much better multiline support, people are more likely to
135 want to use them as such. Might as well name them correctly.
149 want to use them as such. Might as well name them correctly.
136
150
137 * IPython/Magic.py: substantial cleanup. While we can't stop
151 * IPython/Magic.py: substantial cleanup. While we can't stop
138 using magics as mixins, due to the existing customizations 'out
152 using magics as mixins, due to the existing customizations 'out
139 there' which rely on the mixin naming conventions, at least I
153 there' which rely on the mixin naming conventions, at least I
140 cleaned out all cross-class name usage. So once we are OK with
154 cleaned out all cross-class name usage. So once we are OK with
141 breaking compatibility, the two systems can be separated.
155 breaking compatibility, the two systems can be separated.
142
156
143 * IPython/Logger.py: major cleanup. This one is NOT a mixin
157 * IPython/Logger.py: major cleanup. This one is NOT a mixin
144 anymore, and the class is a fair bit less hideous as well. New
158 anymore, and the class is a fair bit less hideous as well. New
145 features were also introduced: timestamping of input, and logging
159 features were also introduced: timestamping of input, and logging
146 of output results. These are user-visible with the -t and -o
160 of output results. These are user-visible with the -t and -o
147 options to %logstart. Closes
161 options to %logstart. Closes
148 http://www.scipy.net/roundup/ipython/issue11 and a request by
162 http://www.scipy.net/roundup/ipython/issue11 and a request by
149 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
163 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
150
164
151 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
165 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
152
166
153 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
167 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
154 better hadnle backslashes in paths. See the thread 'More Windows
168 better hadnle backslashes in paths. See the thread 'More Windows
155 questions part 2 - \/ characters revisited' on the iypthon user
169 questions part 2 - \/ characters revisited' on the iypthon user
156 list:
170 list:
157 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
171 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
158
172
159 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
173 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
160
174
161 (InteractiveShell.__init__): change threaded shells to not use the
175 (InteractiveShell.__init__): change threaded shells to not use the
162 ipython crash handler. This was causing more problems than not,
176 ipython crash handler. This was causing more problems than not,
163 as exceptions in the main thread (GUI code, typically) would
177 as exceptions in the main thread (GUI code, typically) would
164 always show up as a 'crash', when they really weren't.
178 always show up as a 'crash', when they really weren't.
165
179
166 The colors and exception mode commands (%colors/%xmode) have been
180 The colors and exception mode commands (%colors/%xmode) have been
167 synchronized to also take this into account, so users can get
181 synchronized to also take this into account, so users can get
168 verbose exceptions for their threaded code as well. I also added
182 verbose exceptions for their threaded code as well. I also added
169 support for activating pdb inside this exception handler as well,
183 support for activating pdb inside this exception handler as well,
170 so now GUI authors can use IPython's enhanced pdb at runtime.
184 so now GUI authors can use IPython's enhanced pdb at runtime.
171
185
172 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
186 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
173 true by default, and add it to the shipped ipythonrc file. Since
187 true by default, and add it to the shipped ipythonrc file. Since
174 this asks the user before proceeding, I think it's OK to make it
188 this asks the user before proceeding, I think it's OK to make it
175 true by default.
189 true by default.
176
190
177 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
191 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
178 of the previous special-casing of input in the eval loop. I think
192 of the previous special-casing of input in the eval loop. I think
179 this is cleaner, as they really are commands and shouldn't have
193 this is cleaner, as they really are commands and shouldn't have
180 a special role in the middle of the core code.
194 a special role in the middle of the core code.
181
195
182 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
196 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
183
197
184 * IPython/iplib.py (edit_syntax_error): added support for
198 * IPython/iplib.py (edit_syntax_error): added support for
185 automatically reopening the editor if the file had a syntax error
199 automatically reopening the editor if the file had a syntax error
186 in it. Thanks to scottt who provided the patch at:
200 in it. Thanks to scottt who provided the patch at:
187 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
201 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
188 version committed).
202 version committed).
189
203
190 * IPython/iplib.py (handle_normal): add suport for multi-line
204 * IPython/iplib.py (handle_normal): add suport for multi-line
191 input with emtpy lines. This fixes
205 input with emtpy lines. This fixes
192 http://www.scipy.net/roundup/ipython/issue43 and a similar
206 http://www.scipy.net/roundup/ipython/issue43 and a similar
193 discussion on the user list.
207 discussion on the user list.
194
208
195 WARNING: a behavior change is necessarily introduced to support
209 WARNING: a behavior change is necessarily introduced to support
196 blank lines: now a single blank line with whitespace does NOT
210 blank lines: now a single blank line with whitespace does NOT
197 break the input loop, which means that when autoindent is on, by
211 break the input loop, which means that when autoindent is on, by
198 default hitting return on the next (indented) line does NOT exit.
212 default hitting return on the next (indented) line does NOT exit.
199
213
200 Instead, to exit a multiline input you can either have:
214 Instead, to exit a multiline input you can either have:
201
215
202 - TWO whitespace lines (just hit return again), or
216 - TWO whitespace lines (just hit return again), or
203 - a single whitespace line of a different length than provided
217 - a single whitespace line of a different length than provided
204 by the autoindent (add or remove a space).
218 by the autoindent (add or remove a space).
205
219
206 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
220 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
207 module to better organize all readline-related functionality.
221 module to better organize all readline-related functionality.
208 I've deleted FlexCompleter and put all completion clases here.
222 I've deleted FlexCompleter and put all completion clases here.
209
223
210 * IPython/iplib.py (raw_input): improve indentation management.
224 * IPython/iplib.py (raw_input): improve indentation management.
211 It is now possible to paste indented code with autoindent on, and
225 It is now possible to paste indented code with autoindent on, and
212 the code is interpreted correctly (though it still looks bad on
226 the code is interpreted correctly (though it still looks bad on
213 screen, due to the line-oriented nature of ipython).
227 screen, due to the line-oriented nature of ipython).
214 (MagicCompleter.complete): change behavior so that a TAB key on an
228 (MagicCompleter.complete): change behavior so that a TAB key on an
215 otherwise empty line actually inserts a tab, instead of completing
229 otherwise empty line actually inserts a tab, instead of completing
216 on the entire global namespace. This makes it easier to use the
230 on the entire global namespace. This makes it easier to use the
217 TAB key for indentation. After a request by Hans Meine
231 TAB key for indentation. After a request by Hans Meine
218 <hans_meine-AT-gmx.net>
232 <hans_meine-AT-gmx.net>
219 (_prefilter): add support so that typing plain 'exit' or 'quit'
233 (_prefilter): add support so that typing plain 'exit' or 'quit'
220 does a sensible thing. Originally I tried to deviate as little as
234 does a sensible thing. Originally I tried to deviate as little as
221 possible from the default python behavior, but even that one may
235 possible from the default python behavior, but even that one may
222 change in this direction (thread on python-dev to that effect).
236 change in this direction (thread on python-dev to that effect).
223 Regardless, ipython should do the right thing even if CPython's
237 Regardless, ipython should do the right thing even if CPython's
224 '>>>' prompt doesn't.
238 '>>>' prompt doesn't.
225 (InteractiveShell): removed subclassing code.InteractiveConsole
239 (InteractiveShell): removed subclassing code.InteractiveConsole
226 class. By now we'd overridden just about all of its methods: I've
240 class. By now we'd overridden just about all of its methods: I've
227 copied the remaining two over, and now ipython is a standalone
241 copied the remaining two over, and now ipython is a standalone
228 class. This will provide a clearer picture for the chainsaw
242 class. This will provide a clearer picture for the chainsaw
229 branch refactoring.
243 branch refactoring.
230
244
231 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
245 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
232
246
233 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
247 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
234 failures for objects which break when dir() is called on them.
248 failures for objects which break when dir() is called on them.
235
249
236 * IPython/FlexCompleter.py (Completer.__init__): Added support for
250 * IPython/FlexCompleter.py (Completer.__init__): Added support for
237 distinct local and global namespaces in the completer API. This
251 distinct local and global namespaces in the completer API. This
238 change allows us top properly handle completion with distinct
252 change allows us top properly handle completion with distinct
239 scopes, including in embedded instances (this had never really
253 scopes, including in embedded instances (this had never really
240 worked correctly).
254 worked correctly).
241
255
242 Note: this introduces a change in the constructor for
256 Note: this introduces a change in the constructor for
243 MagicCompleter, as a new global_namespace parameter is now the
257 MagicCompleter, as a new global_namespace parameter is now the
244 second argument (the others were bumped one position).
258 second argument (the others were bumped one position).
245
259
246 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
260 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
247
261
248 * IPython/iplib.py (embed_mainloop): fix tab-completion in
262 * IPython/iplib.py (embed_mainloop): fix tab-completion in
249 embedded instances (which can be done now thanks to Vivian's
263 embedded instances (which can be done now thanks to Vivian's
250 frame-handling fixes for pdb).
264 frame-handling fixes for pdb).
251 (InteractiveShell.__init__): Fix namespace handling problem in
265 (InteractiveShell.__init__): Fix namespace handling problem in
252 embedded instances. We were overwriting __main__ unconditionally,
266 embedded instances. We were overwriting __main__ unconditionally,
253 and this should only be done for 'full' (non-embedded) IPython;
267 and this should only be done for 'full' (non-embedded) IPython;
254 embedded instances must respect the caller's __main__. Thanks to
268 embedded instances must respect the caller's __main__. Thanks to
255 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
269 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
256
270
257 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
271 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
258
272
259 * setup.py: added download_url to setup(). This registers the
273 * setup.py: added download_url to setup(). This registers the
260 download address at PyPI, which is not only useful to humans
274 download address at PyPI, which is not only useful to humans
261 browsing the site, but is also picked up by setuptools (the Eggs
275 browsing the site, but is also picked up by setuptools (the Eggs
262 machinery). Thanks to Ville and R. Kern for the info/discussion
276 machinery). Thanks to Ville and R. Kern for the info/discussion
263 on this.
277 on this.
264
278
265 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
279 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
266
280
267 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
281 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
268 This brings a lot of nice functionality to the pdb mode, which now
282 This brings a lot of nice functionality to the pdb mode, which now
269 has tab-completion, syntax highlighting, and better stack handling
283 has tab-completion, syntax highlighting, and better stack handling
270 than before. Many thanks to Vivian De Smedt
284 than before. Many thanks to Vivian De Smedt
271 <vivian-AT-vdesmedt.com> for the original patches.
285 <vivian-AT-vdesmedt.com> for the original patches.
272
286
273 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
287 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
274
288
275 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
289 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
276 sequence to consistently accept the banner argument. The
290 sequence to consistently accept the banner argument. The
277 inconsistency was tripping SAGE, thanks to Gary Zablackis
291 inconsistency was tripping SAGE, thanks to Gary Zablackis
278 <gzabl-AT-yahoo.com> for the report.
292 <gzabl-AT-yahoo.com> for the report.
279
293
280 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
294 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
281
295
282 * IPython/iplib.py (InteractiveShell.post_config_initialization):
296 * IPython/iplib.py (InteractiveShell.post_config_initialization):
283 Fix bug where a naked 'alias' call in the ipythonrc file would
297 Fix bug where a naked 'alias' call in the ipythonrc file would
284 cause a crash. Bug reported by Jorgen Stenarson.
298 cause a crash. Bug reported by Jorgen Stenarson.
285
299
286 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
300 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
287
301
288 * IPython/ipmaker.py (make_IPython): cleanups which should improve
302 * IPython/ipmaker.py (make_IPython): cleanups which should improve
289 startup time.
303 startup time.
290
304
291 * IPython/iplib.py (runcode): my globals 'fix' for embedded
305 * IPython/iplib.py (runcode): my globals 'fix' for embedded
292 instances had introduced a bug with globals in normal code. Now
306 instances had introduced a bug with globals in normal code. Now
293 it's working in all cases.
307 it's working in all cases.
294
308
295 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
309 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
296 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
310 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
297 has been introduced to set the default case sensitivity of the
311 has been introduced to set the default case sensitivity of the
298 searches. Users can still select either mode at runtime on a
312 searches. Users can still select either mode at runtime on a
299 per-search basis.
313 per-search basis.
300
314
301 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
315 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
302
316
303 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
317 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
304 attributes in wildcard searches for subclasses. Modified version
318 attributes in wildcard searches for subclasses. Modified version
305 of a patch by Jorgen.
319 of a patch by Jorgen.
306
320
307 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
321 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
308
322
309 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
323 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
310 embedded instances. I added a user_global_ns attribute to the
324 embedded instances. I added a user_global_ns attribute to the
311 InteractiveShell class to handle this.
325 InteractiveShell class to handle this.
312
326
313 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
327 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
314
328
315 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
329 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
316 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
330 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
317 (reported under win32, but may happen also in other platforms).
331 (reported under win32, but may happen also in other platforms).
318 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
332 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
319
333
320 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
334 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
321
335
322 * IPython/Magic.py (magic_psearch): new support for wildcard
336 * IPython/Magic.py (magic_psearch): new support for wildcard
323 patterns. Now, typing ?a*b will list all names which begin with a
337 patterns. Now, typing ?a*b will list all names which begin with a
324 and end in b, for example. The %psearch magic has full
338 and end in b, for example. The %psearch magic has full
325 docstrings. Many thanks to Jörgen Stenarson
339 docstrings. Many thanks to Jörgen Stenarson
326 <jorgen.stenarson-AT-bostream.nu>, author of the patches
340 <jorgen.stenarson-AT-bostream.nu>, author of the patches
327 implementing this functionality.
341 implementing this functionality.
328
342
329 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
343 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
330
344
331 * Manual: fixed long-standing annoyance of double-dashes (as in
345 * Manual: fixed long-standing annoyance of double-dashes (as in
332 --prefix=~, for example) being stripped in the HTML version. This
346 --prefix=~, for example) being stripped in the HTML version. This
333 is a latex2html bug, but a workaround was provided. Many thanks
347 is a latex2html bug, but a workaround was provided. Many thanks
334 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
348 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
335 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
349 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
336 rolling. This seemingly small issue had tripped a number of users
350 rolling. This seemingly small issue had tripped a number of users
337 when first installing, so I'm glad to see it gone.
351 when first installing, so I'm glad to see it gone.
338
352
339 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
353 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
340
354
341 * IPython/Extensions/numeric_formats.py: fix missing import,
355 * IPython/Extensions/numeric_formats.py: fix missing import,
342 reported by Stephen Walton.
356 reported by Stephen Walton.
343
357
344 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
358 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
345
359
346 * IPython/demo.py: finish demo module, fully documented now.
360 * IPython/demo.py: finish demo module, fully documented now.
347
361
348 * IPython/genutils.py (file_read): simple little utility to read a
362 * IPython/genutils.py (file_read): simple little utility to read a
349 file and ensure it's closed afterwards.
363 file and ensure it's closed afterwards.
350
364
351 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
365 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
352
366
353 * IPython/demo.py (Demo.__init__): added support for individually
367 * IPython/demo.py (Demo.__init__): added support for individually
354 tagging blocks for automatic execution.
368 tagging blocks for automatic execution.
355
369
356 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
370 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
357 syntax-highlighted python sources, requested by John.
371 syntax-highlighted python sources, requested by John.
358
372
359 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
373 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
360
374
361 * IPython/demo.py (Demo.again): fix bug where again() blocks after
375 * IPython/demo.py (Demo.again): fix bug where again() blocks after
362 finishing.
376 finishing.
363
377
364 * IPython/genutils.py (shlex_split): moved from Magic to here,
378 * IPython/genutils.py (shlex_split): moved from Magic to here,
365 where all 2.2 compatibility stuff lives. I needed it for demo.py.
379 where all 2.2 compatibility stuff lives. I needed it for demo.py.
366
380
367 * IPython/demo.py (Demo.__init__): added support for silent
381 * IPython/demo.py (Demo.__init__): added support for silent
368 blocks, improved marks as regexps, docstrings written.
382 blocks, improved marks as regexps, docstrings written.
369 (Demo.__init__): better docstring, added support for sys.argv.
383 (Demo.__init__): better docstring, added support for sys.argv.
370
384
371 * IPython/genutils.py (marquee): little utility used by the demo
385 * IPython/genutils.py (marquee): little utility used by the demo
372 code, handy in general.
386 code, handy in general.
373
387
374 * IPython/demo.py (Demo.__init__): new class for interactive
388 * IPython/demo.py (Demo.__init__): new class for interactive
375 demos. Not documented yet, I just wrote it in a hurry for
389 demos. Not documented yet, I just wrote it in a hurry for
376 scipy'05. Will docstring later.
390 scipy'05. Will docstring later.
377
391
378 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
392 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
379
393
380 * IPython/Shell.py (sigint_handler): Drastic simplification which
394 * IPython/Shell.py (sigint_handler): Drastic simplification which
381 also seems to make Ctrl-C work correctly across threads! This is
395 also seems to make Ctrl-C work correctly across threads! This is
382 so simple, that I can't beleive I'd missed it before. Needs more
396 so simple, that I can't beleive I'd missed it before. Needs more
383 testing, though.
397 testing, though.
384 (KBINT): Never mind, revert changes. I'm sure I'd tried something
398 (KBINT): Never mind, revert changes. I'm sure I'd tried something
385 like this before...
399 like this before...
386
400
387 * IPython/genutils.py (get_home_dir): add protection against
401 * IPython/genutils.py (get_home_dir): add protection against
388 non-dirs in win32 registry.
402 non-dirs in win32 registry.
389
403
390 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
404 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
391 bug where dict was mutated while iterating (pysh crash).
405 bug where dict was mutated while iterating (pysh crash).
392
406
393 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
407 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
394
408
395 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
409 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
396 spurious newlines added by this routine. After a report by
410 spurious newlines added by this routine. After a report by
397 F. Mantegazza.
411 F. Mantegazza.
398
412
399 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
413 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
400
414
401 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
415 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
402 calls. These were a leftover from the GTK 1.x days, and can cause
416 calls. These were a leftover from the GTK 1.x days, and can cause
403 problems in certain cases (after a report by John Hunter).
417 problems in certain cases (after a report by John Hunter).
404
418
405 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
419 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
406 os.getcwd() fails at init time. Thanks to patch from David Remahl
420 os.getcwd() fails at init time. Thanks to patch from David Remahl
407 <chmod007-AT-mac.com>.
421 <chmod007-AT-mac.com>.
408 (InteractiveShell.__init__): prevent certain special magics from
422 (InteractiveShell.__init__): prevent certain special magics from
409 being shadowed by aliases. Closes
423 being shadowed by aliases. Closes
410 http://www.scipy.net/roundup/ipython/issue41.
424 http://www.scipy.net/roundup/ipython/issue41.
411
425
412 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
426 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
413
427
414 * IPython/iplib.py (InteractiveShell.complete): Added new
428 * IPython/iplib.py (InteractiveShell.complete): Added new
415 top-level completion method to expose the completion mechanism
429 top-level completion method to expose the completion mechanism
416 beyond readline-based environments.
430 beyond readline-based environments.
417
431
418 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
432 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
419
433
420 * tools/ipsvnc (svnversion): fix svnversion capture.
434 * tools/ipsvnc (svnversion): fix svnversion capture.
421
435
422 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
436 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
423 attribute to self, which was missing. Before, it was set by a
437 attribute to self, which was missing. Before, it was set by a
424 routine which in certain cases wasn't being called, so the
438 routine which in certain cases wasn't being called, so the
425 instance could end up missing the attribute. This caused a crash.
439 instance could end up missing the attribute. This caused a crash.
426 Closes http://www.scipy.net/roundup/ipython/issue40.
440 Closes http://www.scipy.net/roundup/ipython/issue40.
427
441
428 2005-08-16 Fernando Perez <fperez@colorado.edu>
442 2005-08-16 Fernando Perez <fperez@colorado.edu>
429
443
430 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
444 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
431 contains non-string attribute. Closes
445 contains non-string attribute. Closes
432 http://www.scipy.net/roundup/ipython/issue38.
446 http://www.scipy.net/roundup/ipython/issue38.
433
447
434 2005-08-14 Fernando Perez <fperez@colorado.edu>
448 2005-08-14 Fernando Perez <fperez@colorado.edu>
435
449
436 * tools/ipsvnc: Minor improvements, to add changeset info.
450 * tools/ipsvnc: Minor improvements, to add changeset info.
437
451
438 2005-08-12 Fernando Perez <fperez@colorado.edu>
452 2005-08-12 Fernando Perez <fperez@colorado.edu>
439
453
440 * IPython/iplib.py (runsource): remove self.code_to_run_src
454 * IPython/iplib.py (runsource): remove self.code_to_run_src
441 attribute. I realized this is nothing more than
455 attribute. I realized this is nothing more than
442 '\n'.join(self.buffer), and having the same data in two different
456 '\n'.join(self.buffer), and having the same data in two different
443 places is just asking for synchronization bugs. This may impact
457 places is just asking for synchronization bugs. This may impact
444 people who have custom exception handlers, so I need to warn
458 people who have custom exception handlers, so I need to warn
445 ipython-dev about it (F. Mantegazza may use them).
459 ipython-dev about it (F. Mantegazza may use them).
446
460
447 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
461 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
448
462
449 * IPython/genutils.py: fix 2.2 compatibility (generators)
463 * IPython/genutils.py: fix 2.2 compatibility (generators)
450
464
451 2005-07-18 Fernando Perez <fperez@colorado.edu>
465 2005-07-18 Fernando Perez <fperez@colorado.edu>
452
466
453 * IPython/genutils.py (get_home_dir): fix to help users with
467 * IPython/genutils.py (get_home_dir): fix to help users with
454 invalid $HOME under win32.
468 invalid $HOME under win32.
455
469
456 2005-07-17 Fernando Perez <fperez@colorado.edu>
470 2005-07-17 Fernando Perez <fperez@colorado.edu>
457
471
458 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
472 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
459 some old hacks and clean up a bit other routines; code should be
473 some old hacks and clean up a bit other routines; code should be
460 simpler and a bit faster.
474 simpler and a bit faster.
461
475
462 * IPython/iplib.py (interact): removed some last-resort attempts
476 * IPython/iplib.py (interact): removed some last-resort attempts
463 to survive broken stdout/stderr. That code was only making it
477 to survive broken stdout/stderr. That code was only making it
464 harder to abstract out the i/o (necessary for gui integration),
478 harder to abstract out the i/o (necessary for gui integration),
465 and the crashes it could prevent were extremely rare in practice
479 and the crashes it could prevent were extremely rare in practice
466 (besides being fully user-induced in a pretty violent manner).
480 (besides being fully user-induced in a pretty violent manner).
467
481
468 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
482 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
469 Nothing major yet, but the code is simpler to read; this should
483 Nothing major yet, but the code is simpler to read; this should
470 make it easier to do more serious modifications in the future.
484 make it easier to do more serious modifications in the future.
471
485
472 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
486 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
473 which broke in .15 (thanks to a report by Ville).
487 which broke in .15 (thanks to a report by Ville).
474
488
475 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
489 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
476 be quite correct, I know next to nothing about unicode). This
490 be quite correct, I know next to nothing about unicode). This
477 will allow unicode strings to be used in prompts, amongst other
491 will allow unicode strings to be used in prompts, amongst other
478 cases. It also will prevent ipython from crashing when unicode
492 cases. It also will prevent ipython from crashing when unicode
479 shows up unexpectedly in many places. If ascii encoding fails, we
493 shows up unexpectedly in many places. If ascii encoding fails, we
480 assume utf_8. Currently the encoding is not a user-visible
494 assume utf_8. Currently the encoding is not a user-visible
481 setting, though it could be made so if there is demand for it.
495 setting, though it could be made so if there is demand for it.
482
496
483 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
497 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
484
498
485 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
499 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
486
500
487 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
501 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
488
502
489 * IPython/genutils.py: Add 2.2 compatibility here, so all other
503 * IPython/genutils.py: Add 2.2 compatibility here, so all other
490 code can work transparently for 2.2/2.3.
504 code can work transparently for 2.2/2.3.
491
505
492 2005-07-16 Fernando Perez <fperez@colorado.edu>
506 2005-07-16 Fernando Perez <fperez@colorado.edu>
493
507
494 * IPython/ultraTB.py (ExceptionColors): Make a global variable
508 * IPython/ultraTB.py (ExceptionColors): Make a global variable
495 out of the color scheme table used for coloring exception
509 out of the color scheme table used for coloring exception
496 tracebacks. This allows user code to add new schemes at runtime.
510 tracebacks. This allows user code to add new schemes at runtime.
497 This is a minimally modified version of the patch at
511 This is a minimally modified version of the patch at
498 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
512 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
499 for the contribution.
513 for the contribution.
500
514
501 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
515 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
502 slightly modified version of the patch in
516 slightly modified version of the patch in
503 http://www.scipy.net/roundup/ipython/issue34, which also allows me
517 http://www.scipy.net/roundup/ipython/issue34, which also allows me
504 to remove the previous try/except solution (which was costlier).
518 to remove the previous try/except solution (which was costlier).
505 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
519 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
506
520
507 2005-06-08 Fernando Perez <fperez@colorado.edu>
521 2005-06-08 Fernando Perez <fperez@colorado.edu>
508
522
509 * IPython/iplib.py (write/write_err): Add methods to abstract all
523 * IPython/iplib.py (write/write_err): Add methods to abstract all
510 I/O a bit more.
524 I/O a bit more.
511
525
512 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
526 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
513 warning, reported by Aric Hagberg, fix by JD Hunter.
527 warning, reported by Aric Hagberg, fix by JD Hunter.
514
528
515 2005-06-02 *** Released version 0.6.15
529 2005-06-02 *** Released version 0.6.15
516
530
517 2005-06-01 Fernando Perez <fperez@colorado.edu>
531 2005-06-01 Fernando Perez <fperez@colorado.edu>
518
532
519 * IPython/iplib.py (MagicCompleter.file_matches): Fix
533 * IPython/iplib.py (MagicCompleter.file_matches): Fix
520 tab-completion of filenames within open-quoted strings. Note that
534 tab-completion of filenames within open-quoted strings. Note that
521 this requires that in ~/.ipython/ipythonrc, users change the
535 this requires that in ~/.ipython/ipythonrc, users change the
522 readline delimiters configuration to read:
536 readline delimiters configuration to read:
523
537
524 readline_remove_delims -/~
538 readline_remove_delims -/~
525
539
526
540
527 2005-05-31 *** Released version 0.6.14
541 2005-05-31 *** Released version 0.6.14
528
542
529 2005-05-29 Fernando Perez <fperez@colorado.edu>
543 2005-05-29 Fernando Perez <fperez@colorado.edu>
530
544
531 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
545 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
532 with files not on the filesystem. Reported by Eliyahu Sandler
546 with files not on the filesystem. Reported by Eliyahu Sandler
533 <eli@gondolin.net>
547 <eli@gondolin.net>
534
548
535 2005-05-22 Fernando Perez <fperez@colorado.edu>
549 2005-05-22 Fernando Perez <fperez@colorado.edu>
536
550
537 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
551 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
538 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
552 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
539
553
540 2005-05-19 Fernando Perez <fperez@colorado.edu>
554 2005-05-19 Fernando Perez <fperez@colorado.edu>
541
555
542 * IPython/iplib.py (safe_execfile): close a file which could be
556 * IPython/iplib.py (safe_execfile): close a file which could be
543 left open (causing problems in win32, which locks open files).
557 left open (causing problems in win32, which locks open files).
544 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
558 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
545
559
546 2005-05-18 Fernando Perez <fperez@colorado.edu>
560 2005-05-18 Fernando Perez <fperez@colorado.edu>
547
561
548 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
562 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
549 keyword arguments correctly to safe_execfile().
563 keyword arguments correctly to safe_execfile().
550
564
551 2005-05-13 Fernando Perez <fperez@colorado.edu>
565 2005-05-13 Fernando Perez <fperez@colorado.edu>
552
566
553 * ipython.1: Added info about Qt to manpage, and threads warning
567 * ipython.1: Added info about Qt to manpage, and threads warning
554 to usage page (invoked with --help).
568 to usage page (invoked with --help).
555
569
556 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
570 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
557 new matcher (it goes at the end of the priority list) to do
571 new matcher (it goes at the end of the priority list) to do
558 tab-completion on named function arguments. Submitted by George
572 tab-completion on named function arguments. Submitted by George
559 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
573 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
560 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
574 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
561 for more details.
575 for more details.
562
576
563 * IPython/Magic.py (magic_run): Added new -e flag to ignore
577 * IPython/Magic.py (magic_run): Added new -e flag to ignore
564 SystemExit exceptions in the script being run. Thanks to a report
578 SystemExit exceptions in the script being run. Thanks to a report
565 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
579 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
566 producing very annoying behavior when running unit tests.
580 producing very annoying behavior when running unit tests.
567
581
568 2005-05-12 Fernando Perez <fperez@colorado.edu>
582 2005-05-12 Fernando Perez <fperez@colorado.edu>
569
583
570 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
584 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
571 which I'd broken (again) due to a changed regexp. In the process,
585 which I'd broken (again) due to a changed regexp. In the process,
572 added ';' as an escape to auto-quote the whole line without
586 added ';' as an escape to auto-quote the whole line without
573 splitting its arguments. Thanks to a report by Jerry McRae
587 splitting its arguments. Thanks to a report by Jerry McRae
574 <qrs0xyc02-AT-sneakemail.com>.
588 <qrs0xyc02-AT-sneakemail.com>.
575
589
576 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
590 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
577 possible crashes caused by a TokenError. Reported by Ed Schofield
591 possible crashes caused by a TokenError. Reported by Ed Schofield
578 <schofield-AT-ftw.at>.
592 <schofield-AT-ftw.at>.
579
593
580 2005-05-06 Fernando Perez <fperez@colorado.edu>
594 2005-05-06 Fernando Perez <fperez@colorado.edu>
581
595
582 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
596 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
583
597
584 2005-04-29 Fernando Perez <fperez@colorado.edu>
598 2005-04-29 Fernando Perez <fperez@colorado.edu>
585
599
586 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
600 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
587 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
601 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
588 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
602 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
589 which provides support for Qt interactive usage (similar to the
603 which provides support for Qt interactive usage (similar to the
590 existing one for WX and GTK). This had been often requested.
604 existing one for WX and GTK). This had been often requested.
591
605
592 2005-04-14 *** Released version 0.6.13
606 2005-04-14 *** Released version 0.6.13
593
607
594 2005-04-08 Fernando Perez <fperez@colorado.edu>
608 2005-04-08 Fernando Perez <fperez@colorado.edu>
595
609
596 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
610 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
597 from _ofind, which gets called on almost every input line. Now,
611 from _ofind, which gets called on almost every input line. Now,
598 we only try to get docstrings if they are actually going to be
612 we only try to get docstrings if they are actually going to be
599 used (the overhead of fetching unnecessary docstrings can be
613 used (the overhead of fetching unnecessary docstrings can be
600 noticeable for certain objects, such as Pyro proxies).
614 noticeable for certain objects, such as Pyro proxies).
601
615
602 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
616 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
603 for completers. For some reason I had been passing them the state
617 for completers. For some reason I had been passing them the state
604 variable, which completers never actually need, and was in
618 variable, which completers never actually need, and was in
605 conflict with the rlcompleter API. Custom completers ONLY need to
619 conflict with the rlcompleter API. Custom completers ONLY need to
606 take the text parameter.
620 take the text parameter.
607
621
608 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
622 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
609 work correctly in pysh. I've also moved all the logic which used
623 work correctly in pysh. I've also moved all the logic which used
610 to be in pysh.py here, which will prevent problems with future
624 to be in pysh.py here, which will prevent problems with future
611 upgrades. However, this time I must warn users to update their
625 upgrades. However, this time I must warn users to update their
612 pysh profile to include the line
626 pysh profile to include the line
613
627
614 import_all IPython.Extensions.InterpreterExec
628 import_all IPython.Extensions.InterpreterExec
615
629
616 because otherwise things won't work for them. They MUST also
630 because otherwise things won't work for them. They MUST also
617 delete pysh.py and the line
631 delete pysh.py and the line
618
632
619 execfile pysh.py
633 execfile pysh.py
620
634
621 from their ipythonrc-pysh.
635 from their ipythonrc-pysh.
622
636
623 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
637 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
624 robust in the face of objects whose dir() returns non-strings
638 robust in the face of objects whose dir() returns non-strings
625 (which it shouldn't, but some broken libs like ITK do). Thanks to
639 (which it shouldn't, but some broken libs like ITK do). Thanks to
626 a patch by John Hunter (implemented differently, though). Also
640 a patch by John Hunter (implemented differently, though). Also
627 minor improvements by using .extend instead of + on lists.
641 minor improvements by using .extend instead of + on lists.
628
642
629 * pysh.py:
643 * pysh.py:
630
644
631 2005-04-06 Fernando Perez <fperez@colorado.edu>
645 2005-04-06 Fernando Perez <fperez@colorado.edu>
632
646
633 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
647 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
634 by default, so that all users benefit from it. Those who don't
648 by default, so that all users benefit from it. Those who don't
635 want it can still turn it off.
649 want it can still turn it off.
636
650
637 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
651 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
638 config file, I'd forgotten about this, so users were getting it
652 config file, I'd forgotten about this, so users were getting it
639 off by default.
653 off by default.
640
654
641 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
655 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
642 consistency. Now magics can be called in multiline statements,
656 consistency. Now magics can be called in multiline statements,
643 and python variables can be expanded in magic calls via $var.
657 and python variables can be expanded in magic calls via $var.
644 This makes the magic system behave just like aliases or !system
658 This makes the magic system behave just like aliases or !system
645 calls.
659 calls.
646
660
647 2005-03-28 Fernando Perez <fperez@colorado.edu>
661 2005-03-28 Fernando Perez <fperez@colorado.edu>
648
662
649 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
663 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
650 expensive string additions for building command. Add support for
664 expensive string additions for building command. Add support for
651 trailing ';' when autocall is used.
665 trailing ';' when autocall is used.
652
666
653 2005-03-26 Fernando Perez <fperez@colorado.edu>
667 2005-03-26 Fernando Perez <fperez@colorado.edu>
654
668
655 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
669 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
656 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
670 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
657 ipython.el robust against prompts with any number of spaces
671 ipython.el robust against prompts with any number of spaces
658 (including 0) after the ':' character.
672 (including 0) after the ':' character.
659
673
660 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
674 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
661 continuation prompt, which misled users to think the line was
675 continuation prompt, which misled users to think the line was
662 already indented. Closes debian Bug#300847, reported to me by
676 already indented. Closes debian Bug#300847, reported to me by
663 Norbert Tretkowski <tretkowski-AT-inittab.de>.
677 Norbert Tretkowski <tretkowski-AT-inittab.de>.
664
678
665 2005-03-23 Fernando Perez <fperez@colorado.edu>
679 2005-03-23 Fernando Perez <fperez@colorado.edu>
666
680
667 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
681 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
668 properly aligned if they have embedded newlines.
682 properly aligned if they have embedded newlines.
669
683
670 * IPython/iplib.py (runlines): Add a public method to expose
684 * IPython/iplib.py (runlines): Add a public method to expose
671 IPython's code execution machinery, so that users can run strings
685 IPython's code execution machinery, so that users can run strings
672 as if they had been typed at the prompt interactively.
686 as if they had been typed at the prompt interactively.
673 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
687 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
674 methods which can call the system shell, but with python variable
688 methods which can call the system shell, but with python variable
675 expansion. The three such methods are: __IPYTHON__.system,
689 expansion. The three such methods are: __IPYTHON__.system,
676 .getoutput and .getoutputerror. These need to be documented in a
690 .getoutput and .getoutputerror. These need to be documented in a
677 'public API' section (to be written) of the manual.
691 'public API' section (to be written) of the manual.
678
692
679 2005-03-20 Fernando Perez <fperez@colorado.edu>
693 2005-03-20 Fernando Perez <fperez@colorado.edu>
680
694
681 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
695 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
682 for custom exception handling. This is quite powerful, and it
696 for custom exception handling. This is quite powerful, and it
683 allows for user-installable exception handlers which can trap
697 allows for user-installable exception handlers which can trap
684 custom exceptions at runtime and treat them separately from
698 custom exceptions at runtime and treat them separately from
685 IPython's default mechanisms. At the request of Frédéric
699 IPython's default mechanisms. At the request of Frédéric
686 Mantegazza <mantegazza-AT-ill.fr>.
700 Mantegazza <mantegazza-AT-ill.fr>.
687 (InteractiveShell.set_custom_completer): public API function to
701 (InteractiveShell.set_custom_completer): public API function to
688 add new completers at runtime.
702 add new completers at runtime.
689
703
690 2005-03-19 Fernando Perez <fperez@colorado.edu>
704 2005-03-19 Fernando Perez <fperez@colorado.edu>
691
705
692 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
706 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
693 allow objects which provide their docstrings via non-standard
707 allow objects which provide their docstrings via non-standard
694 mechanisms (like Pyro proxies) to still be inspected by ipython's
708 mechanisms (like Pyro proxies) to still be inspected by ipython's
695 ? system.
709 ? system.
696
710
697 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
711 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
698 automatic capture system. I tried quite hard to make it work
712 automatic capture system. I tried quite hard to make it work
699 reliably, and simply failed. I tried many combinations with the
713 reliably, and simply failed. I tried many combinations with the
700 subprocess module, but eventually nothing worked in all needed
714 subprocess module, but eventually nothing worked in all needed
701 cases (not blocking stdin for the child, duplicating stdout
715 cases (not blocking stdin for the child, duplicating stdout
702 without blocking, etc). The new %sc/%sx still do capture to these
716 without blocking, etc). The new %sc/%sx still do capture to these
703 magical list/string objects which make shell use much more
717 magical list/string objects which make shell use much more
704 conveninent, so not all is lost.
718 conveninent, so not all is lost.
705
719
706 XXX - FIX MANUAL for the change above!
720 XXX - FIX MANUAL for the change above!
707
721
708 (runsource): I copied code.py's runsource() into ipython to modify
722 (runsource): I copied code.py's runsource() into ipython to modify
709 it a bit. Now the code object and source to be executed are
723 it a bit. Now the code object and source to be executed are
710 stored in ipython. This makes this info accessible to third-party
724 stored in ipython. This makes this info accessible to third-party
711 tools, like custom exception handlers. After a request by Frédéric
725 tools, like custom exception handlers. After a request by Frédéric
712 Mantegazza <mantegazza-AT-ill.fr>.
726 Mantegazza <mantegazza-AT-ill.fr>.
713
727
714 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
728 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
715 history-search via readline (like C-p/C-n). I'd wanted this for a
729 history-search via readline (like C-p/C-n). I'd wanted this for a
716 long time, but only recently found out how to do it. For users
730 long time, but only recently found out how to do it. For users
717 who already have their ipythonrc files made and want this, just
731 who already have their ipythonrc files made and want this, just
718 add:
732 add:
719
733
720 readline_parse_and_bind "\e[A": history-search-backward
734 readline_parse_and_bind "\e[A": history-search-backward
721 readline_parse_and_bind "\e[B": history-search-forward
735 readline_parse_and_bind "\e[B": history-search-forward
722
736
723 2005-03-18 Fernando Perez <fperez@colorado.edu>
737 2005-03-18 Fernando Perez <fperez@colorado.edu>
724
738
725 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
739 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
726 LSString and SList classes which allow transparent conversions
740 LSString and SList classes which allow transparent conversions
727 between list mode and whitespace-separated string.
741 between list mode and whitespace-separated string.
728 (magic_r): Fix recursion problem in %r.
742 (magic_r): Fix recursion problem in %r.
729
743
730 * IPython/genutils.py (LSString): New class to be used for
744 * IPython/genutils.py (LSString): New class to be used for
731 automatic storage of the results of all alias/system calls in _o
745 automatic storage of the results of all alias/system calls in _o
732 and _e (stdout/err). These provide a .l/.list attribute which
746 and _e (stdout/err). These provide a .l/.list attribute which
733 does automatic splitting on newlines. This means that for most
747 does automatic splitting on newlines. This means that for most
734 uses, you'll never need to do capturing of output with %sc/%sx
748 uses, you'll never need to do capturing of output with %sc/%sx
735 anymore, since ipython keeps this always done for you. Note that
749 anymore, since ipython keeps this always done for you. Note that
736 only the LAST results are stored, the _o/e variables are
750 only the LAST results are stored, the _o/e variables are
737 overwritten on each call. If you need to save their contents
751 overwritten on each call. If you need to save their contents
738 further, simply bind them to any other name.
752 further, simply bind them to any other name.
739
753
740 2005-03-17 Fernando Perez <fperez@colorado.edu>
754 2005-03-17 Fernando Perez <fperez@colorado.edu>
741
755
742 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
756 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
743 prompt namespace handling.
757 prompt namespace handling.
744
758
745 2005-03-16 Fernando Perez <fperez@colorado.edu>
759 2005-03-16 Fernando Perez <fperez@colorado.edu>
746
760
747 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
761 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
748 classic prompts to be '>>> ' (final space was missing, and it
762 classic prompts to be '>>> ' (final space was missing, and it
749 trips the emacs python mode).
763 trips the emacs python mode).
750 (BasePrompt.__str__): Added safe support for dynamic prompt
764 (BasePrompt.__str__): Added safe support for dynamic prompt
751 strings. Now you can set your prompt string to be '$x', and the
765 strings. Now you can set your prompt string to be '$x', and the
752 value of x will be printed from your interactive namespace. The
766 value of x will be printed from your interactive namespace. The
753 interpolation syntax includes the full Itpl support, so
767 interpolation syntax includes the full Itpl support, so
754 ${foo()+x+bar()} is a valid prompt string now, and the function
768 ${foo()+x+bar()} is a valid prompt string now, and the function
755 calls will be made at runtime.
769 calls will be made at runtime.
756
770
757 2005-03-15 Fernando Perez <fperez@colorado.edu>
771 2005-03-15 Fernando Perez <fperez@colorado.edu>
758
772
759 * IPython/Magic.py (magic_history): renamed %hist to %history, to
773 * IPython/Magic.py (magic_history): renamed %hist to %history, to
760 avoid name clashes in pylab. %hist still works, it just forwards
774 avoid name clashes in pylab. %hist still works, it just forwards
761 the call to %history.
775 the call to %history.
762
776
763 2005-03-02 *** Released version 0.6.12
777 2005-03-02 *** Released version 0.6.12
764
778
765 2005-03-02 Fernando Perez <fperez@colorado.edu>
779 2005-03-02 Fernando Perez <fperez@colorado.edu>
766
780
767 * IPython/iplib.py (handle_magic): log magic calls properly as
781 * IPython/iplib.py (handle_magic): log magic calls properly as
768 ipmagic() function calls.
782 ipmagic() function calls.
769
783
770 * IPython/Magic.py (magic_time): Improved %time to support
784 * IPython/Magic.py (magic_time): Improved %time to support
771 statements and provide wall-clock as well as CPU time.
785 statements and provide wall-clock as well as CPU time.
772
786
773 2005-02-27 Fernando Perez <fperez@colorado.edu>
787 2005-02-27 Fernando Perez <fperez@colorado.edu>
774
788
775 * IPython/hooks.py: New hooks module, to expose user-modifiable
789 * IPython/hooks.py: New hooks module, to expose user-modifiable
776 IPython functionality in a clean manner. For now only the editor
790 IPython functionality in a clean manner. For now only the editor
777 hook is actually written, and other thigns which I intend to turn
791 hook is actually written, and other thigns which I intend to turn
778 into proper hooks aren't yet there. The display and prefilter
792 into proper hooks aren't yet there. The display and prefilter
779 stuff, for example, should be hooks. But at least now the
793 stuff, for example, should be hooks. But at least now the
780 framework is in place, and the rest can be moved here with more
794 framework is in place, and the rest can be moved here with more
781 time later. IPython had had a .hooks variable for a long time for
795 time later. IPython had had a .hooks variable for a long time for
782 this purpose, but I'd never actually used it for anything.
796 this purpose, but I'd never actually used it for anything.
783
797
784 2005-02-26 Fernando Perez <fperez@colorado.edu>
798 2005-02-26 Fernando Perez <fperez@colorado.edu>
785
799
786 * IPython/ipmaker.py (make_IPython): make the default ipython
800 * IPython/ipmaker.py (make_IPython): make the default ipython
787 directory be called _ipython under win32, to follow more the
801 directory be called _ipython under win32, to follow more the
788 naming peculiarities of that platform (where buggy software like
802 naming peculiarities of that platform (where buggy software like
789 Visual Sourcesafe breaks with .named directories). Reported by
803 Visual Sourcesafe breaks with .named directories). Reported by
790 Ville Vainio.
804 Ville Vainio.
791
805
792 2005-02-23 Fernando Perez <fperez@colorado.edu>
806 2005-02-23 Fernando Perez <fperez@colorado.edu>
793
807
794 * IPython/iplib.py (InteractiveShell.__init__): removed a few
808 * IPython/iplib.py (InteractiveShell.__init__): removed a few
795 auto_aliases for win32 which were causing problems. Users can
809 auto_aliases for win32 which were causing problems. Users can
796 define the ones they personally like.
810 define the ones they personally like.
797
811
798 2005-02-21 Fernando Perez <fperez@colorado.edu>
812 2005-02-21 Fernando Perez <fperez@colorado.edu>
799
813
800 * IPython/Magic.py (magic_time): new magic to time execution of
814 * IPython/Magic.py (magic_time): new magic to time execution of
801 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
815 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
802
816
803 2005-02-19 Fernando Perez <fperez@colorado.edu>
817 2005-02-19 Fernando Perez <fperez@colorado.edu>
804
818
805 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
819 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
806 into keys (for prompts, for example).
820 into keys (for prompts, for example).
807
821
808 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
822 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
809 prompts in case users want them. This introduces a small behavior
823 prompts in case users want them. This introduces a small behavior
810 change: ipython does not automatically add a space to all prompts
824 change: ipython does not automatically add a space to all prompts
811 anymore. To get the old prompts with a space, users should add it
825 anymore. To get the old prompts with a space, users should add it
812 manually to their ipythonrc file, so for example prompt_in1 should
826 manually to their ipythonrc file, so for example prompt_in1 should
813 now read 'In [\#]: ' instead of 'In [\#]:'.
827 now read 'In [\#]: ' instead of 'In [\#]:'.
814 (BasePrompt.__init__): New option prompts_pad_left (only in rc
828 (BasePrompt.__init__): New option prompts_pad_left (only in rc
815 file) to control left-padding of secondary prompts.
829 file) to control left-padding of secondary prompts.
816
830
817 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
831 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
818 the profiler can't be imported. Fix for Debian, which removed
832 the profiler can't be imported. Fix for Debian, which removed
819 profile.py because of License issues. I applied a slightly
833 profile.py because of License issues. I applied a slightly
820 modified version of the original Debian patch at
834 modified version of the original Debian patch at
821 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
835 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
822
836
823 2005-02-17 Fernando Perez <fperez@colorado.edu>
837 2005-02-17 Fernando Perez <fperez@colorado.edu>
824
838
825 * IPython/genutils.py (native_line_ends): Fix bug which would
839 * IPython/genutils.py (native_line_ends): Fix bug which would
826 cause improper line-ends under win32 b/c I was not opening files
840 cause improper line-ends under win32 b/c I was not opening files
827 in binary mode. Bug report and fix thanks to Ville.
841 in binary mode. Bug report and fix thanks to Ville.
828
842
829 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
843 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
830 trying to catch spurious foo[1] autocalls. My fix actually broke
844 trying to catch spurious foo[1] autocalls. My fix actually broke
831 ',/' autoquote/call with explicit escape (bad regexp).
845 ',/' autoquote/call with explicit escape (bad regexp).
832
846
833 2005-02-15 *** Released version 0.6.11
847 2005-02-15 *** Released version 0.6.11
834
848
835 2005-02-14 Fernando Perez <fperez@colorado.edu>
849 2005-02-14 Fernando Perez <fperez@colorado.edu>
836
850
837 * IPython/background_jobs.py: New background job management
851 * IPython/background_jobs.py: New background job management
838 subsystem. This is implemented via a new set of classes, and
852 subsystem. This is implemented via a new set of classes, and
839 IPython now provides a builtin 'jobs' object for background job
853 IPython now provides a builtin 'jobs' object for background job
840 execution. A convenience %bg magic serves as a lightweight
854 execution. A convenience %bg magic serves as a lightweight
841 frontend for starting the more common type of calls. This was
855 frontend for starting the more common type of calls. This was
842 inspired by discussions with B. Granger and the BackgroundCommand
856 inspired by discussions with B. Granger and the BackgroundCommand
843 class described in the book Python Scripting for Computational
857 class described in the book Python Scripting for Computational
844 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
858 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
845 (although ultimately no code from this text was used, as IPython's
859 (although ultimately no code from this text was used, as IPython's
846 system is a separate implementation).
860 system is a separate implementation).
847
861
848 * IPython/iplib.py (MagicCompleter.python_matches): add new option
862 * IPython/iplib.py (MagicCompleter.python_matches): add new option
849 to control the completion of single/double underscore names
863 to control the completion of single/double underscore names
850 separately. As documented in the example ipytonrc file, the
864 separately. As documented in the example ipytonrc file, the
851 readline_omit__names variable can now be set to 2, to omit even
865 readline_omit__names variable can now be set to 2, to omit even
852 single underscore names. Thanks to a patch by Brian Wong
866 single underscore names. Thanks to a patch by Brian Wong
853 <BrianWong-AT-AirgoNetworks.Com>.
867 <BrianWong-AT-AirgoNetworks.Com>.
854 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
868 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
855 be autocalled as foo([1]) if foo were callable. A problem for
869 be autocalled as foo([1]) if foo were callable. A problem for
856 things which are both callable and implement __getitem__.
870 things which are both callable and implement __getitem__.
857 (init_readline): Fix autoindentation for win32. Thanks to a patch
871 (init_readline): Fix autoindentation for win32. Thanks to a patch
858 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
872 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
859
873
860 2005-02-12 Fernando Perez <fperez@colorado.edu>
874 2005-02-12 Fernando Perez <fperez@colorado.edu>
861
875
862 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
876 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
863 which I had written long ago to sort out user error messages which
877 which I had written long ago to sort out user error messages which
864 may occur during startup. This seemed like a good idea initially,
878 may occur during startup. This seemed like a good idea initially,
865 but it has proven a disaster in retrospect. I don't want to
879 but it has proven a disaster in retrospect. I don't want to
866 change much code for now, so my fix is to set the internal 'debug'
880 change much code for now, so my fix is to set the internal 'debug'
867 flag to true everywhere, whose only job was precisely to control
881 flag to true everywhere, whose only job was precisely to control
868 this subsystem. This closes issue 28 (as well as avoiding all
882 this subsystem. This closes issue 28 (as well as avoiding all
869 sorts of strange hangups which occur from time to time).
883 sorts of strange hangups which occur from time to time).
870
884
871 2005-02-07 Fernando Perez <fperez@colorado.edu>
885 2005-02-07 Fernando Perez <fperez@colorado.edu>
872
886
873 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
887 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
874 previous call produced a syntax error.
888 previous call produced a syntax error.
875
889
876 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
890 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
877 classes without constructor.
891 classes without constructor.
878
892
879 2005-02-06 Fernando Perez <fperez@colorado.edu>
893 2005-02-06 Fernando Perez <fperez@colorado.edu>
880
894
881 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
895 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
882 completions with the results of each matcher, so we return results
896 completions with the results of each matcher, so we return results
883 to the user from all namespaces. This breaks with ipython
897 to the user from all namespaces. This breaks with ipython
884 tradition, but I think it's a nicer behavior. Now you get all
898 tradition, but I think it's a nicer behavior. Now you get all
885 possible completions listed, from all possible namespaces (python,
899 possible completions listed, from all possible namespaces (python,
886 filesystem, magics...) After a request by John Hunter
900 filesystem, magics...) After a request by John Hunter
887 <jdhunter-AT-nitace.bsd.uchicago.edu>.
901 <jdhunter-AT-nitace.bsd.uchicago.edu>.
888
902
889 2005-02-05 Fernando Perez <fperez@colorado.edu>
903 2005-02-05 Fernando Perez <fperez@colorado.edu>
890
904
891 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
905 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
892 the call had quote characters in it (the quotes were stripped).
906 the call had quote characters in it (the quotes were stripped).
893
907
894 2005-01-31 Fernando Perez <fperez@colorado.edu>
908 2005-01-31 Fernando Perez <fperez@colorado.edu>
895
909
896 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
910 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
897 Itpl.itpl() to make the code more robust against psyco
911 Itpl.itpl() to make the code more robust against psyco
898 optimizations.
912 optimizations.
899
913
900 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
914 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
901 of causing an exception. Quicker, cleaner.
915 of causing an exception. Quicker, cleaner.
902
916
903 2005-01-28 Fernando Perez <fperez@colorado.edu>
917 2005-01-28 Fernando Perez <fperez@colorado.edu>
904
918
905 * scripts/ipython_win_post_install.py (install): hardcode
919 * scripts/ipython_win_post_install.py (install): hardcode
906 sys.prefix+'python.exe' as the executable path. It turns out that
920 sys.prefix+'python.exe' as the executable path. It turns out that
907 during the post-installation run, sys.executable resolves to the
921 during the post-installation run, sys.executable resolves to the
908 name of the binary installer! I should report this as a distutils
922 name of the binary installer! I should report this as a distutils
909 bug, I think. I updated the .10 release with this tiny fix, to
923 bug, I think. I updated the .10 release with this tiny fix, to
910 avoid annoying the lists further.
924 avoid annoying the lists further.
911
925
912 2005-01-27 *** Released version 0.6.10
926 2005-01-27 *** Released version 0.6.10
913
927
914 2005-01-27 Fernando Perez <fperez@colorado.edu>
928 2005-01-27 Fernando Perez <fperez@colorado.edu>
915
929
916 * IPython/numutils.py (norm): Added 'inf' as optional name for
930 * IPython/numutils.py (norm): Added 'inf' as optional name for
917 L-infinity norm, included references to mathworld.com for vector
931 L-infinity norm, included references to mathworld.com for vector
918 norm definitions.
932 norm definitions.
919 (amin/amax): added amin/amax for array min/max. Similar to what
933 (amin/amax): added amin/amax for array min/max. Similar to what
920 pylab ships with after the recent reorganization of names.
934 pylab ships with after the recent reorganization of names.
921 (spike/spike_odd): removed deprecated spike/spike_odd functions.
935 (spike/spike_odd): removed deprecated spike/spike_odd functions.
922
936
923 * ipython.el: committed Alex's recent fixes and improvements.
937 * ipython.el: committed Alex's recent fixes and improvements.
924 Tested with python-mode from CVS, and it looks excellent. Since
938 Tested with python-mode from CVS, and it looks excellent. Since
925 python-mode hasn't released anything in a while, I'm temporarily
939 python-mode hasn't released anything in a while, I'm temporarily
926 putting a copy of today's CVS (v 4.70) of python-mode in:
940 putting a copy of today's CVS (v 4.70) of python-mode in:
927 http://ipython.scipy.org/tmp/python-mode.el
941 http://ipython.scipy.org/tmp/python-mode.el
928
942
929 * scripts/ipython_win_post_install.py (install): Win32 fix to use
943 * scripts/ipython_win_post_install.py (install): Win32 fix to use
930 sys.executable for the executable name, instead of assuming it's
944 sys.executable for the executable name, instead of assuming it's
931 called 'python.exe' (the post-installer would have produced broken
945 called 'python.exe' (the post-installer would have produced broken
932 setups on systems with a differently named python binary).
946 setups on systems with a differently named python binary).
933
947
934 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
948 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
935 references to os.linesep, to make the code more
949 references to os.linesep, to make the code more
936 platform-independent. This is also part of the win32 coloring
950 platform-independent. This is also part of the win32 coloring
937 fixes.
951 fixes.
938
952
939 * IPython/genutils.py (page_dumb): Remove attempts to chop long
953 * IPython/genutils.py (page_dumb): Remove attempts to chop long
940 lines, which actually cause coloring bugs because the length of
954 lines, which actually cause coloring bugs because the length of
941 the line is very difficult to correctly compute with embedded
955 the line is very difficult to correctly compute with embedded
942 escapes. This was the source of all the coloring problems under
956 escapes. This was the source of all the coloring problems under
943 Win32. I think that _finally_, Win32 users have a properly
957 Win32. I think that _finally_, Win32 users have a properly
944 working ipython in all respects. This would never have happened
958 working ipython in all respects. This would never have happened
945 if not for Gary Bishop and Viktor Ransmayr's great help and work.
959 if not for Gary Bishop and Viktor Ransmayr's great help and work.
946
960
947 2005-01-26 *** Released version 0.6.9
961 2005-01-26 *** Released version 0.6.9
948
962
949 2005-01-25 Fernando Perez <fperez@colorado.edu>
963 2005-01-25 Fernando Perez <fperez@colorado.edu>
950
964
951 * setup.py: finally, we have a true Windows installer, thanks to
965 * setup.py: finally, we have a true Windows installer, thanks to
952 the excellent work of Viktor Ransmayr
966 the excellent work of Viktor Ransmayr
953 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
967 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
954 Windows users. The setup routine is quite a bit cleaner thanks to
968 Windows users. The setup routine is quite a bit cleaner thanks to
955 this, and the post-install script uses the proper functions to
969 this, and the post-install script uses the proper functions to
956 allow a clean de-installation using the standard Windows Control
970 allow a clean de-installation using the standard Windows Control
957 Panel.
971 Panel.
958
972
959 * IPython/genutils.py (get_home_dir): changed to use the $HOME
973 * IPython/genutils.py (get_home_dir): changed to use the $HOME
960 environment variable under all OSes (including win32) if
974 environment variable under all OSes (including win32) if
961 available. This will give consistency to win32 users who have set
975 available. This will give consistency to win32 users who have set
962 this variable for any reason. If os.environ['HOME'] fails, the
976 this variable for any reason. If os.environ['HOME'] fails, the
963 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
977 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
964
978
965 2005-01-24 Fernando Perez <fperez@colorado.edu>
979 2005-01-24 Fernando Perez <fperez@colorado.edu>
966
980
967 * IPython/numutils.py (empty_like): add empty_like(), similar to
981 * IPython/numutils.py (empty_like): add empty_like(), similar to
968 zeros_like() but taking advantage of the new empty() Numeric routine.
982 zeros_like() but taking advantage of the new empty() Numeric routine.
969
983
970 2005-01-23 *** Released version 0.6.8
984 2005-01-23 *** Released version 0.6.8
971
985
972 2005-01-22 Fernando Perez <fperez@colorado.edu>
986 2005-01-22 Fernando Perez <fperez@colorado.edu>
973
987
974 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
988 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
975 automatic show() calls. After discussing things with JDH, it
989 automatic show() calls. After discussing things with JDH, it
976 turns out there are too many corner cases where this can go wrong.
990 turns out there are too many corner cases where this can go wrong.
977 It's best not to try to be 'too smart', and simply have ipython
991 It's best not to try to be 'too smart', and simply have ipython
978 reproduce as much as possible the default behavior of a normal
992 reproduce as much as possible the default behavior of a normal
979 python shell.
993 python shell.
980
994
981 * IPython/iplib.py (InteractiveShell.__init__): Modified the
995 * IPython/iplib.py (InteractiveShell.__init__): Modified the
982 line-splitting regexp and _prefilter() to avoid calling getattr()
996 line-splitting regexp and _prefilter() to avoid calling getattr()
983 on assignments. This closes
997 on assignments. This closes
984 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
998 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
985 readline uses getattr(), so a simple <TAB> keypress is still
999 readline uses getattr(), so a simple <TAB> keypress is still
986 enough to trigger getattr() calls on an object.
1000 enough to trigger getattr() calls on an object.
987
1001
988 2005-01-21 Fernando Perez <fperez@colorado.edu>
1002 2005-01-21 Fernando Perez <fperez@colorado.edu>
989
1003
990 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1004 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
991 docstring under pylab so it doesn't mask the original.
1005 docstring under pylab so it doesn't mask the original.
992
1006
993 2005-01-21 *** Released version 0.6.7
1007 2005-01-21 *** Released version 0.6.7
994
1008
995 2005-01-21 Fernando Perez <fperez@colorado.edu>
1009 2005-01-21 Fernando Perez <fperez@colorado.edu>
996
1010
997 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1011 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
998 signal handling for win32 users in multithreaded mode.
1012 signal handling for win32 users in multithreaded mode.
999
1013
1000 2005-01-17 Fernando Perez <fperez@colorado.edu>
1014 2005-01-17 Fernando Perez <fperez@colorado.edu>
1001
1015
1002 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1016 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1003 instances with no __init__. After a crash report by Norbert Nemec
1017 instances with no __init__. After a crash report by Norbert Nemec
1004 <Norbert-AT-nemec-online.de>.
1018 <Norbert-AT-nemec-online.de>.
1005
1019
1006 2005-01-14 Fernando Perez <fperez@colorado.edu>
1020 2005-01-14 Fernando Perez <fperez@colorado.edu>
1007
1021
1008 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1022 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1009 names for verbose exceptions, when multiple dotted names and the
1023 names for verbose exceptions, when multiple dotted names and the
1010 'parent' object were present on the same line.
1024 'parent' object were present on the same line.
1011
1025
1012 2005-01-11 Fernando Perez <fperez@colorado.edu>
1026 2005-01-11 Fernando Perez <fperez@colorado.edu>
1013
1027
1014 * IPython/genutils.py (flag_calls): new utility to trap and flag
1028 * IPython/genutils.py (flag_calls): new utility to trap and flag
1015 calls in functions. I need it to clean up matplotlib support.
1029 calls in functions. I need it to clean up matplotlib support.
1016 Also removed some deprecated code in genutils.
1030 Also removed some deprecated code in genutils.
1017
1031
1018 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1032 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1019 that matplotlib scripts called with %run, which don't call show()
1033 that matplotlib scripts called with %run, which don't call show()
1020 themselves, still have their plotting windows open.
1034 themselves, still have their plotting windows open.
1021
1035
1022 2005-01-05 Fernando Perez <fperez@colorado.edu>
1036 2005-01-05 Fernando Perez <fperez@colorado.edu>
1023
1037
1024 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1038 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1025 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1039 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1026
1040
1027 2004-12-19 Fernando Perez <fperez@colorado.edu>
1041 2004-12-19 Fernando Perez <fperez@colorado.edu>
1028
1042
1029 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1043 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1030 parent_runcode, which was an eyesore. The same result can be
1044 parent_runcode, which was an eyesore. The same result can be
1031 obtained with Python's regular superclass mechanisms.
1045 obtained with Python's regular superclass mechanisms.
1032
1046
1033 2004-12-17 Fernando Perez <fperez@colorado.edu>
1047 2004-12-17 Fernando Perez <fperez@colorado.edu>
1034
1048
1035 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1049 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1036 reported by Prabhu.
1050 reported by Prabhu.
1037 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1051 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1038 sys.stderr) instead of explicitly calling sys.stderr. This helps
1052 sys.stderr) instead of explicitly calling sys.stderr. This helps
1039 maintain our I/O abstractions clean, for future GUI embeddings.
1053 maintain our I/O abstractions clean, for future GUI embeddings.
1040
1054
1041 * IPython/genutils.py (info): added new utility for sys.stderr
1055 * IPython/genutils.py (info): added new utility for sys.stderr
1042 unified info message handling (thin wrapper around warn()).
1056 unified info message handling (thin wrapper around warn()).
1043
1057
1044 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1058 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1045 composite (dotted) names on verbose exceptions.
1059 composite (dotted) names on verbose exceptions.
1046 (VerboseTB.nullrepr): harden against another kind of errors which
1060 (VerboseTB.nullrepr): harden against another kind of errors which
1047 Python's inspect module can trigger, and which were crashing
1061 Python's inspect module can trigger, and which were crashing
1048 IPython. Thanks to a report by Marco Lombardi
1062 IPython. Thanks to a report by Marco Lombardi
1049 <mlombard-AT-ma010192.hq.eso.org>.
1063 <mlombard-AT-ma010192.hq.eso.org>.
1050
1064
1051 2004-12-13 *** Released version 0.6.6
1065 2004-12-13 *** Released version 0.6.6
1052
1066
1053 2004-12-12 Fernando Perez <fperez@colorado.edu>
1067 2004-12-12 Fernando Perez <fperez@colorado.edu>
1054
1068
1055 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1069 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1056 generated by pygtk upon initialization if it was built without
1070 generated by pygtk upon initialization if it was built without
1057 threads (for matplotlib users). After a crash reported by
1071 threads (for matplotlib users). After a crash reported by
1058 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1072 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1059
1073
1060 * IPython/ipmaker.py (make_IPython): fix small bug in the
1074 * IPython/ipmaker.py (make_IPython): fix small bug in the
1061 import_some parameter for multiple imports.
1075 import_some parameter for multiple imports.
1062
1076
1063 * IPython/iplib.py (ipmagic): simplified the interface of
1077 * IPython/iplib.py (ipmagic): simplified the interface of
1064 ipmagic() to take a single string argument, just as it would be
1078 ipmagic() to take a single string argument, just as it would be
1065 typed at the IPython cmd line.
1079 typed at the IPython cmd line.
1066 (ipalias): Added new ipalias() with an interface identical to
1080 (ipalias): Added new ipalias() with an interface identical to
1067 ipmagic(). This completes exposing a pure python interface to the
1081 ipmagic(). This completes exposing a pure python interface to the
1068 alias and magic system, which can be used in loops or more complex
1082 alias and magic system, which can be used in loops or more complex
1069 code where IPython's automatic line mangling is not active.
1083 code where IPython's automatic line mangling is not active.
1070
1084
1071 * IPython/genutils.py (timing): changed interface of timing to
1085 * IPython/genutils.py (timing): changed interface of timing to
1072 simply run code once, which is the most common case. timings()
1086 simply run code once, which is the most common case. timings()
1073 remains unchanged, for the cases where you want multiple runs.
1087 remains unchanged, for the cases where you want multiple runs.
1074
1088
1075 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1089 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1076 bug where Python2.2 crashes with exec'ing code which does not end
1090 bug where Python2.2 crashes with exec'ing code which does not end
1077 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1091 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1078 before.
1092 before.
1079
1093
1080 2004-12-10 Fernando Perez <fperez@colorado.edu>
1094 2004-12-10 Fernando Perez <fperez@colorado.edu>
1081
1095
1082 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1096 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1083 -t to -T, to accomodate the new -t flag in %run (the %run and
1097 -t to -T, to accomodate the new -t flag in %run (the %run and
1084 %prun options are kind of intermixed, and it's not easy to change
1098 %prun options are kind of intermixed, and it's not easy to change
1085 this with the limitations of python's getopt).
1099 this with the limitations of python's getopt).
1086
1100
1087 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1101 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1088 the execution of scripts. It's not as fine-tuned as timeit.py,
1102 the execution of scripts. It's not as fine-tuned as timeit.py,
1089 but it works from inside ipython (and under 2.2, which lacks
1103 but it works from inside ipython (and under 2.2, which lacks
1090 timeit.py). Optionally a number of runs > 1 can be given for
1104 timeit.py). Optionally a number of runs > 1 can be given for
1091 timing very short-running code.
1105 timing very short-running code.
1092
1106
1093 * IPython/genutils.py (uniq_stable): new routine which returns a
1107 * IPython/genutils.py (uniq_stable): new routine which returns a
1094 list of unique elements in any iterable, but in stable order of
1108 list of unique elements in any iterable, but in stable order of
1095 appearance. I needed this for the ultraTB fixes, and it's a handy
1109 appearance. I needed this for the ultraTB fixes, and it's a handy
1096 utility.
1110 utility.
1097
1111
1098 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1112 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1099 dotted names in Verbose exceptions. This had been broken since
1113 dotted names in Verbose exceptions. This had been broken since
1100 the very start, now x.y will properly be printed in a Verbose
1114 the very start, now x.y will properly be printed in a Verbose
1101 traceback, instead of x being shown and y appearing always as an
1115 traceback, instead of x being shown and y appearing always as an
1102 'undefined global'. Getting this to work was a bit tricky,
1116 'undefined global'. Getting this to work was a bit tricky,
1103 because by default python tokenizers are stateless. Saved by
1117 because by default python tokenizers are stateless. Saved by
1104 python's ability to easily add a bit of state to an arbitrary
1118 python's ability to easily add a bit of state to an arbitrary
1105 function (without needing to build a full-blown callable object).
1119 function (without needing to build a full-blown callable object).
1106
1120
1107 Also big cleanup of this code, which had horrendous runtime
1121 Also big cleanup of this code, which had horrendous runtime
1108 lookups of zillions of attributes for colorization. Moved all
1122 lookups of zillions of attributes for colorization. Moved all
1109 this code into a few templates, which make it cleaner and quicker.
1123 this code into a few templates, which make it cleaner and quicker.
1110
1124
1111 Printout quality was also improved for Verbose exceptions: one
1125 Printout quality was also improved for Verbose exceptions: one
1112 variable per line, and memory addresses are printed (this can be
1126 variable per line, and memory addresses are printed (this can be
1113 quite handy in nasty debugging situations, which is what Verbose
1127 quite handy in nasty debugging situations, which is what Verbose
1114 is for).
1128 is for).
1115
1129
1116 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1130 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1117 the command line as scripts to be loaded by embedded instances.
1131 the command line as scripts to be loaded by embedded instances.
1118 Doing so has the potential for an infinite recursion if there are
1132 Doing so has the potential for an infinite recursion if there are
1119 exceptions thrown in the process. This fixes a strange crash
1133 exceptions thrown in the process. This fixes a strange crash
1120 reported by Philippe MULLER <muller-AT-irit.fr>.
1134 reported by Philippe MULLER <muller-AT-irit.fr>.
1121
1135
1122 2004-12-09 Fernando Perez <fperez@colorado.edu>
1136 2004-12-09 Fernando Perez <fperez@colorado.edu>
1123
1137
1124 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1138 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1125 to reflect new names in matplotlib, which now expose the
1139 to reflect new names in matplotlib, which now expose the
1126 matlab-compatible interface via a pylab module instead of the
1140 matlab-compatible interface via a pylab module instead of the
1127 'matlab' name. The new code is backwards compatible, so users of
1141 'matlab' name. The new code is backwards compatible, so users of
1128 all matplotlib versions are OK. Patch by J. Hunter.
1142 all matplotlib versions are OK. Patch by J. Hunter.
1129
1143
1130 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1144 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1131 of __init__ docstrings for instances (class docstrings are already
1145 of __init__ docstrings for instances (class docstrings are already
1132 automatically printed). Instances with customized docstrings
1146 automatically printed). Instances with customized docstrings
1133 (indep. of the class) are also recognized and all 3 separate
1147 (indep. of the class) are also recognized and all 3 separate
1134 docstrings are printed (instance, class, constructor). After some
1148 docstrings are printed (instance, class, constructor). After some
1135 comments/suggestions by J. Hunter.
1149 comments/suggestions by J. Hunter.
1136
1150
1137 2004-12-05 Fernando Perez <fperez@colorado.edu>
1151 2004-12-05 Fernando Perez <fperez@colorado.edu>
1138
1152
1139 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1153 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1140 warnings when tab-completion fails and triggers an exception.
1154 warnings when tab-completion fails and triggers an exception.
1141
1155
1142 2004-12-03 Fernando Perez <fperez@colorado.edu>
1156 2004-12-03 Fernando Perez <fperez@colorado.edu>
1143
1157
1144 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1158 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1145 be triggered when using 'run -p'. An incorrect option flag was
1159 be triggered when using 'run -p'. An incorrect option flag was
1146 being set ('d' instead of 'D').
1160 being set ('d' instead of 'D').
1147 (manpage): fix missing escaped \- sign.
1161 (manpage): fix missing escaped \- sign.
1148
1162
1149 2004-11-30 *** Released version 0.6.5
1163 2004-11-30 *** Released version 0.6.5
1150
1164
1151 2004-11-30 Fernando Perez <fperez@colorado.edu>
1165 2004-11-30 Fernando Perez <fperez@colorado.edu>
1152
1166
1153 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1167 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1154 setting with -d option.
1168 setting with -d option.
1155
1169
1156 * setup.py (docfiles): Fix problem where the doc glob I was using
1170 * setup.py (docfiles): Fix problem where the doc glob I was using
1157 was COMPLETELY BROKEN. It was giving the right files by pure
1171 was COMPLETELY BROKEN. It was giving the right files by pure
1158 accident, but failed once I tried to include ipython.el. Note:
1172 accident, but failed once I tried to include ipython.el. Note:
1159 glob() does NOT allow you to do exclusion on multiple endings!
1173 glob() does NOT allow you to do exclusion on multiple endings!
1160
1174
1161 2004-11-29 Fernando Perez <fperez@colorado.edu>
1175 2004-11-29 Fernando Perez <fperez@colorado.edu>
1162
1176
1163 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1177 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1164 the manpage as the source. Better formatting & consistency.
1178 the manpage as the source. Better formatting & consistency.
1165
1179
1166 * IPython/Magic.py (magic_run): Added new -d option, to run
1180 * IPython/Magic.py (magic_run): Added new -d option, to run
1167 scripts under the control of the python pdb debugger. Note that
1181 scripts under the control of the python pdb debugger. Note that
1168 this required changing the %prun option -d to -D, to avoid a clash
1182 this required changing the %prun option -d to -D, to avoid a clash
1169 (since %run must pass options to %prun, and getopt is too dumb to
1183 (since %run must pass options to %prun, and getopt is too dumb to
1170 handle options with string values with embedded spaces). Thanks
1184 handle options with string values with embedded spaces). Thanks
1171 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1185 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1172 (magic_who_ls): added type matching to %who and %whos, so that one
1186 (magic_who_ls): added type matching to %who and %whos, so that one
1173 can filter their output to only include variables of certain
1187 can filter their output to only include variables of certain
1174 types. Another suggestion by Matthew.
1188 types. Another suggestion by Matthew.
1175 (magic_whos): Added memory summaries in kb and Mb for arrays.
1189 (magic_whos): Added memory summaries in kb and Mb for arrays.
1176 (magic_who): Improve formatting (break lines every 9 vars).
1190 (magic_who): Improve formatting (break lines every 9 vars).
1177
1191
1178 2004-11-28 Fernando Perez <fperez@colorado.edu>
1192 2004-11-28 Fernando Perez <fperez@colorado.edu>
1179
1193
1180 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1194 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1181 cache when empty lines were present.
1195 cache when empty lines were present.
1182
1196
1183 2004-11-24 Fernando Perez <fperez@colorado.edu>
1197 2004-11-24 Fernando Perez <fperez@colorado.edu>
1184
1198
1185 * IPython/usage.py (__doc__): document the re-activated threading
1199 * IPython/usage.py (__doc__): document the re-activated threading
1186 options for WX and GTK.
1200 options for WX and GTK.
1187
1201
1188 2004-11-23 Fernando Perez <fperez@colorado.edu>
1202 2004-11-23 Fernando Perez <fperez@colorado.edu>
1189
1203
1190 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1204 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1191 the -wthread and -gthread options, along with a new -tk one to try
1205 the -wthread and -gthread options, along with a new -tk one to try
1192 and coordinate Tk threading with wx/gtk. The tk support is very
1206 and coordinate Tk threading with wx/gtk. The tk support is very
1193 platform dependent, since it seems to require Tcl and Tk to be
1207 platform dependent, since it seems to require Tcl and Tk to be
1194 built with threads (Fedora1/2 appears NOT to have it, but in
1208 built with threads (Fedora1/2 appears NOT to have it, but in
1195 Prabhu's Debian boxes it works OK). But even with some Tk
1209 Prabhu's Debian boxes it works OK). But even with some Tk
1196 limitations, this is a great improvement.
1210 limitations, this is a great improvement.
1197
1211
1198 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1212 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1199 info in user prompts. Patch by Prabhu.
1213 info in user prompts. Patch by Prabhu.
1200
1214
1201 2004-11-18 Fernando Perez <fperez@colorado.edu>
1215 2004-11-18 Fernando Perez <fperez@colorado.edu>
1202
1216
1203 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1217 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1204 EOFErrors and bail, to avoid infinite loops if a non-terminating
1218 EOFErrors and bail, to avoid infinite loops if a non-terminating
1205 file is fed into ipython. Patch submitted in issue 19 by user,
1219 file is fed into ipython. Patch submitted in issue 19 by user,
1206 many thanks.
1220 many thanks.
1207
1221
1208 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1222 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1209 autoquote/parens in continuation prompts, which can cause lots of
1223 autoquote/parens in continuation prompts, which can cause lots of
1210 problems. Closes roundup issue 20.
1224 problems. Closes roundup issue 20.
1211
1225
1212 2004-11-17 Fernando Perez <fperez@colorado.edu>
1226 2004-11-17 Fernando Perez <fperez@colorado.edu>
1213
1227
1214 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1228 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1215 reported as debian bug #280505. I'm not sure my local changelog
1229 reported as debian bug #280505. I'm not sure my local changelog
1216 entry has the proper debian format (Jack?).
1230 entry has the proper debian format (Jack?).
1217
1231
1218 2004-11-08 *** Released version 0.6.4
1232 2004-11-08 *** Released version 0.6.4
1219
1233
1220 2004-11-08 Fernando Perez <fperez@colorado.edu>
1234 2004-11-08 Fernando Perez <fperez@colorado.edu>
1221
1235
1222 * IPython/iplib.py (init_readline): Fix exit message for Windows
1236 * IPython/iplib.py (init_readline): Fix exit message for Windows
1223 when readline is active. Thanks to a report by Eric Jones
1237 when readline is active. Thanks to a report by Eric Jones
1224 <eric-AT-enthought.com>.
1238 <eric-AT-enthought.com>.
1225
1239
1226 2004-11-07 Fernando Perez <fperez@colorado.edu>
1240 2004-11-07 Fernando Perez <fperez@colorado.edu>
1227
1241
1228 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1242 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1229 sometimes seen by win2k/cygwin users.
1243 sometimes seen by win2k/cygwin users.
1230
1244
1231 2004-11-06 Fernando Perez <fperez@colorado.edu>
1245 2004-11-06 Fernando Perez <fperez@colorado.edu>
1232
1246
1233 * IPython/iplib.py (interact): Change the handling of %Exit from
1247 * IPython/iplib.py (interact): Change the handling of %Exit from
1234 trying to propagate a SystemExit to an internal ipython flag.
1248 trying to propagate a SystemExit to an internal ipython flag.
1235 This is less elegant than using Python's exception mechanism, but
1249 This is less elegant than using Python's exception mechanism, but
1236 I can't get that to work reliably with threads, so under -pylab
1250 I can't get that to work reliably with threads, so under -pylab
1237 %Exit was hanging IPython. Cross-thread exception handling is
1251 %Exit was hanging IPython. Cross-thread exception handling is
1238 really a bitch. Thaks to a bug report by Stephen Walton
1252 really a bitch. Thaks to a bug report by Stephen Walton
1239 <stephen.walton-AT-csun.edu>.
1253 <stephen.walton-AT-csun.edu>.
1240
1254
1241 2004-11-04 Fernando Perez <fperez@colorado.edu>
1255 2004-11-04 Fernando Perez <fperez@colorado.edu>
1242
1256
1243 * IPython/iplib.py (raw_input_original): store a pointer to the
1257 * IPython/iplib.py (raw_input_original): store a pointer to the
1244 true raw_input to harden against code which can modify it
1258 true raw_input to harden against code which can modify it
1245 (wx.py.PyShell does this and would otherwise crash ipython).
1259 (wx.py.PyShell does this and would otherwise crash ipython).
1246 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1260 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1247
1261
1248 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1262 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1249 Ctrl-C problem, which does not mess up the input line.
1263 Ctrl-C problem, which does not mess up the input line.
1250
1264
1251 2004-11-03 Fernando Perez <fperez@colorado.edu>
1265 2004-11-03 Fernando Perez <fperez@colorado.edu>
1252
1266
1253 * IPython/Release.py: Changed licensing to BSD, in all files.
1267 * IPython/Release.py: Changed licensing to BSD, in all files.
1254 (name): lowercase name for tarball/RPM release.
1268 (name): lowercase name for tarball/RPM release.
1255
1269
1256 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1270 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1257 use throughout ipython.
1271 use throughout ipython.
1258
1272
1259 * IPython/Magic.py (Magic._ofind): Switch to using the new
1273 * IPython/Magic.py (Magic._ofind): Switch to using the new
1260 OInspect.getdoc() function.
1274 OInspect.getdoc() function.
1261
1275
1262 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1276 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1263 of the line currently being canceled via Ctrl-C. It's extremely
1277 of the line currently being canceled via Ctrl-C. It's extremely
1264 ugly, but I don't know how to do it better (the problem is one of
1278 ugly, but I don't know how to do it better (the problem is one of
1265 handling cross-thread exceptions).
1279 handling cross-thread exceptions).
1266
1280
1267 2004-10-28 Fernando Perez <fperez@colorado.edu>
1281 2004-10-28 Fernando Perez <fperez@colorado.edu>
1268
1282
1269 * IPython/Shell.py (signal_handler): add signal handlers to trap
1283 * IPython/Shell.py (signal_handler): add signal handlers to trap
1270 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1284 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1271 report by Francesc Alted.
1285 report by Francesc Alted.
1272
1286
1273 2004-10-21 Fernando Perez <fperez@colorado.edu>
1287 2004-10-21 Fernando Perez <fperez@colorado.edu>
1274
1288
1275 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1289 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1276 to % for pysh syntax extensions.
1290 to % for pysh syntax extensions.
1277
1291
1278 2004-10-09 Fernando Perez <fperez@colorado.edu>
1292 2004-10-09 Fernando Perez <fperez@colorado.edu>
1279
1293
1280 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1294 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1281 arrays to print a more useful summary, without calling str(arr).
1295 arrays to print a more useful summary, without calling str(arr).
1282 This avoids the problem of extremely lengthy computations which
1296 This avoids the problem of extremely lengthy computations which
1283 occur if arr is large, and appear to the user as a system lockup
1297 occur if arr is large, and appear to the user as a system lockup
1284 with 100% cpu activity. After a suggestion by Kristian Sandberg
1298 with 100% cpu activity. After a suggestion by Kristian Sandberg
1285 <Kristian.Sandberg@colorado.edu>.
1299 <Kristian.Sandberg@colorado.edu>.
1286 (Magic.__init__): fix bug in global magic escapes not being
1300 (Magic.__init__): fix bug in global magic escapes not being
1287 correctly set.
1301 correctly set.
1288
1302
1289 2004-10-08 Fernando Perez <fperez@colorado.edu>
1303 2004-10-08 Fernando Perez <fperez@colorado.edu>
1290
1304
1291 * IPython/Magic.py (__license__): change to absolute imports of
1305 * IPython/Magic.py (__license__): change to absolute imports of
1292 ipython's own internal packages, to start adapting to the absolute
1306 ipython's own internal packages, to start adapting to the absolute
1293 import requirement of PEP-328.
1307 import requirement of PEP-328.
1294
1308
1295 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1309 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1296 files, and standardize author/license marks through the Release
1310 files, and standardize author/license marks through the Release
1297 module instead of having per/file stuff (except for files with
1311 module instead of having per/file stuff (except for files with
1298 particular licenses, like the MIT/PSF-licensed codes).
1312 particular licenses, like the MIT/PSF-licensed codes).
1299
1313
1300 * IPython/Debugger.py: remove dead code for python 2.1
1314 * IPython/Debugger.py: remove dead code for python 2.1
1301
1315
1302 2004-10-04 Fernando Perez <fperez@colorado.edu>
1316 2004-10-04 Fernando Perez <fperez@colorado.edu>
1303
1317
1304 * IPython/iplib.py (ipmagic): New function for accessing magics
1318 * IPython/iplib.py (ipmagic): New function for accessing magics
1305 via a normal python function call.
1319 via a normal python function call.
1306
1320
1307 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1321 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1308 from '@' to '%', to accomodate the new @decorator syntax of python
1322 from '@' to '%', to accomodate the new @decorator syntax of python
1309 2.4.
1323 2.4.
1310
1324
1311 2004-09-29 Fernando Perez <fperez@colorado.edu>
1325 2004-09-29 Fernando Perez <fperez@colorado.edu>
1312
1326
1313 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1327 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1314 matplotlib.use to prevent running scripts which try to switch
1328 matplotlib.use to prevent running scripts which try to switch
1315 interactive backends from within ipython. This will just crash
1329 interactive backends from within ipython. This will just crash
1316 the python interpreter, so we can't allow it (but a detailed error
1330 the python interpreter, so we can't allow it (but a detailed error
1317 is given to the user).
1331 is given to the user).
1318
1332
1319 2004-09-28 Fernando Perez <fperez@colorado.edu>
1333 2004-09-28 Fernando Perez <fperez@colorado.edu>
1320
1334
1321 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1335 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1322 matplotlib-related fixes so that using @run with non-matplotlib
1336 matplotlib-related fixes so that using @run with non-matplotlib
1323 scripts doesn't pop up spurious plot windows. This requires
1337 scripts doesn't pop up spurious plot windows. This requires
1324 matplotlib >= 0.63, where I had to make some changes as well.
1338 matplotlib >= 0.63, where I had to make some changes as well.
1325
1339
1326 * IPython/ipmaker.py (make_IPython): update version requirement to
1340 * IPython/ipmaker.py (make_IPython): update version requirement to
1327 python 2.2.
1341 python 2.2.
1328
1342
1329 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1343 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1330 banner arg for embedded customization.
1344 banner arg for embedded customization.
1331
1345
1332 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1346 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1333 explicit uses of __IP as the IPython's instance name. Now things
1347 explicit uses of __IP as the IPython's instance name. Now things
1334 are properly handled via the shell.name value. The actual code
1348 are properly handled via the shell.name value. The actual code
1335 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1349 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1336 is much better than before. I'll clean things completely when the
1350 is much better than before. I'll clean things completely when the
1337 magic stuff gets a real overhaul.
1351 magic stuff gets a real overhaul.
1338
1352
1339 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1353 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1340 minor changes to debian dir.
1354 minor changes to debian dir.
1341
1355
1342 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1356 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1343 pointer to the shell itself in the interactive namespace even when
1357 pointer to the shell itself in the interactive namespace even when
1344 a user-supplied dict is provided. This is needed for embedding
1358 a user-supplied dict is provided. This is needed for embedding
1345 purposes (found by tests with Michel Sanner).
1359 purposes (found by tests with Michel Sanner).
1346
1360
1347 2004-09-27 Fernando Perez <fperez@colorado.edu>
1361 2004-09-27 Fernando Perez <fperez@colorado.edu>
1348
1362
1349 * IPython/UserConfig/ipythonrc: remove []{} from
1363 * IPython/UserConfig/ipythonrc: remove []{} from
1350 readline_remove_delims, so that things like [modname.<TAB> do
1364 readline_remove_delims, so that things like [modname.<TAB> do
1351 proper completion. This disables [].TAB, but that's a less common
1365 proper completion. This disables [].TAB, but that's a less common
1352 case than module names in list comprehensions, for example.
1366 case than module names in list comprehensions, for example.
1353 Thanks to a report by Andrea Riciputi.
1367 Thanks to a report by Andrea Riciputi.
1354
1368
1355 2004-09-09 Fernando Perez <fperez@colorado.edu>
1369 2004-09-09 Fernando Perez <fperez@colorado.edu>
1356
1370
1357 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1371 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1358 blocking problems in win32 and osx. Fix by John.
1372 blocking problems in win32 and osx. Fix by John.
1359
1373
1360 2004-09-08 Fernando Perez <fperez@colorado.edu>
1374 2004-09-08 Fernando Perez <fperez@colorado.edu>
1361
1375
1362 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1376 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1363 for Win32 and OSX. Fix by John Hunter.
1377 for Win32 and OSX. Fix by John Hunter.
1364
1378
1365 2004-08-30 *** Released version 0.6.3
1379 2004-08-30 *** Released version 0.6.3
1366
1380
1367 2004-08-30 Fernando Perez <fperez@colorado.edu>
1381 2004-08-30 Fernando Perez <fperez@colorado.edu>
1368
1382
1369 * setup.py (isfile): Add manpages to list of dependent files to be
1383 * setup.py (isfile): Add manpages to list of dependent files to be
1370 updated.
1384 updated.
1371
1385
1372 2004-08-27 Fernando Perez <fperez@colorado.edu>
1386 2004-08-27 Fernando Perez <fperez@colorado.edu>
1373
1387
1374 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1388 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1375 for now. They don't really work with standalone WX/GTK code
1389 for now. They don't really work with standalone WX/GTK code
1376 (though matplotlib IS working fine with both of those backends).
1390 (though matplotlib IS working fine with both of those backends).
1377 This will neeed much more testing. I disabled most things with
1391 This will neeed much more testing. I disabled most things with
1378 comments, so turning it back on later should be pretty easy.
1392 comments, so turning it back on later should be pretty easy.
1379
1393
1380 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1394 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1381 autocalling of expressions like r'foo', by modifying the line
1395 autocalling of expressions like r'foo', by modifying the line
1382 split regexp. Closes
1396 split regexp. Closes
1383 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1397 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1384 Riley <ipythonbugs-AT-sabi.net>.
1398 Riley <ipythonbugs-AT-sabi.net>.
1385 (InteractiveShell.mainloop): honor --nobanner with banner
1399 (InteractiveShell.mainloop): honor --nobanner with banner
1386 extensions.
1400 extensions.
1387
1401
1388 * IPython/Shell.py: Significant refactoring of all classes, so
1402 * IPython/Shell.py: Significant refactoring of all classes, so
1389 that we can really support ALL matplotlib backends and threading
1403 that we can really support ALL matplotlib backends and threading
1390 models (John spotted a bug with Tk which required this). Now we
1404 models (John spotted a bug with Tk which required this). Now we
1391 should support single-threaded, WX-threads and GTK-threads, both
1405 should support single-threaded, WX-threads and GTK-threads, both
1392 for generic code and for matplotlib.
1406 for generic code and for matplotlib.
1393
1407
1394 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1408 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1395 -pylab, to simplify things for users. Will also remove the pylab
1409 -pylab, to simplify things for users. Will also remove the pylab
1396 profile, since now all of matplotlib configuration is directly
1410 profile, since now all of matplotlib configuration is directly
1397 handled here. This also reduces startup time.
1411 handled here. This also reduces startup time.
1398
1412
1399 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1413 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1400 shell wasn't being correctly called. Also in IPShellWX.
1414 shell wasn't being correctly called. Also in IPShellWX.
1401
1415
1402 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1416 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1403 fine-tune banner.
1417 fine-tune banner.
1404
1418
1405 * IPython/numutils.py (spike): Deprecate these spike functions,
1419 * IPython/numutils.py (spike): Deprecate these spike functions,
1406 delete (long deprecated) gnuplot_exec handler.
1420 delete (long deprecated) gnuplot_exec handler.
1407
1421
1408 2004-08-26 Fernando Perez <fperez@colorado.edu>
1422 2004-08-26 Fernando Perez <fperez@colorado.edu>
1409
1423
1410 * ipython.1: Update for threading options, plus some others which
1424 * ipython.1: Update for threading options, plus some others which
1411 were missing.
1425 were missing.
1412
1426
1413 * IPython/ipmaker.py (__call__): Added -wthread option for
1427 * IPython/ipmaker.py (__call__): Added -wthread option for
1414 wxpython thread handling. Make sure threading options are only
1428 wxpython thread handling. Make sure threading options are only
1415 valid at the command line.
1429 valid at the command line.
1416
1430
1417 * scripts/ipython: moved shell selection into a factory function
1431 * scripts/ipython: moved shell selection into a factory function
1418 in Shell.py, to keep the starter script to a minimum.
1432 in Shell.py, to keep the starter script to a minimum.
1419
1433
1420 2004-08-25 Fernando Perez <fperez@colorado.edu>
1434 2004-08-25 Fernando Perez <fperez@colorado.edu>
1421
1435
1422 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1436 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1423 John. Along with some recent changes he made to matplotlib, the
1437 John. Along with some recent changes he made to matplotlib, the
1424 next versions of both systems should work very well together.
1438 next versions of both systems should work very well together.
1425
1439
1426 2004-08-24 Fernando Perez <fperez@colorado.edu>
1440 2004-08-24 Fernando Perez <fperez@colorado.edu>
1427
1441
1428 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1442 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1429 tried to switch the profiling to using hotshot, but I'm getting
1443 tried to switch the profiling to using hotshot, but I'm getting
1430 strange errors from prof.runctx() there. I may be misreading the
1444 strange errors from prof.runctx() there. I may be misreading the
1431 docs, but it looks weird. For now the profiling code will
1445 docs, but it looks weird. For now the profiling code will
1432 continue to use the standard profiler.
1446 continue to use the standard profiler.
1433
1447
1434 2004-08-23 Fernando Perez <fperez@colorado.edu>
1448 2004-08-23 Fernando Perez <fperez@colorado.edu>
1435
1449
1436 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1450 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1437 threaded shell, by John Hunter. It's not quite ready yet, but
1451 threaded shell, by John Hunter. It's not quite ready yet, but
1438 close.
1452 close.
1439
1453
1440 2004-08-22 Fernando Perez <fperez@colorado.edu>
1454 2004-08-22 Fernando Perez <fperez@colorado.edu>
1441
1455
1442 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1456 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1443 in Magic and ultraTB.
1457 in Magic and ultraTB.
1444
1458
1445 * ipython.1: document threading options in manpage.
1459 * ipython.1: document threading options in manpage.
1446
1460
1447 * scripts/ipython: Changed name of -thread option to -gthread,
1461 * scripts/ipython: Changed name of -thread option to -gthread,
1448 since this is GTK specific. I want to leave the door open for a
1462 since this is GTK specific. I want to leave the door open for a
1449 -wthread option for WX, which will most likely be necessary. This
1463 -wthread option for WX, which will most likely be necessary. This
1450 change affects usage and ipmaker as well.
1464 change affects usage and ipmaker as well.
1451
1465
1452 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1466 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1453 handle the matplotlib shell issues. Code by John Hunter
1467 handle the matplotlib shell issues. Code by John Hunter
1454 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1468 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1455 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1469 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1456 broken (and disabled for end users) for now, but it puts the
1470 broken (and disabled for end users) for now, but it puts the
1457 infrastructure in place.
1471 infrastructure in place.
1458
1472
1459 2004-08-21 Fernando Perez <fperez@colorado.edu>
1473 2004-08-21 Fernando Perez <fperez@colorado.edu>
1460
1474
1461 * ipythonrc-pylab: Add matplotlib support.
1475 * ipythonrc-pylab: Add matplotlib support.
1462
1476
1463 * matplotlib_config.py: new files for matplotlib support, part of
1477 * matplotlib_config.py: new files for matplotlib support, part of
1464 the pylab profile.
1478 the pylab profile.
1465
1479
1466 * IPython/usage.py (__doc__): documented the threading options.
1480 * IPython/usage.py (__doc__): documented the threading options.
1467
1481
1468 2004-08-20 Fernando Perez <fperez@colorado.edu>
1482 2004-08-20 Fernando Perez <fperez@colorado.edu>
1469
1483
1470 * ipython: Modified the main calling routine to handle the -thread
1484 * ipython: Modified the main calling routine to handle the -thread
1471 and -mpthread options. This needs to be done as a top-level hack,
1485 and -mpthread options. This needs to be done as a top-level hack,
1472 because it determines which class to instantiate for IPython
1486 because it determines which class to instantiate for IPython
1473 itself.
1487 itself.
1474
1488
1475 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1489 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1476 classes to support multithreaded GTK operation without blocking,
1490 classes to support multithreaded GTK operation without blocking,
1477 and matplotlib with all backends. This is a lot of still very
1491 and matplotlib with all backends. This is a lot of still very
1478 experimental code, and threads are tricky. So it may still have a
1492 experimental code, and threads are tricky. So it may still have a
1479 few rough edges... This code owes a lot to
1493 few rough edges... This code owes a lot to
1480 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1494 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1481 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1495 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1482 to John Hunter for all the matplotlib work.
1496 to John Hunter for all the matplotlib work.
1483
1497
1484 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1498 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1485 options for gtk thread and matplotlib support.
1499 options for gtk thread and matplotlib support.
1486
1500
1487 2004-08-16 Fernando Perez <fperez@colorado.edu>
1501 2004-08-16 Fernando Perez <fperez@colorado.edu>
1488
1502
1489 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1503 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1490 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1504 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1491 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1505 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1492
1506
1493 2004-08-11 Fernando Perez <fperez@colorado.edu>
1507 2004-08-11 Fernando Perez <fperez@colorado.edu>
1494
1508
1495 * setup.py (isfile): Fix build so documentation gets updated for
1509 * setup.py (isfile): Fix build so documentation gets updated for
1496 rpms (it was only done for .tgz builds).
1510 rpms (it was only done for .tgz builds).
1497
1511
1498 2004-08-10 Fernando Perez <fperez@colorado.edu>
1512 2004-08-10 Fernando Perez <fperez@colorado.edu>
1499
1513
1500 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1514 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1501
1515
1502 * iplib.py : Silence syntax error exceptions in tab-completion.
1516 * iplib.py : Silence syntax error exceptions in tab-completion.
1503
1517
1504 2004-08-05 Fernando Perez <fperez@colorado.edu>
1518 2004-08-05 Fernando Perez <fperez@colorado.edu>
1505
1519
1506 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1520 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1507 'color off' mark for continuation prompts. This was causing long
1521 'color off' mark for continuation prompts. This was causing long
1508 continuation lines to mis-wrap.
1522 continuation lines to mis-wrap.
1509
1523
1510 2004-08-01 Fernando Perez <fperez@colorado.edu>
1524 2004-08-01 Fernando Perez <fperez@colorado.edu>
1511
1525
1512 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1526 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1513 for building ipython to be a parameter. All this is necessary
1527 for building ipython to be a parameter. All this is necessary
1514 right now to have a multithreaded version, but this insane
1528 right now to have a multithreaded version, but this insane
1515 non-design will be cleaned up soon. For now, it's a hack that
1529 non-design will be cleaned up soon. For now, it's a hack that
1516 works.
1530 works.
1517
1531
1518 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1532 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1519 args in various places. No bugs so far, but it's a dangerous
1533 args in various places. No bugs so far, but it's a dangerous
1520 practice.
1534 practice.
1521
1535
1522 2004-07-31 Fernando Perez <fperez@colorado.edu>
1536 2004-07-31 Fernando Perez <fperez@colorado.edu>
1523
1537
1524 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1538 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1525 fix completion of files with dots in their names under most
1539 fix completion of files with dots in their names under most
1526 profiles (pysh was OK because the completion order is different).
1540 profiles (pysh was OK because the completion order is different).
1527
1541
1528 2004-07-27 Fernando Perez <fperez@colorado.edu>
1542 2004-07-27 Fernando Perez <fperez@colorado.edu>
1529
1543
1530 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1544 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1531 keywords manually, b/c the one in keyword.py was removed in python
1545 keywords manually, b/c the one in keyword.py was removed in python
1532 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1546 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1533 This is NOT a bug under python 2.3 and earlier.
1547 This is NOT a bug under python 2.3 and earlier.
1534
1548
1535 2004-07-26 Fernando Perez <fperez@colorado.edu>
1549 2004-07-26 Fernando Perez <fperez@colorado.edu>
1536
1550
1537 * IPython/ultraTB.py (VerboseTB.text): Add another
1551 * IPython/ultraTB.py (VerboseTB.text): Add another
1538 linecache.checkcache() call to try to prevent inspect.py from
1552 linecache.checkcache() call to try to prevent inspect.py from
1539 crashing under python 2.3. I think this fixes
1553 crashing under python 2.3. I think this fixes
1540 http://www.scipy.net/roundup/ipython/issue17.
1554 http://www.scipy.net/roundup/ipython/issue17.
1541
1555
1542 2004-07-26 *** Released version 0.6.2
1556 2004-07-26 *** Released version 0.6.2
1543
1557
1544 2004-07-26 Fernando Perez <fperez@colorado.edu>
1558 2004-07-26 Fernando Perez <fperez@colorado.edu>
1545
1559
1546 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1560 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1547 fail for any number.
1561 fail for any number.
1548 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1562 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1549 empty bookmarks.
1563 empty bookmarks.
1550
1564
1551 2004-07-26 *** Released version 0.6.1
1565 2004-07-26 *** Released version 0.6.1
1552
1566
1553 2004-07-26 Fernando Perez <fperez@colorado.edu>
1567 2004-07-26 Fernando Perez <fperez@colorado.edu>
1554
1568
1555 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1569 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1556
1570
1557 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1571 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1558 escaping '()[]{}' in filenames.
1572 escaping '()[]{}' in filenames.
1559
1573
1560 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1574 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1561 Python 2.2 users who lack a proper shlex.split.
1575 Python 2.2 users who lack a proper shlex.split.
1562
1576
1563 2004-07-19 Fernando Perez <fperez@colorado.edu>
1577 2004-07-19 Fernando Perez <fperez@colorado.edu>
1564
1578
1565 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1579 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1566 for reading readline's init file. I follow the normal chain:
1580 for reading readline's init file. I follow the normal chain:
1567 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1581 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1568 report by Mike Heeter. This closes
1582 report by Mike Heeter. This closes
1569 http://www.scipy.net/roundup/ipython/issue16.
1583 http://www.scipy.net/roundup/ipython/issue16.
1570
1584
1571 2004-07-18 Fernando Perez <fperez@colorado.edu>
1585 2004-07-18 Fernando Perez <fperez@colorado.edu>
1572
1586
1573 * IPython/iplib.py (__init__): Add better handling of '\' under
1587 * IPython/iplib.py (__init__): Add better handling of '\' under
1574 Win32 for filenames. After a patch by Ville.
1588 Win32 for filenames. After a patch by Ville.
1575
1589
1576 2004-07-17 Fernando Perez <fperez@colorado.edu>
1590 2004-07-17 Fernando Perez <fperez@colorado.edu>
1577
1591
1578 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1592 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1579 autocalling would be triggered for 'foo is bar' if foo is
1593 autocalling would be triggered for 'foo is bar' if foo is
1580 callable. I also cleaned up the autocall detection code to use a
1594 callable. I also cleaned up the autocall detection code to use a
1581 regexp, which is faster. Bug reported by Alexander Schmolck.
1595 regexp, which is faster. Bug reported by Alexander Schmolck.
1582
1596
1583 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1597 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1584 '?' in them would confuse the help system. Reported by Alex
1598 '?' in them would confuse the help system. Reported by Alex
1585 Schmolck.
1599 Schmolck.
1586
1600
1587 2004-07-16 Fernando Perez <fperez@colorado.edu>
1601 2004-07-16 Fernando Perez <fperez@colorado.edu>
1588
1602
1589 * IPython/GnuplotInteractive.py (__all__): added plot2.
1603 * IPython/GnuplotInteractive.py (__all__): added plot2.
1590
1604
1591 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1605 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1592 plotting dictionaries, lists or tuples of 1d arrays.
1606 plotting dictionaries, lists or tuples of 1d arrays.
1593
1607
1594 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1608 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1595 optimizations.
1609 optimizations.
1596
1610
1597 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1611 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1598 the information which was there from Janko's original IPP code:
1612 the information which was there from Janko's original IPP code:
1599
1613
1600 03.05.99 20:53 porto.ifm.uni-kiel.de
1614 03.05.99 20:53 porto.ifm.uni-kiel.de
1601 --Started changelog.
1615 --Started changelog.
1602 --make clear do what it say it does
1616 --make clear do what it say it does
1603 --added pretty output of lines from inputcache
1617 --added pretty output of lines from inputcache
1604 --Made Logger a mixin class, simplifies handling of switches
1618 --Made Logger a mixin class, simplifies handling of switches
1605 --Added own completer class. .string<TAB> expands to last history
1619 --Added own completer class. .string<TAB> expands to last history
1606 line which starts with string. The new expansion is also present
1620 line which starts with string. The new expansion is also present
1607 with Ctrl-r from the readline library. But this shows, who this
1621 with Ctrl-r from the readline library. But this shows, who this
1608 can be done for other cases.
1622 can be done for other cases.
1609 --Added convention that all shell functions should accept a
1623 --Added convention that all shell functions should accept a
1610 parameter_string This opens the door for different behaviour for
1624 parameter_string This opens the door for different behaviour for
1611 each function. @cd is a good example of this.
1625 each function. @cd is a good example of this.
1612
1626
1613 04.05.99 12:12 porto.ifm.uni-kiel.de
1627 04.05.99 12:12 porto.ifm.uni-kiel.de
1614 --added logfile rotation
1628 --added logfile rotation
1615 --added new mainloop method which freezes first the namespace
1629 --added new mainloop method which freezes first the namespace
1616
1630
1617 07.05.99 21:24 porto.ifm.uni-kiel.de
1631 07.05.99 21:24 porto.ifm.uni-kiel.de
1618 --added the docreader classes. Now there is a help system.
1632 --added the docreader classes. Now there is a help system.
1619 -This is only a first try. Currently it's not easy to put new
1633 -This is only a first try. Currently it's not easy to put new
1620 stuff in the indices. But this is the way to go. Info would be
1634 stuff in the indices. But this is the way to go. Info would be
1621 better, but HTML is every where and not everybody has an info
1635 better, but HTML is every where and not everybody has an info
1622 system installed and it's not so easy to change html-docs to info.
1636 system installed and it's not so easy to change html-docs to info.
1623 --added global logfile option
1637 --added global logfile option
1624 --there is now a hook for object inspection method pinfo needs to
1638 --there is now a hook for object inspection method pinfo needs to
1625 be provided for this. Can be reached by two '??'.
1639 be provided for this. Can be reached by two '??'.
1626
1640
1627 08.05.99 20:51 porto.ifm.uni-kiel.de
1641 08.05.99 20:51 porto.ifm.uni-kiel.de
1628 --added a README
1642 --added a README
1629 --bug in rc file. Something has changed so functions in the rc
1643 --bug in rc file. Something has changed so functions in the rc
1630 file need to reference the shell and not self. Not clear if it's a
1644 file need to reference the shell and not self. Not clear if it's a
1631 bug or feature.
1645 bug or feature.
1632 --changed rc file for new behavior
1646 --changed rc file for new behavior
1633
1647
1634 2004-07-15 Fernando Perez <fperez@colorado.edu>
1648 2004-07-15 Fernando Perez <fperez@colorado.edu>
1635
1649
1636 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1650 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1637 cache was falling out of sync in bizarre manners when multi-line
1651 cache was falling out of sync in bizarre manners when multi-line
1638 input was present. Minor optimizations and cleanup.
1652 input was present. Minor optimizations and cleanup.
1639
1653
1640 (Logger): Remove old Changelog info for cleanup. This is the
1654 (Logger): Remove old Changelog info for cleanup. This is the
1641 information which was there from Janko's original code:
1655 information which was there from Janko's original code:
1642
1656
1643 Changes to Logger: - made the default log filename a parameter
1657 Changes to Logger: - made the default log filename a parameter
1644
1658
1645 - put a check for lines beginning with !@? in log(). Needed
1659 - put a check for lines beginning with !@? in log(). Needed
1646 (even if the handlers properly log their lines) for mid-session
1660 (even if the handlers properly log their lines) for mid-session
1647 logging activation to work properly. Without this, lines logged
1661 logging activation to work properly. Without this, lines logged
1648 in mid session, which get read from the cache, would end up
1662 in mid session, which get read from the cache, would end up
1649 'bare' (with !@? in the open) in the log. Now they are caught
1663 'bare' (with !@? in the open) in the log. Now they are caught
1650 and prepended with a #.
1664 and prepended with a #.
1651
1665
1652 * IPython/iplib.py (InteractiveShell.init_readline): added check
1666 * IPython/iplib.py (InteractiveShell.init_readline): added check
1653 in case MagicCompleter fails to be defined, so we don't crash.
1667 in case MagicCompleter fails to be defined, so we don't crash.
1654
1668
1655 2004-07-13 Fernando Perez <fperez@colorado.edu>
1669 2004-07-13 Fernando Perez <fperez@colorado.edu>
1656
1670
1657 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1671 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1658 of EPS if the requested filename ends in '.eps'.
1672 of EPS if the requested filename ends in '.eps'.
1659
1673
1660 2004-07-04 Fernando Perez <fperez@colorado.edu>
1674 2004-07-04 Fernando Perez <fperez@colorado.edu>
1661
1675
1662 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1676 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1663 escaping of quotes when calling the shell.
1677 escaping of quotes when calling the shell.
1664
1678
1665 2004-07-02 Fernando Perez <fperez@colorado.edu>
1679 2004-07-02 Fernando Perez <fperez@colorado.edu>
1666
1680
1667 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1681 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1668 gettext not working because we were clobbering '_'. Fixes
1682 gettext not working because we were clobbering '_'. Fixes
1669 http://www.scipy.net/roundup/ipython/issue6.
1683 http://www.scipy.net/roundup/ipython/issue6.
1670
1684
1671 2004-07-01 Fernando Perez <fperez@colorado.edu>
1685 2004-07-01 Fernando Perez <fperez@colorado.edu>
1672
1686
1673 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1687 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1674 into @cd. Patch by Ville.
1688 into @cd. Patch by Ville.
1675
1689
1676 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1690 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1677 new function to store things after ipmaker runs. Patch by Ville.
1691 new function to store things after ipmaker runs. Patch by Ville.
1678 Eventually this will go away once ipmaker is removed and the class
1692 Eventually this will go away once ipmaker is removed and the class
1679 gets cleaned up, but for now it's ok. Key functionality here is
1693 gets cleaned up, but for now it's ok. Key functionality here is
1680 the addition of the persistent storage mechanism, a dict for
1694 the addition of the persistent storage mechanism, a dict for
1681 keeping data across sessions (for now just bookmarks, but more can
1695 keeping data across sessions (for now just bookmarks, but more can
1682 be implemented later).
1696 be implemented later).
1683
1697
1684 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1698 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1685 persistent across sections. Patch by Ville, I modified it
1699 persistent across sections. Patch by Ville, I modified it
1686 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1700 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1687 added a '-l' option to list all bookmarks.
1701 added a '-l' option to list all bookmarks.
1688
1702
1689 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1703 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1690 center for cleanup. Registered with atexit.register(). I moved
1704 center for cleanup. Registered with atexit.register(). I moved
1691 here the old exit_cleanup(). After a patch by Ville.
1705 here the old exit_cleanup(). After a patch by Ville.
1692
1706
1693 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1707 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1694 characters in the hacked shlex_split for python 2.2.
1708 characters in the hacked shlex_split for python 2.2.
1695
1709
1696 * IPython/iplib.py (file_matches): more fixes to filenames with
1710 * IPython/iplib.py (file_matches): more fixes to filenames with
1697 whitespace in them. It's not perfect, but limitations in python's
1711 whitespace in them. It's not perfect, but limitations in python's
1698 readline make it impossible to go further.
1712 readline make it impossible to go further.
1699
1713
1700 2004-06-29 Fernando Perez <fperez@colorado.edu>
1714 2004-06-29 Fernando Perez <fperez@colorado.edu>
1701
1715
1702 * IPython/iplib.py (file_matches): escape whitespace correctly in
1716 * IPython/iplib.py (file_matches): escape whitespace correctly in
1703 filename completions. Bug reported by Ville.
1717 filename completions. Bug reported by Ville.
1704
1718
1705 2004-06-28 Fernando Perez <fperez@colorado.edu>
1719 2004-06-28 Fernando Perez <fperez@colorado.edu>
1706
1720
1707 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1721 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1708 the history file will be called 'history-PROFNAME' (or just
1722 the history file will be called 'history-PROFNAME' (or just
1709 'history' if no profile is loaded). I was getting annoyed at
1723 'history' if no profile is loaded). I was getting annoyed at
1710 getting my Numerical work history clobbered by pysh sessions.
1724 getting my Numerical work history clobbered by pysh sessions.
1711
1725
1712 * IPython/iplib.py (InteractiveShell.__init__): Internal
1726 * IPython/iplib.py (InteractiveShell.__init__): Internal
1713 getoutputerror() function so that we can honor the system_verbose
1727 getoutputerror() function so that we can honor the system_verbose
1714 flag for _all_ system calls. I also added escaping of #
1728 flag for _all_ system calls. I also added escaping of #
1715 characters here to avoid confusing Itpl.
1729 characters here to avoid confusing Itpl.
1716
1730
1717 * IPython/Magic.py (shlex_split): removed call to shell in
1731 * IPython/Magic.py (shlex_split): removed call to shell in
1718 parse_options and replaced it with shlex.split(). The annoying
1732 parse_options and replaced it with shlex.split(). The annoying
1719 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1733 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1720 to backport it from 2.3, with several frail hacks (the shlex
1734 to backport it from 2.3, with several frail hacks (the shlex
1721 module is rather limited in 2.2). Thanks to a suggestion by Ville
1735 module is rather limited in 2.2). Thanks to a suggestion by Ville
1722 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1736 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1723 problem.
1737 problem.
1724
1738
1725 (Magic.magic_system_verbose): new toggle to print the actual
1739 (Magic.magic_system_verbose): new toggle to print the actual
1726 system calls made by ipython. Mainly for debugging purposes.
1740 system calls made by ipython. Mainly for debugging purposes.
1727
1741
1728 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1742 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1729 doesn't support persistence. Reported (and fix suggested) by
1743 doesn't support persistence. Reported (and fix suggested) by
1730 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1744 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1731
1745
1732 2004-06-26 Fernando Perez <fperez@colorado.edu>
1746 2004-06-26 Fernando Perez <fperez@colorado.edu>
1733
1747
1734 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1748 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1735 continue prompts.
1749 continue prompts.
1736
1750
1737 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1751 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1738 function (basically a big docstring) and a few more things here to
1752 function (basically a big docstring) and a few more things here to
1739 speedup startup. pysh.py is now very lightweight. We want because
1753 speedup startup. pysh.py is now very lightweight. We want because
1740 it gets execfile'd, while InterpreterExec gets imported, so
1754 it gets execfile'd, while InterpreterExec gets imported, so
1741 byte-compilation saves time.
1755 byte-compilation saves time.
1742
1756
1743 2004-06-25 Fernando Perez <fperez@colorado.edu>
1757 2004-06-25 Fernando Perez <fperez@colorado.edu>
1744
1758
1745 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1759 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1746 -NUM', which was recently broken.
1760 -NUM', which was recently broken.
1747
1761
1748 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1762 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1749 in multi-line input (but not !!, which doesn't make sense there).
1763 in multi-line input (but not !!, which doesn't make sense there).
1750
1764
1751 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1765 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1752 It's just too useful, and people can turn it off in the less
1766 It's just too useful, and people can turn it off in the less
1753 common cases where it's a problem.
1767 common cases where it's a problem.
1754
1768
1755 2004-06-24 Fernando Perez <fperez@colorado.edu>
1769 2004-06-24 Fernando Perez <fperez@colorado.edu>
1756
1770
1757 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1771 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1758 special syntaxes (like alias calling) is now allied in multi-line
1772 special syntaxes (like alias calling) is now allied in multi-line
1759 input. This is still _very_ experimental, but it's necessary for
1773 input. This is still _very_ experimental, but it's necessary for
1760 efficient shell usage combining python looping syntax with system
1774 efficient shell usage combining python looping syntax with system
1761 calls. For now it's restricted to aliases, I don't think it
1775 calls. For now it's restricted to aliases, I don't think it
1762 really even makes sense to have this for magics.
1776 really even makes sense to have this for magics.
1763
1777
1764 2004-06-23 Fernando Perez <fperez@colorado.edu>
1778 2004-06-23 Fernando Perez <fperez@colorado.edu>
1765
1779
1766 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1780 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1767 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1781 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1768
1782
1769 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1783 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1770 extensions under Windows (after code sent by Gary Bishop). The
1784 extensions under Windows (after code sent by Gary Bishop). The
1771 extensions considered 'executable' are stored in IPython's rc
1785 extensions considered 'executable' are stored in IPython's rc
1772 structure as win_exec_ext.
1786 structure as win_exec_ext.
1773
1787
1774 * IPython/genutils.py (shell): new function, like system() but
1788 * IPython/genutils.py (shell): new function, like system() but
1775 without return value. Very useful for interactive shell work.
1789 without return value. Very useful for interactive shell work.
1776
1790
1777 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1791 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1778 delete aliases.
1792 delete aliases.
1779
1793
1780 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1794 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1781 sure that the alias table doesn't contain python keywords.
1795 sure that the alias table doesn't contain python keywords.
1782
1796
1783 2004-06-21 Fernando Perez <fperez@colorado.edu>
1797 2004-06-21 Fernando Perez <fperez@colorado.edu>
1784
1798
1785 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1799 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1786 non-existent items are found in $PATH. Reported by Thorsten.
1800 non-existent items are found in $PATH. Reported by Thorsten.
1787
1801
1788 2004-06-20 Fernando Perez <fperez@colorado.edu>
1802 2004-06-20 Fernando Perez <fperez@colorado.edu>
1789
1803
1790 * IPython/iplib.py (complete): modified the completer so that the
1804 * IPython/iplib.py (complete): modified the completer so that the
1791 order of priorities can be easily changed at runtime.
1805 order of priorities can be easily changed at runtime.
1792
1806
1793 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1807 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1794 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1808 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1795
1809
1796 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1810 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1797 expand Python variables prepended with $ in all system calls. The
1811 expand Python variables prepended with $ in all system calls. The
1798 same was done to InteractiveShell.handle_shell_escape. Now all
1812 same was done to InteractiveShell.handle_shell_escape. Now all
1799 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1813 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1800 expansion of python variables and expressions according to the
1814 expansion of python variables and expressions according to the
1801 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1815 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1802
1816
1803 Though PEP-215 has been rejected, a similar (but simpler) one
1817 Though PEP-215 has been rejected, a similar (but simpler) one
1804 seems like it will go into Python 2.4, PEP-292 -
1818 seems like it will go into Python 2.4, PEP-292 -
1805 http://www.python.org/peps/pep-0292.html.
1819 http://www.python.org/peps/pep-0292.html.
1806
1820
1807 I'll keep the full syntax of PEP-215, since IPython has since the
1821 I'll keep the full syntax of PEP-215, since IPython has since the
1808 start used Ka-Ping Yee's reference implementation discussed there
1822 start used Ka-Ping Yee's reference implementation discussed there
1809 (Itpl), and I actually like the powerful semantics it offers.
1823 (Itpl), and I actually like the powerful semantics it offers.
1810
1824
1811 In order to access normal shell variables, the $ has to be escaped
1825 In order to access normal shell variables, the $ has to be escaped
1812 via an extra $. For example:
1826 via an extra $. For example:
1813
1827
1814 In [7]: PATH='a python variable'
1828 In [7]: PATH='a python variable'
1815
1829
1816 In [8]: !echo $PATH
1830 In [8]: !echo $PATH
1817 a python variable
1831 a python variable
1818
1832
1819 In [9]: !echo $$PATH
1833 In [9]: !echo $$PATH
1820 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1834 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1821
1835
1822 (Magic.parse_options): escape $ so the shell doesn't evaluate
1836 (Magic.parse_options): escape $ so the shell doesn't evaluate
1823 things prematurely.
1837 things prematurely.
1824
1838
1825 * IPython/iplib.py (InteractiveShell.call_alias): added the
1839 * IPython/iplib.py (InteractiveShell.call_alias): added the
1826 ability for aliases to expand python variables via $.
1840 ability for aliases to expand python variables via $.
1827
1841
1828 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1842 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1829 system, now there's a @rehash/@rehashx pair of magics. These work
1843 system, now there's a @rehash/@rehashx pair of magics. These work
1830 like the csh rehash command, and can be invoked at any time. They
1844 like the csh rehash command, and can be invoked at any time. They
1831 build a table of aliases to everything in the user's $PATH
1845 build a table of aliases to everything in the user's $PATH
1832 (@rehash uses everything, @rehashx is slower but only adds
1846 (@rehash uses everything, @rehashx is slower but only adds
1833 executable files). With this, the pysh.py-based shell profile can
1847 executable files). With this, the pysh.py-based shell profile can
1834 now simply call rehash upon startup, and full access to all
1848 now simply call rehash upon startup, and full access to all
1835 programs in the user's path is obtained.
1849 programs in the user's path is obtained.
1836
1850
1837 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1851 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1838 functionality is now fully in place. I removed the old dynamic
1852 functionality is now fully in place. I removed the old dynamic
1839 code generation based approach, in favor of a much lighter one
1853 code generation based approach, in favor of a much lighter one
1840 based on a simple dict. The advantage is that this allows me to
1854 based on a simple dict. The advantage is that this allows me to
1841 now have thousands of aliases with negligible cost (unthinkable
1855 now have thousands of aliases with negligible cost (unthinkable
1842 with the old system).
1856 with the old system).
1843
1857
1844 2004-06-19 Fernando Perez <fperez@colorado.edu>
1858 2004-06-19 Fernando Perez <fperez@colorado.edu>
1845
1859
1846 * IPython/iplib.py (__init__): extended MagicCompleter class to
1860 * IPython/iplib.py (__init__): extended MagicCompleter class to
1847 also complete (last in priority) on user aliases.
1861 also complete (last in priority) on user aliases.
1848
1862
1849 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1863 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1850 call to eval.
1864 call to eval.
1851 (ItplNS.__init__): Added a new class which functions like Itpl,
1865 (ItplNS.__init__): Added a new class which functions like Itpl,
1852 but allows configuring the namespace for the evaluation to occur
1866 but allows configuring the namespace for the evaluation to occur
1853 in.
1867 in.
1854
1868
1855 2004-06-18 Fernando Perez <fperez@colorado.edu>
1869 2004-06-18 Fernando Perez <fperez@colorado.edu>
1856
1870
1857 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1871 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1858 better message when 'exit' or 'quit' are typed (a common newbie
1872 better message when 'exit' or 'quit' are typed (a common newbie
1859 confusion).
1873 confusion).
1860
1874
1861 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1875 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1862 check for Windows users.
1876 check for Windows users.
1863
1877
1864 * IPython/iplib.py (InteractiveShell.user_setup): removed
1878 * IPython/iplib.py (InteractiveShell.user_setup): removed
1865 disabling of colors for Windows. I'll test at runtime and issue a
1879 disabling of colors for Windows. I'll test at runtime and issue a
1866 warning if Gary's readline isn't found, as to nudge users to
1880 warning if Gary's readline isn't found, as to nudge users to
1867 download it.
1881 download it.
1868
1882
1869 2004-06-16 Fernando Perez <fperez@colorado.edu>
1883 2004-06-16 Fernando Perez <fperez@colorado.edu>
1870
1884
1871 * IPython/genutils.py (Stream.__init__): changed to print errors
1885 * IPython/genutils.py (Stream.__init__): changed to print errors
1872 to sys.stderr. I had a circular dependency here. Now it's
1886 to sys.stderr. I had a circular dependency here. Now it's
1873 possible to run ipython as IDLE's shell (consider this pre-alpha,
1887 possible to run ipython as IDLE's shell (consider this pre-alpha,
1874 since true stdout things end up in the starting terminal instead
1888 since true stdout things end up in the starting terminal instead
1875 of IDLE's out).
1889 of IDLE's out).
1876
1890
1877 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1891 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1878 users who haven't # updated their prompt_in2 definitions. Remove
1892 users who haven't # updated their prompt_in2 definitions. Remove
1879 eventually.
1893 eventually.
1880 (multiple_replace): added credit to original ASPN recipe.
1894 (multiple_replace): added credit to original ASPN recipe.
1881
1895
1882 2004-06-15 Fernando Perez <fperez@colorado.edu>
1896 2004-06-15 Fernando Perez <fperez@colorado.edu>
1883
1897
1884 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1898 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1885 list of auto-defined aliases.
1899 list of auto-defined aliases.
1886
1900
1887 2004-06-13 Fernando Perez <fperez@colorado.edu>
1901 2004-06-13 Fernando Perez <fperez@colorado.edu>
1888
1902
1889 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1903 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1890 install was really requested (so setup.py can be used for other
1904 install was really requested (so setup.py can be used for other
1891 things under Windows).
1905 things under Windows).
1892
1906
1893 2004-06-10 Fernando Perez <fperez@colorado.edu>
1907 2004-06-10 Fernando Perez <fperez@colorado.edu>
1894
1908
1895 * IPython/Logger.py (Logger.create_log): Manually remove any old
1909 * IPython/Logger.py (Logger.create_log): Manually remove any old
1896 backup, since os.remove may fail under Windows. Fixes bug
1910 backup, since os.remove may fail under Windows. Fixes bug
1897 reported by Thorsten.
1911 reported by Thorsten.
1898
1912
1899 2004-06-09 Fernando Perez <fperez@colorado.edu>
1913 2004-06-09 Fernando Perez <fperez@colorado.edu>
1900
1914
1901 * examples/example-embed.py: fixed all references to %n (replaced
1915 * examples/example-embed.py: fixed all references to %n (replaced
1902 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1916 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1903 for all examples and the manual as well.
1917 for all examples and the manual as well.
1904
1918
1905 2004-06-08 Fernando Perez <fperez@colorado.edu>
1919 2004-06-08 Fernando Perez <fperez@colorado.edu>
1906
1920
1907 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1921 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1908 alignment and color management. All 3 prompt subsystems now
1922 alignment and color management. All 3 prompt subsystems now
1909 inherit from BasePrompt.
1923 inherit from BasePrompt.
1910
1924
1911 * tools/release: updates for windows installer build and tag rpms
1925 * tools/release: updates for windows installer build and tag rpms
1912 with python version (since paths are fixed).
1926 with python version (since paths are fixed).
1913
1927
1914 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1928 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1915 which will become eventually obsolete. Also fixed the default
1929 which will become eventually obsolete. Also fixed the default
1916 prompt_in2 to use \D, so at least new users start with the correct
1930 prompt_in2 to use \D, so at least new users start with the correct
1917 defaults.
1931 defaults.
1918 WARNING: Users with existing ipythonrc files will need to apply
1932 WARNING: Users with existing ipythonrc files will need to apply
1919 this fix manually!
1933 this fix manually!
1920
1934
1921 * setup.py: make windows installer (.exe). This is finally the
1935 * setup.py: make windows installer (.exe). This is finally the
1922 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1936 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1923 which I hadn't included because it required Python 2.3 (or recent
1937 which I hadn't included because it required Python 2.3 (or recent
1924 distutils).
1938 distutils).
1925
1939
1926 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1940 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1927 usage of new '\D' escape.
1941 usage of new '\D' escape.
1928
1942
1929 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1943 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1930 lacks os.getuid())
1944 lacks os.getuid())
1931 (CachedOutput.set_colors): Added the ability to turn coloring
1945 (CachedOutput.set_colors): Added the ability to turn coloring
1932 on/off with @colors even for manually defined prompt colors. It
1946 on/off with @colors even for manually defined prompt colors. It
1933 uses a nasty global, but it works safely and via the generic color
1947 uses a nasty global, but it works safely and via the generic color
1934 handling mechanism.
1948 handling mechanism.
1935 (Prompt2.__init__): Introduced new escape '\D' for continuation
1949 (Prompt2.__init__): Introduced new escape '\D' for continuation
1936 prompts. It represents the counter ('\#') as dots.
1950 prompts. It represents the counter ('\#') as dots.
1937 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1951 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1938 need to update their ipythonrc files and replace '%n' with '\D' in
1952 need to update their ipythonrc files and replace '%n' with '\D' in
1939 their prompt_in2 settings everywhere. Sorry, but there's
1953 their prompt_in2 settings everywhere. Sorry, but there's
1940 otherwise no clean way to get all prompts to properly align. The
1954 otherwise no clean way to get all prompts to properly align. The
1941 ipythonrc shipped with IPython has been updated.
1955 ipythonrc shipped with IPython has been updated.
1942
1956
1943 2004-06-07 Fernando Perez <fperez@colorado.edu>
1957 2004-06-07 Fernando Perez <fperez@colorado.edu>
1944
1958
1945 * setup.py (isfile): Pass local_icons option to latex2html, so the
1959 * setup.py (isfile): Pass local_icons option to latex2html, so the
1946 resulting HTML file is self-contained. Thanks to
1960 resulting HTML file is self-contained. Thanks to
1947 dryice-AT-liu.com.cn for the tip.
1961 dryice-AT-liu.com.cn for the tip.
1948
1962
1949 * pysh.py: I created a new profile 'shell', which implements a
1963 * pysh.py: I created a new profile 'shell', which implements a
1950 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1964 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1951 system shell, nor will it become one anytime soon. It's mainly
1965 system shell, nor will it become one anytime soon. It's mainly
1952 meant to illustrate the use of the new flexible bash-like prompts.
1966 meant to illustrate the use of the new flexible bash-like prompts.
1953 I guess it could be used by hardy souls for true shell management,
1967 I guess it could be used by hardy souls for true shell management,
1954 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1968 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1955 profile. This uses the InterpreterExec extension provided by
1969 profile. This uses the InterpreterExec extension provided by
1956 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1970 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1957
1971
1958 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1972 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1959 auto-align itself with the length of the previous input prompt
1973 auto-align itself with the length of the previous input prompt
1960 (taking into account the invisible color escapes).
1974 (taking into account the invisible color escapes).
1961 (CachedOutput.__init__): Large restructuring of this class. Now
1975 (CachedOutput.__init__): Large restructuring of this class. Now
1962 all three prompts (primary1, primary2, output) are proper objects,
1976 all three prompts (primary1, primary2, output) are proper objects,
1963 managed by the 'parent' CachedOutput class. The code is still a
1977 managed by the 'parent' CachedOutput class. The code is still a
1964 bit hackish (all prompts share state via a pointer to the cache),
1978 bit hackish (all prompts share state via a pointer to the cache),
1965 but it's overall far cleaner than before.
1979 but it's overall far cleaner than before.
1966
1980
1967 * IPython/genutils.py (getoutputerror): modified to add verbose,
1981 * IPython/genutils.py (getoutputerror): modified to add verbose,
1968 debug and header options. This makes the interface of all getout*
1982 debug and header options. This makes the interface of all getout*
1969 functions uniform.
1983 functions uniform.
1970 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1984 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1971
1985
1972 * IPython/Magic.py (Magic.default_option): added a function to
1986 * IPython/Magic.py (Magic.default_option): added a function to
1973 allow registering default options for any magic command. This
1987 allow registering default options for any magic command. This
1974 makes it easy to have profiles which customize the magics globally
1988 makes it easy to have profiles which customize the magics globally
1975 for a certain use. The values set through this function are
1989 for a certain use. The values set through this function are
1976 picked up by the parse_options() method, which all magics should
1990 picked up by the parse_options() method, which all magics should
1977 use to parse their options.
1991 use to parse their options.
1978
1992
1979 * IPython/genutils.py (warn): modified the warnings framework to
1993 * IPython/genutils.py (warn): modified the warnings framework to
1980 use the Term I/O class. I'm trying to slowly unify all of
1994 use the Term I/O class. I'm trying to slowly unify all of
1981 IPython's I/O operations to pass through Term.
1995 IPython's I/O operations to pass through Term.
1982
1996
1983 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1997 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1984 the secondary prompt to correctly match the length of the primary
1998 the secondary prompt to correctly match the length of the primary
1985 one for any prompt. Now multi-line code will properly line up
1999 one for any prompt. Now multi-line code will properly line up
1986 even for path dependent prompts, such as the new ones available
2000 even for path dependent prompts, such as the new ones available
1987 via the prompt_specials.
2001 via the prompt_specials.
1988
2002
1989 2004-06-06 Fernando Perez <fperez@colorado.edu>
2003 2004-06-06 Fernando Perez <fperez@colorado.edu>
1990
2004
1991 * IPython/Prompts.py (prompt_specials): Added the ability to have
2005 * IPython/Prompts.py (prompt_specials): Added the ability to have
1992 bash-like special sequences in the prompts, which get
2006 bash-like special sequences in the prompts, which get
1993 automatically expanded. Things like hostname, current working
2007 automatically expanded. Things like hostname, current working
1994 directory and username are implemented already, but it's easy to
2008 directory and username are implemented already, but it's easy to
1995 add more in the future. Thanks to a patch by W.J. van der Laan
2009 add more in the future. Thanks to a patch by W.J. van der Laan
1996 <gnufnork-AT-hetdigitalegat.nl>
2010 <gnufnork-AT-hetdigitalegat.nl>
1997 (prompt_specials): Added color support for prompt strings, so
2011 (prompt_specials): Added color support for prompt strings, so
1998 users can define arbitrary color setups for their prompts.
2012 users can define arbitrary color setups for their prompts.
1999
2013
2000 2004-06-05 Fernando Perez <fperez@colorado.edu>
2014 2004-06-05 Fernando Perez <fperez@colorado.edu>
2001
2015
2002 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2016 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2003 code to load Gary Bishop's readline and configure it
2017 code to load Gary Bishop's readline and configure it
2004 automatically. Thanks to Gary for help on this.
2018 automatically. Thanks to Gary for help on this.
2005
2019
2006 2004-06-01 Fernando Perez <fperez@colorado.edu>
2020 2004-06-01 Fernando Perez <fperez@colorado.edu>
2007
2021
2008 * IPython/Logger.py (Logger.create_log): fix bug for logging
2022 * IPython/Logger.py (Logger.create_log): fix bug for logging
2009 with no filename (previous fix was incomplete).
2023 with no filename (previous fix was incomplete).
2010
2024
2011 2004-05-25 Fernando Perez <fperez@colorado.edu>
2025 2004-05-25 Fernando Perez <fperez@colorado.edu>
2012
2026
2013 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2027 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2014 parens would get passed to the shell.
2028 parens would get passed to the shell.
2015
2029
2016 2004-05-20 Fernando Perez <fperez@colorado.edu>
2030 2004-05-20 Fernando Perez <fperez@colorado.edu>
2017
2031
2018 * IPython/Magic.py (Magic.magic_prun): changed default profile
2032 * IPython/Magic.py (Magic.magic_prun): changed default profile
2019 sort order to 'time' (the more common profiling need).
2033 sort order to 'time' (the more common profiling need).
2020
2034
2021 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2035 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2022 so that source code shown is guaranteed in sync with the file on
2036 so that source code shown is guaranteed in sync with the file on
2023 disk (also changed in psource). Similar fix to the one for
2037 disk (also changed in psource). Similar fix to the one for
2024 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2038 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2025 <yann.ledu-AT-noos.fr>.
2039 <yann.ledu-AT-noos.fr>.
2026
2040
2027 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2041 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2028 with a single option would not be correctly parsed. Closes
2042 with a single option would not be correctly parsed. Closes
2029 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2043 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2030 introduced in 0.6.0 (on 2004-05-06).
2044 introduced in 0.6.0 (on 2004-05-06).
2031
2045
2032 2004-05-13 *** Released version 0.6.0
2046 2004-05-13 *** Released version 0.6.0
2033
2047
2034 2004-05-13 Fernando Perez <fperez@colorado.edu>
2048 2004-05-13 Fernando Perez <fperez@colorado.edu>
2035
2049
2036 * debian/: Added debian/ directory to CVS, so that debian support
2050 * debian/: Added debian/ directory to CVS, so that debian support
2037 is publicly accessible. The debian package is maintained by Jack
2051 is publicly accessible. The debian package is maintained by Jack
2038 Moffit <jack-AT-xiph.org>.
2052 Moffit <jack-AT-xiph.org>.
2039
2053
2040 * Documentation: included the notes about an ipython-based system
2054 * Documentation: included the notes about an ipython-based system
2041 shell (the hypothetical 'pysh') into the new_design.pdf document,
2055 shell (the hypothetical 'pysh') into the new_design.pdf document,
2042 so that these ideas get distributed to users along with the
2056 so that these ideas get distributed to users along with the
2043 official documentation.
2057 official documentation.
2044
2058
2045 2004-05-10 Fernando Perez <fperez@colorado.edu>
2059 2004-05-10 Fernando Perez <fperez@colorado.edu>
2046
2060
2047 * IPython/Logger.py (Logger.create_log): fix recently introduced
2061 * IPython/Logger.py (Logger.create_log): fix recently introduced
2048 bug (misindented line) where logstart would fail when not given an
2062 bug (misindented line) where logstart would fail when not given an
2049 explicit filename.
2063 explicit filename.
2050
2064
2051 2004-05-09 Fernando Perez <fperez@colorado.edu>
2065 2004-05-09 Fernando Perez <fperez@colorado.edu>
2052
2066
2053 * IPython/Magic.py (Magic.parse_options): skip system call when
2067 * IPython/Magic.py (Magic.parse_options): skip system call when
2054 there are no options to look for. Faster, cleaner for the common
2068 there are no options to look for. Faster, cleaner for the common
2055 case.
2069 case.
2056
2070
2057 * Documentation: many updates to the manual: describing Windows
2071 * Documentation: many updates to the manual: describing Windows
2058 support better, Gnuplot updates, credits, misc small stuff. Also
2072 support better, Gnuplot updates, credits, misc small stuff. Also
2059 updated the new_design doc a bit.
2073 updated the new_design doc a bit.
2060
2074
2061 2004-05-06 *** Released version 0.6.0.rc1
2075 2004-05-06 *** Released version 0.6.0.rc1
2062
2076
2063 2004-05-06 Fernando Perez <fperez@colorado.edu>
2077 2004-05-06 Fernando Perez <fperez@colorado.edu>
2064
2078
2065 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2079 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2066 operations to use the vastly more efficient list/''.join() method.
2080 operations to use the vastly more efficient list/''.join() method.
2067 (FormattedTB.text): Fix
2081 (FormattedTB.text): Fix
2068 http://www.scipy.net/roundup/ipython/issue12 - exception source
2082 http://www.scipy.net/roundup/ipython/issue12 - exception source
2069 extract not updated after reload. Thanks to Mike Salib
2083 extract not updated after reload. Thanks to Mike Salib
2070 <msalib-AT-mit.edu> for pinning the source of the problem.
2084 <msalib-AT-mit.edu> for pinning the source of the problem.
2071 Fortunately, the solution works inside ipython and doesn't require
2085 Fortunately, the solution works inside ipython and doesn't require
2072 any changes to python proper.
2086 any changes to python proper.
2073
2087
2074 * IPython/Magic.py (Magic.parse_options): Improved to process the
2088 * IPython/Magic.py (Magic.parse_options): Improved to process the
2075 argument list as a true shell would (by actually using the
2089 argument list as a true shell would (by actually using the
2076 underlying system shell). This way, all @magics automatically get
2090 underlying system shell). This way, all @magics automatically get
2077 shell expansion for variables. Thanks to a comment by Alex
2091 shell expansion for variables. Thanks to a comment by Alex
2078 Schmolck.
2092 Schmolck.
2079
2093
2080 2004-04-04 Fernando Perez <fperez@colorado.edu>
2094 2004-04-04 Fernando Perez <fperez@colorado.edu>
2081
2095
2082 * IPython/iplib.py (InteractiveShell.interact): Added a special
2096 * IPython/iplib.py (InteractiveShell.interact): Added a special
2083 trap for a debugger quit exception, which is basically impossible
2097 trap for a debugger quit exception, which is basically impossible
2084 to handle by normal mechanisms, given what pdb does to the stack.
2098 to handle by normal mechanisms, given what pdb does to the stack.
2085 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2099 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2086
2100
2087 2004-04-03 Fernando Perez <fperez@colorado.edu>
2101 2004-04-03 Fernando Perez <fperez@colorado.edu>
2088
2102
2089 * IPython/genutils.py (Term): Standardized the names of the Term
2103 * IPython/genutils.py (Term): Standardized the names of the Term
2090 class streams to cin/cout/cerr, following C++ naming conventions
2104 class streams to cin/cout/cerr, following C++ naming conventions
2091 (I can't use in/out/err because 'in' is not a valid attribute
2105 (I can't use in/out/err because 'in' is not a valid attribute
2092 name).
2106 name).
2093
2107
2094 * IPython/iplib.py (InteractiveShell.interact): don't increment
2108 * IPython/iplib.py (InteractiveShell.interact): don't increment
2095 the prompt if there's no user input. By Daniel 'Dang' Griffith
2109 the prompt if there's no user input. By Daniel 'Dang' Griffith
2096 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2110 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2097 Francois Pinard.
2111 Francois Pinard.
2098
2112
2099 2004-04-02 Fernando Perez <fperez@colorado.edu>
2113 2004-04-02 Fernando Perez <fperez@colorado.edu>
2100
2114
2101 * IPython/genutils.py (Stream.__init__): Modified to survive at
2115 * IPython/genutils.py (Stream.__init__): Modified to survive at
2102 least importing in contexts where stdin/out/err aren't true file
2116 least importing in contexts where stdin/out/err aren't true file
2103 objects, such as PyCrust (they lack fileno() and mode). However,
2117 objects, such as PyCrust (they lack fileno() and mode). However,
2104 the recovery facilities which rely on these things existing will
2118 the recovery facilities which rely on these things existing will
2105 not work.
2119 not work.
2106
2120
2107 2004-04-01 Fernando Perez <fperez@colorado.edu>
2121 2004-04-01 Fernando Perez <fperez@colorado.edu>
2108
2122
2109 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2123 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2110 use the new getoutputerror() function, so it properly
2124 use the new getoutputerror() function, so it properly
2111 distinguishes stdout/err.
2125 distinguishes stdout/err.
2112
2126
2113 * IPython/genutils.py (getoutputerror): added a function to
2127 * IPython/genutils.py (getoutputerror): added a function to
2114 capture separately the standard output and error of a command.
2128 capture separately the standard output and error of a command.
2115 After a comment from dang on the mailing lists. This code is
2129 After a comment from dang on the mailing lists. This code is
2116 basically a modified version of commands.getstatusoutput(), from
2130 basically a modified version of commands.getstatusoutput(), from
2117 the standard library.
2131 the standard library.
2118
2132
2119 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2133 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2120 '!!' as a special syntax (shorthand) to access @sx.
2134 '!!' as a special syntax (shorthand) to access @sx.
2121
2135
2122 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2136 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2123 command and return its output as a list split on '\n'.
2137 command and return its output as a list split on '\n'.
2124
2138
2125 2004-03-31 Fernando Perez <fperez@colorado.edu>
2139 2004-03-31 Fernando Perez <fperez@colorado.edu>
2126
2140
2127 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2141 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2128 method to dictionaries used as FakeModule instances if they lack
2142 method to dictionaries used as FakeModule instances if they lack
2129 it. At least pydoc in python2.3 breaks for runtime-defined
2143 it. At least pydoc in python2.3 breaks for runtime-defined
2130 functions without this hack. At some point I need to _really_
2144 functions without this hack. At some point I need to _really_
2131 understand what FakeModule is doing, because it's a gross hack.
2145 understand what FakeModule is doing, because it's a gross hack.
2132 But it solves Arnd's problem for now...
2146 But it solves Arnd's problem for now...
2133
2147
2134 2004-02-27 Fernando Perez <fperez@colorado.edu>
2148 2004-02-27 Fernando Perez <fperez@colorado.edu>
2135
2149
2136 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2150 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2137 mode would behave erratically. Also increased the number of
2151 mode would behave erratically. Also increased the number of
2138 possible logs in rotate mod to 999. Thanks to Rod Holland
2152 possible logs in rotate mod to 999. Thanks to Rod Holland
2139 <rhh@StructureLABS.com> for the report and fixes.
2153 <rhh@StructureLABS.com> for the report and fixes.
2140
2154
2141 2004-02-26 Fernando Perez <fperez@colorado.edu>
2155 2004-02-26 Fernando Perez <fperez@colorado.edu>
2142
2156
2143 * IPython/genutils.py (page): Check that the curses module really
2157 * IPython/genutils.py (page): Check that the curses module really
2144 has the initscr attribute before trying to use it. For some
2158 has the initscr attribute before trying to use it. For some
2145 reason, the Solaris curses module is missing this. I think this
2159 reason, the Solaris curses module is missing this. I think this
2146 should be considered a Solaris python bug, but I'm not sure.
2160 should be considered a Solaris python bug, but I'm not sure.
2147
2161
2148 2004-01-17 Fernando Perez <fperez@colorado.edu>
2162 2004-01-17 Fernando Perez <fperez@colorado.edu>
2149
2163
2150 * IPython/genutils.py (Stream.__init__): Changes to try to make
2164 * IPython/genutils.py (Stream.__init__): Changes to try to make
2151 ipython robust against stdin/out/err being closed by the user.
2165 ipython robust against stdin/out/err being closed by the user.
2152 This is 'user error' (and blocks a normal python session, at least
2166 This is 'user error' (and blocks a normal python session, at least
2153 the stdout case). However, Ipython should be able to survive such
2167 the stdout case). However, Ipython should be able to survive such
2154 instances of abuse as gracefully as possible. To simplify the
2168 instances of abuse as gracefully as possible. To simplify the
2155 coding and maintain compatibility with Gary Bishop's Term
2169 coding and maintain compatibility with Gary Bishop's Term
2156 contributions, I've made use of classmethods for this. I think
2170 contributions, I've made use of classmethods for this. I think
2157 this introduces a dependency on python 2.2.
2171 this introduces a dependency on python 2.2.
2158
2172
2159 2004-01-13 Fernando Perez <fperez@colorado.edu>
2173 2004-01-13 Fernando Perez <fperez@colorado.edu>
2160
2174
2161 * IPython/numutils.py (exp_safe): simplified the code a bit and
2175 * IPython/numutils.py (exp_safe): simplified the code a bit and
2162 removed the need for importing the kinds module altogether.
2176 removed the need for importing the kinds module altogether.
2163
2177
2164 2004-01-06 Fernando Perez <fperez@colorado.edu>
2178 2004-01-06 Fernando Perez <fperez@colorado.edu>
2165
2179
2166 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2180 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2167 a magic function instead, after some community feedback. No
2181 a magic function instead, after some community feedback. No
2168 special syntax will exist for it, but its name is deliberately
2182 special syntax will exist for it, but its name is deliberately
2169 very short.
2183 very short.
2170
2184
2171 2003-12-20 Fernando Perez <fperez@colorado.edu>
2185 2003-12-20 Fernando Perez <fperez@colorado.edu>
2172
2186
2173 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2187 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2174 new functionality, to automagically assign the result of a shell
2188 new functionality, to automagically assign the result of a shell
2175 command to a variable. I'll solicit some community feedback on
2189 command to a variable. I'll solicit some community feedback on
2176 this before making it permanent.
2190 this before making it permanent.
2177
2191
2178 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2192 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2179 requested about callables for which inspect couldn't obtain a
2193 requested about callables for which inspect couldn't obtain a
2180 proper argspec. Thanks to a crash report sent by Etienne
2194 proper argspec. Thanks to a crash report sent by Etienne
2181 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2195 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2182
2196
2183 2003-12-09 Fernando Perez <fperez@colorado.edu>
2197 2003-12-09 Fernando Perez <fperez@colorado.edu>
2184
2198
2185 * IPython/genutils.py (page): patch for the pager to work across
2199 * IPython/genutils.py (page): patch for the pager to work across
2186 various versions of Windows. By Gary Bishop.
2200 various versions of Windows. By Gary Bishop.
2187
2201
2188 2003-12-04 Fernando Perez <fperez@colorado.edu>
2202 2003-12-04 Fernando Perez <fperez@colorado.edu>
2189
2203
2190 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2204 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2191 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2205 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2192 While I tested this and it looks ok, there may still be corner
2206 While I tested this and it looks ok, there may still be corner
2193 cases I've missed.
2207 cases I've missed.
2194
2208
2195 2003-12-01 Fernando Perez <fperez@colorado.edu>
2209 2003-12-01 Fernando Perez <fperez@colorado.edu>
2196
2210
2197 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2211 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2198 where a line like 'p,q=1,2' would fail because the automagic
2212 where a line like 'p,q=1,2' would fail because the automagic
2199 system would be triggered for @p.
2213 system would be triggered for @p.
2200
2214
2201 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2215 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2202 cleanups, code unmodified.
2216 cleanups, code unmodified.
2203
2217
2204 * IPython/genutils.py (Term): added a class for IPython to handle
2218 * IPython/genutils.py (Term): added a class for IPython to handle
2205 output. In most cases it will just be a proxy for stdout/err, but
2219 output. In most cases it will just be a proxy for stdout/err, but
2206 having this allows modifications to be made for some platforms,
2220 having this allows modifications to be made for some platforms,
2207 such as handling color escapes under Windows. All of this code
2221 such as handling color escapes under Windows. All of this code
2208 was contributed by Gary Bishop, with minor modifications by me.
2222 was contributed by Gary Bishop, with minor modifications by me.
2209 The actual changes affect many files.
2223 The actual changes affect many files.
2210
2224
2211 2003-11-30 Fernando Perez <fperez@colorado.edu>
2225 2003-11-30 Fernando Perez <fperez@colorado.edu>
2212
2226
2213 * IPython/iplib.py (file_matches): new completion code, courtesy
2227 * IPython/iplib.py (file_matches): new completion code, courtesy
2214 of Jeff Collins. This enables filename completion again under
2228 of Jeff Collins. This enables filename completion again under
2215 python 2.3, which disabled it at the C level.
2229 python 2.3, which disabled it at the C level.
2216
2230
2217 2003-11-11 Fernando Perez <fperez@colorado.edu>
2231 2003-11-11 Fernando Perez <fperez@colorado.edu>
2218
2232
2219 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2233 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2220 for Numeric.array(map(...)), but often convenient.
2234 for Numeric.array(map(...)), but often convenient.
2221
2235
2222 2003-11-05 Fernando Perez <fperez@colorado.edu>
2236 2003-11-05 Fernando Perez <fperez@colorado.edu>
2223
2237
2224 * IPython/numutils.py (frange): Changed a call from int() to
2238 * IPython/numutils.py (frange): Changed a call from int() to
2225 int(round()) to prevent a problem reported with arange() in the
2239 int(round()) to prevent a problem reported with arange() in the
2226 numpy list.
2240 numpy list.
2227
2241
2228 2003-10-06 Fernando Perez <fperez@colorado.edu>
2242 2003-10-06 Fernando Perez <fperez@colorado.edu>
2229
2243
2230 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2244 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2231 prevent crashes if sys lacks an argv attribute (it happens with
2245 prevent crashes if sys lacks an argv attribute (it happens with
2232 embedded interpreters which build a bare-bones sys module).
2246 embedded interpreters which build a bare-bones sys module).
2233 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2247 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2234
2248
2235 2003-09-24 Fernando Perez <fperez@colorado.edu>
2249 2003-09-24 Fernando Perez <fperez@colorado.edu>
2236
2250
2237 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2251 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2238 to protect against poorly written user objects where __getattr__
2252 to protect against poorly written user objects where __getattr__
2239 raises exceptions other than AttributeError. Thanks to a bug
2253 raises exceptions other than AttributeError. Thanks to a bug
2240 report by Oliver Sander <osander-AT-gmx.de>.
2254 report by Oliver Sander <osander-AT-gmx.de>.
2241
2255
2242 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2256 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2243 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2257 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2244
2258
2245 2003-09-09 Fernando Perez <fperez@colorado.edu>
2259 2003-09-09 Fernando Perez <fperez@colorado.edu>
2246
2260
2247 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2261 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2248 unpacking a list whith a callable as first element would
2262 unpacking a list whith a callable as first element would
2249 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2263 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2250 Collins.
2264 Collins.
2251
2265
2252 2003-08-25 *** Released version 0.5.0
2266 2003-08-25 *** Released version 0.5.0
2253
2267
2254 2003-08-22 Fernando Perez <fperez@colorado.edu>
2268 2003-08-22 Fernando Perez <fperez@colorado.edu>
2255
2269
2256 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2270 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2257 improperly defined user exceptions. Thanks to feedback from Mark
2271 improperly defined user exceptions. Thanks to feedback from Mark
2258 Russell <mrussell-AT-verio.net>.
2272 Russell <mrussell-AT-verio.net>.
2259
2273
2260 2003-08-20 Fernando Perez <fperez@colorado.edu>
2274 2003-08-20 Fernando Perez <fperez@colorado.edu>
2261
2275
2262 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2276 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2263 printing so that it would print multi-line string forms starting
2277 printing so that it would print multi-line string forms starting
2264 with a new line. This way the formatting is better respected for
2278 with a new line. This way the formatting is better respected for
2265 objects which work hard to make nice string forms.
2279 objects which work hard to make nice string forms.
2266
2280
2267 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2281 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2268 autocall would overtake data access for objects with both
2282 autocall would overtake data access for objects with both
2269 __getitem__ and __call__.
2283 __getitem__ and __call__.
2270
2284
2271 2003-08-19 *** Released version 0.5.0-rc1
2285 2003-08-19 *** Released version 0.5.0-rc1
2272
2286
2273 2003-08-19 Fernando Perez <fperez@colorado.edu>
2287 2003-08-19 Fernando Perez <fperez@colorado.edu>
2274
2288
2275 * IPython/deep_reload.py (load_tail): single tiny change here
2289 * IPython/deep_reload.py (load_tail): single tiny change here
2276 seems to fix the long-standing bug of dreload() failing to work
2290 seems to fix the long-standing bug of dreload() failing to work
2277 for dotted names. But this module is pretty tricky, so I may have
2291 for dotted names. But this module is pretty tricky, so I may have
2278 missed some subtlety. Needs more testing!.
2292 missed some subtlety. Needs more testing!.
2279
2293
2280 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2294 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2281 exceptions which have badly implemented __str__ methods.
2295 exceptions which have badly implemented __str__ methods.
2282 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2296 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2283 which I've been getting reports about from Python 2.3 users. I
2297 which I've been getting reports about from Python 2.3 users. I
2284 wish I had a simple test case to reproduce the problem, so I could
2298 wish I had a simple test case to reproduce the problem, so I could
2285 either write a cleaner workaround or file a bug report if
2299 either write a cleaner workaround or file a bug report if
2286 necessary.
2300 necessary.
2287
2301
2288 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2302 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2289 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2303 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2290 a bug report by Tjabo Kloppenburg.
2304 a bug report by Tjabo Kloppenburg.
2291
2305
2292 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2306 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2293 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2307 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2294 seems rather unstable. Thanks to a bug report by Tjabo
2308 seems rather unstable. Thanks to a bug report by Tjabo
2295 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2309 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2296
2310
2297 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2311 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2298 this out soon because of the critical fixes in the inner loop for
2312 this out soon because of the critical fixes in the inner loop for
2299 generators.
2313 generators.
2300
2314
2301 * IPython/Magic.py (Magic.getargspec): removed. This (and
2315 * IPython/Magic.py (Magic.getargspec): removed. This (and
2302 _get_def) have been obsoleted by OInspect for a long time, I
2316 _get_def) have been obsoleted by OInspect for a long time, I
2303 hadn't noticed that they were dead code.
2317 hadn't noticed that they were dead code.
2304 (Magic._ofind): restored _ofind functionality for a few literals
2318 (Magic._ofind): restored _ofind functionality for a few literals
2305 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2319 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2306 for things like "hello".capitalize?, since that would require a
2320 for things like "hello".capitalize?, since that would require a
2307 potentially dangerous eval() again.
2321 potentially dangerous eval() again.
2308
2322
2309 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2323 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2310 logic a bit more to clean up the escapes handling and minimize the
2324 logic a bit more to clean up the escapes handling and minimize the
2311 use of _ofind to only necessary cases. The interactive 'feel' of
2325 use of _ofind to only necessary cases. The interactive 'feel' of
2312 IPython should have improved quite a bit with the changes in
2326 IPython should have improved quite a bit with the changes in
2313 _prefilter and _ofind (besides being far safer than before).
2327 _prefilter and _ofind (besides being far safer than before).
2314
2328
2315 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2329 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2316 obscure, never reported). Edit would fail to find the object to
2330 obscure, never reported). Edit would fail to find the object to
2317 edit under some circumstances.
2331 edit under some circumstances.
2318 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2332 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2319 which were causing double-calling of generators. Those eval calls
2333 which were causing double-calling of generators. Those eval calls
2320 were _very_ dangerous, since code with side effects could be
2334 were _very_ dangerous, since code with side effects could be
2321 triggered. As they say, 'eval is evil'... These were the
2335 triggered. As they say, 'eval is evil'... These were the
2322 nastiest evals in IPython. Besides, _ofind is now far simpler,
2336 nastiest evals in IPython. Besides, _ofind is now far simpler,
2323 and it should also be quite a bit faster. Its use of inspect is
2337 and it should also be quite a bit faster. Its use of inspect is
2324 also safer, so perhaps some of the inspect-related crashes I've
2338 also safer, so perhaps some of the inspect-related crashes I've
2325 seen lately with Python 2.3 might be taken care of. That will
2339 seen lately with Python 2.3 might be taken care of. That will
2326 need more testing.
2340 need more testing.
2327
2341
2328 2003-08-17 Fernando Perez <fperez@colorado.edu>
2342 2003-08-17 Fernando Perez <fperez@colorado.edu>
2329
2343
2330 * IPython/iplib.py (InteractiveShell._prefilter): significant
2344 * IPython/iplib.py (InteractiveShell._prefilter): significant
2331 simplifications to the logic for handling user escapes. Faster
2345 simplifications to the logic for handling user escapes. Faster
2332 and simpler code.
2346 and simpler code.
2333
2347
2334 2003-08-14 Fernando Perez <fperez@colorado.edu>
2348 2003-08-14 Fernando Perez <fperez@colorado.edu>
2335
2349
2336 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2350 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2337 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2351 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2338 but it should be quite a bit faster. And the recursive version
2352 but it should be quite a bit faster. And the recursive version
2339 generated O(log N) intermediate storage for all rank>1 arrays,
2353 generated O(log N) intermediate storage for all rank>1 arrays,
2340 even if they were contiguous.
2354 even if they were contiguous.
2341 (l1norm): Added this function.
2355 (l1norm): Added this function.
2342 (norm): Added this function for arbitrary norms (including
2356 (norm): Added this function for arbitrary norms (including
2343 l-infinity). l1 and l2 are still special cases for convenience
2357 l-infinity). l1 and l2 are still special cases for convenience
2344 and speed.
2358 and speed.
2345
2359
2346 2003-08-03 Fernando Perez <fperez@colorado.edu>
2360 2003-08-03 Fernando Perez <fperez@colorado.edu>
2347
2361
2348 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2362 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2349 exceptions, which now raise PendingDeprecationWarnings in Python
2363 exceptions, which now raise PendingDeprecationWarnings in Python
2350 2.3. There were some in Magic and some in Gnuplot2.
2364 2.3. There were some in Magic and some in Gnuplot2.
2351
2365
2352 2003-06-30 Fernando Perez <fperez@colorado.edu>
2366 2003-06-30 Fernando Perez <fperez@colorado.edu>
2353
2367
2354 * IPython/genutils.py (page): modified to call curses only for
2368 * IPython/genutils.py (page): modified to call curses only for
2355 terminals where TERM=='xterm'. After problems under many other
2369 terminals where TERM=='xterm'. After problems under many other
2356 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2370 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2357
2371
2358 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2372 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2359 would be triggered when readline was absent. This was just an old
2373 would be triggered when readline was absent. This was just an old
2360 debugging statement I'd forgotten to take out.
2374 debugging statement I'd forgotten to take out.
2361
2375
2362 2003-06-20 Fernando Perez <fperez@colorado.edu>
2376 2003-06-20 Fernando Perez <fperez@colorado.edu>
2363
2377
2364 * IPython/genutils.py (clock): modified to return only user time
2378 * IPython/genutils.py (clock): modified to return only user time
2365 (not counting system time), after a discussion on scipy. While
2379 (not counting system time), after a discussion on scipy. While
2366 system time may be a useful quantity occasionally, it may much
2380 system time may be a useful quantity occasionally, it may much
2367 more easily be skewed by occasional swapping or other similar
2381 more easily be skewed by occasional swapping or other similar
2368 activity.
2382 activity.
2369
2383
2370 2003-06-05 Fernando Perez <fperez@colorado.edu>
2384 2003-06-05 Fernando Perez <fperez@colorado.edu>
2371
2385
2372 * IPython/numutils.py (identity): new function, for building
2386 * IPython/numutils.py (identity): new function, for building
2373 arbitrary rank Kronecker deltas (mostly backwards compatible with
2387 arbitrary rank Kronecker deltas (mostly backwards compatible with
2374 Numeric.identity)
2388 Numeric.identity)
2375
2389
2376 2003-06-03 Fernando Perez <fperez@colorado.edu>
2390 2003-06-03 Fernando Perez <fperez@colorado.edu>
2377
2391
2378 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2392 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2379 arguments passed to magics with spaces, to allow trailing '\' to
2393 arguments passed to magics with spaces, to allow trailing '\' to
2380 work normally (mainly for Windows users).
2394 work normally (mainly for Windows users).
2381
2395
2382 2003-05-29 Fernando Perez <fperez@colorado.edu>
2396 2003-05-29 Fernando Perez <fperez@colorado.edu>
2383
2397
2384 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2398 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2385 instead of pydoc.help. This fixes a bizarre behavior where
2399 instead of pydoc.help. This fixes a bizarre behavior where
2386 printing '%s' % locals() would trigger the help system. Now
2400 printing '%s' % locals() would trigger the help system. Now
2387 ipython behaves like normal python does.
2401 ipython behaves like normal python does.
2388
2402
2389 Note that if one does 'from pydoc import help', the bizarre
2403 Note that if one does 'from pydoc import help', the bizarre
2390 behavior returns, but this will also happen in normal python, so
2404 behavior returns, but this will also happen in normal python, so
2391 it's not an ipython bug anymore (it has to do with how pydoc.help
2405 it's not an ipython bug anymore (it has to do with how pydoc.help
2392 is implemented).
2406 is implemented).
2393
2407
2394 2003-05-22 Fernando Perez <fperez@colorado.edu>
2408 2003-05-22 Fernando Perez <fperez@colorado.edu>
2395
2409
2396 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2410 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2397 return [] instead of None when nothing matches, also match to end
2411 return [] instead of None when nothing matches, also match to end
2398 of line. Patch by Gary Bishop.
2412 of line. Patch by Gary Bishop.
2399
2413
2400 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2414 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2401 protection as before, for files passed on the command line. This
2415 protection as before, for files passed on the command line. This
2402 prevents the CrashHandler from kicking in if user files call into
2416 prevents the CrashHandler from kicking in if user files call into
2403 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2417 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2404 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2418 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2405
2419
2406 2003-05-20 *** Released version 0.4.0
2420 2003-05-20 *** Released version 0.4.0
2407
2421
2408 2003-05-20 Fernando Perez <fperez@colorado.edu>
2422 2003-05-20 Fernando Perez <fperez@colorado.edu>
2409
2423
2410 * setup.py: added support for manpages. It's a bit hackish b/c of
2424 * setup.py: added support for manpages. It's a bit hackish b/c of
2411 a bug in the way the bdist_rpm distutils target handles gzipped
2425 a bug in the way the bdist_rpm distutils target handles gzipped
2412 manpages, but it works. After a patch by Jack.
2426 manpages, but it works. After a patch by Jack.
2413
2427
2414 2003-05-19 Fernando Perez <fperez@colorado.edu>
2428 2003-05-19 Fernando Perez <fperez@colorado.edu>
2415
2429
2416 * IPython/numutils.py: added a mockup of the kinds module, since
2430 * IPython/numutils.py: added a mockup of the kinds module, since
2417 it was recently removed from Numeric. This way, numutils will
2431 it was recently removed from Numeric. This way, numutils will
2418 work for all users even if they are missing kinds.
2432 work for all users even if they are missing kinds.
2419
2433
2420 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2434 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2421 failure, which can occur with SWIG-wrapped extensions. After a
2435 failure, which can occur with SWIG-wrapped extensions. After a
2422 crash report from Prabhu.
2436 crash report from Prabhu.
2423
2437
2424 2003-05-16 Fernando Perez <fperez@colorado.edu>
2438 2003-05-16 Fernando Perez <fperez@colorado.edu>
2425
2439
2426 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2440 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2427 protect ipython from user code which may call directly
2441 protect ipython from user code which may call directly
2428 sys.excepthook (this looks like an ipython crash to the user, even
2442 sys.excepthook (this looks like an ipython crash to the user, even
2429 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2443 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2430 This is especially important to help users of WxWindows, but may
2444 This is especially important to help users of WxWindows, but may
2431 also be useful in other cases.
2445 also be useful in other cases.
2432
2446
2433 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2447 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2434 an optional tb_offset to be specified, and to preserve exception
2448 an optional tb_offset to be specified, and to preserve exception
2435 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2449 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2436
2450
2437 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2451 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2438
2452
2439 2003-05-15 Fernando Perez <fperez@colorado.edu>
2453 2003-05-15 Fernando Perez <fperez@colorado.edu>
2440
2454
2441 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2455 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2442 installing for a new user under Windows.
2456 installing for a new user under Windows.
2443
2457
2444 2003-05-12 Fernando Perez <fperez@colorado.edu>
2458 2003-05-12 Fernando Perez <fperez@colorado.edu>
2445
2459
2446 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2460 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2447 handler for Emacs comint-based lines. Currently it doesn't do
2461 handler for Emacs comint-based lines. Currently it doesn't do
2448 much (but importantly, it doesn't update the history cache). In
2462 much (but importantly, it doesn't update the history cache). In
2449 the future it may be expanded if Alex needs more functionality
2463 the future it may be expanded if Alex needs more functionality
2450 there.
2464 there.
2451
2465
2452 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2466 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2453 info to crash reports.
2467 info to crash reports.
2454
2468
2455 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2469 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2456 just like Python's -c. Also fixed crash with invalid -color
2470 just like Python's -c. Also fixed crash with invalid -color
2457 option value at startup. Thanks to Will French
2471 option value at startup. Thanks to Will French
2458 <wfrench-AT-bestweb.net> for the bug report.
2472 <wfrench-AT-bestweb.net> for the bug report.
2459
2473
2460 2003-05-09 Fernando Perez <fperez@colorado.edu>
2474 2003-05-09 Fernando Perez <fperez@colorado.edu>
2461
2475
2462 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2476 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2463 to EvalDict (it's a mapping, after all) and simplified its code
2477 to EvalDict (it's a mapping, after all) and simplified its code
2464 quite a bit, after a nice discussion on c.l.py where Gustavo
2478 quite a bit, after a nice discussion on c.l.py where Gustavo
2465 Córdova <gcordova-AT-sismex.com> suggested the new version.
2479 Córdova <gcordova-AT-sismex.com> suggested the new version.
2466
2480
2467 2003-04-30 Fernando Perez <fperez@colorado.edu>
2481 2003-04-30 Fernando Perez <fperez@colorado.edu>
2468
2482
2469 * IPython/genutils.py (timings_out): modified it to reduce its
2483 * IPython/genutils.py (timings_out): modified it to reduce its
2470 overhead in the common reps==1 case.
2484 overhead in the common reps==1 case.
2471
2485
2472 2003-04-29 Fernando Perez <fperez@colorado.edu>
2486 2003-04-29 Fernando Perez <fperez@colorado.edu>
2473
2487
2474 * IPython/genutils.py (timings_out): Modified to use the resource
2488 * IPython/genutils.py (timings_out): Modified to use the resource
2475 module, which avoids the wraparound problems of time.clock().
2489 module, which avoids the wraparound problems of time.clock().
2476
2490
2477 2003-04-17 *** Released version 0.2.15pre4
2491 2003-04-17 *** Released version 0.2.15pre4
2478
2492
2479 2003-04-17 Fernando Perez <fperez@colorado.edu>
2493 2003-04-17 Fernando Perez <fperez@colorado.edu>
2480
2494
2481 * setup.py (scriptfiles): Split windows-specific stuff over to a
2495 * setup.py (scriptfiles): Split windows-specific stuff over to a
2482 separate file, in an attempt to have a Windows GUI installer.
2496 separate file, in an attempt to have a Windows GUI installer.
2483 That didn't work, but part of the groundwork is done.
2497 That didn't work, but part of the groundwork is done.
2484
2498
2485 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2499 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2486 indent/unindent with 4 spaces. Particularly useful in combination
2500 indent/unindent with 4 spaces. Particularly useful in combination
2487 with the new auto-indent option.
2501 with the new auto-indent option.
2488
2502
2489 2003-04-16 Fernando Perez <fperez@colorado.edu>
2503 2003-04-16 Fernando Perez <fperez@colorado.edu>
2490
2504
2491 * IPython/Magic.py: various replacements of self.rc for
2505 * IPython/Magic.py: various replacements of self.rc for
2492 self.shell.rc. A lot more remains to be done to fully disentangle
2506 self.shell.rc. A lot more remains to be done to fully disentangle
2493 this class from the main Shell class.
2507 this class from the main Shell class.
2494
2508
2495 * IPython/GnuplotRuntime.py: added checks for mouse support so
2509 * IPython/GnuplotRuntime.py: added checks for mouse support so
2496 that we don't try to enable it if the current gnuplot doesn't
2510 that we don't try to enable it if the current gnuplot doesn't
2497 really support it. Also added checks so that we don't try to
2511 really support it. Also added checks so that we don't try to
2498 enable persist under Windows (where Gnuplot doesn't recognize the
2512 enable persist under Windows (where Gnuplot doesn't recognize the
2499 option).
2513 option).
2500
2514
2501 * IPython/iplib.py (InteractiveShell.interact): Added optional
2515 * IPython/iplib.py (InteractiveShell.interact): Added optional
2502 auto-indenting code, after a patch by King C. Shu
2516 auto-indenting code, after a patch by King C. Shu
2503 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2517 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2504 get along well with pasting indented code. If I ever figure out
2518 get along well with pasting indented code. If I ever figure out
2505 how to make that part go well, it will become on by default.
2519 how to make that part go well, it will become on by default.
2506
2520
2507 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2521 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2508 crash ipython if there was an unmatched '%' in the user's prompt
2522 crash ipython if there was an unmatched '%' in the user's prompt
2509 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2523 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2510
2524
2511 * IPython/iplib.py (InteractiveShell.interact): removed the
2525 * IPython/iplib.py (InteractiveShell.interact): removed the
2512 ability to ask the user whether he wants to crash or not at the
2526 ability to ask the user whether he wants to crash or not at the
2513 'last line' exception handler. Calling functions at that point
2527 'last line' exception handler. Calling functions at that point
2514 changes the stack, and the error reports would have incorrect
2528 changes the stack, and the error reports would have incorrect
2515 tracebacks.
2529 tracebacks.
2516
2530
2517 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2531 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2518 pass through a peger a pretty-printed form of any object. After a
2532 pass through a peger a pretty-printed form of any object. After a
2519 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2533 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2520
2534
2521 2003-04-14 Fernando Perez <fperez@colorado.edu>
2535 2003-04-14 Fernando Perez <fperez@colorado.edu>
2522
2536
2523 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2537 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2524 all files in ~ would be modified at first install (instead of
2538 all files in ~ would be modified at first install (instead of
2525 ~/.ipython). This could be potentially disastrous, as the
2539 ~/.ipython). This could be potentially disastrous, as the
2526 modification (make line-endings native) could damage binary files.
2540 modification (make line-endings native) could damage binary files.
2527
2541
2528 2003-04-10 Fernando Perez <fperez@colorado.edu>
2542 2003-04-10 Fernando Perez <fperez@colorado.edu>
2529
2543
2530 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2544 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2531 handle only lines which are invalid python. This now means that
2545 handle only lines which are invalid python. This now means that
2532 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2546 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2533 for the bug report.
2547 for the bug report.
2534
2548
2535 2003-04-01 Fernando Perez <fperez@colorado.edu>
2549 2003-04-01 Fernando Perez <fperez@colorado.edu>
2536
2550
2537 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2551 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2538 where failing to set sys.last_traceback would crash pdb.pm().
2552 where failing to set sys.last_traceback would crash pdb.pm().
2539 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2553 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2540 report.
2554 report.
2541
2555
2542 2003-03-25 Fernando Perez <fperez@colorado.edu>
2556 2003-03-25 Fernando Perez <fperez@colorado.edu>
2543
2557
2544 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2558 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2545 before printing it (it had a lot of spurious blank lines at the
2559 before printing it (it had a lot of spurious blank lines at the
2546 end).
2560 end).
2547
2561
2548 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2562 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2549 output would be sent 21 times! Obviously people don't use this
2563 output would be sent 21 times! Obviously people don't use this
2550 too often, or I would have heard about it.
2564 too often, or I would have heard about it.
2551
2565
2552 2003-03-24 Fernando Perez <fperez@colorado.edu>
2566 2003-03-24 Fernando Perez <fperez@colorado.edu>
2553
2567
2554 * setup.py (scriptfiles): renamed the data_files parameter from
2568 * setup.py (scriptfiles): renamed the data_files parameter from
2555 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2569 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2556 for the patch.
2570 for the patch.
2557
2571
2558 2003-03-20 Fernando Perez <fperez@colorado.edu>
2572 2003-03-20 Fernando Perez <fperez@colorado.edu>
2559
2573
2560 * IPython/genutils.py (error): added error() and fatal()
2574 * IPython/genutils.py (error): added error() and fatal()
2561 functions.
2575 functions.
2562
2576
2563 2003-03-18 *** Released version 0.2.15pre3
2577 2003-03-18 *** Released version 0.2.15pre3
2564
2578
2565 2003-03-18 Fernando Perez <fperez@colorado.edu>
2579 2003-03-18 Fernando Perez <fperez@colorado.edu>
2566
2580
2567 * setupext/install_data_ext.py
2581 * setupext/install_data_ext.py
2568 (install_data_ext.initialize_options): Class contributed by Jack
2582 (install_data_ext.initialize_options): Class contributed by Jack
2569 Moffit for fixing the old distutils hack. He is sending this to
2583 Moffit for fixing the old distutils hack. He is sending this to
2570 the distutils folks so in the future we may not need it as a
2584 the distutils folks so in the future we may not need it as a
2571 private fix.
2585 private fix.
2572
2586
2573 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2587 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2574 changes for Debian packaging. See his patch for full details.
2588 changes for Debian packaging. See his patch for full details.
2575 The old distutils hack of making the ipythonrc* files carry a
2589 The old distutils hack of making the ipythonrc* files carry a
2576 bogus .py extension is gone, at last. Examples were moved to a
2590 bogus .py extension is gone, at last. Examples were moved to a
2577 separate subdir under doc/, and the separate executable scripts
2591 separate subdir under doc/, and the separate executable scripts
2578 now live in their own directory. Overall a great cleanup. The
2592 now live in their own directory. Overall a great cleanup. The
2579 manual was updated to use the new files, and setup.py has been
2593 manual was updated to use the new files, and setup.py has been
2580 fixed for this setup.
2594 fixed for this setup.
2581
2595
2582 * IPython/PyColorize.py (Parser.usage): made non-executable and
2596 * IPython/PyColorize.py (Parser.usage): made non-executable and
2583 created a pycolor wrapper around it to be included as a script.
2597 created a pycolor wrapper around it to be included as a script.
2584
2598
2585 2003-03-12 *** Released version 0.2.15pre2
2599 2003-03-12 *** Released version 0.2.15pre2
2586
2600
2587 2003-03-12 Fernando Perez <fperez@colorado.edu>
2601 2003-03-12 Fernando Perez <fperez@colorado.edu>
2588
2602
2589 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2603 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2590 long-standing problem with garbage characters in some terminals.
2604 long-standing problem with garbage characters in some terminals.
2591 The issue was really that the \001 and \002 escapes must _only_ be
2605 The issue was really that the \001 and \002 escapes must _only_ be
2592 passed to input prompts (which call readline), but _never_ to
2606 passed to input prompts (which call readline), but _never_ to
2593 normal text to be printed on screen. I changed ColorANSI to have
2607 normal text to be printed on screen. I changed ColorANSI to have
2594 two classes: TermColors and InputTermColors, each with the
2608 two classes: TermColors and InputTermColors, each with the
2595 appropriate escapes for input prompts or normal text. The code in
2609 appropriate escapes for input prompts or normal text. The code in
2596 Prompts.py got slightly more complicated, but this very old and
2610 Prompts.py got slightly more complicated, but this very old and
2597 annoying bug is finally fixed.
2611 annoying bug is finally fixed.
2598
2612
2599 All the credit for nailing down the real origin of this problem
2613 All the credit for nailing down the real origin of this problem
2600 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2614 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2601 *Many* thanks to him for spending quite a bit of effort on this.
2615 *Many* thanks to him for spending quite a bit of effort on this.
2602
2616
2603 2003-03-05 *** Released version 0.2.15pre1
2617 2003-03-05 *** Released version 0.2.15pre1
2604
2618
2605 2003-03-03 Fernando Perez <fperez@colorado.edu>
2619 2003-03-03 Fernando Perez <fperez@colorado.edu>
2606
2620
2607 * IPython/FakeModule.py: Moved the former _FakeModule to a
2621 * IPython/FakeModule.py: Moved the former _FakeModule to a
2608 separate file, because it's also needed by Magic (to fix a similar
2622 separate file, because it's also needed by Magic (to fix a similar
2609 pickle-related issue in @run).
2623 pickle-related issue in @run).
2610
2624
2611 2003-03-02 Fernando Perez <fperez@colorado.edu>
2625 2003-03-02 Fernando Perez <fperez@colorado.edu>
2612
2626
2613 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2627 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2614 the autocall option at runtime.
2628 the autocall option at runtime.
2615 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2629 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2616 across Magic.py to start separating Magic from InteractiveShell.
2630 across Magic.py to start separating Magic from InteractiveShell.
2617 (Magic._ofind): Fixed to return proper namespace for dotted
2631 (Magic._ofind): Fixed to return proper namespace for dotted
2618 names. Before, a dotted name would always return 'not currently
2632 names. Before, a dotted name would always return 'not currently
2619 defined', because it would find the 'parent'. s.x would be found,
2633 defined', because it would find the 'parent'. s.x would be found,
2620 but since 'x' isn't defined by itself, it would get confused.
2634 but since 'x' isn't defined by itself, it would get confused.
2621 (Magic.magic_run): Fixed pickling problems reported by Ralf
2635 (Magic.magic_run): Fixed pickling problems reported by Ralf
2622 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2636 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2623 that I'd used when Mike Heeter reported similar issues at the
2637 that I'd used when Mike Heeter reported similar issues at the
2624 top-level, but now for @run. It boils down to injecting the
2638 top-level, but now for @run. It boils down to injecting the
2625 namespace where code is being executed with something that looks
2639 namespace where code is being executed with something that looks
2626 enough like a module to fool pickle.dump(). Since a pickle stores
2640 enough like a module to fool pickle.dump(). Since a pickle stores
2627 a named reference to the importing module, we need this for
2641 a named reference to the importing module, we need this for
2628 pickles to save something sensible.
2642 pickles to save something sensible.
2629
2643
2630 * IPython/ipmaker.py (make_IPython): added an autocall option.
2644 * IPython/ipmaker.py (make_IPython): added an autocall option.
2631
2645
2632 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2646 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2633 the auto-eval code. Now autocalling is an option, and the code is
2647 the auto-eval code. Now autocalling is an option, and the code is
2634 also vastly safer. There is no more eval() involved at all.
2648 also vastly safer. There is no more eval() involved at all.
2635
2649
2636 2003-03-01 Fernando Perez <fperez@colorado.edu>
2650 2003-03-01 Fernando Perez <fperez@colorado.edu>
2637
2651
2638 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2652 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2639 dict with named keys instead of a tuple.
2653 dict with named keys instead of a tuple.
2640
2654
2641 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2655 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2642
2656
2643 * setup.py (make_shortcut): Fixed message about directories
2657 * setup.py (make_shortcut): Fixed message about directories
2644 created during Windows installation (the directories were ok, just
2658 created during Windows installation (the directories were ok, just
2645 the printed message was misleading). Thanks to Chris Liechti
2659 the printed message was misleading). Thanks to Chris Liechti
2646 <cliechti-AT-gmx.net> for the heads up.
2660 <cliechti-AT-gmx.net> for the heads up.
2647
2661
2648 2003-02-21 Fernando Perez <fperez@colorado.edu>
2662 2003-02-21 Fernando Perez <fperez@colorado.edu>
2649
2663
2650 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2664 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2651 of ValueError exception when checking for auto-execution. This
2665 of ValueError exception when checking for auto-execution. This
2652 one is raised by things like Numeric arrays arr.flat when the
2666 one is raised by things like Numeric arrays arr.flat when the
2653 array is non-contiguous.
2667 array is non-contiguous.
2654
2668
2655 2003-01-31 Fernando Perez <fperez@colorado.edu>
2669 2003-01-31 Fernando Perez <fperez@colorado.edu>
2656
2670
2657 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2671 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2658 not return any value at all (even though the command would get
2672 not return any value at all (even though the command would get
2659 executed).
2673 executed).
2660 (xsys): Flush stdout right after printing the command to ensure
2674 (xsys): Flush stdout right after printing the command to ensure
2661 proper ordering of commands and command output in the total
2675 proper ordering of commands and command output in the total
2662 output.
2676 output.
2663 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2677 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2664 system/getoutput as defaults. The old ones are kept for
2678 system/getoutput as defaults. The old ones are kept for
2665 compatibility reasons, so no code which uses this library needs
2679 compatibility reasons, so no code which uses this library needs
2666 changing.
2680 changing.
2667
2681
2668 2003-01-27 *** Released version 0.2.14
2682 2003-01-27 *** Released version 0.2.14
2669
2683
2670 2003-01-25 Fernando Perez <fperez@colorado.edu>
2684 2003-01-25 Fernando Perez <fperez@colorado.edu>
2671
2685
2672 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2686 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2673 functions defined in previous edit sessions could not be re-edited
2687 functions defined in previous edit sessions could not be re-edited
2674 (because the temp files were immediately removed). Now temp files
2688 (because the temp files were immediately removed). Now temp files
2675 are removed only at IPython's exit.
2689 are removed only at IPython's exit.
2676 (Magic.magic_run): Improved @run to perform shell-like expansions
2690 (Magic.magic_run): Improved @run to perform shell-like expansions
2677 on its arguments (~users and $VARS). With this, @run becomes more
2691 on its arguments (~users and $VARS). With this, @run becomes more
2678 like a normal command-line.
2692 like a normal command-line.
2679
2693
2680 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2694 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2681 bugs related to embedding and cleaned up that code. A fairly
2695 bugs related to embedding and cleaned up that code. A fairly
2682 important one was the impossibility to access the global namespace
2696 important one was the impossibility to access the global namespace
2683 through the embedded IPython (only local variables were visible).
2697 through the embedded IPython (only local variables were visible).
2684
2698
2685 2003-01-14 Fernando Perez <fperez@colorado.edu>
2699 2003-01-14 Fernando Perez <fperez@colorado.edu>
2686
2700
2687 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2701 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2688 auto-calling to be a bit more conservative. Now it doesn't get
2702 auto-calling to be a bit more conservative. Now it doesn't get
2689 triggered if any of '!=()<>' are in the rest of the input line, to
2703 triggered if any of '!=()<>' are in the rest of the input line, to
2690 allow comparing callables. Thanks to Alex for the heads up.
2704 allow comparing callables. Thanks to Alex for the heads up.
2691
2705
2692 2003-01-07 Fernando Perez <fperez@colorado.edu>
2706 2003-01-07 Fernando Perez <fperez@colorado.edu>
2693
2707
2694 * IPython/genutils.py (page): fixed estimation of the number of
2708 * IPython/genutils.py (page): fixed estimation of the number of
2695 lines in a string to be paged to simply count newlines. This
2709 lines in a string to be paged to simply count newlines. This
2696 prevents over-guessing due to embedded escape sequences. A better
2710 prevents over-guessing due to embedded escape sequences. A better
2697 long-term solution would involve stripping out the control chars
2711 long-term solution would involve stripping out the control chars
2698 for the count, but it's potentially so expensive I just don't
2712 for the count, but it's potentially so expensive I just don't
2699 think it's worth doing.
2713 think it's worth doing.
2700
2714
2701 2002-12-19 *** Released version 0.2.14pre50
2715 2002-12-19 *** Released version 0.2.14pre50
2702
2716
2703 2002-12-19 Fernando Perez <fperez@colorado.edu>
2717 2002-12-19 Fernando Perez <fperez@colorado.edu>
2704
2718
2705 * tools/release (version): Changed release scripts to inform
2719 * tools/release (version): Changed release scripts to inform
2706 Andrea and build a NEWS file with a list of recent changes.
2720 Andrea and build a NEWS file with a list of recent changes.
2707
2721
2708 * IPython/ColorANSI.py (__all__): changed terminal detection
2722 * IPython/ColorANSI.py (__all__): changed terminal detection
2709 code. Seems to work better for xterms without breaking
2723 code. Seems to work better for xterms without breaking
2710 konsole. Will need more testing to determine if WinXP and Mac OSX
2724 konsole. Will need more testing to determine if WinXP and Mac OSX
2711 also work ok.
2725 also work ok.
2712
2726
2713 2002-12-18 *** Released version 0.2.14pre49
2727 2002-12-18 *** Released version 0.2.14pre49
2714
2728
2715 2002-12-18 Fernando Perez <fperez@colorado.edu>
2729 2002-12-18 Fernando Perez <fperez@colorado.edu>
2716
2730
2717 * Docs: added new info about Mac OSX, from Andrea.
2731 * Docs: added new info about Mac OSX, from Andrea.
2718
2732
2719 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2733 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2720 allow direct plotting of python strings whose format is the same
2734 allow direct plotting of python strings whose format is the same
2721 of gnuplot data files.
2735 of gnuplot data files.
2722
2736
2723 2002-12-16 Fernando Perez <fperez@colorado.edu>
2737 2002-12-16 Fernando Perez <fperez@colorado.edu>
2724
2738
2725 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2739 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2726 value of exit question to be acknowledged.
2740 value of exit question to be acknowledged.
2727
2741
2728 2002-12-03 Fernando Perez <fperez@colorado.edu>
2742 2002-12-03 Fernando Perez <fperez@colorado.edu>
2729
2743
2730 * IPython/ipmaker.py: removed generators, which had been added
2744 * IPython/ipmaker.py: removed generators, which had been added
2731 by mistake in an earlier debugging run. This was causing trouble
2745 by mistake in an earlier debugging run. This was causing trouble
2732 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2746 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2733 for pointing this out.
2747 for pointing this out.
2734
2748
2735 2002-11-17 Fernando Perez <fperez@colorado.edu>
2749 2002-11-17 Fernando Perez <fperez@colorado.edu>
2736
2750
2737 * Manual: updated the Gnuplot section.
2751 * Manual: updated the Gnuplot section.
2738
2752
2739 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2753 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2740 a much better split of what goes in Runtime and what goes in
2754 a much better split of what goes in Runtime and what goes in
2741 Interactive.
2755 Interactive.
2742
2756
2743 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2757 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2744 being imported from iplib.
2758 being imported from iplib.
2745
2759
2746 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2760 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2747 for command-passing. Now the global Gnuplot instance is called
2761 for command-passing. Now the global Gnuplot instance is called
2748 'gp' instead of 'g', which was really a far too fragile and
2762 'gp' instead of 'g', which was really a far too fragile and
2749 common name.
2763 common name.
2750
2764
2751 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2765 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2752 bounding boxes generated by Gnuplot for square plots.
2766 bounding boxes generated by Gnuplot for square plots.
2753
2767
2754 * IPython/genutils.py (popkey): new function added. I should
2768 * IPython/genutils.py (popkey): new function added. I should
2755 suggest this on c.l.py as a dict method, it seems useful.
2769 suggest this on c.l.py as a dict method, it seems useful.
2756
2770
2757 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2771 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2758 to transparently handle PostScript generation. MUCH better than
2772 to transparently handle PostScript generation. MUCH better than
2759 the previous plot_eps/replot_eps (which I removed now). The code
2773 the previous plot_eps/replot_eps (which I removed now). The code
2760 is also fairly clean and well documented now (including
2774 is also fairly clean and well documented now (including
2761 docstrings).
2775 docstrings).
2762
2776
2763 2002-11-13 Fernando Perez <fperez@colorado.edu>
2777 2002-11-13 Fernando Perez <fperez@colorado.edu>
2764
2778
2765 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2779 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2766 (inconsistent with options).
2780 (inconsistent with options).
2767
2781
2768 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2782 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2769 manually disabled, I don't know why. Fixed it.
2783 manually disabled, I don't know why. Fixed it.
2770 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2784 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2771 eps output.
2785 eps output.
2772
2786
2773 2002-11-12 Fernando Perez <fperez@colorado.edu>
2787 2002-11-12 Fernando Perez <fperez@colorado.edu>
2774
2788
2775 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2789 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2776 don't propagate up to caller. Fixes crash reported by François
2790 don't propagate up to caller. Fixes crash reported by François
2777 Pinard.
2791 Pinard.
2778
2792
2779 2002-11-09 Fernando Perez <fperez@colorado.edu>
2793 2002-11-09 Fernando Perez <fperez@colorado.edu>
2780
2794
2781 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2795 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2782 history file for new users.
2796 history file for new users.
2783 (make_IPython): fixed bug where initial install would leave the
2797 (make_IPython): fixed bug where initial install would leave the
2784 user running in the .ipython dir.
2798 user running in the .ipython dir.
2785 (make_IPython): fixed bug where config dir .ipython would be
2799 (make_IPython): fixed bug where config dir .ipython would be
2786 created regardless of the given -ipythondir option. Thanks to Cory
2800 created regardless of the given -ipythondir option. Thanks to Cory
2787 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2801 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2788
2802
2789 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2803 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2790 type confirmations. Will need to use it in all of IPython's code
2804 type confirmations. Will need to use it in all of IPython's code
2791 consistently.
2805 consistently.
2792
2806
2793 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2807 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2794 context to print 31 lines instead of the default 5. This will make
2808 context to print 31 lines instead of the default 5. This will make
2795 the crash reports extremely detailed in case the problem is in
2809 the crash reports extremely detailed in case the problem is in
2796 libraries I don't have access to.
2810 libraries I don't have access to.
2797
2811
2798 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2812 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2799 line of defense' code to still crash, but giving users fair
2813 line of defense' code to still crash, but giving users fair
2800 warning. I don't want internal errors to go unreported: if there's
2814 warning. I don't want internal errors to go unreported: if there's
2801 an internal problem, IPython should crash and generate a full
2815 an internal problem, IPython should crash and generate a full
2802 report.
2816 report.
2803
2817
2804 2002-11-08 Fernando Perez <fperez@colorado.edu>
2818 2002-11-08 Fernando Perez <fperez@colorado.edu>
2805
2819
2806 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2820 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2807 otherwise uncaught exceptions which can appear if people set
2821 otherwise uncaught exceptions which can appear if people set
2808 sys.stdout to something badly broken. Thanks to a crash report
2822 sys.stdout to something badly broken. Thanks to a crash report
2809 from henni-AT-mail.brainbot.com.
2823 from henni-AT-mail.brainbot.com.
2810
2824
2811 2002-11-04 Fernando Perez <fperez@colorado.edu>
2825 2002-11-04 Fernando Perez <fperez@colorado.edu>
2812
2826
2813 * IPython/iplib.py (InteractiveShell.interact): added
2827 * IPython/iplib.py (InteractiveShell.interact): added
2814 __IPYTHON__active to the builtins. It's a flag which goes on when
2828 __IPYTHON__active to the builtins. It's a flag which goes on when
2815 the interaction starts and goes off again when it stops. This
2829 the interaction starts and goes off again when it stops. This
2816 allows embedding code to detect being inside IPython. Before this
2830 allows embedding code to detect being inside IPython. Before this
2817 was done via __IPYTHON__, but that only shows that an IPython
2831 was done via __IPYTHON__, but that only shows that an IPython
2818 instance has been created.
2832 instance has been created.
2819
2833
2820 * IPython/Magic.py (Magic.magic_env): I realized that in a
2834 * IPython/Magic.py (Magic.magic_env): I realized that in a
2821 UserDict, instance.data holds the data as a normal dict. So I
2835 UserDict, instance.data holds the data as a normal dict. So I
2822 modified @env to return os.environ.data instead of rebuilding a
2836 modified @env to return os.environ.data instead of rebuilding a
2823 dict by hand.
2837 dict by hand.
2824
2838
2825 2002-11-02 Fernando Perez <fperez@colorado.edu>
2839 2002-11-02 Fernando Perez <fperez@colorado.edu>
2826
2840
2827 * IPython/genutils.py (warn): changed so that level 1 prints no
2841 * IPython/genutils.py (warn): changed so that level 1 prints no
2828 header. Level 2 is now the default (with 'WARNING' header, as
2842 header. Level 2 is now the default (with 'WARNING' header, as
2829 before). I think I tracked all places where changes were needed in
2843 before). I think I tracked all places where changes were needed in
2830 IPython, but outside code using the old level numbering may have
2844 IPython, but outside code using the old level numbering may have
2831 broken.
2845 broken.
2832
2846
2833 * IPython/iplib.py (InteractiveShell.runcode): added this to
2847 * IPython/iplib.py (InteractiveShell.runcode): added this to
2834 handle the tracebacks in SystemExit traps correctly. The previous
2848 handle the tracebacks in SystemExit traps correctly. The previous
2835 code (through interact) was printing more of the stack than
2849 code (through interact) was printing more of the stack than
2836 necessary, showing IPython internal code to the user.
2850 necessary, showing IPython internal code to the user.
2837
2851
2838 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2852 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2839 default. Now that the default at the confirmation prompt is yes,
2853 default. Now that the default at the confirmation prompt is yes,
2840 it's not so intrusive. François' argument that ipython sessions
2854 it's not so intrusive. François' argument that ipython sessions
2841 tend to be complex enough not to lose them from an accidental C-d,
2855 tend to be complex enough not to lose them from an accidental C-d,
2842 is a valid one.
2856 is a valid one.
2843
2857
2844 * IPython/iplib.py (InteractiveShell.interact): added a
2858 * IPython/iplib.py (InteractiveShell.interact): added a
2845 showtraceback() call to the SystemExit trap, and modified the exit
2859 showtraceback() call to the SystemExit trap, and modified the exit
2846 confirmation to have yes as the default.
2860 confirmation to have yes as the default.
2847
2861
2848 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2862 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2849 this file. It's been gone from the code for a long time, this was
2863 this file. It's been gone from the code for a long time, this was
2850 simply leftover junk.
2864 simply leftover junk.
2851
2865
2852 2002-11-01 Fernando Perez <fperez@colorado.edu>
2866 2002-11-01 Fernando Perez <fperez@colorado.edu>
2853
2867
2854 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2868 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2855 added. If set, IPython now traps EOF and asks for
2869 added. If set, IPython now traps EOF and asks for
2856 confirmation. After a request by François Pinard.
2870 confirmation. After a request by François Pinard.
2857
2871
2858 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2872 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2859 of @abort, and with a new (better) mechanism for handling the
2873 of @abort, and with a new (better) mechanism for handling the
2860 exceptions.
2874 exceptions.
2861
2875
2862 2002-10-27 Fernando Perez <fperez@colorado.edu>
2876 2002-10-27 Fernando Perez <fperez@colorado.edu>
2863
2877
2864 * IPython/usage.py (__doc__): updated the --help information and
2878 * IPython/usage.py (__doc__): updated the --help information and
2865 the ipythonrc file to indicate that -log generates
2879 the ipythonrc file to indicate that -log generates
2866 ./ipython.log. Also fixed the corresponding info in @logstart.
2880 ./ipython.log. Also fixed the corresponding info in @logstart.
2867 This and several other fixes in the manuals thanks to reports by
2881 This and several other fixes in the manuals thanks to reports by
2868 François Pinard <pinard-AT-iro.umontreal.ca>.
2882 François Pinard <pinard-AT-iro.umontreal.ca>.
2869
2883
2870 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2884 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2871 refer to @logstart (instead of @log, which doesn't exist).
2885 refer to @logstart (instead of @log, which doesn't exist).
2872
2886
2873 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2887 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2874 AttributeError crash. Thanks to Christopher Armstrong
2888 AttributeError crash. Thanks to Christopher Armstrong
2875 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2889 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2876 introduced recently (in 0.2.14pre37) with the fix to the eval
2890 introduced recently (in 0.2.14pre37) with the fix to the eval
2877 problem mentioned below.
2891 problem mentioned below.
2878
2892
2879 2002-10-17 Fernando Perez <fperez@colorado.edu>
2893 2002-10-17 Fernando Perez <fperez@colorado.edu>
2880
2894
2881 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2895 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2882 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2896 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2883
2897
2884 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2898 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2885 this function to fix a problem reported by Alex Schmolck. He saw
2899 this function to fix a problem reported by Alex Schmolck. He saw
2886 it with list comprehensions and generators, which were getting
2900 it with list comprehensions and generators, which were getting
2887 called twice. The real problem was an 'eval' call in testing for
2901 called twice. The real problem was an 'eval' call in testing for
2888 automagic which was evaluating the input line silently.
2902 automagic which was evaluating the input line silently.
2889
2903
2890 This is a potentially very nasty bug, if the input has side
2904 This is a potentially very nasty bug, if the input has side
2891 effects which must not be repeated. The code is much cleaner now,
2905 effects which must not be repeated. The code is much cleaner now,
2892 without any blanket 'except' left and with a regexp test for
2906 without any blanket 'except' left and with a regexp test for
2893 actual function names.
2907 actual function names.
2894
2908
2895 But an eval remains, which I'm not fully comfortable with. I just
2909 But an eval remains, which I'm not fully comfortable with. I just
2896 don't know how to find out if an expression could be a callable in
2910 don't know how to find out if an expression could be a callable in
2897 the user's namespace without doing an eval on the string. However
2911 the user's namespace without doing an eval on the string. However
2898 that string is now much more strictly checked so that no code
2912 that string is now much more strictly checked so that no code
2899 slips by, so the eval should only happen for things that can
2913 slips by, so the eval should only happen for things that can
2900 really be only function/method names.
2914 really be only function/method names.
2901
2915
2902 2002-10-15 Fernando Perez <fperez@colorado.edu>
2916 2002-10-15 Fernando Perez <fperez@colorado.edu>
2903
2917
2904 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2918 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2905 OSX information to main manual, removed README_Mac_OSX file from
2919 OSX information to main manual, removed README_Mac_OSX file from
2906 distribution. Also updated credits for recent additions.
2920 distribution. Also updated credits for recent additions.
2907
2921
2908 2002-10-10 Fernando Perez <fperez@colorado.edu>
2922 2002-10-10 Fernando Perez <fperez@colorado.edu>
2909
2923
2910 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2924 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2911 terminal-related issues. Many thanks to Andrea Riciputi
2925 terminal-related issues. Many thanks to Andrea Riciputi
2912 <andrea.riciputi-AT-libero.it> for writing it.
2926 <andrea.riciputi-AT-libero.it> for writing it.
2913
2927
2914 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2928 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2915 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2929 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2916
2930
2917 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2931 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2918 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2932 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2919 <syver-en-AT-online.no> who both submitted patches for this problem.
2933 <syver-en-AT-online.no> who both submitted patches for this problem.
2920
2934
2921 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2935 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2922 global embedding to make sure that things don't overwrite user
2936 global embedding to make sure that things don't overwrite user
2923 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2937 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2924
2938
2925 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2939 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2926 compatibility. Thanks to Hayden Callow
2940 compatibility. Thanks to Hayden Callow
2927 <h.callow-AT-elec.canterbury.ac.nz>
2941 <h.callow-AT-elec.canterbury.ac.nz>
2928
2942
2929 2002-10-04 Fernando Perez <fperez@colorado.edu>
2943 2002-10-04 Fernando Perez <fperez@colorado.edu>
2930
2944
2931 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2945 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2932 Gnuplot.File objects.
2946 Gnuplot.File objects.
2933
2947
2934 2002-07-23 Fernando Perez <fperez@colorado.edu>
2948 2002-07-23 Fernando Perez <fperez@colorado.edu>
2935
2949
2936 * IPython/genutils.py (timing): Added timings() and timing() for
2950 * IPython/genutils.py (timing): Added timings() and timing() for
2937 quick access to the most commonly needed data, the execution
2951 quick access to the most commonly needed data, the execution
2938 times. Old timing() renamed to timings_out().
2952 times. Old timing() renamed to timings_out().
2939
2953
2940 2002-07-18 Fernando Perez <fperez@colorado.edu>
2954 2002-07-18 Fernando Perez <fperez@colorado.edu>
2941
2955
2942 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2956 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2943 bug with nested instances disrupting the parent's tab completion.
2957 bug with nested instances disrupting the parent's tab completion.
2944
2958
2945 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2959 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2946 all_completions code to begin the emacs integration.
2960 all_completions code to begin the emacs integration.
2947
2961
2948 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2962 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2949 argument to allow titling individual arrays when plotting.
2963 argument to allow titling individual arrays when plotting.
2950
2964
2951 2002-07-15 Fernando Perez <fperez@colorado.edu>
2965 2002-07-15 Fernando Perez <fperez@colorado.edu>
2952
2966
2953 * setup.py (make_shortcut): changed to retrieve the value of
2967 * setup.py (make_shortcut): changed to retrieve the value of
2954 'Program Files' directory from the registry (this value changes in
2968 'Program Files' directory from the registry (this value changes in
2955 non-english versions of Windows). Thanks to Thomas Fanslau
2969 non-english versions of Windows). Thanks to Thomas Fanslau
2956 <tfanslau-AT-gmx.de> for the report.
2970 <tfanslau-AT-gmx.de> for the report.
2957
2971
2958 2002-07-10 Fernando Perez <fperez@colorado.edu>
2972 2002-07-10 Fernando Perez <fperez@colorado.edu>
2959
2973
2960 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2974 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2961 a bug in pdb, which crashes if a line with only whitespace is
2975 a bug in pdb, which crashes if a line with only whitespace is
2962 entered. Bug report submitted to sourceforge.
2976 entered. Bug report submitted to sourceforge.
2963
2977
2964 2002-07-09 Fernando Perez <fperez@colorado.edu>
2978 2002-07-09 Fernando Perez <fperez@colorado.edu>
2965
2979
2966 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2980 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2967 reporting exceptions (it's a bug in inspect.py, I just set a
2981 reporting exceptions (it's a bug in inspect.py, I just set a
2968 workaround).
2982 workaround).
2969
2983
2970 2002-07-08 Fernando Perez <fperez@colorado.edu>
2984 2002-07-08 Fernando Perez <fperez@colorado.edu>
2971
2985
2972 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2986 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2973 __IPYTHON__ in __builtins__ to show up in user_ns.
2987 __IPYTHON__ in __builtins__ to show up in user_ns.
2974
2988
2975 2002-07-03 Fernando Perez <fperez@colorado.edu>
2989 2002-07-03 Fernando Perez <fperez@colorado.edu>
2976
2990
2977 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2991 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2978 name from @gp_set_instance to @gp_set_default.
2992 name from @gp_set_instance to @gp_set_default.
2979
2993
2980 * IPython/ipmaker.py (make_IPython): default editor value set to
2994 * IPython/ipmaker.py (make_IPython): default editor value set to
2981 '0' (a string), to match the rc file. Otherwise will crash when
2995 '0' (a string), to match the rc file. Otherwise will crash when
2982 .strip() is called on it.
2996 .strip() is called on it.
2983
2997
2984
2998
2985 2002-06-28 Fernando Perez <fperez@colorado.edu>
2999 2002-06-28 Fernando Perez <fperez@colorado.edu>
2986
3000
2987 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3001 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2988 of files in current directory when a file is executed via
3002 of files in current directory when a file is executed via
2989 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3003 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2990
3004
2991 * setup.py (manfiles): fix for rpm builds, submitted by RA
3005 * setup.py (manfiles): fix for rpm builds, submitted by RA
2992 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3006 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2993
3007
2994 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3008 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2995 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3009 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2996 string!). A. Schmolck caught this one.
3010 string!). A. Schmolck caught this one.
2997
3011
2998 2002-06-27 Fernando Perez <fperez@colorado.edu>
3012 2002-06-27 Fernando Perez <fperez@colorado.edu>
2999
3013
3000 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3014 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3001 defined files at the cmd line. __name__ wasn't being set to
3015 defined files at the cmd line. __name__ wasn't being set to
3002 __main__.
3016 __main__.
3003
3017
3004 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3018 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3005 regular lists and tuples besides Numeric arrays.
3019 regular lists and tuples besides Numeric arrays.
3006
3020
3007 * IPython/Prompts.py (CachedOutput.__call__): Added output
3021 * IPython/Prompts.py (CachedOutput.__call__): Added output
3008 supression for input ending with ';'. Similar to Mathematica and
3022 supression for input ending with ';'. Similar to Mathematica and
3009 Matlab. The _* vars and Out[] list are still updated, just like
3023 Matlab. The _* vars and Out[] list are still updated, just like
3010 Mathematica behaves.
3024 Mathematica behaves.
3011
3025
3012 2002-06-25 Fernando Perez <fperez@colorado.edu>
3026 2002-06-25 Fernando Perez <fperez@colorado.edu>
3013
3027
3014 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3028 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3015 .ini extensions for profiels under Windows.
3029 .ini extensions for profiels under Windows.
3016
3030
3017 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3031 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3018 string form. Fix contributed by Alexander Schmolck
3032 string form. Fix contributed by Alexander Schmolck
3019 <a.schmolck-AT-gmx.net>
3033 <a.schmolck-AT-gmx.net>
3020
3034
3021 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3035 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3022 pre-configured Gnuplot instance.
3036 pre-configured Gnuplot instance.
3023
3037
3024 2002-06-21 Fernando Perez <fperez@colorado.edu>
3038 2002-06-21 Fernando Perez <fperez@colorado.edu>
3025
3039
3026 * IPython/numutils.py (exp_safe): new function, works around the
3040 * IPython/numutils.py (exp_safe): new function, works around the
3027 underflow problems in Numeric.
3041 underflow problems in Numeric.
3028 (log2): New fn. Safe log in base 2: returns exact integer answer
3042 (log2): New fn. Safe log in base 2: returns exact integer answer
3029 for exact integer powers of 2.
3043 for exact integer powers of 2.
3030
3044
3031 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3045 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3032 properly.
3046 properly.
3033
3047
3034 2002-06-20 Fernando Perez <fperez@colorado.edu>
3048 2002-06-20 Fernando Perez <fperez@colorado.edu>
3035
3049
3036 * IPython/genutils.py (timing): new function like
3050 * IPython/genutils.py (timing): new function like
3037 Mathematica's. Similar to time_test, but returns more info.
3051 Mathematica's. Similar to time_test, but returns more info.
3038
3052
3039 2002-06-18 Fernando Perez <fperez@colorado.edu>
3053 2002-06-18 Fernando Perez <fperez@colorado.edu>
3040
3054
3041 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3055 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3042 according to Mike Heeter's suggestions.
3056 according to Mike Heeter's suggestions.
3043
3057
3044 2002-06-16 Fernando Perez <fperez@colorado.edu>
3058 2002-06-16 Fernando Perez <fperez@colorado.edu>
3045
3059
3046 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3060 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3047 system. GnuplotMagic is gone as a user-directory option. New files
3061 system. GnuplotMagic is gone as a user-directory option. New files
3048 make it easier to use all the gnuplot stuff both from external
3062 make it easier to use all the gnuplot stuff both from external
3049 programs as well as from IPython. Had to rewrite part of
3063 programs as well as from IPython. Had to rewrite part of
3050 hardcopy() b/c of a strange bug: often the ps files simply don't
3064 hardcopy() b/c of a strange bug: often the ps files simply don't
3051 get created, and require a repeat of the command (often several
3065 get created, and require a repeat of the command (often several
3052 times).
3066 times).
3053
3067
3054 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3068 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3055 resolve output channel at call time, so that if sys.stderr has
3069 resolve output channel at call time, so that if sys.stderr has
3056 been redirected by user this gets honored.
3070 been redirected by user this gets honored.
3057
3071
3058 2002-06-13 Fernando Perez <fperez@colorado.edu>
3072 2002-06-13 Fernando Perez <fperez@colorado.edu>
3059
3073
3060 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3074 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3061 IPShell. Kept a copy with the old names to avoid breaking people's
3075 IPShell. Kept a copy with the old names to avoid breaking people's
3062 embedded code.
3076 embedded code.
3063
3077
3064 * IPython/ipython: simplified it to the bare minimum after
3078 * IPython/ipython: simplified it to the bare minimum after
3065 Holger's suggestions. Added info about how to use it in
3079 Holger's suggestions. Added info about how to use it in
3066 PYTHONSTARTUP.
3080 PYTHONSTARTUP.
3067
3081
3068 * IPython/Shell.py (IPythonShell): changed the options passing
3082 * IPython/Shell.py (IPythonShell): changed the options passing
3069 from a string with funky %s replacements to a straight list. Maybe
3083 from a string with funky %s replacements to a straight list. Maybe
3070 a bit more typing, but it follows sys.argv conventions, so there's
3084 a bit more typing, but it follows sys.argv conventions, so there's
3071 less special-casing to remember.
3085 less special-casing to remember.
3072
3086
3073 2002-06-12 Fernando Perez <fperez@colorado.edu>
3087 2002-06-12 Fernando Perez <fperez@colorado.edu>
3074
3088
3075 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3089 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3076 command. Thanks to a suggestion by Mike Heeter.
3090 command. Thanks to a suggestion by Mike Heeter.
3077 (Magic.magic_pfile): added behavior to look at filenames if given
3091 (Magic.magic_pfile): added behavior to look at filenames if given
3078 arg is not a defined object.
3092 arg is not a defined object.
3079 (Magic.magic_save): New @save function to save code snippets. Also
3093 (Magic.magic_save): New @save function to save code snippets. Also
3080 a Mike Heeter idea.
3094 a Mike Heeter idea.
3081
3095
3082 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3096 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3083 plot() and replot(). Much more convenient now, especially for
3097 plot() and replot(). Much more convenient now, especially for
3084 interactive use.
3098 interactive use.
3085
3099
3086 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3100 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3087 filenames.
3101 filenames.
3088
3102
3089 2002-06-02 Fernando Perez <fperez@colorado.edu>
3103 2002-06-02 Fernando Perez <fperez@colorado.edu>
3090
3104
3091 * IPython/Struct.py (Struct.__init__): modified to admit
3105 * IPython/Struct.py (Struct.__init__): modified to admit
3092 initialization via another struct.
3106 initialization via another struct.
3093
3107
3094 * IPython/genutils.py (SystemExec.__init__): New stateful
3108 * IPython/genutils.py (SystemExec.__init__): New stateful
3095 interface to xsys and bq. Useful for writing system scripts.
3109 interface to xsys and bq. Useful for writing system scripts.
3096
3110
3097 2002-05-30 Fernando Perez <fperez@colorado.edu>
3111 2002-05-30 Fernando Perez <fperez@colorado.edu>
3098
3112
3099 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3113 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3100 documents. This will make the user download smaller (it's getting
3114 documents. This will make the user download smaller (it's getting
3101 too big).
3115 too big).
3102
3116
3103 2002-05-29 Fernando Perez <fperez@colorado.edu>
3117 2002-05-29 Fernando Perez <fperez@colorado.edu>
3104
3118
3105 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3119 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3106 fix problems with shelve and pickle. Seems to work, but I don't
3120 fix problems with shelve and pickle. Seems to work, but I don't
3107 know if corner cases break it. Thanks to Mike Heeter
3121 know if corner cases break it. Thanks to Mike Heeter
3108 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3122 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3109
3123
3110 2002-05-24 Fernando Perez <fperez@colorado.edu>
3124 2002-05-24 Fernando Perez <fperez@colorado.edu>
3111
3125
3112 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3126 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3113 macros having broken.
3127 macros having broken.
3114
3128
3115 2002-05-21 Fernando Perez <fperez@colorado.edu>
3129 2002-05-21 Fernando Perez <fperez@colorado.edu>
3116
3130
3117 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3131 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3118 introduced logging bug: all history before logging started was
3132 introduced logging bug: all history before logging started was
3119 being written one character per line! This came from the redesign
3133 being written one character per line! This came from the redesign
3120 of the input history as a special list which slices to strings,
3134 of the input history as a special list which slices to strings,
3121 not to lists.
3135 not to lists.
3122
3136
3123 2002-05-20 Fernando Perez <fperez@colorado.edu>
3137 2002-05-20 Fernando Perez <fperez@colorado.edu>
3124
3138
3125 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3139 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3126 be an attribute of all classes in this module. The design of these
3140 be an attribute of all classes in this module. The design of these
3127 classes needs some serious overhauling.
3141 classes needs some serious overhauling.
3128
3142
3129 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3143 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3130 which was ignoring '_' in option names.
3144 which was ignoring '_' in option names.
3131
3145
3132 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3146 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3133 'Verbose_novars' to 'Context' and made it the new default. It's a
3147 'Verbose_novars' to 'Context' and made it the new default. It's a
3134 bit more readable and also safer than verbose.
3148 bit more readable and also safer than verbose.
3135
3149
3136 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3150 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3137 triple-quoted strings.
3151 triple-quoted strings.
3138
3152
3139 * IPython/OInspect.py (__all__): new module exposing the object
3153 * IPython/OInspect.py (__all__): new module exposing the object
3140 introspection facilities. Now the corresponding magics are dummy
3154 introspection facilities. Now the corresponding magics are dummy
3141 wrappers around this. Having this module will make it much easier
3155 wrappers around this. Having this module will make it much easier
3142 to put these functions into our modified pdb.
3156 to put these functions into our modified pdb.
3143 This new object inspector system uses the new colorizing module,
3157 This new object inspector system uses the new colorizing module,
3144 so source code and other things are nicely syntax highlighted.
3158 so source code and other things are nicely syntax highlighted.
3145
3159
3146 2002-05-18 Fernando Perez <fperez@colorado.edu>
3160 2002-05-18 Fernando Perez <fperez@colorado.edu>
3147
3161
3148 * IPython/ColorANSI.py: Split the coloring tools into a separate
3162 * IPython/ColorANSI.py: Split the coloring tools into a separate
3149 module so I can use them in other code easier (they were part of
3163 module so I can use them in other code easier (they were part of
3150 ultraTB).
3164 ultraTB).
3151
3165
3152 2002-05-17 Fernando Perez <fperez@colorado.edu>
3166 2002-05-17 Fernando Perez <fperez@colorado.edu>
3153
3167
3154 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3168 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3155 fixed it to set the global 'g' also to the called instance, as
3169 fixed it to set the global 'g' also to the called instance, as
3156 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3170 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3157 user's 'g' variables).
3171 user's 'g' variables).
3158
3172
3159 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3173 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3160 global variables (aliases to _ih,_oh) so that users which expect
3174 global variables (aliases to _ih,_oh) so that users which expect
3161 In[5] or Out[7] to work aren't unpleasantly surprised.
3175 In[5] or Out[7] to work aren't unpleasantly surprised.
3162 (InputList.__getslice__): new class to allow executing slices of
3176 (InputList.__getslice__): new class to allow executing slices of
3163 input history directly. Very simple class, complements the use of
3177 input history directly. Very simple class, complements the use of
3164 macros.
3178 macros.
3165
3179
3166 2002-05-16 Fernando Perez <fperez@colorado.edu>
3180 2002-05-16 Fernando Perez <fperez@colorado.edu>
3167
3181
3168 * setup.py (docdirbase): make doc directory be just doc/IPython
3182 * setup.py (docdirbase): make doc directory be just doc/IPython
3169 without version numbers, it will reduce clutter for users.
3183 without version numbers, it will reduce clutter for users.
3170
3184
3171 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3185 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3172 execfile call to prevent possible memory leak. See for details:
3186 execfile call to prevent possible memory leak. See for details:
3173 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3187 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3174
3188
3175 2002-05-15 Fernando Perez <fperez@colorado.edu>
3189 2002-05-15 Fernando Perez <fperez@colorado.edu>
3176
3190
3177 * IPython/Magic.py (Magic.magic_psource): made the object
3191 * IPython/Magic.py (Magic.magic_psource): made the object
3178 introspection names be more standard: pdoc, pdef, pfile and
3192 introspection names be more standard: pdoc, pdef, pfile and
3179 psource. They all print/page their output, and it makes
3193 psource. They all print/page their output, and it makes
3180 remembering them easier. Kept old names for compatibility as
3194 remembering them easier. Kept old names for compatibility as
3181 aliases.
3195 aliases.
3182
3196
3183 2002-05-14 Fernando Perez <fperez@colorado.edu>
3197 2002-05-14 Fernando Perez <fperez@colorado.edu>
3184
3198
3185 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3199 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3186 what the mouse problem was. The trick is to use gnuplot with temp
3200 what the mouse problem was. The trick is to use gnuplot with temp
3187 files and NOT with pipes (for data communication), because having
3201 files and NOT with pipes (for data communication), because having
3188 both pipes and the mouse on is bad news.
3202 both pipes and the mouse on is bad news.
3189
3203
3190 2002-05-13 Fernando Perez <fperez@colorado.edu>
3204 2002-05-13 Fernando Perez <fperez@colorado.edu>
3191
3205
3192 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3206 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3193 bug. Information would be reported about builtins even when
3207 bug. Information would be reported about builtins even when
3194 user-defined functions overrode them.
3208 user-defined functions overrode them.
3195
3209
3196 2002-05-11 Fernando Perez <fperez@colorado.edu>
3210 2002-05-11 Fernando Perez <fperez@colorado.edu>
3197
3211
3198 * IPython/__init__.py (__all__): removed FlexCompleter from
3212 * IPython/__init__.py (__all__): removed FlexCompleter from
3199 __all__ so that things don't fail in platforms without readline.
3213 __all__ so that things don't fail in platforms without readline.
3200
3214
3201 2002-05-10 Fernando Perez <fperez@colorado.edu>
3215 2002-05-10 Fernando Perez <fperez@colorado.edu>
3202
3216
3203 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3217 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3204 it requires Numeric, effectively making Numeric a dependency for
3218 it requires Numeric, effectively making Numeric a dependency for
3205 IPython.
3219 IPython.
3206
3220
3207 * Released 0.2.13
3221 * Released 0.2.13
3208
3222
3209 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3223 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3210 profiler interface. Now all the major options from the profiler
3224 profiler interface. Now all the major options from the profiler
3211 module are directly supported in IPython, both for single
3225 module are directly supported in IPython, both for single
3212 expressions (@prun) and for full programs (@run -p).
3226 expressions (@prun) and for full programs (@run -p).
3213
3227
3214 2002-05-09 Fernando Perez <fperez@colorado.edu>
3228 2002-05-09 Fernando Perez <fperez@colorado.edu>
3215
3229
3216 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3230 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3217 magic properly formatted for screen.
3231 magic properly formatted for screen.
3218
3232
3219 * setup.py (make_shortcut): Changed things to put pdf version in
3233 * setup.py (make_shortcut): Changed things to put pdf version in
3220 doc/ instead of doc/manual (had to change lyxport a bit).
3234 doc/ instead of doc/manual (had to change lyxport a bit).
3221
3235
3222 * IPython/Magic.py (Profile.string_stats): made profile runs go
3236 * IPython/Magic.py (Profile.string_stats): made profile runs go
3223 through pager (they are long and a pager allows searching, saving,
3237 through pager (they are long and a pager allows searching, saving,
3224 etc.)
3238 etc.)
3225
3239
3226 2002-05-08 Fernando Perez <fperez@colorado.edu>
3240 2002-05-08 Fernando Perez <fperez@colorado.edu>
3227
3241
3228 * Released 0.2.12
3242 * Released 0.2.12
3229
3243
3230 2002-05-06 Fernando Perez <fperez@colorado.edu>
3244 2002-05-06 Fernando Perez <fperez@colorado.edu>
3231
3245
3232 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3246 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3233 introduced); 'hist n1 n2' was broken.
3247 introduced); 'hist n1 n2' was broken.
3234 (Magic.magic_pdb): added optional on/off arguments to @pdb
3248 (Magic.magic_pdb): added optional on/off arguments to @pdb
3235 (Magic.magic_run): added option -i to @run, which executes code in
3249 (Magic.magic_run): added option -i to @run, which executes code in
3236 the IPython namespace instead of a clean one. Also added @irun as
3250 the IPython namespace instead of a clean one. Also added @irun as
3237 an alias to @run -i.
3251 an alias to @run -i.
3238
3252
3239 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3253 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3240 fixed (it didn't really do anything, the namespaces were wrong).
3254 fixed (it didn't really do anything, the namespaces were wrong).
3241
3255
3242 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3256 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3243
3257
3244 * IPython/__init__.py (__all__): Fixed package namespace, now
3258 * IPython/__init__.py (__all__): Fixed package namespace, now
3245 'import IPython' does give access to IPython.<all> as
3259 'import IPython' does give access to IPython.<all> as
3246 expected. Also renamed __release__ to Release.
3260 expected. Also renamed __release__ to Release.
3247
3261
3248 * IPython/Debugger.py (__license__): created new Pdb class which
3262 * IPython/Debugger.py (__license__): created new Pdb class which
3249 functions like a drop-in for the normal pdb.Pdb but does NOT
3263 functions like a drop-in for the normal pdb.Pdb but does NOT
3250 import readline by default. This way it doesn't muck up IPython's
3264 import readline by default. This way it doesn't muck up IPython's
3251 readline handling, and now tab-completion finally works in the
3265 readline handling, and now tab-completion finally works in the
3252 debugger -- sort of. It completes things globally visible, but the
3266 debugger -- sort of. It completes things globally visible, but the
3253 completer doesn't track the stack as pdb walks it. That's a bit
3267 completer doesn't track the stack as pdb walks it. That's a bit
3254 tricky, and I'll have to implement it later.
3268 tricky, and I'll have to implement it later.
3255
3269
3256 2002-05-05 Fernando Perez <fperez@colorado.edu>
3270 2002-05-05 Fernando Perez <fperez@colorado.edu>
3257
3271
3258 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3272 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3259 magic docstrings when printed via ? (explicit \'s were being
3273 magic docstrings when printed via ? (explicit \'s were being
3260 printed).
3274 printed).
3261
3275
3262 * IPython/ipmaker.py (make_IPython): fixed namespace
3276 * IPython/ipmaker.py (make_IPython): fixed namespace
3263 identification bug. Now variables loaded via logs or command-line
3277 identification bug. Now variables loaded via logs or command-line
3264 files are recognized in the interactive namespace by @who.
3278 files are recognized in the interactive namespace by @who.
3265
3279
3266 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3280 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3267 log replay system stemming from the string form of Structs.
3281 log replay system stemming from the string form of Structs.
3268
3282
3269 * IPython/Magic.py (Macro.__init__): improved macros to properly
3283 * IPython/Magic.py (Macro.__init__): improved macros to properly
3270 handle magic commands in them.
3284 handle magic commands in them.
3271 (Magic.magic_logstart): usernames are now expanded so 'logstart
3285 (Magic.magic_logstart): usernames are now expanded so 'logstart
3272 ~/mylog' now works.
3286 ~/mylog' now works.
3273
3287
3274 * IPython/iplib.py (complete): fixed bug where paths starting with
3288 * IPython/iplib.py (complete): fixed bug where paths starting with
3275 '/' would be completed as magic names.
3289 '/' would be completed as magic names.
3276
3290
3277 2002-05-04 Fernando Perez <fperez@colorado.edu>
3291 2002-05-04 Fernando Perez <fperez@colorado.edu>
3278
3292
3279 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3293 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3280 allow running full programs under the profiler's control.
3294 allow running full programs under the profiler's control.
3281
3295
3282 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3296 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3283 mode to report exceptions verbosely but without formatting
3297 mode to report exceptions verbosely but without formatting
3284 variables. This addresses the issue of ipython 'freezing' (it's
3298 variables. This addresses the issue of ipython 'freezing' (it's
3285 not frozen, but caught in an expensive formatting loop) when huge
3299 not frozen, but caught in an expensive formatting loop) when huge
3286 variables are in the context of an exception.
3300 variables are in the context of an exception.
3287 (VerboseTB.text): Added '--->' markers at line where exception was
3301 (VerboseTB.text): Added '--->' markers at line where exception was
3288 triggered. Much clearer to read, especially in NoColor modes.
3302 triggered. Much clearer to read, especially in NoColor modes.
3289
3303
3290 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3304 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3291 implemented in reverse when changing to the new parse_options().
3305 implemented in reverse when changing to the new parse_options().
3292
3306
3293 2002-05-03 Fernando Perez <fperez@colorado.edu>
3307 2002-05-03 Fernando Perez <fperez@colorado.edu>
3294
3308
3295 * IPython/Magic.py (Magic.parse_options): new function so that
3309 * IPython/Magic.py (Magic.parse_options): new function so that
3296 magics can parse options easier.
3310 magics can parse options easier.
3297 (Magic.magic_prun): new function similar to profile.run(),
3311 (Magic.magic_prun): new function similar to profile.run(),
3298 suggested by Chris Hart.
3312 suggested by Chris Hart.
3299 (Magic.magic_cd): fixed behavior so that it only changes if
3313 (Magic.magic_cd): fixed behavior so that it only changes if
3300 directory actually is in history.
3314 directory actually is in history.
3301
3315
3302 * IPython/usage.py (__doc__): added information about potential
3316 * IPython/usage.py (__doc__): added information about potential
3303 slowness of Verbose exception mode when there are huge data
3317 slowness of Verbose exception mode when there are huge data
3304 structures to be formatted (thanks to Archie Paulson).
3318 structures to be formatted (thanks to Archie Paulson).
3305
3319
3306 * IPython/ipmaker.py (make_IPython): Changed default logging
3320 * IPython/ipmaker.py (make_IPython): Changed default logging
3307 (when simply called with -log) to use curr_dir/ipython.log in
3321 (when simply called with -log) to use curr_dir/ipython.log in
3308 rotate mode. Fixed crash which was occuring with -log before
3322 rotate mode. Fixed crash which was occuring with -log before
3309 (thanks to Jim Boyle).
3323 (thanks to Jim Boyle).
3310
3324
3311 2002-05-01 Fernando Perez <fperez@colorado.edu>
3325 2002-05-01 Fernando Perez <fperez@colorado.edu>
3312
3326
3313 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3327 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3314 was nasty -- though somewhat of a corner case).
3328 was nasty -- though somewhat of a corner case).
3315
3329
3316 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3330 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3317 text (was a bug).
3331 text (was a bug).
3318
3332
3319 2002-04-30 Fernando Perez <fperez@colorado.edu>
3333 2002-04-30 Fernando Perez <fperez@colorado.edu>
3320
3334
3321 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3335 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3322 a print after ^D or ^C from the user so that the In[] prompt
3336 a print after ^D or ^C from the user so that the In[] prompt
3323 doesn't over-run the gnuplot one.
3337 doesn't over-run the gnuplot one.
3324
3338
3325 2002-04-29 Fernando Perez <fperez@colorado.edu>
3339 2002-04-29 Fernando Perez <fperez@colorado.edu>
3326
3340
3327 * Released 0.2.10
3341 * Released 0.2.10
3328
3342
3329 * IPython/__release__.py (version): get date dynamically.
3343 * IPython/__release__.py (version): get date dynamically.
3330
3344
3331 * Misc. documentation updates thanks to Arnd's comments. Also ran
3345 * Misc. documentation updates thanks to Arnd's comments. Also ran
3332 a full spellcheck on the manual (hadn't been done in a while).
3346 a full spellcheck on the manual (hadn't been done in a while).
3333
3347
3334 2002-04-27 Fernando Perez <fperez@colorado.edu>
3348 2002-04-27 Fernando Perez <fperez@colorado.edu>
3335
3349
3336 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3350 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3337 starting a log in mid-session would reset the input history list.
3351 starting a log in mid-session would reset the input history list.
3338
3352
3339 2002-04-26 Fernando Perez <fperez@colorado.edu>
3353 2002-04-26 Fernando Perez <fperez@colorado.edu>
3340
3354
3341 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3355 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3342 all files were being included in an update. Now anything in
3356 all files were being included in an update. Now anything in
3343 UserConfig that matches [A-Za-z]*.py will go (this excludes
3357 UserConfig that matches [A-Za-z]*.py will go (this excludes
3344 __init__.py)
3358 __init__.py)
3345
3359
3346 2002-04-25 Fernando Perez <fperez@colorado.edu>
3360 2002-04-25 Fernando Perez <fperez@colorado.edu>
3347
3361
3348 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3362 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3349 to __builtins__ so that any form of embedded or imported code can
3363 to __builtins__ so that any form of embedded or imported code can
3350 test for being inside IPython.
3364 test for being inside IPython.
3351
3365
3352 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3366 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3353 changed to GnuplotMagic because it's now an importable module,
3367 changed to GnuplotMagic because it's now an importable module,
3354 this makes the name follow that of the standard Gnuplot module.
3368 this makes the name follow that of the standard Gnuplot module.
3355 GnuplotMagic can now be loaded at any time in mid-session.
3369 GnuplotMagic can now be loaded at any time in mid-session.
3356
3370
3357 2002-04-24 Fernando Perez <fperez@colorado.edu>
3371 2002-04-24 Fernando Perez <fperez@colorado.edu>
3358
3372
3359 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3373 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3360 the globals (IPython has its own namespace) and the
3374 the globals (IPython has its own namespace) and the
3361 PhysicalQuantity stuff is much better anyway.
3375 PhysicalQuantity stuff is much better anyway.
3362
3376
3363 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3377 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3364 embedding example to standard user directory for
3378 embedding example to standard user directory for
3365 distribution. Also put it in the manual.
3379 distribution. Also put it in the manual.
3366
3380
3367 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3381 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3368 instance as first argument (so it doesn't rely on some obscure
3382 instance as first argument (so it doesn't rely on some obscure
3369 hidden global).
3383 hidden global).
3370
3384
3371 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3385 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3372 delimiters. While it prevents ().TAB from working, it allows
3386 delimiters. While it prevents ().TAB from working, it allows
3373 completions in open (... expressions. This is by far a more common
3387 completions in open (... expressions. This is by far a more common
3374 case.
3388 case.
3375
3389
3376 2002-04-23 Fernando Perez <fperez@colorado.edu>
3390 2002-04-23 Fernando Perez <fperez@colorado.edu>
3377
3391
3378 * IPython/Extensions/InterpreterPasteInput.py: new
3392 * IPython/Extensions/InterpreterPasteInput.py: new
3379 syntax-processing module for pasting lines with >>> or ... at the
3393 syntax-processing module for pasting lines with >>> or ... at the
3380 start.
3394 start.
3381
3395
3382 * IPython/Extensions/PhysicalQ_Interactive.py
3396 * IPython/Extensions/PhysicalQ_Interactive.py
3383 (PhysicalQuantityInteractive.__int__): fixed to work with either
3397 (PhysicalQuantityInteractive.__int__): fixed to work with either
3384 Numeric or math.
3398 Numeric or math.
3385
3399
3386 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3400 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3387 provided profiles. Now we have:
3401 provided profiles. Now we have:
3388 -math -> math module as * and cmath with its own namespace.
3402 -math -> math module as * and cmath with its own namespace.
3389 -numeric -> Numeric as *, plus gnuplot & grace
3403 -numeric -> Numeric as *, plus gnuplot & grace
3390 -physics -> same as before
3404 -physics -> same as before
3391
3405
3392 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3406 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3393 user-defined magics wouldn't be found by @magic if they were
3407 user-defined magics wouldn't be found by @magic if they were
3394 defined as class methods. Also cleaned up the namespace search
3408 defined as class methods. Also cleaned up the namespace search
3395 logic and the string building (to use %s instead of many repeated
3409 logic and the string building (to use %s instead of many repeated
3396 string adds).
3410 string adds).
3397
3411
3398 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3412 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3399 of user-defined magics to operate with class methods (cleaner, in
3413 of user-defined magics to operate with class methods (cleaner, in
3400 line with the gnuplot code).
3414 line with the gnuplot code).
3401
3415
3402 2002-04-22 Fernando Perez <fperez@colorado.edu>
3416 2002-04-22 Fernando Perez <fperez@colorado.edu>
3403
3417
3404 * setup.py: updated dependency list so that manual is updated when
3418 * setup.py: updated dependency list so that manual is updated when
3405 all included files change.
3419 all included files change.
3406
3420
3407 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3421 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3408 the delimiter removal option (the fix is ugly right now).
3422 the delimiter removal option (the fix is ugly right now).
3409
3423
3410 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3424 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3411 all of the math profile (quicker loading, no conflict between
3425 all of the math profile (quicker loading, no conflict between
3412 g-9.8 and g-gnuplot).
3426 g-9.8 and g-gnuplot).
3413
3427
3414 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3428 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3415 name of post-mortem files to IPython_crash_report.txt.
3429 name of post-mortem files to IPython_crash_report.txt.
3416
3430
3417 * Cleanup/update of the docs. Added all the new readline info and
3431 * Cleanup/update of the docs. Added all the new readline info and
3418 formatted all lists as 'real lists'.
3432 formatted all lists as 'real lists'.
3419
3433
3420 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3434 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3421 tab-completion options, since the full readline parse_and_bind is
3435 tab-completion options, since the full readline parse_and_bind is
3422 now accessible.
3436 now accessible.
3423
3437
3424 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3438 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3425 handling of readline options. Now users can specify any string to
3439 handling of readline options. Now users can specify any string to
3426 be passed to parse_and_bind(), as well as the delimiters to be
3440 be passed to parse_and_bind(), as well as the delimiters to be
3427 removed.
3441 removed.
3428 (InteractiveShell.__init__): Added __name__ to the global
3442 (InteractiveShell.__init__): Added __name__ to the global
3429 namespace so that things like Itpl which rely on its existence
3443 namespace so that things like Itpl which rely on its existence
3430 don't crash.
3444 don't crash.
3431 (InteractiveShell._prefilter): Defined the default with a _ so
3445 (InteractiveShell._prefilter): Defined the default with a _ so
3432 that prefilter() is easier to override, while the default one
3446 that prefilter() is easier to override, while the default one
3433 remains available.
3447 remains available.
3434
3448
3435 2002-04-18 Fernando Perez <fperez@colorado.edu>
3449 2002-04-18 Fernando Perez <fperez@colorado.edu>
3436
3450
3437 * Added information about pdb in the docs.
3451 * Added information about pdb in the docs.
3438
3452
3439 2002-04-17 Fernando Perez <fperez@colorado.edu>
3453 2002-04-17 Fernando Perez <fperez@colorado.edu>
3440
3454
3441 * IPython/ipmaker.py (make_IPython): added rc_override option to
3455 * IPython/ipmaker.py (make_IPython): added rc_override option to
3442 allow passing config options at creation time which may override
3456 allow passing config options at creation time which may override
3443 anything set in the config files or command line. This is
3457 anything set in the config files or command line. This is
3444 particularly useful for configuring embedded instances.
3458 particularly useful for configuring embedded instances.
3445
3459
3446 2002-04-15 Fernando Perez <fperez@colorado.edu>
3460 2002-04-15 Fernando Perez <fperez@colorado.edu>
3447
3461
3448 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3462 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3449 crash embedded instances because of the input cache falling out of
3463 crash embedded instances because of the input cache falling out of
3450 sync with the output counter.
3464 sync with the output counter.
3451
3465
3452 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3466 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3453 mode which calls pdb after an uncaught exception in IPython itself.
3467 mode which calls pdb after an uncaught exception in IPython itself.
3454
3468
3455 2002-04-14 Fernando Perez <fperez@colorado.edu>
3469 2002-04-14 Fernando Perez <fperez@colorado.edu>
3456
3470
3457 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3471 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3458 readline, fix it back after each call.
3472 readline, fix it back after each call.
3459
3473
3460 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3474 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3461 method to force all access via __call__(), which guarantees that
3475 method to force all access via __call__(), which guarantees that
3462 traceback references are properly deleted.
3476 traceback references are properly deleted.
3463
3477
3464 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3478 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3465 improve printing when pprint is in use.
3479 improve printing when pprint is in use.
3466
3480
3467 2002-04-13 Fernando Perez <fperez@colorado.edu>
3481 2002-04-13 Fernando Perez <fperez@colorado.edu>
3468
3482
3469 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3483 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3470 exceptions aren't caught anymore. If the user triggers one, he
3484 exceptions aren't caught anymore. If the user triggers one, he
3471 should know why he's doing it and it should go all the way up,
3485 should know why he's doing it and it should go all the way up,
3472 just like any other exception. So now @abort will fully kill the
3486 just like any other exception. So now @abort will fully kill the
3473 embedded interpreter and the embedding code (unless that happens
3487 embedded interpreter and the embedding code (unless that happens
3474 to catch SystemExit).
3488 to catch SystemExit).
3475
3489
3476 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3490 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3477 and a debugger() method to invoke the interactive pdb debugger
3491 and a debugger() method to invoke the interactive pdb debugger
3478 after printing exception information. Also added the corresponding
3492 after printing exception information. Also added the corresponding
3479 -pdb option and @pdb magic to control this feature, and updated
3493 -pdb option and @pdb magic to control this feature, and updated
3480 the docs. After a suggestion from Christopher Hart
3494 the docs. After a suggestion from Christopher Hart
3481 (hart-AT-caltech.edu).
3495 (hart-AT-caltech.edu).
3482
3496
3483 2002-04-12 Fernando Perez <fperez@colorado.edu>
3497 2002-04-12 Fernando Perez <fperez@colorado.edu>
3484
3498
3485 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3499 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3486 the exception handlers defined by the user (not the CrashHandler)
3500 the exception handlers defined by the user (not the CrashHandler)
3487 so that user exceptions don't trigger an ipython bug report.
3501 so that user exceptions don't trigger an ipython bug report.
3488
3502
3489 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3503 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3490 configurable (it should have always been so).
3504 configurable (it should have always been so).
3491
3505
3492 2002-03-26 Fernando Perez <fperez@colorado.edu>
3506 2002-03-26 Fernando Perez <fperez@colorado.edu>
3493
3507
3494 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3508 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3495 and there to fix embedding namespace issues. This should all be
3509 and there to fix embedding namespace issues. This should all be
3496 done in a more elegant way.
3510 done in a more elegant way.
3497
3511
3498 2002-03-25 Fernando Perez <fperez@colorado.edu>
3512 2002-03-25 Fernando Perez <fperez@colorado.edu>
3499
3513
3500 * IPython/genutils.py (get_home_dir): Try to make it work under
3514 * IPython/genutils.py (get_home_dir): Try to make it work under
3501 win9x also.
3515 win9x also.
3502
3516
3503 2002-03-20 Fernando Perez <fperez@colorado.edu>
3517 2002-03-20 Fernando Perez <fperez@colorado.edu>
3504
3518
3505 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3519 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3506 sys.displayhook untouched upon __init__.
3520 sys.displayhook untouched upon __init__.
3507
3521
3508 2002-03-19 Fernando Perez <fperez@colorado.edu>
3522 2002-03-19 Fernando Perez <fperez@colorado.edu>
3509
3523
3510 * Released 0.2.9 (for embedding bug, basically).
3524 * Released 0.2.9 (for embedding bug, basically).
3511
3525
3512 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3526 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3513 exceptions so that enclosing shell's state can be restored.
3527 exceptions so that enclosing shell's state can be restored.
3514
3528
3515 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3529 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3516 naming conventions in the .ipython/ dir.
3530 naming conventions in the .ipython/ dir.
3517
3531
3518 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3532 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3519 from delimiters list so filenames with - in them get expanded.
3533 from delimiters list so filenames with - in them get expanded.
3520
3534
3521 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3535 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3522 sys.displayhook not being properly restored after an embedded call.
3536 sys.displayhook not being properly restored after an embedded call.
3523
3537
3524 2002-03-18 Fernando Perez <fperez@colorado.edu>
3538 2002-03-18 Fernando Perez <fperez@colorado.edu>
3525
3539
3526 * Released 0.2.8
3540 * Released 0.2.8
3527
3541
3528 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3542 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3529 some files weren't being included in a -upgrade.
3543 some files weren't being included in a -upgrade.
3530 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3544 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3531 on' so that the first tab completes.
3545 on' so that the first tab completes.
3532 (InteractiveShell.handle_magic): fixed bug with spaces around
3546 (InteractiveShell.handle_magic): fixed bug with spaces around
3533 quotes breaking many magic commands.
3547 quotes breaking many magic commands.
3534
3548
3535 * setup.py: added note about ignoring the syntax error messages at
3549 * setup.py: added note about ignoring the syntax error messages at
3536 installation.
3550 installation.
3537
3551
3538 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3552 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3539 streamlining the gnuplot interface, now there's only one magic @gp.
3553 streamlining the gnuplot interface, now there's only one magic @gp.
3540
3554
3541 2002-03-17 Fernando Perez <fperez@colorado.edu>
3555 2002-03-17 Fernando Perez <fperez@colorado.edu>
3542
3556
3543 * IPython/UserConfig/magic_gnuplot.py: new name for the
3557 * IPython/UserConfig/magic_gnuplot.py: new name for the
3544 example-magic_pm.py file. Much enhanced system, now with a shell
3558 example-magic_pm.py file. Much enhanced system, now with a shell
3545 for communicating directly with gnuplot, one command at a time.
3559 for communicating directly with gnuplot, one command at a time.
3546
3560
3547 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3561 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3548 setting __name__=='__main__'.
3562 setting __name__=='__main__'.
3549
3563
3550 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3564 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3551 mini-shell for accessing gnuplot from inside ipython. Should
3565 mini-shell for accessing gnuplot from inside ipython. Should
3552 extend it later for grace access too. Inspired by Arnd's
3566 extend it later for grace access too. Inspired by Arnd's
3553 suggestion.
3567 suggestion.
3554
3568
3555 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3569 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3556 calling magic functions with () in their arguments. Thanks to Arnd
3570 calling magic functions with () in their arguments. Thanks to Arnd
3557 Baecker for pointing this to me.
3571 Baecker for pointing this to me.
3558
3572
3559 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3573 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3560 infinitely for integer or complex arrays (only worked with floats).
3574 infinitely for integer or complex arrays (only worked with floats).
3561
3575
3562 2002-03-16 Fernando Perez <fperez@colorado.edu>
3576 2002-03-16 Fernando Perez <fperez@colorado.edu>
3563
3577
3564 * setup.py: Merged setup and setup_windows into a single script
3578 * setup.py: Merged setup and setup_windows into a single script
3565 which properly handles things for windows users.
3579 which properly handles things for windows users.
3566
3580
3567 2002-03-15 Fernando Perez <fperez@colorado.edu>
3581 2002-03-15 Fernando Perez <fperez@colorado.edu>
3568
3582
3569 * Big change to the manual: now the magics are all automatically
3583 * Big change to the manual: now the magics are all automatically
3570 documented. This information is generated from their docstrings
3584 documented. This information is generated from their docstrings
3571 and put in a latex file included by the manual lyx file. This way
3585 and put in a latex file included by the manual lyx file. This way
3572 we get always up to date information for the magics. The manual
3586 we get always up to date information for the magics. The manual
3573 now also has proper version information, also auto-synced.
3587 now also has proper version information, also auto-synced.
3574
3588
3575 For this to work, an undocumented --magic_docstrings option was added.
3589 For this to work, an undocumented --magic_docstrings option was added.
3576
3590
3577 2002-03-13 Fernando Perez <fperez@colorado.edu>
3591 2002-03-13 Fernando Perez <fperez@colorado.edu>
3578
3592
3579 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3593 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3580 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3594 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3581
3595
3582 2002-03-12 Fernando Perez <fperez@colorado.edu>
3596 2002-03-12 Fernando Perez <fperez@colorado.edu>
3583
3597
3584 * IPython/ultraTB.py (TermColors): changed color escapes again to
3598 * IPython/ultraTB.py (TermColors): changed color escapes again to
3585 fix the (old, reintroduced) line-wrapping bug. Basically, if
3599 fix the (old, reintroduced) line-wrapping bug. Basically, if
3586 \001..\002 aren't given in the color escapes, lines get wrapped
3600 \001..\002 aren't given in the color escapes, lines get wrapped
3587 weirdly. But giving those screws up old xterms and emacs terms. So
3601 weirdly. But giving those screws up old xterms and emacs terms. So
3588 I added some logic for emacs terms to be ok, but I can't identify old
3602 I added some logic for emacs terms to be ok, but I can't identify old
3589 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3603 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3590
3604
3591 2002-03-10 Fernando Perez <fperez@colorado.edu>
3605 2002-03-10 Fernando Perez <fperez@colorado.edu>
3592
3606
3593 * IPython/usage.py (__doc__): Various documentation cleanups and
3607 * IPython/usage.py (__doc__): Various documentation cleanups and
3594 updates, both in usage docstrings and in the manual.
3608 updates, both in usage docstrings and in the manual.
3595
3609
3596 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3610 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3597 handling of caching. Set minimum acceptabe value for having a
3611 handling of caching. Set minimum acceptabe value for having a
3598 cache at 20 values.
3612 cache at 20 values.
3599
3613
3600 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3614 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3601 install_first_time function to a method, renamed it and added an
3615 install_first_time function to a method, renamed it and added an
3602 'upgrade' mode. Now people can update their config directory with
3616 'upgrade' mode. Now people can update their config directory with
3603 a simple command line switch (-upgrade, also new).
3617 a simple command line switch (-upgrade, also new).
3604
3618
3605 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3619 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3606 @file (convenient for automagic users under Python >= 2.2).
3620 @file (convenient for automagic users under Python >= 2.2).
3607 Removed @files (it seemed more like a plural than an abbrev. of
3621 Removed @files (it seemed more like a plural than an abbrev. of
3608 'file show').
3622 'file show').
3609
3623
3610 * IPython/iplib.py (install_first_time): Fixed crash if there were
3624 * IPython/iplib.py (install_first_time): Fixed crash if there were
3611 backup files ('~') in .ipython/ install directory.
3625 backup files ('~') in .ipython/ install directory.
3612
3626
3613 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3627 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3614 system. Things look fine, but these changes are fairly
3628 system. Things look fine, but these changes are fairly
3615 intrusive. Test them for a few days.
3629 intrusive. Test them for a few days.
3616
3630
3617 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3631 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3618 the prompts system. Now all in/out prompt strings are user
3632 the prompts system. Now all in/out prompt strings are user
3619 controllable. This is particularly useful for embedding, as one
3633 controllable. This is particularly useful for embedding, as one
3620 can tag embedded instances with particular prompts.
3634 can tag embedded instances with particular prompts.
3621
3635
3622 Also removed global use of sys.ps1/2, which now allows nested
3636 Also removed global use of sys.ps1/2, which now allows nested
3623 embeddings without any problems. Added command-line options for
3637 embeddings without any problems. Added command-line options for
3624 the prompt strings.
3638 the prompt strings.
3625
3639
3626 2002-03-08 Fernando Perez <fperez@colorado.edu>
3640 2002-03-08 Fernando Perez <fperez@colorado.edu>
3627
3641
3628 * IPython/UserConfig/example-embed-short.py (ipshell): added
3642 * IPython/UserConfig/example-embed-short.py (ipshell): added
3629 example file with the bare minimum code for embedding.
3643 example file with the bare minimum code for embedding.
3630
3644
3631 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3645 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3632 functionality for the embeddable shell to be activated/deactivated
3646 functionality for the embeddable shell to be activated/deactivated
3633 either globally or at each call.
3647 either globally or at each call.
3634
3648
3635 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3649 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3636 rewriting the prompt with '--->' for auto-inputs with proper
3650 rewriting the prompt with '--->' for auto-inputs with proper
3637 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3651 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3638 this is handled by the prompts class itself, as it should.
3652 this is handled by the prompts class itself, as it should.
3639
3653
3640 2002-03-05 Fernando Perez <fperez@colorado.edu>
3654 2002-03-05 Fernando Perez <fperez@colorado.edu>
3641
3655
3642 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3656 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3643 @logstart to avoid name clashes with the math log function.
3657 @logstart to avoid name clashes with the math log function.
3644
3658
3645 * Big updates to X/Emacs section of the manual.
3659 * Big updates to X/Emacs section of the manual.
3646
3660
3647 * Removed ipython_emacs. Milan explained to me how to pass
3661 * Removed ipython_emacs. Milan explained to me how to pass
3648 arguments to ipython through Emacs. Some day I'm going to end up
3662 arguments to ipython through Emacs. Some day I'm going to end up
3649 learning some lisp...
3663 learning some lisp...
3650
3664
3651 2002-03-04 Fernando Perez <fperez@colorado.edu>
3665 2002-03-04 Fernando Perez <fperez@colorado.edu>
3652
3666
3653 * IPython/ipython_emacs: Created script to be used as the
3667 * IPython/ipython_emacs: Created script to be used as the
3654 py-python-command Emacs variable so we can pass IPython
3668 py-python-command Emacs variable so we can pass IPython
3655 parameters. I can't figure out how to tell Emacs directly to pass
3669 parameters. I can't figure out how to tell Emacs directly to pass
3656 parameters to IPython, so a dummy shell script will do it.
3670 parameters to IPython, so a dummy shell script will do it.
3657
3671
3658 Other enhancements made for things to work better under Emacs'
3672 Other enhancements made for things to work better under Emacs'
3659 various types of terminals. Many thanks to Milan Zamazal
3673 various types of terminals. Many thanks to Milan Zamazal
3660 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3674 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3661
3675
3662 2002-03-01 Fernando Perez <fperez@colorado.edu>
3676 2002-03-01 Fernando Perez <fperez@colorado.edu>
3663
3677
3664 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3678 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3665 that loading of readline is now optional. This gives better
3679 that loading of readline is now optional. This gives better
3666 control to emacs users.
3680 control to emacs users.
3667
3681
3668 * IPython/ultraTB.py (__date__): Modified color escape sequences
3682 * IPython/ultraTB.py (__date__): Modified color escape sequences
3669 and now things work fine under xterm and in Emacs' term buffers
3683 and now things work fine under xterm and in Emacs' term buffers
3670 (though not shell ones). Well, in emacs you get colors, but all
3684 (though not shell ones). Well, in emacs you get colors, but all
3671 seem to be 'light' colors (no difference between dark and light
3685 seem to be 'light' colors (no difference between dark and light
3672 ones). But the garbage chars are gone, and also in xterms. It
3686 ones). But the garbage chars are gone, and also in xterms. It
3673 seems that now I'm using 'cleaner' ansi sequences.
3687 seems that now I'm using 'cleaner' ansi sequences.
3674
3688
3675 2002-02-21 Fernando Perez <fperez@colorado.edu>
3689 2002-02-21 Fernando Perez <fperez@colorado.edu>
3676
3690
3677 * Released 0.2.7 (mainly to publish the scoping fix).
3691 * Released 0.2.7 (mainly to publish the scoping fix).
3678
3692
3679 * IPython/Logger.py (Logger.logstate): added. A corresponding
3693 * IPython/Logger.py (Logger.logstate): added. A corresponding
3680 @logstate magic was created.
3694 @logstate magic was created.
3681
3695
3682 * IPython/Magic.py: fixed nested scoping problem under Python
3696 * IPython/Magic.py: fixed nested scoping problem under Python
3683 2.1.x (automagic wasn't working).
3697 2.1.x (automagic wasn't working).
3684
3698
3685 2002-02-20 Fernando Perez <fperez@colorado.edu>
3699 2002-02-20 Fernando Perez <fperez@colorado.edu>
3686
3700
3687 * Released 0.2.6.
3701 * Released 0.2.6.
3688
3702
3689 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3703 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3690 option so that logs can come out without any headers at all.
3704 option so that logs can come out without any headers at all.
3691
3705
3692 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3706 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3693 SciPy.
3707 SciPy.
3694
3708
3695 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3709 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3696 that embedded IPython calls don't require vars() to be explicitly
3710 that embedded IPython calls don't require vars() to be explicitly
3697 passed. Now they are extracted from the caller's frame (code
3711 passed. Now they are extracted from the caller's frame (code
3698 snatched from Eric Jones' weave). Added better documentation to
3712 snatched from Eric Jones' weave). Added better documentation to
3699 the section on embedding and the example file.
3713 the section on embedding and the example file.
3700
3714
3701 * IPython/genutils.py (page): Changed so that under emacs, it just
3715 * IPython/genutils.py (page): Changed so that under emacs, it just
3702 prints the string. You can then page up and down in the emacs
3716 prints the string. You can then page up and down in the emacs
3703 buffer itself. This is how the builtin help() works.
3717 buffer itself. This is how the builtin help() works.
3704
3718
3705 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3719 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3706 macro scoping: macros need to be executed in the user's namespace
3720 macro scoping: macros need to be executed in the user's namespace
3707 to work as if they had been typed by the user.
3721 to work as if they had been typed by the user.
3708
3722
3709 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3723 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3710 execute automatically (no need to type 'exec...'). They then
3724 execute automatically (no need to type 'exec...'). They then
3711 behave like 'true macros'. The printing system was also modified
3725 behave like 'true macros'. The printing system was also modified
3712 for this to work.
3726 for this to work.
3713
3727
3714 2002-02-19 Fernando Perez <fperez@colorado.edu>
3728 2002-02-19 Fernando Perez <fperez@colorado.edu>
3715
3729
3716 * IPython/genutils.py (page_file): new function for paging files
3730 * IPython/genutils.py (page_file): new function for paging files
3717 in an OS-independent way. Also necessary for file viewing to work
3731 in an OS-independent way. Also necessary for file viewing to work
3718 well inside Emacs buffers.
3732 well inside Emacs buffers.
3719 (page): Added checks for being in an emacs buffer.
3733 (page): Added checks for being in an emacs buffer.
3720 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3734 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3721 same bug in iplib.
3735 same bug in iplib.
3722
3736
3723 2002-02-18 Fernando Perez <fperez@colorado.edu>
3737 2002-02-18 Fernando Perez <fperez@colorado.edu>
3724
3738
3725 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3739 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3726 of readline so that IPython can work inside an Emacs buffer.
3740 of readline so that IPython can work inside an Emacs buffer.
3727
3741
3728 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3742 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3729 method signatures (they weren't really bugs, but it looks cleaner
3743 method signatures (they weren't really bugs, but it looks cleaner
3730 and keeps PyChecker happy).
3744 and keeps PyChecker happy).
3731
3745
3732 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3746 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3733 for implementing various user-defined hooks. Currently only
3747 for implementing various user-defined hooks. Currently only
3734 display is done.
3748 display is done.
3735
3749
3736 * IPython/Prompts.py (CachedOutput._display): changed display
3750 * IPython/Prompts.py (CachedOutput._display): changed display
3737 functions so that they can be dynamically changed by users easily.
3751 functions so that they can be dynamically changed by users easily.
3738
3752
3739 * IPython/Extensions/numeric_formats.py (num_display): added an
3753 * IPython/Extensions/numeric_formats.py (num_display): added an
3740 extension for printing NumPy arrays in flexible manners. It
3754 extension for printing NumPy arrays in flexible manners. It
3741 doesn't do anything yet, but all the structure is in
3755 doesn't do anything yet, but all the structure is in
3742 place. Ultimately the plan is to implement output format control
3756 place. Ultimately the plan is to implement output format control
3743 like in Octave.
3757 like in Octave.
3744
3758
3745 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3759 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3746 methods are found at run-time by all the automatic machinery.
3760 methods are found at run-time by all the automatic machinery.
3747
3761
3748 2002-02-17 Fernando Perez <fperez@colorado.edu>
3762 2002-02-17 Fernando Perez <fperez@colorado.edu>
3749
3763
3750 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3764 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3751 whole file a little.
3765 whole file a little.
3752
3766
3753 * ToDo: closed this document. Now there's a new_design.lyx
3767 * ToDo: closed this document. Now there's a new_design.lyx
3754 document for all new ideas. Added making a pdf of it for the
3768 document for all new ideas. Added making a pdf of it for the
3755 end-user distro.
3769 end-user distro.
3756
3770
3757 * IPython/Logger.py (Logger.switch_log): Created this to replace
3771 * IPython/Logger.py (Logger.switch_log): Created this to replace
3758 logon() and logoff(). It also fixes a nasty crash reported by
3772 logon() and logoff(). It also fixes a nasty crash reported by
3759 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3773 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3760
3774
3761 * IPython/iplib.py (complete): got auto-completion to work with
3775 * IPython/iplib.py (complete): got auto-completion to work with
3762 automagic (I had wanted this for a long time).
3776 automagic (I had wanted this for a long time).
3763
3777
3764 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3778 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3765 to @file, since file() is now a builtin and clashes with automagic
3779 to @file, since file() is now a builtin and clashes with automagic
3766 for @file.
3780 for @file.
3767
3781
3768 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3782 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3769 of this was previously in iplib, which had grown to more than 2000
3783 of this was previously in iplib, which had grown to more than 2000
3770 lines, way too long. No new functionality, but it makes managing
3784 lines, way too long. No new functionality, but it makes managing
3771 the code a bit easier.
3785 the code a bit easier.
3772
3786
3773 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3787 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3774 information to crash reports.
3788 information to crash reports.
3775
3789
3776 2002-02-12 Fernando Perez <fperez@colorado.edu>
3790 2002-02-12 Fernando Perez <fperez@colorado.edu>
3777
3791
3778 * Released 0.2.5.
3792 * Released 0.2.5.
3779
3793
3780 2002-02-11 Fernando Perez <fperez@colorado.edu>
3794 2002-02-11 Fernando Perez <fperez@colorado.edu>
3781
3795
3782 * Wrote a relatively complete Windows installer. It puts
3796 * Wrote a relatively complete Windows installer. It puts
3783 everything in place, creates Start Menu entries and fixes the
3797 everything in place, creates Start Menu entries and fixes the
3784 color issues. Nothing fancy, but it works.
3798 color issues. Nothing fancy, but it works.
3785
3799
3786 2002-02-10 Fernando Perez <fperez@colorado.edu>
3800 2002-02-10 Fernando Perez <fperez@colorado.edu>
3787
3801
3788 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3802 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3789 os.path.expanduser() call so that we can type @run ~/myfile.py and
3803 os.path.expanduser() call so that we can type @run ~/myfile.py and
3790 have thigs work as expected.
3804 have thigs work as expected.
3791
3805
3792 * IPython/genutils.py (page): fixed exception handling so things
3806 * IPython/genutils.py (page): fixed exception handling so things
3793 work both in Unix and Windows correctly. Quitting a pager triggers
3807 work both in Unix and Windows correctly. Quitting a pager triggers
3794 an IOError/broken pipe in Unix, and in windows not finding a pager
3808 an IOError/broken pipe in Unix, and in windows not finding a pager
3795 is also an IOError, so I had to actually look at the return value
3809 is also an IOError, so I had to actually look at the return value
3796 of the exception, not just the exception itself. Should be ok now.
3810 of the exception, not just the exception itself. Should be ok now.
3797
3811
3798 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3812 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3799 modified to allow case-insensitive color scheme changes.
3813 modified to allow case-insensitive color scheme changes.
3800
3814
3801 2002-02-09 Fernando Perez <fperez@colorado.edu>
3815 2002-02-09 Fernando Perez <fperez@colorado.edu>
3802
3816
3803 * IPython/genutils.py (native_line_ends): new function to leave
3817 * IPython/genutils.py (native_line_ends): new function to leave
3804 user config files with os-native line-endings.
3818 user config files with os-native line-endings.
3805
3819
3806 * README and manual updates.
3820 * README and manual updates.
3807
3821
3808 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3822 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3809 instead of StringType to catch Unicode strings.
3823 instead of StringType to catch Unicode strings.
3810
3824
3811 * IPython/genutils.py (filefind): fixed bug for paths with
3825 * IPython/genutils.py (filefind): fixed bug for paths with
3812 embedded spaces (very common in Windows).
3826 embedded spaces (very common in Windows).
3813
3827
3814 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3828 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3815 files under Windows, so that they get automatically associated
3829 files under Windows, so that they get automatically associated
3816 with a text editor. Windows makes it a pain to handle
3830 with a text editor. Windows makes it a pain to handle
3817 extension-less files.
3831 extension-less files.
3818
3832
3819 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3833 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3820 warning about readline only occur for Posix. In Windows there's no
3834 warning about readline only occur for Posix. In Windows there's no
3821 way to get readline, so why bother with the warning.
3835 way to get readline, so why bother with the warning.
3822
3836
3823 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3837 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3824 for __str__ instead of dir(self), since dir() changed in 2.2.
3838 for __str__ instead of dir(self), since dir() changed in 2.2.
3825
3839
3826 * Ported to Windows! Tested on XP, I suspect it should work fine
3840 * Ported to Windows! Tested on XP, I suspect it should work fine
3827 on NT/2000, but I don't think it will work on 98 et al. That
3841 on NT/2000, but I don't think it will work on 98 et al. That
3828 series of Windows is such a piece of junk anyway that I won't try
3842 series of Windows is such a piece of junk anyway that I won't try
3829 porting it there. The XP port was straightforward, showed a few
3843 porting it there. The XP port was straightforward, showed a few
3830 bugs here and there (fixed all), in particular some string
3844 bugs here and there (fixed all), in particular some string
3831 handling stuff which required considering Unicode strings (which
3845 handling stuff which required considering Unicode strings (which
3832 Windows uses). This is good, but hasn't been too tested :) No
3846 Windows uses). This is good, but hasn't been too tested :) No
3833 fancy installer yet, I'll put a note in the manual so people at
3847 fancy installer yet, I'll put a note in the manual so people at
3834 least make manually a shortcut.
3848 least make manually a shortcut.
3835
3849
3836 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3850 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3837 into a single one, "colors". This now controls both prompt and
3851 into a single one, "colors". This now controls both prompt and
3838 exception color schemes, and can be changed both at startup
3852 exception color schemes, and can be changed both at startup
3839 (either via command-line switches or via ipythonrc files) and at
3853 (either via command-line switches or via ipythonrc files) and at
3840 runtime, with @colors.
3854 runtime, with @colors.
3841 (Magic.magic_run): renamed @prun to @run and removed the old
3855 (Magic.magic_run): renamed @prun to @run and removed the old
3842 @run. The two were too similar to warrant keeping both.
3856 @run. The two were too similar to warrant keeping both.
3843
3857
3844 2002-02-03 Fernando Perez <fperez@colorado.edu>
3858 2002-02-03 Fernando Perez <fperez@colorado.edu>
3845
3859
3846 * IPython/iplib.py (install_first_time): Added comment on how to
3860 * IPython/iplib.py (install_first_time): Added comment on how to
3847 configure the color options for first-time users. Put a <return>
3861 configure the color options for first-time users. Put a <return>
3848 request at the end so that small-terminal users get a chance to
3862 request at the end so that small-terminal users get a chance to
3849 read the startup info.
3863 read the startup info.
3850
3864
3851 2002-01-23 Fernando Perez <fperez@colorado.edu>
3865 2002-01-23 Fernando Perez <fperez@colorado.edu>
3852
3866
3853 * IPython/iplib.py (CachedOutput.update): Changed output memory
3867 * IPython/iplib.py (CachedOutput.update): Changed output memory
3854 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3868 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3855 input history we still use _i. Did this b/c these variable are
3869 input history we still use _i. Did this b/c these variable are
3856 very commonly used in interactive work, so the less we need to
3870 very commonly used in interactive work, so the less we need to
3857 type the better off we are.
3871 type the better off we are.
3858 (Magic.magic_prun): updated @prun to better handle the namespaces
3872 (Magic.magic_prun): updated @prun to better handle the namespaces
3859 the file will run in, including a fix for __name__ not being set
3873 the file will run in, including a fix for __name__ not being set
3860 before.
3874 before.
3861
3875
3862 2002-01-20 Fernando Perez <fperez@colorado.edu>
3876 2002-01-20 Fernando Perez <fperez@colorado.edu>
3863
3877
3864 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3878 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3865 extra garbage for Python 2.2. Need to look more carefully into
3879 extra garbage for Python 2.2. Need to look more carefully into
3866 this later.
3880 this later.
3867
3881
3868 2002-01-19 Fernando Perez <fperez@colorado.edu>
3882 2002-01-19 Fernando Perez <fperez@colorado.edu>
3869
3883
3870 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3884 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3871 display SyntaxError exceptions properly formatted when they occur
3885 display SyntaxError exceptions properly formatted when they occur
3872 (they can be triggered by imported code).
3886 (they can be triggered by imported code).
3873
3887
3874 2002-01-18 Fernando Perez <fperez@colorado.edu>
3888 2002-01-18 Fernando Perez <fperez@colorado.edu>
3875
3889
3876 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3890 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3877 SyntaxError exceptions are reported nicely formatted, instead of
3891 SyntaxError exceptions are reported nicely formatted, instead of
3878 spitting out only offset information as before.
3892 spitting out only offset information as before.
3879 (Magic.magic_prun): Added the @prun function for executing
3893 (Magic.magic_prun): Added the @prun function for executing
3880 programs with command line args inside IPython.
3894 programs with command line args inside IPython.
3881
3895
3882 2002-01-16 Fernando Perez <fperez@colorado.edu>
3896 2002-01-16 Fernando Perez <fperez@colorado.edu>
3883
3897
3884 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3898 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3885 to *not* include the last item given in a range. This brings their
3899 to *not* include the last item given in a range. This brings their
3886 behavior in line with Python's slicing:
3900 behavior in line with Python's slicing:
3887 a[n1:n2] -> a[n1]...a[n2-1]
3901 a[n1:n2] -> a[n1]...a[n2-1]
3888 It may be a bit less convenient, but I prefer to stick to Python's
3902 It may be a bit less convenient, but I prefer to stick to Python's
3889 conventions *everywhere*, so users never have to wonder.
3903 conventions *everywhere*, so users never have to wonder.
3890 (Magic.magic_macro): Added @macro function to ease the creation of
3904 (Magic.magic_macro): Added @macro function to ease the creation of
3891 macros.
3905 macros.
3892
3906
3893 2002-01-05 Fernando Perez <fperez@colorado.edu>
3907 2002-01-05 Fernando Perez <fperez@colorado.edu>
3894
3908
3895 * Released 0.2.4.
3909 * Released 0.2.4.
3896
3910
3897 * IPython/iplib.py (Magic.magic_pdef):
3911 * IPython/iplib.py (Magic.magic_pdef):
3898 (InteractiveShell.safe_execfile): report magic lines and error
3912 (InteractiveShell.safe_execfile): report magic lines and error
3899 lines without line numbers so one can easily copy/paste them for
3913 lines without line numbers so one can easily copy/paste them for
3900 re-execution.
3914 re-execution.
3901
3915
3902 * Updated manual with recent changes.
3916 * Updated manual with recent changes.
3903
3917
3904 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3918 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3905 docstring printing when class? is called. Very handy for knowing
3919 docstring printing when class? is called. Very handy for knowing
3906 how to create class instances (as long as __init__ is well
3920 how to create class instances (as long as __init__ is well
3907 documented, of course :)
3921 documented, of course :)
3908 (Magic.magic_doc): print both class and constructor docstrings.
3922 (Magic.magic_doc): print both class and constructor docstrings.
3909 (Magic.magic_pdef): give constructor info if passed a class and
3923 (Magic.magic_pdef): give constructor info if passed a class and
3910 __call__ info for callable object instances.
3924 __call__ info for callable object instances.
3911
3925
3912 2002-01-04 Fernando Perez <fperez@colorado.edu>
3926 2002-01-04 Fernando Perez <fperez@colorado.edu>
3913
3927
3914 * Made deep_reload() off by default. It doesn't always work
3928 * Made deep_reload() off by default. It doesn't always work
3915 exactly as intended, so it's probably safer to have it off. It's
3929 exactly as intended, so it's probably safer to have it off. It's
3916 still available as dreload() anyway, so nothing is lost.
3930 still available as dreload() anyway, so nothing is lost.
3917
3931
3918 2002-01-02 Fernando Perez <fperez@colorado.edu>
3932 2002-01-02 Fernando Perez <fperez@colorado.edu>
3919
3933
3920 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3934 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3921 so I wanted an updated release).
3935 so I wanted an updated release).
3922
3936
3923 2001-12-27 Fernando Perez <fperez@colorado.edu>
3937 2001-12-27 Fernando Perez <fperez@colorado.edu>
3924
3938
3925 * IPython/iplib.py (InteractiveShell.interact): Added the original
3939 * IPython/iplib.py (InteractiveShell.interact): Added the original
3926 code from 'code.py' for this module in order to change the
3940 code from 'code.py' for this module in order to change the
3927 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3941 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3928 the history cache would break when the user hit Ctrl-C, and
3942 the history cache would break when the user hit Ctrl-C, and
3929 interact() offers no way to add any hooks to it.
3943 interact() offers no way to add any hooks to it.
3930
3944
3931 2001-12-23 Fernando Perez <fperez@colorado.edu>
3945 2001-12-23 Fernando Perez <fperez@colorado.edu>
3932
3946
3933 * setup.py: added check for 'MANIFEST' before trying to remove
3947 * setup.py: added check for 'MANIFEST' before trying to remove
3934 it. Thanks to Sean Reifschneider.
3948 it. Thanks to Sean Reifschneider.
3935
3949
3936 2001-12-22 Fernando Perez <fperez@colorado.edu>
3950 2001-12-22 Fernando Perez <fperez@colorado.edu>
3937
3951
3938 * Released 0.2.2.
3952 * Released 0.2.2.
3939
3953
3940 * Finished (reasonably) writing the manual. Later will add the
3954 * Finished (reasonably) writing the manual. Later will add the
3941 python-standard navigation stylesheets, but for the time being
3955 python-standard navigation stylesheets, but for the time being
3942 it's fairly complete. Distribution will include html and pdf
3956 it's fairly complete. Distribution will include html and pdf
3943 versions.
3957 versions.
3944
3958
3945 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3959 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3946 (MayaVi author).
3960 (MayaVi author).
3947
3961
3948 2001-12-21 Fernando Perez <fperez@colorado.edu>
3962 2001-12-21 Fernando Perez <fperez@colorado.edu>
3949
3963
3950 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3964 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3951 good public release, I think (with the manual and the distutils
3965 good public release, I think (with the manual and the distutils
3952 installer). The manual can use some work, but that can go
3966 installer). The manual can use some work, but that can go
3953 slowly. Otherwise I think it's quite nice for end users. Next
3967 slowly. Otherwise I think it's quite nice for end users. Next
3954 summer, rewrite the guts of it...
3968 summer, rewrite the guts of it...
3955
3969
3956 * Changed format of ipythonrc files to use whitespace as the
3970 * Changed format of ipythonrc files to use whitespace as the
3957 separator instead of an explicit '='. Cleaner.
3971 separator instead of an explicit '='. Cleaner.
3958
3972
3959 2001-12-20 Fernando Perez <fperez@colorado.edu>
3973 2001-12-20 Fernando Perez <fperez@colorado.edu>
3960
3974
3961 * Started a manual in LyX. For now it's just a quick merge of the
3975 * Started a manual in LyX. For now it's just a quick merge of the
3962 various internal docstrings and READMEs. Later it may grow into a
3976 various internal docstrings and READMEs. Later it may grow into a
3963 nice, full-blown manual.
3977 nice, full-blown manual.
3964
3978
3965 * Set up a distutils based installer. Installation should now be
3979 * Set up a distutils based installer. Installation should now be
3966 trivially simple for end-users.
3980 trivially simple for end-users.
3967
3981
3968 2001-12-11 Fernando Perez <fperez@colorado.edu>
3982 2001-12-11 Fernando Perez <fperez@colorado.edu>
3969
3983
3970 * Released 0.2.0. First public release, announced it at
3984 * Released 0.2.0. First public release, announced it at
3971 comp.lang.python. From now on, just bugfixes...
3985 comp.lang.python. From now on, just bugfixes...
3972
3986
3973 * Went through all the files, set copyright/license notices and
3987 * Went through all the files, set copyright/license notices and
3974 cleaned up things. Ready for release.
3988 cleaned up things. Ready for release.
3975
3989
3976 2001-12-10 Fernando Perez <fperez@colorado.edu>
3990 2001-12-10 Fernando Perez <fperez@colorado.edu>
3977
3991
3978 * Changed the first-time installer not to use tarfiles. It's more
3992 * Changed the first-time installer not to use tarfiles. It's more
3979 robust now and less unix-dependent. Also makes it easier for
3993 robust now and less unix-dependent. Also makes it easier for
3980 people to later upgrade versions.
3994 people to later upgrade versions.
3981
3995
3982 * Changed @exit to @abort to reflect the fact that it's pretty
3996 * Changed @exit to @abort to reflect the fact that it's pretty
3983 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3997 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3984 becomes significant only when IPyhton is embedded: in that case,
3998 becomes significant only when IPyhton is embedded: in that case,
3985 C-D closes IPython only, but @abort kills the enclosing program
3999 C-D closes IPython only, but @abort kills the enclosing program
3986 too (unless it had called IPython inside a try catching
4000 too (unless it had called IPython inside a try catching
3987 SystemExit).
4001 SystemExit).
3988
4002
3989 * Created Shell module which exposes the actuall IPython Shell
4003 * Created Shell module which exposes the actuall IPython Shell
3990 classes, currently the normal and the embeddable one. This at
4004 classes, currently the normal and the embeddable one. This at
3991 least offers a stable interface we won't need to change when
4005 least offers a stable interface we won't need to change when
3992 (later) the internals are rewritten. That rewrite will be confined
4006 (later) the internals are rewritten. That rewrite will be confined
3993 to iplib and ipmaker, but the Shell interface should remain as is.
4007 to iplib and ipmaker, but the Shell interface should remain as is.
3994
4008
3995 * Added embed module which offers an embeddable IPShell object,
4009 * Added embed module which offers an embeddable IPShell object,
3996 useful to fire up IPython *inside* a running program. Great for
4010 useful to fire up IPython *inside* a running program. Great for
3997 debugging or dynamical data analysis.
4011 debugging or dynamical data analysis.
3998
4012
3999 2001-12-08 Fernando Perez <fperez@colorado.edu>
4013 2001-12-08 Fernando Perez <fperez@colorado.edu>
4000
4014
4001 * Fixed small bug preventing seeing info from methods of defined
4015 * Fixed small bug preventing seeing info from methods of defined
4002 objects (incorrect namespace in _ofind()).
4016 objects (incorrect namespace in _ofind()).
4003
4017
4004 * Documentation cleanup. Moved the main usage docstrings to a
4018 * Documentation cleanup. Moved the main usage docstrings to a
4005 separate file, usage.py (cleaner to maintain, and hopefully in the
4019 separate file, usage.py (cleaner to maintain, and hopefully in the
4006 future some perlpod-like way of producing interactive, man and
4020 future some perlpod-like way of producing interactive, man and
4007 html docs out of it will be found).
4021 html docs out of it will be found).
4008
4022
4009 * Added @profile to see your profile at any time.
4023 * Added @profile to see your profile at any time.
4010
4024
4011 * Added @p as an alias for 'print'. It's especially convenient if
4025 * Added @p as an alias for 'print'. It's especially convenient if
4012 using automagic ('p x' prints x).
4026 using automagic ('p x' prints x).
4013
4027
4014 * Small cleanups and fixes after a pychecker run.
4028 * Small cleanups and fixes after a pychecker run.
4015
4029
4016 * Changed the @cd command to handle @cd - and @cd -<n> for
4030 * Changed the @cd command to handle @cd - and @cd -<n> for
4017 visiting any directory in _dh.
4031 visiting any directory in _dh.
4018
4032
4019 * Introduced _dh, a history of visited directories. @dhist prints
4033 * Introduced _dh, a history of visited directories. @dhist prints
4020 it out with numbers.
4034 it out with numbers.
4021
4035
4022 2001-12-07 Fernando Perez <fperez@colorado.edu>
4036 2001-12-07 Fernando Perez <fperez@colorado.edu>
4023
4037
4024 * Released 0.1.22
4038 * Released 0.1.22
4025
4039
4026 * Made initialization a bit more robust against invalid color
4040 * Made initialization a bit more robust against invalid color
4027 options in user input (exit, not traceback-crash).
4041 options in user input (exit, not traceback-crash).
4028
4042
4029 * Changed the bug crash reporter to write the report only in the
4043 * Changed the bug crash reporter to write the report only in the
4030 user's .ipython directory. That way IPython won't litter people's
4044 user's .ipython directory. That way IPython won't litter people's
4031 hard disks with crash files all over the place. Also print on
4045 hard disks with crash files all over the place. Also print on
4032 screen the necessary mail command.
4046 screen the necessary mail command.
4033
4047
4034 * With the new ultraTB, implemented LightBG color scheme for light
4048 * With the new ultraTB, implemented LightBG color scheme for light
4035 background terminals. A lot of people like white backgrounds, so I
4049 background terminals. A lot of people like white backgrounds, so I
4036 guess we should at least give them something readable.
4050 guess we should at least give them something readable.
4037
4051
4038 2001-12-06 Fernando Perez <fperez@colorado.edu>
4052 2001-12-06 Fernando Perez <fperez@colorado.edu>
4039
4053
4040 * Modified the structure of ultraTB. Now there's a proper class
4054 * Modified the structure of ultraTB. Now there's a proper class
4041 for tables of color schemes which allow adding schemes easily and
4055 for tables of color schemes which allow adding schemes easily and
4042 switching the active scheme without creating a new instance every
4056 switching the active scheme without creating a new instance every
4043 time (which was ridiculous). The syntax for creating new schemes
4057 time (which was ridiculous). The syntax for creating new schemes
4044 is also cleaner. I think ultraTB is finally done, with a clean
4058 is also cleaner. I think ultraTB is finally done, with a clean
4045 class structure. Names are also much cleaner (now there's proper
4059 class structure. Names are also much cleaner (now there's proper
4046 color tables, no need for every variable to also have 'color' in
4060 color tables, no need for every variable to also have 'color' in
4047 its name).
4061 its name).
4048
4062
4049 * Broke down genutils into separate files. Now genutils only
4063 * Broke down genutils into separate files. Now genutils only
4050 contains utility functions, and classes have been moved to their
4064 contains utility functions, and classes have been moved to their
4051 own files (they had enough independent functionality to warrant
4065 own files (they had enough independent functionality to warrant
4052 it): ConfigLoader, OutputTrap, Struct.
4066 it): ConfigLoader, OutputTrap, Struct.
4053
4067
4054 2001-12-05 Fernando Perez <fperez@colorado.edu>
4068 2001-12-05 Fernando Perez <fperez@colorado.edu>
4055
4069
4056 * IPython turns 21! Released version 0.1.21, as a candidate for
4070 * IPython turns 21! Released version 0.1.21, as a candidate for
4057 public consumption. If all goes well, release in a few days.
4071 public consumption. If all goes well, release in a few days.
4058
4072
4059 * Fixed path bug (files in Extensions/ directory wouldn't be found
4073 * Fixed path bug (files in Extensions/ directory wouldn't be found
4060 unless IPython/ was explicitly in sys.path).
4074 unless IPython/ was explicitly in sys.path).
4061
4075
4062 * Extended the FlexCompleter class as MagicCompleter to allow
4076 * Extended the FlexCompleter class as MagicCompleter to allow
4063 completion of @-starting lines.
4077 completion of @-starting lines.
4064
4078
4065 * Created __release__.py file as a central repository for release
4079 * Created __release__.py file as a central repository for release
4066 info that other files can read from.
4080 info that other files can read from.
4067
4081
4068 * Fixed small bug in logging: when logging was turned on in
4082 * Fixed small bug in logging: when logging was turned on in
4069 mid-session, old lines with special meanings (!@?) were being
4083 mid-session, old lines with special meanings (!@?) were being
4070 logged without the prepended comment, which is necessary since
4084 logged without the prepended comment, which is necessary since
4071 they are not truly valid python syntax. This should make session
4085 they are not truly valid python syntax. This should make session
4072 restores produce less errors.
4086 restores produce less errors.
4073
4087
4074 * The namespace cleanup forced me to make a FlexCompleter class
4088 * The namespace cleanup forced me to make a FlexCompleter class
4075 which is nothing but a ripoff of rlcompleter, but with selectable
4089 which is nothing but a ripoff of rlcompleter, but with selectable
4076 namespace (rlcompleter only works in __main__.__dict__). I'll try
4090 namespace (rlcompleter only works in __main__.__dict__). I'll try
4077 to submit a note to the authors to see if this change can be
4091 to submit a note to the authors to see if this change can be
4078 incorporated in future rlcompleter releases (Dec.6: done)
4092 incorporated in future rlcompleter releases (Dec.6: done)
4079
4093
4080 * More fixes to namespace handling. It was a mess! Now all
4094 * More fixes to namespace handling. It was a mess! Now all
4081 explicit references to __main__.__dict__ are gone (except when
4095 explicit references to __main__.__dict__ are gone (except when
4082 really needed) and everything is handled through the namespace
4096 really needed) and everything is handled through the namespace
4083 dicts in the IPython instance. We seem to be getting somewhere
4097 dicts in the IPython instance. We seem to be getting somewhere
4084 with this, finally...
4098 with this, finally...
4085
4099
4086 * Small documentation updates.
4100 * Small documentation updates.
4087
4101
4088 * Created the Extensions directory under IPython (with an
4102 * Created the Extensions directory under IPython (with an
4089 __init__.py). Put the PhysicalQ stuff there. This directory should
4103 __init__.py). Put the PhysicalQ stuff there. This directory should
4090 be used for all special-purpose extensions.
4104 be used for all special-purpose extensions.
4091
4105
4092 * File renaming:
4106 * File renaming:
4093 ipythonlib --> ipmaker
4107 ipythonlib --> ipmaker
4094 ipplib --> iplib
4108 ipplib --> iplib
4095 This makes a bit more sense in terms of what these files actually do.
4109 This makes a bit more sense in terms of what these files actually do.
4096
4110
4097 * Moved all the classes and functions in ipythonlib to ipplib, so
4111 * Moved all the classes and functions in ipythonlib to ipplib, so
4098 now ipythonlib only has make_IPython(). This will ease up its
4112 now ipythonlib only has make_IPython(). This will ease up its
4099 splitting in smaller functional chunks later.
4113 splitting in smaller functional chunks later.
4100
4114
4101 * Cleaned up (done, I think) output of @whos. Better column
4115 * Cleaned up (done, I think) output of @whos. Better column
4102 formatting, and now shows str(var) for as much as it can, which is
4116 formatting, and now shows str(var) for as much as it can, which is
4103 typically what one gets with a 'print var'.
4117 typically what one gets with a 'print var'.
4104
4118
4105 2001-12-04 Fernando Perez <fperez@colorado.edu>
4119 2001-12-04 Fernando Perez <fperez@colorado.edu>
4106
4120
4107 * Fixed namespace problems. Now builtin/IPyhton/user names get
4121 * Fixed namespace problems. Now builtin/IPyhton/user names get
4108 properly reported in their namespace. Internal namespace handling
4122 properly reported in their namespace. Internal namespace handling
4109 is finally getting decent (not perfect yet, but much better than
4123 is finally getting decent (not perfect yet, but much better than
4110 the ad-hoc mess we had).
4124 the ad-hoc mess we had).
4111
4125
4112 * Removed -exit option. If people just want to run a python
4126 * Removed -exit option. If people just want to run a python
4113 script, that's what the normal interpreter is for. Less
4127 script, that's what the normal interpreter is for. Less
4114 unnecessary options, less chances for bugs.
4128 unnecessary options, less chances for bugs.
4115
4129
4116 * Added a crash handler which generates a complete post-mortem if
4130 * Added a crash handler which generates a complete post-mortem if
4117 IPython crashes. This will help a lot in tracking bugs down the
4131 IPython crashes. This will help a lot in tracking bugs down the
4118 road.
4132 road.
4119
4133
4120 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4134 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4121 which were boud to functions being reassigned would bypass the
4135 which were boud to functions being reassigned would bypass the
4122 logger, breaking the sync of _il with the prompt counter. This
4136 logger, breaking the sync of _il with the prompt counter. This
4123 would then crash IPython later when a new line was logged.
4137 would then crash IPython later when a new line was logged.
4124
4138
4125 2001-12-02 Fernando Perez <fperez@colorado.edu>
4139 2001-12-02 Fernando Perez <fperez@colorado.edu>
4126
4140
4127 * Made IPython a package. This means people don't have to clutter
4141 * Made IPython a package. This means people don't have to clutter
4128 their sys.path with yet another directory. Changed the INSTALL
4142 their sys.path with yet another directory. Changed the INSTALL
4129 file accordingly.
4143 file accordingly.
4130
4144
4131 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4145 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4132 sorts its output (so @who shows it sorted) and @whos formats the
4146 sorts its output (so @who shows it sorted) and @whos formats the
4133 table according to the width of the first column. Nicer, easier to
4147 table according to the width of the first column. Nicer, easier to
4134 read. Todo: write a generic table_format() which takes a list of
4148 read. Todo: write a generic table_format() which takes a list of
4135 lists and prints it nicely formatted, with optional row/column
4149 lists and prints it nicely formatted, with optional row/column
4136 separators and proper padding and justification.
4150 separators and proper padding and justification.
4137
4151
4138 * Released 0.1.20
4152 * Released 0.1.20
4139
4153
4140 * Fixed bug in @log which would reverse the inputcache list (a
4154 * Fixed bug in @log which would reverse the inputcache list (a
4141 copy operation was missing).
4155 copy operation was missing).
4142
4156
4143 * Code cleanup. @config was changed to use page(). Better, since
4157 * Code cleanup. @config was changed to use page(). Better, since
4144 its output is always quite long.
4158 its output is always quite long.
4145
4159
4146 * Itpl is back as a dependency. I was having too many problems
4160 * Itpl is back as a dependency. I was having too many problems
4147 getting the parametric aliases to work reliably, and it's just
4161 getting the parametric aliases to work reliably, and it's just
4148 easier to code weird string operations with it than playing %()s
4162 easier to code weird string operations with it than playing %()s
4149 games. It's only ~6k, so I don't think it's too big a deal.
4163 games. It's only ~6k, so I don't think it's too big a deal.
4150
4164
4151 * Found (and fixed) a very nasty bug with history. !lines weren't
4165 * Found (and fixed) a very nasty bug with history. !lines weren't
4152 getting cached, and the out of sync caches would crash
4166 getting cached, and the out of sync caches would crash
4153 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4167 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4154 division of labor a bit better. Bug fixed, cleaner structure.
4168 division of labor a bit better. Bug fixed, cleaner structure.
4155
4169
4156 2001-12-01 Fernando Perez <fperez@colorado.edu>
4170 2001-12-01 Fernando Perez <fperez@colorado.edu>
4157
4171
4158 * Released 0.1.19
4172 * Released 0.1.19
4159
4173
4160 * Added option -n to @hist to prevent line number printing. Much
4174 * Added option -n to @hist to prevent line number printing. Much
4161 easier to copy/paste code this way.
4175 easier to copy/paste code this way.
4162
4176
4163 * Created global _il to hold the input list. Allows easy
4177 * Created global _il to hold the input list. Allows easy
4164 re-execution of blocks of code by slicing it (inspired by Janko's
4178 re-execution of blocks of code by slicing it (inspired by Janko's
4165 comment on 'macros').
4179 comment on 'macros').
4166
4180
4167 * Small fixes and doc updates.
4181 * Small fixes and doc updates.
4168
4182
4169 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4183 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4170 much too fragile with automagic. Handles properly multi-line
4184 much too fragile with automagic. Handles properly multi-line
4171 statements and takes parameters.
4185 statements and takes parameters.
4172
4186
4173 2001-11-30 Fernando Perez <fperez@colorado.edu>
4187 2001-11-30 Fernando Perez <fperez@colorado.edu>
4174
4188
4175 * Version 0.1.18 released.
4189 * Version 0.1.18 released.
4176
4190
4177 * Fixed nasty namespace bug in initial module imports.
4191 * Fixed nasty namespace bug in initial module imports.
4178
4192
4179 * Added copyright/license notes to all code files (except
4193 * Added copyright/license notes to all code files (except
4180 DPyGetOpt). For the time being, LGPL. That could change.
4194 DPyGetOpt). For the time being, LGPL. That could change.
4181
4195
4182 * Rewrote a much nicer README, updated INSTALL, cleaned up
4196 * Rewrote a much nicer README, updated INSTALL, cleaned up
4183 ipythonrc-* samples.
4197 ipythonrc-* samples.
4184
4198
4185 * Overall code/documentation cleanup. Basically ready for
4199 * Overall code/documentation cleanup. Basically ready for
4186 release. Only remaining thing: licence decision (LGPL?).
4200 release. Only remaining thing: licence decision (LGPL?).
4187
4201
4188 * Converted load_config to a class, ConfigLoader. Now recursion
4202 * Converted load_config to a class, ConfigLoader. Now recursion
4189 control is better organized. Doesn't include the same file twice.
4203 control is better organized. Doesn't include the same file twice.
4190
4204
4191 2001-11-29 Fernando Perez <fperez@colorado.edu>
4205 2001-11-29 Fernando Perez <fperez@colorado.edu>
4192
4206
4193 * Got input history working. Changed output history variables from
4207 * Got input history working. Changed output history variables from
4194 _p to _o so that _i is for input and _o for output. Just cleaner
4208 _p to _o so that _i is for input and _o for output. Just cleaner
4195 convention.
4209 convention.
4196
4210
4197 * Implemented parametric aliases. This pretty much allows the
4211 * Implemented parametric aliases. This pretty much allows the
4198 alias system to offer full-blown shell convenience, I think.
4212 alias system to offer full-blown shell convenience, I think.
4199
4213
4200 * Version 0.1.17 released, 0.1.18 opened.
4214 * Version 0.1.17 released, 0.1.18 opened.
4201
4215
4202 * dot_ipython/ipythonrc (alias): added documentation.
4216 * dot_ipython/ipythonrc (alias): added documentation.
4203 (xcolor): Fixed small bug (xcolors -> xcolor)
4217 (xcolor): Fixed small bug (xcolors -> xcolor)
4204
4218
4205 * Changed the alias system. Now alias is a magic command to define
4219 * Changed the alias system. Now alias is a magic command to define
4206 aliases just like the shell. Rationale: the builtin magics should
4220 aliases just like the shell. Rationale: the builtin magics should
4207 be there for things deeply connected to IPython's
4221 be there for things deeply connected to IPython's
4208 architecture. And this is a much lighter system for what I think
4222 architecture. And this is a much lighter system for what I think
4209 is the really important feature: allowing users to define quickly
4223 is the really important feature: allowing users to define quickly
4210 magics that will do shell things for them, so they can customize
4224 magics that will do shell things for them, so they can customize
4211 IPython easily to match their work habits. If someone is really
4225 IPython easily to match their work habits. If someone is really
4212 desperate to have another name for a builtin alias, they can
4226 desperate to have another name for a builtin alias, they can
4213 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4227 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4214 works.
4228 works.
4215
4229
4216 2001-11-28 Fernando Perez <fperez@colorado.edu>
4230 2001-11-28 Fernando Perez <fperez@colorado.edu>
4217
4231
4218 * Changed @file so that it opens the source file at the proper
4232 * Changed @file so that it opens the source file at the proper
4219 line. Since it uses less, if your EDITOR environment is
4233 line. Since it uses less, if your EDITOR environment is
4220 configured, typing v will immediately open your editor of choice
4234 configured, typing v will immediately open your editor of choice
4221 right at the line where the object is defined. Not as quick as
4235 right at the line where the object is defined. Not as quick as
4222 having a direct @edit command, but for all intents and purposes it
4236 having a direct @edit command, but for all intents and purposes it
4223 works. And I don't have to worry about writing @edit to deal with
4237 works. And I don't have to worry about writing @edit to deal with
4224 all the editors, less does that.
4238 all the editors, less does that.
4225
4239
4226 * Version 0.1.16 released, 0.1.17 opened.
4240 * Version 0.1.16 released, 0.1.17 opened.
4227
4241
4228 * Fixed some nasty bugs in the page/page_dumb combo that could
4242 * Fixed some nasty bugs in the page/page_dumb combo that could
4229 crash IPython.
4243 crash IPython.
4230
4244
4231 2001-11-27 Fernando Perez <fperez@colorado.edu>
4245 2001-11-27 Fernando Perez <fperez@colorado.edu>
4232
4246
4233 * Version 0.1.15 released, 0.1.16 opened.
4247 * Version 0.1.15 released, 0.1.16 opened.
4234
4248
4235 * Finally got ? and ?? to work for undefined things: now it's
4249 * Finally got ? and ?? to work for undefined things: now it's
4236 possible to type {}.get? and get information about the get method
4250 possible to type {}.get? and get information about the get method
4237 of dicts, or os.path? even if only os is defined (so technically
4251 of dicts, or os.path? even if only os is defined (so technically
4238 os.path isn't). Works at any level. For example, after import os,
4252 os.path isn't). Works at any level. For example, after import os,
4239 os?, os.path?, os.path.abspath? all work. This is great, took some
4253 os?, os.path?, os.path.abspath? all work. This is great, took some
4240 work in _ofind.
4254 work in _ofind.
4241
4255
4242 * Fixed more bugs with logging. The sanest way to do it was to add
4256 * Fixed more bugs with logging. The sanest way to do it was to add
4243 to @log a 'mode' parameter. Killed two in one shot (this mode
4257 to @log a 'mode' parameter. Killed two in one shot (this mode
4244 option was a request of Janko's). I think it's finally clean
4258 option was a request of Janko's). I think it's finally clean
4245 (famous last words).
4259 (famous last words).
4246
4260
4247 * Added a page_dumb() pager which does a decent job of paging on
4261 * Added a page_dumb() pager which does a decent job of paging on
4248 screen, if better things (like less) aren't available. One less
4262 screen, if better things (like less) aren't available. One less
4249 unix dependency (someday maybe somebody will port this to
4263 unix dependency (someday maybe somebody will port this to
4250 windows).
4264 windows).
4251
4265
4252 * Fixed problem in magic_log: would lock of logging out if log
4266 * Fixed problem in magic_log: would lock of logging out if log
4253 creation failed (because it would still think it had succeeded).
4267 creation failed (because it would still think it had succeeded).
4254
4268
4255 * Improved the page() function using curses to auto-detect screen
4269 * Improved the page() function using curses to auto-detect screen
4256 size. Now it can make a much better decision on whether to print
4270 size. Now it can make a much better decision on whether to print
4257 or page a string. Option screen_length was modified: a value 0
4271 or page a string. Option screen_length was modified: a value 0
4258 means auto-detect, and that's the default now.
4272 means auto-detect, and that's the default now.
4259
4273
4260 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4274 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4261 go out. I'll test it for a few days, then talk to Janko about
4275 go out. I'll test it for a few days, then talk to Janko about
4262 licences and announce it.
4276 licences and announce it.
4263
4277
4264 * Fixed the length of the auto-generated ---> prompt which appears
4278 * Fixed the length of the auto-generated ---> prompt which appears
4265 for auto-parens and auto-quotes. Getting this right isn't trivial,
4279 for auto-parens and auto-quotes. Getting this right isn't trivial,
4266 with all the color escapes, different prompt types and optional
4280 with all the color escapes, different prompt types and optional
4267 separators. But it seems to be working in all the combinations.
4281 separators. But it seems to be working in all the combinations.
4268
4282
4269 2001-11-26 Fernando Perez <fperez@colorado.edu>
4283 2001-11-26 Fernando Perez <fperez@colorado.edu>
4270
4284
4271 * Wrote a regexp filter to get option types from the option names
4285 * Wrote a regexp filter to get option types from the option names
4272 string. This eliminates the need to manually keep two duplicate
4286 string. This eliminates the need to manually keep two duplicate
4273 lists.
4287 lists.
4274
4288
4275 * Removed the unneeded check_option_names. Now options are handled
4289 * Removed the unneeded check_option_names. Now options are handled
4276 in a much saner manner and it's easy to visually check that things
4290 in a much saner manner and it's easy to visually check that things
4277 are ok.
4291 are ok.
4278
4292
4279 * Updated version numbers on all files I modified to carry a
4293 * Updated version numbers on all files I modified to carry a
4280 notice so Janko and Nathan have clear version markers.
4294 notice so Janko and Nathan have clear version markers.
4281
4295
4282 * Updated docstring for ultraTB with my changes. I should send
4296 * Updated docstring for ultraTB with my changes. I should send
4283 this to Nathan.
4297 this to Nathan.
4284
4298
4285 * Lots of small fixes. Ran everything through pychecker again.
4299 * Lots of small fixes. Ran everything through pychecker again.
4286
4300
4287 * Made loading of deep_reload an cmd line option. If it's not too
4301 * Made loading of deep_reload an cmd line option. If it's not too
4288 kosher, now people can just disable it. With -nodeep_reload it's
4302 kosher, now people can just disable it. With -nodeep_reload it's
4289 still available as dreload(), it just won't overwrite reload().
4303 still available as dreload(), it just won't overwrite reload().
4290
4304
4291 * Moved many options to the no| form (-opt and -noopt
4305 * Moved many options to the no| form (-opt and -noopt
4292 accepted). Cleaner.
4306 accepted). Cleaner.
4293
4307
4294 * Changed magic_log so that if called with no parameters, it uses
4308 * Changed magic_log so that if called with no parameters, it uses
4295 'rotate' mode. That way auto-generated logs aren't automatically
4309 'rotate' mode. That way auto-generated logs aren't automatically
4296 over-written. For normal logs, now a backup is made if it exists
4310 over-written. For normal logs, now a backup is made if it exists
4297 (only 1 level of backups). A new 'backup' mode was added to the
4311 (only 1 level of backups). A new 'backup' mode was added to the
4298 Logger class to support this. This was a request by Janko.
4312 Logger class to support this. This was a request by Janko.
4299
4313
4300 * Added @logoff/@logon to stop/restart an active log.
4314 * Added @logoff/@logon to stop/restart an active log.
4301
4315
4302 * Fixed a lot of bugs in log saving/replay. It was pretty
4316 * Fixed a lot of bugs in log saving/replay. It was pretty
4303 broken. Now special lines (!@,/) appear properly in the command
4317 broken. Now special lines (!@,/) appear properly in the command
4304 history after a log replay.
4318 history after a log replay.
4305
4319
4306 * Tried and failed to implement full session saving via pickle. My
4320 * Tried and failed to implement full session saving via pickle. My
4307 idea was to pickle __main__.__dict__, but modules can't be
4321 idea was to pickle __main__.__dict__, but modules can't be
4308 pickled. This would be a better alternative to replaying logs, but
4322 pickled. This would be a better alternative to replaying logs, but
4309 seems quite tricky to get to work. Changed -session to be called
4323 seems quite tricky to get to work. Changed -session to be called
4310 -logplay, which more accurately reflects what it does. And if we
4324 -logplay, which more accurately reflects what it does. And if we
4311 ever get real session saving working, -session is now available.
4325 ever get real session saving working, -session is now available.
4312
4326
4313 * Implemented color schemes for prompts also. As for tracebacks,
4327 * Implemented color schemes for prompts also. As for tracebacks,
4314 currently only NoColor and Linux are supported. But now the
4328 currently only NoColor and Linux are supported. But now the
4315 infrastructure is in place, based on a generic ColorScheme
4329 infrastructure is in place, based on a generic ColorScheme
4316 class. So writing and activating new schemes both for the prompts
4330 class. So writing and activating new schemes both for the prompts
4317 and the tracebacks should be straightforward.
4331 and the tracebacks should be straightforward.
4318
4332
4319 * Version 0.1.13 released, 0.1.14 opened.
4333 * Version 0.1.13 released, 0.1.14 opened.
4320
4334
4321 * Changed handling of options for output cache. Now counter is
4335 * Changed handling of options for output cache. Now counter is
4322 hardwired starting at 1 and one specifies the maximum number of
4336 hardwired starting at 1 and one specifies the maximum number of
4323 entries *in the outcache* (not the max prompt counter). This is
4337 entries *in the outcache* (not the max prompt counter). This is
4324 much better, since many statements won't increase the cache
4338 much better, since many statements won't increase the cache
4325 count. It also eliminated some confusing options, now there's only
4339 count. It also eliminated some confusing options, now there's only
4326 one: cache_size.
4340 one: cache_size.
4327
4341
4328 * Added 'alias' magic function and magic_alias option in the
4342 * Added 'alias' magic function and magic_alias option in the
4329 ipythonrc file. Now the user can easily define whatever names he
4343 ipythonrc file. Now the user can easily define whatever names he
4330 wants for the magic functions without having to play weird
4344 wants for the magic functions without having to play weird
4331 namespace games. This gives IPython a real shell-like feel.
4345 namespace games. This gives IPython a real shell-like feel.
4332
4346
4333 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4347 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4334 @ or not).
4348 @ or not).
4335
4349
4336 This was one of the last remaining 'visible' bugs (that I know
4350 This was one of the last remaining 'visible' bugs (that I know
4337 of). I think if I can clean up the session loading so it works
4351 of). I think if I can clean up the session loading so it works
4338 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4352 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4339 about licensing).
4353 about licensing).
4340
4354
4341 2001-11-25 Fernando Perez <fperez@colorado.edu>
4355 2001-11-25 Fernando Perez <fperez@colorado.edu>
4342
4356
4343 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4357 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4344 there's a cleaner distinction between what ? and ?? show.
4358 there's a cleaner distinction between what ? and ?? show.
4345
4359
4346 * Added screen_length option. Now the user can define his own
4360 * Added screen_length option. Now the user can define his own
4347 screen size for page() operations.
4361 screen size for page() operations.
4348
4362
4349 * Implemented magic shell-like functions with automatic code
4363 * Implemented magic shell-like functions with automatic code
4350 generation. Now adding another function is just a matter of adding
4364 generation. Now adding another function is just a matter of adding
4351 an entry to a dict, and the function is dynamically generated at
4365 an entry to a dict, and the function is dynamically generated at
4352 run-time. Python has some really cool features!
4366 run-time. Python has some really cool features!
4353
4367
4354 * Renamed many options to cleanup conventions a little. Now all
4368 * Renamed many options to cleanup conventions a little. Now all
4355 are lowercase, and only underscores where needed. Also in the code
4369 are lowercase, and only underscores where needed. Also in the code
4356 option name tables are clearer.
4370 option name tables are clearer.
4357
4371
4358 * Changed prompts a little. Now input is 'In [n]:' instead of
4372 * Changed prompts a little. Now input is 'In [n]:' instead of
4359 'In[n]:='. This allows it the numbers to be aligned with the
4373 'In[n]:='. This allows it the numbers to be aligned with the
4360 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4374 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4361 Python (it was a Mathematica thing). The '...' continuation prompt
4375 Python (it was a Mathematica thing). The '...' continuation prompt
4362 was also changed a little to align better.
4376 was also changed a little to align better.
4363
4377
4364 * Fixed bug when flushing output cache. Not all _p<n> variables
4378 * Fixed bug when flushing output cache. Not all _p<n> variables
4365 exist, so their deletion needs to be wrapped in a try:
4379 exist, so their deletion needs to be wrapped in a try:
4366
4380
4367 * Figured out how to properly use inspect.formatargspec() (it
4381 * Figured out how to properly use inspect.formatargspec() (it
4368 requires the args preceded by *). So I removed all the code from
4382 requires the args preceded by *). So I removed all the code from
4369 _get_pdef in Magic, which was just replicating that.
4383 _get_pdef in Magic, which was just replicating that.
4370
4384
4371 * Added test to prefilter to allow redefining magic function names
4385 * Added test to prefilter to allow redefining magic function names
4372 as variables. This is ok, since the @ form is always available,
4386 as variables. This is ok, since the @ form is always available,
4373 but whe should allow the user to define a variable called 'ls' if
4387 but whe should allow the user to define a variable called 'ls' if
4374 he needs it.
4388 he needs it.
4375
4389
4376 * Moved the ToDo information from README into a separate ToDo.
4390 * Moved the ToDo information from README into a separate ToDo.
4377
4391
4378 * General code cleanup and small bugfixes. I think it's close to a
4392 * General code cleanup and small bugfixes. I think it's close to a
4379 state where it can be released, obviously with a big 'beta'
4393 state where it can be released, obviously with a big 'beta'
4380 warning on it.
4394 warning on it.
4381
4395
4382 * Got the magic function split to work. Now all magics are defined
4396 * Got the magic function split to work. Now all magics are defined
4383 in a separate class. It just organizes things a bit, and now
4397 in a separate class. It just organizes things a bit, and now
4384 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4398 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4385 was too long).
4399 was too long).
4386
4400
4387 * Changed @clear to @reset to avoid potential confusions with
4401 * Changed @clear to @reset to avoid potential confusions with
4388 the shell command clear. Also renamed @cl to @clear, which does
4402 the shell command clear. Also renamed @cl to @clear, which does
4389 exactly what people expect it to from their shell experience.
4403 exactly what people expect it to from their shell experience.
4390
4404
4391 Added a check to the @reset command (since it's so
4405 Added a check to the @reset command (since it's so
4392 destructive, it's probably a good idea to ask for confirmation).
4406 destructive, it's probably a good idea to ask for confirmation).
4393 But now reset only works for full namespace resetting. Since the
4407 But now reset only works for full namespace resetting. Since the
4394 del keyword is already there for deleting a few specific
4408 del keyword is already there for deleting a few specific
4395 variables, I don't see the point of having a redundant magic
4409 variables, I don't see the point of having a redundant magic
4396 function for the same task.
4410 function for the same task.
4397
4411
4398 2001-11-24 Fernando Perez <fperez@colorado.edu>
4412 2001-11-24 Fernando Perez <fperez@colorado.edu>
4399
4413
4400 * Updated the builtin docs (esp. the ? ones).
4414 * Updated the builtin docs (esp. the ? ones).
4401
4415
4402 * Ran all the code through pychecker. Not terribly impressed with
4416 * Ran all the code through pychecker. Not terribly impressed with
4403 it: lots of spurious warnings and didn't really find anything of
4417 it: lots of spurious warnings and didn't really find anything of
4404 substance (just a few modules being imported and not used).
4418 substance (just a few modules being imported and not used).
4405
4419
4406 * Implemented the new ultraTB functionality into IPython. New
4420 * Implemented the new ultraTB functionality into IPython. New
4407 option: xcolors. This chooses color scheme. xmode now only selects
4421 option: xcolors. This chooses color scheme. xmode now only selects
4408 between Plain and Verbose. Better orthogonality.
4422 between Plain and Verbose. Better orthogonality.
4409
4423
4410 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4424 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4411 mode and color scheme for the exception handlers. Now it's
4425 mode and color scheme for the exception handlers. Now it's
4412 possible to have the verbose traceback with no coloring.
4426 possible to have the verbose traceback with no coloring.
4413
4427
4414 2001-11-23 Fernando Perez <fperez@colorado.edu>
4428 2001-11-23 Fernando Perez <fperez@colorado.edu>
4415
4429
4416 * Version 0.1.12 released, 0.1.13 opened.
4430 * Version 0.1.12 released, 0.1.13 opened.
4417
4431
4418 * Removed option to set auto-quote and auto-paren escapes by
4432 * Removed option to set auto-quote and auto-paren escapes by
4419 user. The chances of breaking valid syntax are just too high. If
4433 user. The chances of breaking valid syntax are just too high. If
4420 someone *really* wants, they can always dig into the code.
4434 someone *really* wants, they can always dig into the code.
4421
4435
4422 * Made prompt separators configurable.
4436 * Made prompt separators configurable.
4423
4437
4424 2001-11-22 Fernando Perez <fperez@colorado.edu>
4438 2001-11-22 Fernando Perez <fperez@colorado.edu>
4425
4439
4426 * Small bugfixes in many places.
4440 * Small bugfixes in many places.
4427
4441
4428 * Removed the MyCompleter class from ipplib. It seemed redundant
4442 * Removed the MyCompleter class from ipplib. It seemed redundant
4429 with the C-p,C-n history search functionality. Less code to
4443 with the C-p,C-n history search functionality. Less code to
4430 maintain.
4444 maintain.
4431
4445
4432 * Moved all the original ipython.py code into ipythonlib.py. Right
4446 * Moved all the original ipython.py code into ipythonlib.py. Right
4433 now it's just one big dump into a function called make_IPython, so
4447 now it's just one big dump into a function called make_IPython, so
4434 no real modularity has been gained. But at least it makes the
4448 no real modularity has been gained. But at least it makes the
4435 wrapper script tiny, and since ipythonlib is a module, it gets
4449 wrapper script tiny, and since ipythonlib is a module, it gets
4436 compiled and startup is much faster.
4450 compiled and startup is much faster.
4437
4451
4438 This is a reasobably 'deep' change, so we should test it for a
4452 This is a reasobably 'deep' change, so we should test it for a
4439 while without messing too much more with the code.
4453 while without messing too much more with the code.
4440
4454
4441 2001-11-21 Fernando Perez <fperez@colorado.edu>
4455 2001-11-21 Fernando Perez <fperez@colorado.edu>
4442
4456
4443 * Version 0.1.11 released, 0.1.12 opened for further work.
4457 * Version 0.1.11 released, 0.1.12 opened for further work.
4444
4458
4445 * Removed dependency on Itpl. It was only needed in one place. It
4459 * Removed dependency on Itpl. It was only needed in one place. It
4446 would be nice if this became part of python, though. It makes life
4460 would be nice if this became part of python, though. It makes life
4447 *a lot* easier in some cases.
4461 *a lot* easier in some cases.
4448
4462
4449 * Simplified the prefilter code a bit. Now all handlers are
4463 * Simplified the prefilter code a bit. Now all handlers are
4450 expected to explicitly return a value (at least a blank string).
4464 expected to explicitly return a value (at least a blank string).
4451
4465
4452 * Heavy edits in ipplib. Removed the help system altogether. Now
4466 * Heavy edits in ipplib. Removed the help system altogether. Now
4453 obj?/?? is used for inspecting objects, a magic @doc prints
4467 obj?/?? is used for inspecting objects, a magic @doc prints
4454 docstrings, and full-blown Python help is accessed via the 'help'
4468 docstrings, and full-blown Python help is accessed via the 'help'
4455 keyword. This cleans up a lot of code (less to maintain) and does
4469 keyword. This cleans up a lot of code (less to maintain) and does
4456 the job. Since 'help' is now a standard Python component, might as
4470 the job. Since 'help' is now a standard Python component, might as
4457 well use it and remove duplicate functionality.
4471 well use it and remove duplicate functionality.
4458
4472
4459 Also removed the option to use ipplib as a standalone program. By
4473 Also removed the option to use ipplib as a standalone program. By
4460 now it's too dependent on other parts of IPython to function alone.
4474 now it's too dependent on other parts of IPython to function alone.
4461
4475
4462 * Fixed bug in genutils.pager. It would crash if the pager was
4476 * Fixed bug in genutils.pager. It would crash if the pager was
4463 exited immediately after opening (broken pipe).
4477 exited immediately after opening (broken pipe).
4464
4478
4465 * Trimmed down the VerboseTB reporting a little. The header is
4479 * Trimmed down the VerboseTB reporting a little. The header is
4466 much shorter now and the repeated exception arguments at the end
4480 much shorter now and the repeated exception arguments at the end
4467 have been removed. For interactive use the old header seemed a bit
4481 have been removed. For interactive use the old header seemed a bit
4468 excessive.
4482 excessive.
4469
4483
4470 * Fixed small bug in output of @whos for variables with multi-word
4484 * Fixed small bug in output of @whos for variables with multi-word
4471 types (only first word was displayed).
4485 types (only first word was displayed).
4472
4486
4473 2001-11-17 Fernando Perez <fperez@colorado.edu>
4487 2001-11-17 Fernando Perez <fperez@colorado.edu>
4474
4488
4475 * Version 0.1.10 released, 0.1.11 opened for further work.
4489 * Version 0.1.10 released, 0.1.11 opened for further work.
4476
4490
4477 * Modified dirs and friends. dirs now *returns* the stack (not
4491 * Modified dirs and friends. dirs now *returns* the stack (not
4478 prints), so one can manipulate it as a variable. Convenient to
4492 prints), so one can manipulate it as a variable. Convenient to
4479 travel along many directories.
4493 travel along many directories.
4480
4494
4481 * Fixed bug in magic_pdef: would only work with functions with
4495 * Fixed bug in magic_pdef: would only work with functions with
4482 arguments with default values.
4496 arguments with default values.
4483
4497
4484 2001-11-14 Fernando Perez <fperez@colorado.edu>
4498 2001-11-14 Fernando Perez <fperez@colorado.edu>
4485
4499
4486 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4500 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4487 example with IPython. Various other minor fixes and cleanups.
4501 example with IPython. Various other minor fixes and cleanups.
4488
4502
4489 * Version 0.1.9 released, 0.1.10 opened for further work.
4503 * Version 0.1.9 released, 0.1.10 opened for further work.
4490
4504
4491 * Added sys.path to the list of directories searched in the
4505 * Added sys.path to the list of directories searched in the
4492 execfile= option. It used to be the current directory and the
4506 execfile= option. It used to be the current directory and the
4493 user's IPYTHONDIR only.
4507 user's IPYTHONDIR only.
4494
4508
4495 2001-11-13 Fernando Perez <fperez@colorado.edu>
4509 2001-11-13 Fernando Perez <fperez@colorado.edu>
4496
4510
4497 * Reinstated the raw_input/prefilter separation that Janko had
4511 * Reinstated the raw_input/prefilter separation that Janko had
4498 initially. This gives a more convenient setup for extending the
4512 initially. This gives a more convenient setup for extending the
4499 pre-processor from the outside: raw_input always gets a string,
4513 pre-processor from the outside: raw_input always gets a string,
4500 and prefilter has to process it. We can then redefine prefilter
4514 and prefilter has to process it. We can then redefine prefilter
4501 from the outside and implement extensions for special
4515 from the outside and implement extensions for special
4502 purposes.
4516 purposes.
4503
4517
4504 Today I got one for inputting PhysicalQuantity objects
4518 Today I got one for inputting PhysicalQuantity objects
4505 (from Scientific) without needing any function calls at
4519 (from Scientific) without needing any function calls at
4506 all. Extremely convenient, and it's all done as a user-level
4520 all. Extremely convenient, and it's all done as a user-level
4507 extension (no IPython code was touched). Now instead of:
4521 extension (no IPython code was touched). Now instead of:
4508 a = PhysicalQuantity(4.2,'m/s**2')
4522 a = PhysicalQuantity(4.2,'m/s**2')
4509 one can simply say
4523 one can simply say
4510 a = 4.2 m/s**2
4524 a = 4.2 m/s**2
4511 or even
4525 or even
4512 a = 4.2 m/s^2
4526 a = 4.2 m/s^2
4513
4527
4514 I use this, but it's also a proof of concept: IPython really is
4528 I use this, but it's also a proof of concept: IPython really is
4515 fully user-extensible, even at the level of the parsing of the
4529 fully user-extensible, even at the level of the parsing of the
4516 command line. It's not trivial, but it's perfectly doable.
4530 command line. It's not trivial, but it's perfectly doable.
4517
4531
4518 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4532 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4519 the problem of modules being loaded in the inverse order in which
4533 the problem of modules being loaded in the inverse order in which
4520 they were defined in
4534 they were defined in
4521
4535
4522 * Version 0.1.8 released, 0.1.9 opened for further work.
4536 * Version 0.1.8 released, 0.1.9 opened for further work.
4523
4537
4524 * Added magics pdef, source and file. They respectively show the
4538 * Added magics pdef, source and file. They respectively show the
4525 definition line ('prototype' in C), source code and full python
4539 definition line ('prototype' in C), source code and full python
4526 file for any callable object. The object inspector oinfo uses
4540 file for any callable object. The object inspector oinfo uses
4527 these to show the same information.
4541 these to show the same information.
4528
4542
4529 * Version 0.1.7 released, 0.1.8 opened for further work.
4543 * Version 0.1.7 released, 0.1.8 opened for further work.
4530
4544
4531 * Separated all the magic functions into a class called Magic. The
4545 * Separated all the magic functions into a class called Magic. The
4532 InteractiveShell class was becoming too big for Xemacs to handle
4546 InteractiveShell class was becoming too big for Xemacs to handle
4533 (de-indenting a line would lock it up for 10 seconds while it
4547 (de-indenting a line would lock it up for 10 seconds while it
4534 backtracked on the whole class!)
4548 backtracked on the whole class!)
4535
4549
4536 FIXME: didn't work. It can be done, but right now namespaces are
4550 FIXME: didn't work. It can be done, but right now namespaces are
4537 all messed up. Do it later (reverted it for now, so at least
4551 all messed up. Do it later (reverted it for now, so at least
4538 everything works as before).
4552 everything works as before).
4539
4553
4540 * Got the object introspection system (magic_oinfo) working! I
4554 * Got the object introspection system (magic_oinfo) working! I
4541 think this is pretty much ready for release to Janko, so he can
4555 think this is pretty much ready for release to Janko, so he can
4542 test it for a while and then announce it. Pretty much 100% of what
4556 test it for a while and then announce it. Pretty much 100% of what
4543 I wanted for the 'phase 1' release is ready. Happy, tired.
4557 I wanted for the 'phase 1' release is ready. Happy, tired.
4544
4558
4545 2001-11-12 Fernando Perez <fperez@colorado.edu>
4559 2001-11-12 Fernando Perez <fperez@colorado.edu>
4546
4560
4547 * Version 0.1.6 released, 0.1.7 opened for further work.
4561 * Version 0.1.6 released, 0.1.7 opened for further work.
4548
4562
4549 * Fixed bug in printing: it used to test for truth before
4563 * Fixed bug in printing: it used to test for truth before
4550 printing, so 0 wouldn't print. Now checks for None.
4564 printing, so 0 wouldn't print. Now checks for None.
4551
4565
4552 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4566 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4553 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4567 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4554 reaches by hand into the outputcache. Think of a better way to do
4568 reaches by hand into the outputcache. Think of a better way to do
4555 this later.
4569 this later.
4556
4570
4557 * Various small fixes thanks to Nathan's comments.
4571 * Various small fixes thanks to Nathan's comments.
4558
4572
4559 * Changed magic_pprint to magic_Pprint. This way it doesn't
4573 * Changed magic_pprint to magic_Pprint. This way it doesn't
4560 collide with pprint() and the name is consistent with the command
4574 collide with pprint() and the name is consistent with the command
4561 line option.
4575 line option.
4562
4576
4563 * Changed prompt counter behavior to be fully like
4577 * Changed prompt counter behavior to be fully like
4564 Mathematica's. That is, even input that doesn't return a result
4578 Mathematica's. That is, even input that doesn't return a result
4565 raises the prompt counter. The old behavior was kind of confusing
4579 raises the prompt counter. The old behavior was kind of confusing
4566 (getting the same prompt number several times if the operation
4580 (getting the same prompt number several times if the operation
4567 didn't return a result).
4581 didn't return a result).
4568
4582
4569 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4583 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4570
4584
4571 * Fixed -Classic mode (wasn't working anymore).
4585 * Fixed -Classic mode (wasn't working anymore).
4572
4586
4573 * Added colored prompts using Nathan's new code. Colors are
4587 * Added colored prompts using Nathan's new code. Colors are
4574 currently hardwired, they can be user-configurable. For
4588 currently hardwired, they can be user-configurable. For
4575 developers, they can be chosen in file ipythonlib.py, at the
4589 developers, they can be chosen in file ipythonlib.py, at the
4576 beginning of the CachedOutput class def.
4590 beginning of the CachedOutput class def.
4577
4591
4578 2001-11-11 Fernando Perez <fperez@colorado.edu>
4592 2001-11-11 Fernando Perez <fperez@colorado.edu>
4579
4593
4580 * Version 0.1.5 released, 0.1.6 opened for further work.
4594 * Version 0.1.5 released, 0.1.6 opened for further work.
4581
4595
4582 * Changed magic_env to *return* the environment as a dict (not to
4596 * Changed magic_env to *return* the environment as a dict (not to
4583 print it). This way it prints, but it can also be processed.
4597 print it). This way it prints, but it can also be processed.
4584
4598
4585 * Added Verbose exception reporting to interactive
4599 * Added Verbose exception reporting to interactive
4586 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4600 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4587 traceback. Had to make some changes to the ultraTB file. This is
4601 traceback. Had to make some changes to the ultraTB file. This is
4588 probably the last 'big' thing in my mental todo list. This ties
4602 probably the last 'big' thing in my mental todo list. This ties
4589 in with the next entry:
4603 in with the next entry:
4590
4604
4591 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4605 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4592 has to specify is Plain, Color or Verbose for all exception
4606 has to specify is Plain, Color or Verbose for all exception
4593 handling.
4607 handling.
4594
4608
4595 * Removed ShellServices option. All this can really be done via
4609 * Removed ShellServices option. All this can really be done via
4596 the magic system. It's easier to extend, cleaner and has automatic
4610 the magic system. It's easier to extend, cleaner and has automatic
4597 namespace protection and documentation.
4611 namespace protection and documentation.
4598
4612
4599 2001-11-09 Fernando Perez <fperez@colorado.edu>
4613 2001-11-09 Fernando Perez <fperez@colorado.edu>
4600
4614
4601 * Fixed bug in output cache flushing (missing parameter to
4615 * Fixed bug in output cache flushing (missing parameter to
4602 __init__). Other small bugs fixed (found using pychecker).
4616 __init__). Other small bugs fixed (found using pychecker).
4603
4617
4604 * Version 0.1.4 opened for bugfixing.
4618 * Version 0.1.4 opened for bugfixing.
4605
4619
4606 2001-11-07 Fernando Perez <fperez@colorado.edu>
4620 2001-11-07 Fernando Perez <fperez@colorado.edu>
4607
4621
4608 * Version 0.1.3 released, mainly because of the raw_input bug.
4622 * Version 0.1.3 released, mainly because of the raw_input bug.
4609
4623
4610 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4624 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4611 and when testing for whether things were callable, a call could
4625 and when testing for whether things were callable, a call could
4612 actually be made to certain functions. They would get called again
4626 actually be made to certain functions. They would get called again
4613 once 'really' executed, with a resulting double call. A disaster
4627 once 'really' executed, with a resulting double call. A disaster
4614 in many cases (list.reverse() would never work!).
4628 in many cases (list.reverse() would never work!).
4615
4629
4616 * Removed prefilter() function, moved its code to raw_input (which
4630 * Removed prefilter() function, moved its code to raw_input (which
4617 after all was just a near-empty caller for prefilter). This saves
4631 after all was just a near-empty caller for prefilter). This saves
4618 a function call on every prompt, and simplifies the class a tiny bit.
4632 a function call on every prompt, and simplifies the class a tiny bit.
4619
4633
4620 * Fix _ip to __ip name in magic example file.
4634 * Fix _ip to __ip name in magic example file.
4621
4635
4622 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4636 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4623 work with non-gnu versions of tar.
4637 work with non-gnu versions of tar.
4624
4638
4625 2001-11-06 Fernando Perez <fperez@colorado.edu>
4639 2001-11-06 Fernando Perez <fperez@colorado.edu>
4626
4640
4627 * Version 0.1.2. Just to keep track of the recent changes.
4641 * Version 0.1.2. Just to keep track of the recent changes.
4628
4642
4629 * Fixed nasty bug in output prompt routine. It used to check 'if
4643 * Fixed nasty bug in output prompt routine. It used to check 'if
4630 arg != None...'. Problem is, this fails if arg implements a
4644 arg != None...'. Problem is, this fails if arg implements a
4631 special comparison (__cmp__) which disallows comparing to
4645 special comparison (__cmp__) which disallows comparing to
4632 None. Found it when trying to use the PhysicalQuantity module from
4646 None. Found it when trying to use the PhysicalQuantity module from
4633 ScientificPython.
4647 ScientificPython.
4634
4648
4635 2001-11-05 Fernando Perez <fperez@colorado.edu>
4649 2001-11-05 Fernando Perez <fperez@colorado.edu>
4636
4650
4637 * Also added dirs. Now the pushd/popd/dirs family functions
4651 * Also added dirs. Now the pushd/popd/dirs family functions
4638 basically like the shell, with the added convenience of going home
4652 basically like the shell, with the added convenience of going home
4639 when called with no args.
4653 when called with no args.
4640
4654
4641 * pushd/popd slightly modified to mimic shell behavior more
4655 * pushd/popd slightly modified to mimic shell behavior more
4642 closely.
4656 closely.
4643
4657
4644 * Added env,pushd,popd from ShellServices as magic functions. I
4658 * Added env,pushd,popd from ShellServices as magic functions. I
4645 think the cleanest will be to port all desired functions from
4659 think the cleanest will be to port all desired functions from
4646 ShellServices as magics and remove ShellServices altogether. This
4660 ShellServices as magics and remove ShellServices altogether. This
4647 will provide a single, clean way of adding functionality
4661 will provide a single, clean way of adding functionality
4648 (shell-type or otherwise) to IP.
4662 (shell-type or otherwise) to IP.
4649
4663
4650 2001-11-04 Fernando Perez <fperez@colorado.edu>
4664 2001-11-04 Fernando Perez <fperez@colorado.edu>
4651
4665
4652 * Added .ipython/ directory to sys.path. This way users can keep
4666 * Added .ipython/ directory to sys.path. This way users can keep
4653 customizations there and access them via import.
4667 customizations there and access them via import.
4654
4668
4655 2001-11-03 Fernando Perez <fperez@colorado.edu>
4669 2001-11-03 Fernando Perez <fperez@colorado.edu>
4656
4670
4657 * Opened version 0.1.1 for new changes.
4671 * Opened version 0.1.1 for new changes.
4658
4672
4659 * Changed version number to 0.1.0: first 'public' release, sent to
4673 * Changed version number to 0.1.0: first 'public' release, sent to
4660 Nathan and Janko.
4674 Nathan and Janko.
4661
4675
4662 * Lots of small fixes and tweaks.
4676 * Lots of small fixes and tweaks.
4663
4677
4664 * Minor changes to whos format. Now strings are shown, snipped if
4678 * Minor changes to whos format. Now strings are shown, snipped if
4665 too long.
4679 too long.
4666
4680
4667 * Changed ShellServices to work on __main__ so they show up in @who
4681 * Changed ShellServices to work on __main__ so they show up in @who
4668
4682
4669 * Help also works with ? at the end of a line:
4683 * Help also works with ? at the end of a line:
4670 ?sin and sin?
4684 ?sin and sin?
4671 both produce the same effect. This is nice, as often I use the
4685 both produce the same effect. This is nice, as often I use the
4672 tab-complete to find the name of a method, but I used to then have
4686 tab-complete to find the name of a method, but I used to then have
4673 to go to the beginning of the line to put a ? if I wanted more
4687 to go to the beginning of the line to put a ? if I wanted more
4674 info. Now I can just add the ? and hit return. Convenient.
4688 info. Now I can just add the ? and hit return. Convenient.
4675
4689
4676 2001-11-02 Fernando Perez <fperez@colorado.edu>
4690 2001-11-02 Fernando Perez <fperez@colorado.edu>
4677
4691
4678 * Python version check (>=2.1) added.
4692 * Python version check (>=2.1) added.
4679
4693
4680 * Added LazyPython documentation. At this point the docs are quite
4694 * Added LazyPython documentation. At this point the docs are quite
4681 a mess. A cleanup is in order.
4695 a mess. A cleanup is in order.
4682
4696
4683 * Auto-installer created. For some bizarre reason, the zipfiles
4697 * Auto-installer created. For some bizarre reason, the zipfiles
4684 module isn't working on my system. So I made a tar version
4698 module isn't working on my system. So I made a tar version
4685 (hopefully the command line options in various systems won't kill
4699 (hopefully the command line options in various systems won't kill
4686 me).
4700 me).
4687
4701
4688 * Fixes to Struct in genutils. Now all dictionary-like methods are
4702 * Fixes to Struct in genutils. Now all dictionary-like methods are
4689 protected (reasonably).
4703 protected (reasonably).
4690
4704
4691 * Added pager function to genutils and changed ? to print usage
4705 * Added pager function to genutils and changed ? to print usage
4692 note through it (it was too long).
4706 note through it (it was too long).
4693
4707
4694 * Added the LazyPython functionality. Works great! I changed the
4708 * Added the LazyPython functionality. Works great! I changed the
4695 auto-quote escape to ';', it's on home row and next to '. But
4709 auto-quote escape to ';', it's on home row and next to '. But
4696 both auto-quote and auto-paren (still /) escapes are command-line
4710 both auto-quote and auto-paren (still /) escapes are command-line
4697 parameters.
4711 parameters.
4698
4712
4699
4713
4700 2001-11-01 Fernando Perez <fperez@colorado.edu>
4714 2001-11-01 Fernando Perez <fperez@colorado.edu>
4701
4715
4702 * Version changed to 0.0.7. Fairly large change: configuration now
4716 * Version changed to 0.0.7. Fairly large change: configuration now
4703 is all stored in a directory, by default .ipython. There, all
4717 is all stored in a directory, by default .ipython. There, all
4704 config files have normal looking names (not .names)
4718 config files have normal looking names (not .names)
4705
4719
4706 * Version 0.0.6 Released first to Lucas and Archie as a test
4720 * Version 0.0.6 Released first to Lucas and Archie as a test
4707 run. Since it's the first 'semi-public' release, change version to
4721 run. Since it's the first 'semi-public' release, change version to
4708 > 0.0.6 for any changes now.
4722 > 0.0.6 for any changes now.
4709
4723
4710 * Stuff I had put in the ipplib.py changelog:
4724 * Stuff I had put in the ipplib.py changelog:
4711
4725
4712 Changes to InteractiveShell:
4726 Changes to InteractiveShell:
4713
4727
4714 - Made the usage message a parameter.
4728 - Made the usage message a parameter.
4715
4729
4716 - Require the name of the shell variable to be given. It's a bit
4730 - Require the name of the shell variable to be given. It's a bit
4717 of a hack, but allows the name 'shell' not to be hardwire in the
4731 of a hack, but allows the name 'shell' not to be hardwire in the
4718 magic (@) handler, which is problematic b/c it requires
4732 magic (@) handler, which is problematic b/c it requires
4719 polluting the global namespace with 'shell'. This in turn is
4733 polluting the global namespace with 'shell'. This in turn is
4720 fragile: if a user redefines a variable called shell, things
4734 fragile: if a user redefines a variable called shell, things
4721 break.
4735 break.
4722
4736
4723 - magic @: all functions available through @ need to be defined
4737 - magic @: all functions available through @ need to be defined
4724 as magic_<name>, even though they can be called simply as
4738 as magic_<name>, even though they can be called simply as
4725 @<name>. This allows the special command @magic to gather
4739 @<name>. This allows the special command @magic to gather
4726 information automatically about all existing magic functions,
4740 information automatically about all existing magic functions,
4727 even if they are run-time user extensions, by parsing the shell
4741 even if they are run-time user extensions, by parsing the shell
4728 instance __dict__ looking for special magic_ names.
4742 instance __dict__ looking for special magic_ names.
4729
4743
4730 - mainloop: added *two* local namespace parameters. This allows
4744 - mainloop: added *two* local namespace parameters. This allows
4731 the class to differentiate between parameters which were there
4745 the class to differentiate between parameters which were there
4732 before and after command line initialization was processed. This
4746 before and after command line initialization was processed. This
4733 way, later @who can show things loaded at startup by the
4747 way, later @who can show things loaded at startup by the
4734 user. This trick was necessary to make session saving/reloading
4748 user. This trick was necessary to make session saving/reloading
4735 really work: ideally after saving/exiting/reloading a session,
4749 really work: ideally after saving/exiting/reloading a session,
4736 *everythin* should look the same, including the output of @who. I
4750 *everythin* should look the same, including the output of @who. I
4737 was only able to make this work with this double namespace
4751 was only able to make this work with this double namespace
4738 trick.
4752 trick.
4739
4753
4740 - added a header to the logfile which allows (almost) full
4754 - added a header to the logfile which allows (almost) full
4741 session restoring.
4755 session restoring.
4742
4756
4743 - prepend lines beginning with @ or !, with a and log
4757 - prepend lines beginning with @ or !, with a and log
4744 them. Why? !lines: may be useful to know what you did @lines:
4758 them. Why? !lines: may be useful to know what you did @lines:
4745 they may affect session state. So when restoring a session, at
4759 they may affect session state. So when restoring a session, at
4746 least inform the user of their presence. I couldn't quite get
4760 least inform the user of their presence. I couldn't quite get
4747 them to properly re-execute, but at least the user is warned.
4761 them to properly re-execute, but at least the user is warned.
4748
4762
4749 * Started ChangeLog.
4763 * Started ChangeLog.
@@ -1,390 +1,395 b''
1 .\" Hey, EMACS: -*- nroff -*-
1 .\" Hey, EMACS: -*- nroff -*-
2 .\" First parameter, NAME, should be all caps
2 .\" First parameter, NAME, should be all caps
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 .\" other parameters are allowed: see man(7), man(1)
4 .\" other parameters are allowed: see man(7), man(1)
5 .TH IPYTHON 1 "November 30, 2004"
5 .TH IPYTHON 1 "November 30, 2004"
6 .\" Please adjust this date whenever revising the manpage.
6 .\" Please adjust this date whenever revising the manpage.
7 .\"
7 .\"
8 .\" Some roff macros, for reference:
8 .\" Some roff macros, for reference:
9 .\" .nh disable hyphenation
9 .\" .nh disable hyphenation
10 .\" .hy enable hyphenation
10 .\" .hy enable hyphenation
11 .\" .ad l left justify
11 .\" .ad l left justify
12 .\" .ad b justify to both left and right margins
12 .\" .ad b justify to both left and right margins
13 .\" .nf disable filling
13 .\" .nf disable filling
14 .\" .fi enable filling
14 .\" .fi enable filling
15 .\" .br insert line break
15 .\" .br insert line break
16 .\" .sp <n> insert n+1 empty lines
16 .\" .sp <n> insert n+1 empty lines
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
18 .\" .SH section heading
18 .\" .SH section heading
19 .\" .SS secondary section heading
19 .\" .SS secondary section heading
20 .\"
20 .\"
21 .\"
21 .\"
22 .\" To preview this page as plain text: nroff -man ipython.1
22 .\" To preview this page as plain text: nroff -man ipython.1
23 .\"
23 .\"
24 .SH NAME
24 .SH NAME
25 ipython \- An Enhanced Interactive Python
25 ipython \- An Enhanced Interactive Python
26 .SH SYNOPSIS
26 .SH SYNOPSIS
27 .B ipython
27 .B ipython
28 .RI [ options ] " files" ...
28 .RI [ options ] " files" ...
29 .SH DESCRIPTION
29 .SH DESCRIPTION
30 An interactive Python shell with automatic history (input and output),
30 An interactive Python shell with automatic history (input and output),
31 dynamic object introspection, easier configuration, command
31 dynamic object introspection, easier configuration, command
32 completion, access to the system shell, integration with numerical and
32 completion, access to the system shell, integration with numerical and
33 scientific computing tools, and more.
33 scientific computing tools, and more.
34 .SH SPECIAL THREADING OPTIONS
34 .SH SPECIAL THREADING OPTIONS
35 The following special options are ONLY valid at the beginning of the command
35 The following special options are ONLY valid at the beginning of the command
36 line, and not later. This is because they control the initialization of
36 line, and not later. This is because they control the initialization of
37 ipython itself, before the normal option-handling mechanism is active.
37 ipython itself, before the normal option-handling mechanism is active.
38 .TP
38 .TP
39 .B \-gthread, \-qthread, \-wthread, \-pylab
39 .B \-gthread, \-qthread, \-wthread, \-pylab
40 Only ONE of these can be given, and it can only be given as the first option
40 Only ONE of these can be given, and it can only be given as the first option
41 passed to IPython (it will have no effect in any other position). They
41 passed to IPython (it will have no effect in any other position). They
42 provide threading support for the GTK, QT and WXWidgets toolkits, and for the
42 provide threading support for the GTK, QT and WXWidgets toolkits, and for the
43 matplotlib library.
43 matplotlib library.
44 .br
44 .br
45 .sp 1
45 .sp 1
46 With any of the first three options, IPython starts running a separate thread
46 With any of the first three options, IPython starts running a separate thread
47 for the graphical toolkit's operation, so that you can open and control
47 for the graphical toolkit's operation, so that you can open and control
48 graphical elements from within an IPython command line, without blocking. All
48 graphical elements from within an IPython command line, without blocking. All
49 three provide essentially the same functionality, respectively for GTK, QT and
49 three provide essentially the same functionality, respectively for GTK, QT and
50 WXWidgets (via their Python interfaces).
50 WXWidgets (via their Python interfaces).
51 .br
51 .br
52 .sp 1
52 .sp 1
53 If \-pylab is given, IPython loads special support for the matplotlib library
53 If \-pylab is given, IPython loads special support for the matplotlib library
54 (http://matplotlib.sourceforge.net), allowing interactive usage of any of its
54 (http://matplotlib.sourceforge.net), allowing interactive usage of any of its
55 backends as defined in the user's .matplotlibrc file. It automatically
55 backends as defined in the user's .matplotlibrc file. It automatically
56 activates GTK, QT or WX threading for IPyhton if the choice of matplotlib
56 activates GTK, QT or WX threading for IPyhton if the choice of matplotlib
57 backend requires it. It also modifies the %run command to correctly execute
57 backend requires it. It also modifies the %run command to correctly execute
58 (without blocking) any matplotlib-based script which calls show() at the end.
58 (without blocking) any matplotlib-based script which calls show() at the end.
59 .TP
59 .TP
60 .B \-tk
60 .B \-tk
61 The \-g/q/wthread options, and \-pylab (if matplotlib is configured to use
61 The \-g/q/wthread options, and \-pylab (if matplotlib is configured to use
62 GTK, QT or WX), will normally block Tk graphical interfaces. This means that
62 GTK, QT or WX), will normally block Tk graphical interfaces. This means that
63 when GTK, QT or WX threading is active, any attempt to open a Tk GUI will
63 when GTK, QT or WX threading is active, any attempt to open a Tk GUI will
64 result in a dead window, and possibly cause the Python interpreter to crash.
64 result in a dead window, and possibly cause the Python interpreter to crash.
65 An extra option, \-tk, is available to address this issue. It can ONLY be
65 An extra option, \-tk, is available to address this issue. It can ONLY be
66 given as a SECOND option after any of the above (\-gthread, \-qthread,
66 given as a SECOND option after any of the above (\-gthread, \-qthread,
67 \-wthread or \-pylab).
67 \-wthread or \-pylab).
68 .br
68 .br
69 .sp 1
69 .sp 1
70 If \-tk is given, IPython will try to coordinate Tk threading with GTK, QT or
70 If \-tk is given, IPython will try to coordinate Tk threading with GTK, QT or
71 WX. This is however potentially unreliable, and you will have to test on your
71 WX. This is however potentially unreliable, and you will have to test on your
72 platform and Python configuration to determine whether it works for you.
72 platform and Python configuration to determine whether it works for you.
73 Debian users have reported success, apparently due to the fact that Debian
73 Debian users have reported success, apparently due to the fact that Debian
74 builds all of Tcl, Tk, Tkinter and Python with pthreads support. Under other
74 builds all of Tcl, Tk, Tkinter and Python with pthreads support. Under other
75 Linux environments (such as Fedora Core 2), this option has caused random
75 Linux environments (such as Fedora Core 2), this option has caused random
76 crashes and lockups of the Python interpreter. Under other operating systems
76 crashes and lockups of the Python interpreter. Under other operating systems
77 (Mac OSX and Windows), you'll need to try it to find out, since currently no
77 (Mac OSX and Windows), you'll need to try it to find out, since currently no
78 user reports are available.
78 user reports are available.
79 .br
79 .br
80 .sp 1
80 .sp 1
81 There is unfortunately no way for IPython to determine at runtime whether \-tk
81 There is unfortunately no way for IPython to determine at runtime whether \-tk
82 will work reliably or not, so you will need to do some experiments before
82 will work reliably or not, so you will need to do some experiments before
83 relying on it for regular work.
83 relying on it for regular work.
84 .
84 .
85 .SS A WARNING ABOUT SIGNALS AND THREADS
85 .SS A WARNING ABOUT SIGNALS AND THREADS
86 When any of the thread systems (GTK, QT or WX) are active, either directly or
86 When any of the thread systems (GTK, QT or WX) are active, either directly or
87 via \-pylab with a threaded backend, it is impossible to interrupt
87 via \-pylab with a threaded backend, it is impossible to interrupt
88 long-running Python code via Ctrl\-C. IPython can not pass the
88 long-running Python code via Ctrl\-C. IPython can not pass the
89 KeyboardInterrupt exception (or the underlying SIGINT) across threads, so any
89 KeyboardInterrupt exception (or the underlying SIGINT) across threads, so any
90 long-running process started from IPython will run to completion, or will have
90 long-running process started from IPython will run to completion, or will have
91 to be killed via an external (OS-based) mechanism.
91 to be killed via an external (OS-based) mechanism.
92 .br
92 .br
93 .sp 1
93 .sp 1
94 To the best of my knowledge, this limitation is imposed by the Python
94 To the best of my knowledge, this limitation is imposed by the Python
95 interpreter itself, and it comes from the difficulty of writing portable
95 interpreter itself, and it comes from the difficulty of writing portable
96 signal/threaded code. If any user is an expert on this topic and can suggest
96 signal/threaded code. If any user is an expert on this topic and can suggest
97 a better solution, I would love to hear about it. In the IPython sources,
97 a better solution, I would love to hear about it. In the IPython sources,
98 look at the Shell.py module, and in particular at the runcode() method.
98 look at the Shell.py module, and in particular at the runcode() method.
99 .
99 .
100 .SH REGULAR OPTIONS
100 .SH REGULAR OPTIONS
101 After the above threading options have been given, regular options can follow
101 After the above threading options have been given, regular options can follow
102 in any order. All options can be abbreviated to their shortest non-ambiguous
102 in any order. All options can be abbreviated to their shortest non-ambiguous
103 form and are case-sensitive. One or two dashes can be used. Some options
103 form and are case-sensitive. One or two dashes can be used. Some options
104 have an alternate short form, indicated after a |.
104 have an alternate short form, indicated after a |.
105 .br
105 .br
106 .sp 1
106 .sp 1
107 Most options can also be set from your ipythonrc configuration file.
107 Most options can also be set from your ipythonrc configuration file.
108 See the provided examples for assistance. Options given on the
108 See the provided examples for assistance. Options given on the
109 commandline override the values set in the ipythonrc file.
109 commandline override the values set in the ipythonrc file.
110 .br
110 .br
111 .sp 1
111 .sp 1
112 All options with a [no] prepended can be specified in negated form
112 All options with a [no] prepended can be specified in negated form
113 (\-nooption instead of \-option) to turn the feature off.
113 (\-nooption instead of \-option) to turn the feature off.
114 .TP
114 .TP
115 .B \-h, \-\-help
115 .B \-h, \-\-help
116 Show summary of options.
116 Show summary of options.
117 .TP
117 .TP
118 .B \-[no]autocall
118 .B \-autocall <val>
119 Make IPython automatically call any callable object even if you didn't type
119 Make IPython automatically call any callable object even if you didn't type
120 explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
120 explicit parentheses. For example, 'str 43' becomes
121 'str(43)' automatically. The value can be '0' to disable the
122 feature, '1' for 'smart' autocall, where it is not applied if
123 there are no more arguments on the line, and '2' for 'full'
124 autocall, where all callable objects are automatically called
125 (even if no arguments are present). The default is '1'.
121 .TP
126 .TP
122 .B \-[no]autoindent
127 .B \-[no]autoindent
123 Turn automatic indentation on/off.
128 Turn automatic indentation on/off.
124 .TP
129 .TP
125 .B \-[no]automagic
130 .B \-[no]automagic
126 Make magic commands automatic (without needing their first character
131 Make magic commands automatic (without needing their first character
127 to be %). Type %magic at the IPython prompt for more information.
132 to be %). Type %magic at the IPython prompt for more information.
128 .TP
133 .TP
129 .B \-[no]autoedit_syntax
134 .B \-[no]autoedit_syntax
130 When a syntax error occurs after editing a file, automatically open the file
135 When a syntax error occurs after editing a file, automatically open the file
131 to the trouble causing line for convenient fixing.
136 to the trouble causing line for convenient fixing.
132 .TP
137 .TP
133 .B \-[no]banner
138 .B \-[no]banner
134 Print the intial information banner (default on).
139 Print the intial information banner (default on).
135 .TP
140 .TP
136 .B \-c <command>
141 .B \-c <command>
137 Execute the given command string, and set sys.argv to ['c']. This is similar
142 Execute the given command string, and set sys.argv to ['c']. This is similar
138 to the \-c option in the normal Python interpreter.
143 to the \-c option in the normal Python interpreter.
139 .TP
144 .TP
140 .B \-cache_size|cs <n>
145 .B \-cache_size|cs <n>
141 Size of the output cache (maximum number of entries to hold in
146 Size of the output cache (maximum number of entries to hold in
142 memory). The default is 1000, you can change it permanently in your
147 memory). The default is 1000, you can change it permanently in your
143 config file. Setting it to 0 completely disables the caching system,
148 config file. Setting it to 0 completely disables the caching system,
144 and the minimum value accepted is 20 (if you provide a value less than
149 and the minimum value accepted is 20 (if you provide a value less than
145 20, it is reset to 0 and a warning is issued). This limit is defined
150 20, it is reset to 0 and a warning is issued). This limit is defined
146 because otherwise you'll spend more time re-flushing a too small cache
151 because otherwise you'll spend more time re-flushing a too small cache
147 than working.
152 than working.
148 .TP
153 .TP
149 .B \-classic|cl
154 .B \-classic|cl
150 Gives IPython a similar feel to the classic Python prompt.
155 Gives IPython a similar feel to the classic Python prompt.
151 .TP
156 .TP
152 .B \-colors <scheme>
157 .B \-colors <scheme>
153 Color scheme for prompts and exception reporting. Currently
158 Color scheme for prompts and exception reporting. Currently
154 implemented: NoColor, Linux, and LightBG.
159 implemented: NoColor, Linux, and LightBG.
155 .TP
160 .TP
156 .B \-[no]color_info
161 .B \-[no]color_info
157 IPython can display information about objects via a set of functions,
162 IPython can display information about objects via a set of functions,
158 and optionally can use colors for this, syntax highlighting source
163 and optionally can use colors for this, syntax highlighting source
159 code and various other elements. However, because this information is
164 code and various other elements. However, because this information is
160 passed through a pager (like 'less') and many pagers get confused with
165 passed through a pager (like 'less') and many pagers get confused with
161 color codes, this option is off by default. You can test it and turn
166 color codes, this option is off by default. You can test it and turn
162 it on permanently in your ipythonrc file if it works for you. As a
167 it on permanently in your ipythonrc file if it works for you. As a
163 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
168 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
164 that in RedHat 7.2 doesn't.
169 that in RedHat 7.2 doesn't.
165 .br
170 .br
166 .sp 1
171 .sp 1
167 Test it and turn it on permanently if it works with your system. The
172 Test it and turn it on permanently if it works with your system. The
168 magic function @color_info allows you to toggle this interactively for
173 magic function @color_info allows you to toggle this interactively for
169 testing.
174 testing.
170 .TP
175 .TP
171 .B \-[no]confirm_exit
176 .B \-[no]confirm_exit
172 Set to confirm when you try to exit IPython with an EOF (Control-D in
177 Set to confirm when you try to exit IPython with an EOF (Control-D in
173 Unix, Control-Z/Enter in Windows). Note that using the magic functions
178 Unix, Control-Z/Enter in Windows). Note that using the magic functions
174 @Exit or @Quit you can force a direct exit, bypassing any
179 @Exit or @Quit you can force a direct exit, bypassing any
175 confirmation.
180 confirmation.
176 .TP
181 .TP
177 .B \-[no]debug
182 .B \-[no]debug
178 Show information about the loading process. Very useful to pin down
183 Show information about the loading process. Very useful to pin down
179 problems with your configuration files or to get details about session
184 problems with your configuration files or to get details about session
180 restores.
185 restores.
181 .TP
186 .TP
182 .B \-[no]deep_reload
187 .B \-[no]deep_reload
183 IPython can use the deep_reload module which reloads changes in
188 IPython can use the deep_reload module which reloads changes in
184 modules recursively (it replaces the reload() function, so you don't
189 modules recursively (it replaces the reload() function, so you don't
185 need to change anything to use it). deep_reload() forces a full reload
190 need to change anything to use it). deep_reload() forces a full reload
186 of modules whose code may have changed, which the default reload()
191 of modules whose code may have changed, which the default reload()
187 function does not.
192 function does not.
188 .br
193 .br
189 .sp 1
194 .sp 1
190 When deep_reload is off, IPython will use the normal reload(), but
195 When deep_reload is off, IPython will use the normal reload(), but
191 deep_reload will still be available as dreload(). This feature is off
196 deep_reload will still be available as dreload(). This feature is off
192 by default [which means that you have both normal reload() and
197 by default [which means that you have both normal reload() and
193 dreload()].
198 dreload()].
194 .TP
199 .TP
195 .B \-editor <name>
200 .B \-editor <name>
196 Which editor to use with the @edit command. By default, IPython will
201 Which editor to use with the @edit command. By default, IPython will
197 honor your EDITOR environment variable (if not set, vi is the Unix
202 honor your EDITOR environment variable (if not set, vi is the Unix
198 default and notepad the Windows one). Since this editor is invoked on
203 default and notepad the Windows one). Since this editor is invoked on
199 the fly by IPython and is meant for editing small code snippets, you
204 the fly by IPython and is meant for editing small code snippets, you
200 may want to use a small, lightweight editor here (in case your default
205 may want to use a small, lightweight editor here (in case your default
201 EDITOR is something like Emacs).
206 EDITOR is something like Emacs).
202 .TP
207 .TP
203 .B \-ipythondir <name>
208 .B \-ipythondir <name>
204 The name of your IPython configuration directory IPYTHONDIR. This can
209 The name of your IPython configuration directory IPYTHONDIR. This can
205 also be specified through the environment variable IPYTHONDIR.
210 also be specified through the environment variable IPYTHONDIR.
206 .TP
211 .TP
207 .B \-log|l
212 .B \-log|l
208 Generate a log file of all input. The file is named ipython_log.py in your
213 Generate a log file of all input. The file is named ipython_log.py in your
209 current directory (which prevents logs from multiple IPython sessions from
214 current directory (which prevents logs from multiple IPython sessions from
210 trampling each other). You can use this to later restore a session by loading
215 trampling each other). You can use this to later restore a session by loading
211 your logfile as a file to be executed with option -logplay (see below).
216 your logfile as a file to be executed with option -logplay (see below).
212 .TP
217 .TP
213 .B \-logfile|lf
218 .B \-logfile|lf
214 Specify the name of your logfile.
219 Specify the name of your logfile.
215 .TP
220 .TP
216 .B \-logplay|lp
221 .B \-logplay|lp
217 Replay a previous log. For restoring a session as close as possible to
222 Replay a previous log. For restoring a session as close as possible to
218 the state you left it in, use this option (don't just run the
223 the state you left it in, use this option (don't just run the
219 logfile). With \-logplay, IPython will try to reconstruct the previous
224 logfile). With \-logplay, IPython will try to reconstruct the previous
220 working environment in full, not just execute the commands in the
225 working environment in full, not just execute the commands in the
221 logfile.
226 logfile.
222 .br
227 .br
223 .sh 1
228 .sh 1
224 When a session is restored, logging is automatically turned on again
229 When a session is restored, logging is automatically turned on again
225 with the name of the logfile it was invoked with (it is read from the
230 with the name of the logfile it was invoked with (it is read from the
226 log header). So once you've turned logging on for a session, you can
231 log header). So once you've turned logging on for a session, you can
227 quit IPython and reload it as many times as you want and it will
232 quit IPython and reload it as many times as you want and it will
228 continue to log its history and restore from the beginning every time.
233 continue to log its history and restore from the beginning every time.
229 .br
234 .br
230 .sp 1
235 .sp 1
231 Caveats: there are limitations in this option. The history variables
236 Caveats: there are limitations in this option. The history variables
232 _i*,_* and _dh don't get restored properly. In the future we will try
237 _i*,_* and _dh don't get restored properly. In the future we will try
233 to implement full session saving by writing and retrieving a
238 to implement full session saving by writing and retrieving a
234 'snapshot' of the memory state of IPython. But our first attempts
239 'snapshot' of the memory state of IPython. But our first attempts
235 failed because of inherent limitations of Python's Pickle module, so
240 failed because of inherent limitations of Python's Pickle module, so
236 this may have to wait.
241 this may have to wait.
237 .TP
242 .TP
238 .B \-[no]messages
243 .B \-[no]messages
239 Print messages which IPython collects about its startup process
244 Print messages which IPython collects about its startup process
240 (default on).
245 (default on).
241 .TP
246 .TP
242 .B \-[no]pdb
247 .B \-[no]pdb
243 Automatically call the pdb debugger after every uncaught exception. If
248 Automatically call the pdb debugger after every uncaught exception. If
244 you are used to debugging using pdb, this puts you automatically
249 you are used to debugging using pdb, this puts you automatically
245 inside of it after any call (either in IPython or in code called by
250 inside of it after any call (either in IPython or in code called by
246 it) which triggers an exception which goes uncaught.
251 it) which triggers an exception which goes uncaught.
247 .TP
252 .TP
248 .B \-[no]pprint
253 .B \-[no]pprint
249 IPython can optionally use the pprint (pretty printer) module for
254 IPython can optionally use the pprint (pretty printer) module for
250 displaying results. pprint tends to give a nicer display of nested
255 displaying results. pprint tends to give a nicer display of nested
251 data structures. If you like it, you can turn it on permanently in
256 data structures. If you like it, you can turn it on permanently in
252 your config file (default off).
257 your config file (default off).
253 .TP
258 .TP
254 .B \-profile|p <name>
259 .B \-profile|p <name>
255 Assume that your config file is ipythonrc-<name> (looks in current dir
260 Assume that your config file is ipythonrc-<name> (looks in current dir
256 first, then in IPYTHONDIR). This is a quick way to keep and load
261 first, then in IPYTHONDIR). This is a quick way to keep and load
257 multiple config files for different tasks, especially if you use the
262 multiple config files for different tasks, especially if you use the
258 include option of config files. You can keep a basic
263 include option of config files. You can keep a basic
259 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
264 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
260 this one and load extra things for particular tasks. For example:
265 this one and load extra things for particular tasks. For example:
261 .br
266 .br
262 .sp 1
267 .sp 1
263 1) $HOME/.ipython/ipythonrc : load basic things you always want.
268 1) $HOME/.ipython/ipythonrc : load basic things you always want.
264 .br
269 .br
265 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
270 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
266 modules.
271 modules.
267 .br
272 .br
268 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
273 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
269 plotting modules.
274 plotting modules.
270 .br
275 .br
271 .sp 1
276 .sp 1
272 Since it is possible to create an endless loop by having circular file
277 Since it is possible to create an endless loop by having circular file
273 inclusions, IPython will stop if it reaches 15 recursive inclusions.
278 inclusions, IPython will stop if it reaches 15 recursive inclusions.
274 .TP
279 .TP
275 .B \-prompt_in1|pi1 <string>
280 .B \-prompt_in1|pi1 <string>
276 Specify the string used for input prompts. Note that if you are using
281 Specify the string used for input prompts. Note that if you are using
277 numbered prompts, the number is represented with a '\\#' in the
282 numbered prompts, the number is represented with a '\\#' in the
278 string. Don't forget to quote strings with spaces embedded in
283 string. Don't forget to quote strings with spaces embedded in
279 them. Default: 'In [\\#]:'.
284 them. Default: 'In [\\#]:'.
280 .br
285 .br
281 .sp 1
286 .sp 1
282 Most bash-like escapes can be used to customize IPython's prompts, as well as
287 Most bash-like escapes can be used to customize IPython's prompts, as well as
283 a few additional ones which are IPython-specific. All valid prompt escapes
288 a few additional ones which are IPython-specific. All valid prompt escapes
284 are described in detail in the Customization section of the IPython HTML/PDF
289 are described in detail in the Customization section of the IPython HTML/PDF
285 manual.
290 manual.
286 .TP
291 .TP
287 .B \-prompt_in2|pi2 <string>
292 .B \-prompt_in2|pi2 <string>
288 Similar to the previous option, but used for the continuation prompts. The
293 Similar to the previous option, but used for the continuation prompts. The
289 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
294 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
290 (so you can have your continuation prompt aligned with your input
295 (so you can have your continuation prompt aligned with your input
291 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
296 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
292 with 'In [\\#]').
297 with 'In [\\#]').
293 .TP
298 .TP
294 .B \-prompt_out|po <string>
299 .B \-prompt_out|po <string>
295 String used for output prompts, also uses numbers like prompt_in1.
300 String used for output prompts, also uses numbers like prompt_in1.
296 Default: 'Out[\\#]:'.
301 Default: 'Out[\\#]:'.
297 .TP
302 .TP
298 .B \-quick
303 .B \-quick
299 Start in bare bones mode (no config file loaded).
304 Start in bare bones mode (no config file loaded).
300 .TP
305 .TP
301 .B \-rcfile <name>
306 .B \-rcfile <name>
302 Name of your IPython resource configuration file. normally IPython
307 Name of your IPython resource configuration file. normally IPython
303 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
308 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
304 the loading of your config file fails, IPython starts with a bare
309 the loading of your config file fails, IPython starts with a bare
305 bones configuration (no modules loaded at all).
310 bones configuration (no modules loaded at all).
306 .TP
311 .TP
307 .B \-[no]readline
312 .B \-[no]readline
308 Use the readline library, which is needed to support name completion
313 Use the readline library, which is needed to support name completion
309 and command history, among other things. It is enabled by default, but
314 and command history, among other things. It is enabled by default, but
310 may cause problems for users of X/Emacs in Python comint or shell
315 may cause problems for users of X/Emacs in Python comint or shell
311 buffers.
316 buffers.
312 .br
317 .br
313 .sp 1
318 .sp 1
314 Note that emacs 'eterm' buffers (opened with M-x term) support
319 Note that emacs 'eterm' buffers (opened with M-x term) support
315 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
320 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
316 and C-c !) buffers do not.
321 and C-c !) buffers do not.
317 .TP
322 .TP
318 .B \-screen_length|sl <n>
323 .B \-screen_length|sl <n>
319 Number of lines of your screen. This is used to control printing of
324 Number of lines of your screen. This is used to control printing of
320 very long strings. Strings longer than this number of lines will be
325 very long strings. Strings longer than this number of lines will be
321 sent through a pager instead of directly printed.
326 sent through a pager instead of directly printed.
322 .br
327 .br
323 .sp 1
328 .sp 1
324 The default value for this is 0, which means IPython will auto-detect
329 The default value for this is 0, which means IPython will auto-detect
325 your screen size every time it needs to print certain potentially long
330 your screen size every time it needs to print certain potentially long
326 strings (this doesn't change the behavior of the 'print' keyword, it's
331 strings (this doesn't change the behavior of the 'print' keyword, it's
327 only triggered internally). If for some reason this isn't working well
332 only triggered internally). If for some reason this isn't working well
328 (it needs curses support), specify it yourself. Otherwise don't change
333 (it needs curses support), specify it yourself. Otherwise don't change
329 the default.
334 the default.
330 .TP
335 .TP
331 .B \-separate_in|si <string>
336 .B \-separate_in|si <string>
332 Separator before input prompts. Default '\n'.
337 Separator before input prompts. Default '\n'.
333 .TP
338 .TP
334 .B \-separate_out|so <string>
339 .B \-separate_out|so <string>
335 Separator before output prompts. Default: 0 (nothing).
340 Separator before output prompts. Default: 0 (nothing).
336 .TP
341 .TP
337 .B \-separate_out2|so2 <string>
342 .B \-separate_out2|so2 <string>
338 Separator after output prompts. Default: 0 (nothing).
343 Separator after output prompts. Default: 0 (nothing).
339 .TP
344 .TP
340 .B \-nosep
345 .B \-nosep
341 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
346 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
342 Simply removes all input/output separators.
347 Simply removes all input/output separators.
343 .TP
348 .TP
344 .B \-upgrade
349 .B \-upgrade
345 Allows you to upgrade your IPYTHONDIR configuration when you install a
350 Allows you to upgrade your IPYTHONDIR configuration when you install a
346 new version of IPython. Since new versions may include new command
351 new version of IPython. Since new versions may include new command
347 lines options or example files, this copies updated ipythonrc-type
352 lines options or example files, this copies updated ipythonrc-type
348 files. However, it backs up (with a .old extension) all files which
353 files. However, it backs up (with a .old extension) all files which
349 it overwrites so that you can merge back any custimizations you might
354 it overwrites so that you can merge back any custimizations you might
350 have in your personal files.
355 have in your personal files.
351 .TP
356 .TP
352 .B \-Version
357 .B \-Version
353 Print version information and exit.
358 Print version information and exit.
354 .TP
359 .TP
355 .B \-xmode <modename>
360 .B \-xmode <modename>
356 Mode for exception reporting. The valid modes are Plain, Context, and
361 Mode for exception reporting. The valid modes are Plain, Context, and
357 Verbose.
362 Verbose.
358 .br
363 .br
359 .sp 1
364 .sp 1
360 \- Plain: similar to python's normal traceback printing.
365 \- Plain: similar to python's normal traceback printing.
361 .br
366 .br
362 .sp 1
367 .sp 1
363 \- Context: prints 5 lines of context source code around each line in the
368 \- Context: prints 5 lines of context source code around each line in the
364 traceback.
369 traceback.
365 .br
370 .br
366 .sp 1
371 .sp 1
367 \- Verbose: similar to Context, but additionally prints the variables
372 \- Verbose: similar to Context, but additionally prints the variables
368 currently visible where the exception happened (shortening their strings if
373 currently visible where the exception happened (shortening their strings if
369 too long). This can potentially be very slow, if you happen to have a huge
374 too long). This can potentially be very slow, if you happen to have a huge
370 data structure whose string representation is complex to compute. Your
375 data structure whose string representation is complex to compute. Your
371 computer may appear to freeze for a while with cpu usage at 100%. If this
376 computer may appear to freeze for a while with cpu usage at 100%. If this
372 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
377 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
373 once).
378 once).
374 .
379 .
375 .SH EMBEDDING
380 .SH EMBEDDING
376 It is possible to start an IPython instance inside your own Python
381 It is possible to start an IPython instance inside your own Python
377 programs. In the documentation example files there are some
382 programs. In the documentation example files there are some
378 illustrations on how to do this.
383 illustrations on how to do this.
379 .br
384 .br
380 .sp 1
385 .sp 1
381 This feature allows you to evalutate dynamically the state of your
386 This feature allows you to evalutate dynamically the state of your
382 code, operate with your variables, analyze them, etc. Note however
387 code, operate with your variables, analyze them, etc. Note however
383 that any changes you make to values while in the shell do NOT
388 that any changes you make to values while in the shell do NOT
384 propagate back to the running code, so it is safe to modify your
389 propagate back to the running code, so it is safe to modify your
385 values because you won't break your code in bizarre ways by doing so.
390 values because you won't break your code in bizarre ways by doing so.
386 .SH AUTHOR
391 .SH AUTHOR
387 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
392 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
388 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
393 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
389 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
394 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
390 <jack@xiph.org>, for the Debian project (but may be used by others).
395 <jack@xiph.org>, for the Debian project (but may be used by others).
@@ -1,9161 +1,9173 b''
1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
1 #LyX 1.3 created this file. For more info see http://www.lyx.org/
2 \lyxformat 221
2 \lyxformat 221
3 \textclass article
3 \textclass article
4 \begin_preamble
4 \begin_preamble
5 %\usepackage{ae,aecompl}
5 %\usepackage{ae,aecompl}
6 \usepackage{color}
6 \usepackage{color}
7
7
8 % A few colors to replace the defaults for certain link types
8 % A few colors to replace the defaults for certain link types
9 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
9 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
10 \definecolor{darkorange}{rgb}{.71,0.21,0.01}
10 \definecolor{darkorange}{rgb}{.71,0.21,0.01}
11 \definecolor{darkred}{rgb}{.52,0.08,0.01}
11 \definecolor{darkred}{rgb}{.52,0.08,0.01}
12 \definecolor{darkgreen}{rgb}{.12,.54,.11}
12 \definecolor{darkgreen}{rgb}{.12,.54,.11}
13
13
14 % Use and configure listings package for nicely formatted code
14 % Use and configure listings package for nicely formatted code
15 \usepackage{listings}
15 \usepackage{listings}
16 \lstset{
16 \lstset{
17 language=Python,
17 language=Python,
18 basicstyle=\small\ttfamily,
18 basicstyle=\small\ttfamily,
19 commentstyle=\ttfamily\color{blue},
19 commentstyle=\ttfamily\color{blue},
20 stringstyle=\ttfamily\color{darkorange},
20 stringstyle=\ttfamily\color{darkorange},
21 showstringspaces=false,
21 showstringspaces=false,
22 breaklines=true,
22 breaklines=true,
23 postbreak = \space\dots
23 postbreak = \space\dots
24 }
24 }
25
25
26 \usepackage[%pdftex, % needed for pdflatex
26 \usepackage[%pdftex, % needed for pdflatex
27 breaklinks=true, % so long urls are correctly broken across lines
27 breaklinks=true, % so long urls are correctly broken across lines
28 colorlinks=true,
28 colorlinks=true,
29 urlcolor=blue,
29 urlcolor=blue,
30 linkcolor=darkred,
30 linkcolor=darkred,
31 citecolor=darkgreen,
31 citecolor=darkgreen,
32 ]{hyperref}
32 ]{hyperref}
33
33
34 \usepackage{html}
34 \usepackage{html}
35
35
36 % This helps prevent overly long lines that stretch beyond the margins
36 % This helps prevent overly long lines that stretch beyond the margins
37 \sloppy
37 \sloppy
38
38
39 % Define a \codelist command which either uses listings for latex, or
39 % Define a \codelist command which either uses listings for latex, or
40 % plain verbatim for html (since latex2html doesn't understand the
40 % plain verbatim for html (since latex2html doesn't understand the
41 % listings package).
41 % listings package).
42 \usepackage{verbatim}
42 \usepackage{verbatim}
43 \newcommand{\codelist}[1] {
43 \newcommand{\codelist}[1] {
44 \latex{\lstinputlisting{#1}}
44 \latex{\lstinputlisting{#1}}
45 \html{\verbatiminput{#1}}
45 \html{\verbatiminput{#1}}
46 }
46 }
47 \end_preamble
47 \end_preamble
48 \language english
48 \language english
49 \inputencoding latin1
49 \inputencoding latin1
50 \fontscheme palatino
50 \fontscheme palatino
51 \graphics default
51 \graphics default
52 \paperfontsize 10
52 \paperfontsize 10
53 \spacing single
53 \spacing single
54 \papersize Default
54 \papersize Default
55 \paperpackage a4
55 \paperpackage a4
56 \use_geometry 1
56 \use_geometry 1
57 \use_amsmath 0
57 \use_amsmath 0
58 \use_natbib 0
58 \use_natbib 0
59 \use_numerical_citations 0
59 \use_numerical_citations 0
60 \paperorientation portrait
60 \paperorientation portrait
61 \leftmargin 1.1in
61 \leftmargin 1.1in
62 \topmargin 1in
62 \topmargin 1in
63 \rightmargin 1.1in
63 \rightmargin 1.1in
64 \bottommargin 1in
64 \bottommargin 1in
65 \secnumdepth 3
65 \secnumdepth 3
66 \tocdepth 3
66 \tocdepth 3
67 \paragraph_separation skip
67 \paragraph_separation skip
68 \defskip medskip
68 \defskip medskip
69 \quotes_language english
69 \quotes_language english
70 \quotes_times 2
70 \quotes_times 2
71 \papercolumns 1
71 \papercolumns 1
72 \papersides 1
72 \papersides 1
73 \paperpagestyle fancy
73 \paperpagestyle fancy
74
74
75 \layout Title
75 \layout Title
76
76
77 IPython
77 IPython
78 \newline
78 \newline
79
79
80 \size larger
80 \size larger
81 An enhanced Interactive Python
81 An enhanced Interactive Python
82 \size large
82 \size large
83
83
84 \newline
84 \newline
85 User Manual, v.
85 User Manual, v.
86 __version__
86 __version__
87 \layout Author
87 \layout Author
88
88
89 Fernando P�rez
89 Fernando P�rez
90 \layout Standard
90 \layout Standard
91
91
92
92
93 \begin_inset ERT
93 \begin_inset ERT
94 status Collapsed
94 status Collapsed
95
95
96 \layout Standard
96 \layout Standard
97
97
98 \backslash
98 \backslash
99 latex{
99 latex{
100 \end_inset
100 \end_inset
101
101
102
102
103 \begin_inset LatexCommand \tableofcontents{}
103 \begin_inset LatexCommand \tableofcontents{}
104
104
105 \end_inset
105 \end_inset
106
106
107
107
108 \begin_inset ERT
108 \begin_inset ERT
109 status Collapsed
109 status Collapsed
110
110
111 \layout Standard
111 \layout Standard
112 }
112 }
113 \end_inset
113 \end_inset
114
114
115
115
116 \layout Standard
116 \layout Standard
117
117
118
118
119 \begin_inset ERT
119 \begin_inset ERT
120 status Open
120 status Open
121
121
122 \layout Standard
122 \layout Standard
123
123
124 \backslash
124 \backslash
125 html{
125 html{
126 \backslash
126 \backslash
127 bodytext{bgcolor=#ffffff}}
127 bodytext{bgcolor=#ffffff}}
128 \end_inset
128 \end_inset
129
129
130
130
131 \layout Section
131 \layout Section
132 \pagebreak_top
132 \pagebreak_top
133 Overview
133 Overview
134 \layout Standard
134 \layout Standard
135
135
136 One of Python's most useful features is its interactive interpreter.
136 One of Python's most useful features is its interactive interpreter.
137 This system allows very fast testing of ideas without the overhead of creating
137 This system allows very fast testing of ideas without the overhead of creating
138 test files as is typical in most programming languages.
138 test files as is typical in most programming languages.
139 However, the interpreter supplied with the standard Python distribution
139 However, the interpreter supplied with the standard Python distribution
140 is somewhat limited for extended interactive use.
140 is somewhat limited for extended interactive use.
141 \layout Standard
141 \layout Standard
142
142
143 IPython is a free software project (released under the BSD license) which
143 IPython is a free software project (released under the BSD license) which
144 tries to:
144 tries to:
145 \layout Enumerate
145 \layout Enumerate
146
146
147 Provide an interactive shell superior to Python's default.
147 Provide an interactive shell superior to Python's default.
148 IPython has many features for object introspection, system shell access,
148 IPython has many features for object introspection, system shell access,
149 and its own special command system for adding functionality when working
149 and its own special command system for adding functionality when working
150 interactively.
150 interactively.
151 It tries to be a very efficient environment both for Python code development
151 It tries to be a very efficient environment both for Python code development
152 and for exploration of problems using Python objects (in situations like
152 and for exploration of problems using Python objects (in situations like
153 data analysis).
153 data analysis).
154 \layout Enumerate
154 \layout Enumerate
155
155
156 Serve as an embeddable, ready to use interpreter for your own programs.
156 Serve as an embeddable, ready to use interpreter for your own programs.
157 IPython can be started with a single call from inside another program,
157 IPython can be started with a single call from inside another program,
158 providing access to the current namespace.
158 providing access to the current namespace.
159 This can be very useful both for debugging purposes and for situations
159 This can be very useful both for debugging purposes and for situations
160 where a blend of batch-processing and interactive exploration are needed.
160 where a blend of batch-processing and interactive exploration are needed.
161 \layout Enumerate
161 \layout Enumerate
162
162
163 Offer a flexible framework which can be used as the base environment for
163 Offer a flexible framework which can be used as the base environment for
164 other systems with Python as the underlying language.
164 other systems with Python as the underlying language.
165 Specifically scientific environments like Mathematica, IDL and Matlab inspired
165 Specifically scientific environments like Mathematica, IDL and Matlab inspired
166 its design, but similar ideas can be useful in many fields.
166 its design, but similar ideas can be useful in many fields.
167 \layout Subsection
167 \layout Subsection
168
168
169 Main features
169 Main features
170 \layout Itemize
170 \layout Itemize
171
171
172 Dynamic object introspection.
172 Dynamic object introspection.
173 One can access docstrings, function definition prototypes, source code,
173 One can access docstrings, function definition prototypes, source code,
174 source files and other details of any object accessible to the interpreter
174 source files and other details of any object accessible to the interpreter
175 with a single keystroke (`
175 with a single keystroke (`
176 \family typewriter
176 \family typewriter
177 ?
177 ?
178 \family default
178 \family default
179 ').
179 ').
180 \layout Itemize
180 \layout Itemize
181
181
182 Completion in the local namespace, by typing TAB at the prompt.
182 Completion in the local namespace, by typing TAB at the prompt.
183 This works for keywords, methods, variables and files in the current directory.
183 This works for keywords, methods, variables and files in the current directory.
184 This is supported via the readline library, and full access to configuring
184 This is supported via the readline library, and full access to configuring
185 readline's behavior is provided.
185 readline's behavior is provided.
186 \layout Itemize
186 \layout Itemize
187
187
188 Numbered input/output prompts with command history (persistent across sessions
188 Numbered input/output prompts with command history (persistent across sessions
189 and tied to each profile), full searching in this history and caching of
189 and tied to each profile), full searching in this history and caching of
190 all input and output.
190 all input and output.
191 \layout Itemize
191 \layout Itemize
192
192
193 User-extensible `magic' commands.
193 User-extensible `magic' commands.
194 A set of commands prefixed with
194 A set of commands prefixed with
195 \family typewriter
195 \family typewriter
196 %
196 %
197 \family default
197 \family default
198 is available for controlling IPython itself and provides directory control,
198 is available for controlling IPython itself and provides directory control,
199 namespace information and many aliases to common system shell commands.
199 namespace information and many aliases to common system shell commands.
200 \layout Itemize
200 \layout Itemize
201
201
202 Alias facility for defining your own system aliases.
202 Alias facility for defining your own system aliases.
203 \layout Itemize
203 \layout Itemize
204
204
205 Complete system shell access.
205 Complete system shell access.
206 Lines starting with ! are passed directly to the system shell, and using
206 Lines starting with ! are passed directly to the system shell, and using
207 !! captures shell output into python variables for further use.
207 !! captures shell output into python variables for further use.
208 \layout Itemize
208 \layout Itemize
209
209
210 All calls to the system (via aliases or via !) have their standard output/error
210 All calls to the system (via aliases or via !) have their standard output/error
211 automatically stored as strings, and also available as lists.
211 automatically stored as strings, and also available as lists.
212 \layout Itemize
212 \layout Itemize
213
213
214 Background execution of Python commands in a separate thread.
214 Background execution of Python commands in a separate thread.
215 IPython has an internal job manager called
215 IPython has an internal job manager called
216 \family typewriter
216 \family typewriter
217 jobs
217 jobs
218 \family default
218 \family default
219 , and a conveninence backgrounding magic function called
219 , and a conveninence backgrounding magic function called
220 \family typewriter
220 \family typewriter
221 %bg
221 %bg
222 \family default
222 \family default
223 .
223 .
224 \layout Itemize
224 \layout Itemize
225
225
226 The ability to expand python variables when calling the system shell.
226 The ability to expand python variables when calling the system shell.
227 In a shell command, any python variable prefixed with
227 In a shell command, any python variable prefixed with
228 \family typewriter
228 \family typewriter
229 $
229 $
230 \family default
230 \family default
231 is expanded.
231 is expanded.
232 A double
232 A double
233 \family typewriter
233 \family typewriter
234 $$
234 $$
235 \family default
235 \family default
236 allows passing a literal
236 allows passing a literal
237 \family typewriter
237 \family typewriter
238 $
238 $
239 \family default
239 \family default
240 to the shell (for access to shell and environment variables like
240 to the shell (for access to shell and environment variables like
241 \family typewriter
241 \family typewriter
242 $PATH
242 $PATH
243 \family default
243 \family default
244 ).
244 ).
245 \layout Itemize
245 \layout Itemize
246
246
247 Filesystem navigation, via a magic
247 Filesystem navigation, via a magic
248 \family typewriter
248 \family typewriter
249 %cd
249 %cd
250 \family default
250 \family default
251 command, along with a persistent bookmark system (using
251 command, along with a persistent bookmark system (using
252 \family typewriter
252 \family typewriter
253 %bookmark
253 %bookmark
254 \family default
254 \family default
255 ) for fast access to frequently visited directories.
255 ) for fast access to frequently visited directories.
256 \layout Itemize
256 \layout Itemize
257
257
258 Automatic indentation (optional) of code as you type (through the readline
258 Automatic indentation (optional) of code as you type (through the readline
259 library).
259 library).
260 \layout Itemize
260 \layout Itemize
261
261
262 Macro system for quickly re-executing multiple lines of previous input with
262 Macro system for quickly re-executing multiple lines of previous input with
263 a single name.
263 a single name.
264 \layout Itemize
264 \layout Itemize
265
265
266 Session logging (you can then later use these logs as code in your programs).
266 Session logging (you can then later use these logs as code in your programs).
267 \layout Itemize
267 \layout Itemize
268
268
269 Session restoring: logs can be replayed to restore a previous session to
269 Session restoring: logs can be replayed to restore a previous session to
270 the state where you left it.
270 the state where you left it.
271 \layout Itemize
271 \layout Itemize
272
272
273 Verbose and colored exception traceback printouts.
273 Verbose and colored exception traceback printouts.
274 Easier to parse visually, and in verbose mode they produce a lot of useful
274 Easier to parse visually, and in verbose mode they produce a lot of useful
275 debugging information (basically a terminal version of the cgitb module).
275 debugging information (basically a terminal version of the cgitb module).
276 \layout Itemize
276 \layout Itemize
277
277
278 Auto-parentheses: callable objects can be executed without parentheses:
278 Auto-parentheses: callable objects can be executed without parentheses:
279
279
280 \family typewriter
280 \family typewriter
281 `sin 3'
281 `sin 3'
282 \family default
282 \family default
283 is automatically converted to
283 is automatically converted to
284 \family typewriter
284 \family typewriter
285 `sin(3)
285 `sin(3)
286 \family default
286 \family default
287 '.
287 '.
288 \layout Itemize
288 \layout Itemize
289
289
290 Auto-quoting: using `
290 Auto-quoting: using `
291 \family typewriter
291 \family typewriter
292 ,
292 ,
293 \family default
293 \family default
294 ' or `
294 ' or `
295 \family typewriter
295 \family typewriter
296 ;
296 ;
297 \family default
297 \family default
298 ' as the first character forces auto-quoting of the rest of the line:
298 ' as the first character forces auto-quoting of the rest of the line:
299 \family typewriter
299 \family typewriter
300 `,my_function a\SpecialChar ~
300 `,my_function a\SpecialChar ~
301 b'
301 b'
302 \family default
302 \family default
303 becomes automatically
303 becomes automatically
304 \family typewriter
304 \family typewriter
305 `my_function("a","b")'
305 `my_function("a","b")'
306 \family default
306 \family default
307 , while
307 , while
308 \family typewriter
308 \family typewriter
309 `;my_function a\SpecialChar ~
309 `;my_function a\SpecialChar ~
310 b'
310 b'
311 \family default
311 \family default
312 becomes
312 becomes
313 \family typewriter
313 \family typewriter
314 `my_function("a b")'
314 `my_function("a b")'
315 \family default
315 \family default
316 .
316 .
317 \layout Itemize
317 \layout Itemize
318
318
319 Extensible input syntax.
319 Extensible input syntax.
320 You can define filters that pre-process user input to simplify input in
320 You can define filters that pre-process user input to simplify input in
321 special situations.
321 special situations.
322 This allows for example pasting multi-line code fragments which start with
322 This allows for example pasting multi-line code fragments which start with
323
323
324 \family typewriter
324 \family typewriter
325 `>>>'
325 `>>>'
326 \family default
326 \family default
327 or
327 or
328 \family typewriter
328 \family typewriter
329 `...'
329 `...'
330 \family default
330 \family default
331 such as those from other python sessions or the standard Python documentation.
331 such as those from other python sessions or the standard Python documentation.
332 \layout Itemize
332 \layout Itemize
333
333
334 Flexible configuration system.
334 Flexible configuration system.
335 It uses a configuration file which allows permanent setting of all command-line
335 It uses a configuration file which allows permanent setting of all command-line
336 options, module loading, code and file execution.
336 options, module loading, code and file execution.
337 The system allows recursive file inclusion, so you can have a base file
337 The system allows recursive file inclusion, so you can have a base file
338 with defaults and layers which load other customizations for particular
338 with defaults and layers which load other customizations for particular
339 projects.
339 projects.
340 \layout Itemize
340 \layout Itemize
341
341
342 Embeddable.
342 Embeddable.
343 You can call IPython as a python shell inside your own python programs.
343 You can call IPython as a python shell inside your own python programs.
344 This can be used both for debugging code or for providing interactive abilities
344 This can be used both for debugging code or for providing interactive abilities
345 to your programs with knowledge about the local namespaces (very useful
345 to your programs with knowledge about the local namespaces (very useful
346 in debugging and data analysis situations).
346 in debugging and data analysis situations).
347 \layout Itemize
347 \layout Itemize
348
348
349 Easy debugger access.
349 Easy debugger access.
350 You can set IPython to call up an enhanced version of the Python debugger
350 You can set IPython to call up an enhanced version of the Python debugger
351 (
351 (
352 \family typewriter
352 \family typewriter
353 pdb
353 pdb
354 \family default
354 \family default
355 ) every time there is an uncaught exception.
355 ) every time there is an uncaught exception.
356 This drops you inside the code which triggered the exception with all the
356 This drops you inside the code which triggered the exception with all the
357 data live and it is possible to navigate the stack to rapidly isolate the
357 data live and it is possible to navigate the stack to rapidly isolate the
358 source of a bug.
358 source of a bug.
359 The
359 The
360 \family typewriter
360 \family typewriter
361 %run
361 %run
362 \family default
362 \family default
363 magic command --with the
363 magic command --with the
364 \family typewriter
364 \family typewriter
365 -d
365 -d
366 \family default
366 \family default
367 option-- can run any script under
367 option-- can run any script under
368 \family typewriter
368 \family typewriter
369 pdb
369 pdb
370 \family default
370 \family default
371 's control, automatically setting initial breakpoints for you.
371 's control, automatically setting initial breakpoints for you.
372 This version of
372 This version of
373 \family typewriter
373 \family typewriter
374 pdb
374 pdb
375 \family default
375 \family default
376 has IPython-specific improvements, including tab-completion and traceback
376 has IPython-specific improvements, including tab-completion and traceback
377 coloring support.
377 coloring support.
378 \layout Itemize
378 \layout Itemize
379
379
380 Profiler support.
380 Profiler support.
381 You can run single statements (similar to
381 You can run single statements (similar to
382 \family typewriter
382 \family typewriter
383 profile.run()
383 profile.run()
384 \family default
384 \family default
385 ) or complete programs under the profiler's control.
385 ) or complete programs under the profiler's control.
386 While this is possible with the standard
386 While this is possible with the standard
387 \family typewriter
387 \family typewriter
388 profile
388 profile
389 \family default
389 \family default
390 module, IPython wraps this functionality with magic commands (see
390 module, IPython wraps this functionality with magic commands (see
391 \family typewriter
391 \family typewriter
392 `%prun'
392 `%prun'
393 \family default
393 \family default
394 and
394 and
395 \family typewriter
395 \family typewriter
396 `%run -p
396 `%run -p
397 \family default
397 \family default
398 ') convenient for rapid interactive work.
398 ') convenient for rapid interactive work.
399 \layout Subsection
399 \layout Subsection
400
400
401 Portability and Python requirements
401 Portability and Python requirements
402 \layout Standard
402 \layout Standard
403
403
404
404
405 \series bold
405 \series bold
406 Python requirements:
406 Python requirements:
407 \series default
407 \series default
408 IPython works with Python version 2.2 or newer.
408 IPython works with Python version 2.2 or newer.
409 It has been tested with Python 2.4 and no problems have been reported.
409 It has been tested with Python 2.4 and no problems have been reported.
410 Support for Python 2.1 hasn't been recently tested, since I don't have access
410 Support for Python 2.1 hasn't been recently tested, since I don't have access
411 to it on any of my systems.
411 to it on any of my systems.
412 But I suspect there may be some problems with Python 2.1, because some of
412 But I suspect there may be some problems with Python 2.1, because some of
413 the newer code may use 2.2 features.
413 the newer code may use 2.2 features.
414 \layout Standard
414 \layout Standard
415
415
416 IPython is developed under
416 IPython is developed under
417 \series bold
417 \series bold
418 Linux
418 Linux
419 \series default
419 \series default
420 , but it should work in any reasonable Unix-type system (tested OK under
420 , but it should work in any reasonable Unix-type system (tested OK under
421 Solaris and the *BSD family, for which a port exists thanks to Dryice Liu).
421 Solaris and the *BSD family, for which a port exists thanks to Dryice Liu).
422 \layout Standard
422 \layout Standard
423
423
424
424
425 \series bold
425 \series bold
426 Mac OS X
426 Mac OS X
427 \series default
427 \series default
428 : it works, apparently without any problems (thanks to Jim Boyle at Lawrence
428 : it works, apparently without any problems (thanks to Jim Boyle at Lawrence
429 Livermore for the information).
429 Livermore for the information).
430 Thanks to Andrea Riciputi, Fink support is available.
430 Thanks to Andrea Riciputi, Fink support is available.
431 \layout Standard
431 \layout Standard
432
432
433
433
434 \series bold
434 \series bold
435 CygWin
435 CygWin
436 \series default
436 \series default
437 : it works mostly OK, though some users have reported problems with prompt
437 : it works mostly OK, though some users have reported problems with prompt
438 coloring.
438 coloring.
439 No satisfactory solution to this has been found so far, you may want to
439 No satisfactory solution to this has been found so far, you may want to
440 disable colors permanently in the
440 disable colors permanently in the
441 \family typewriter
441 \family typewriter
442 ipythonrc
442 ipythonrc
443 \family default
443 \family default
444 configuration file if you experience problems.
444 configuration file if you experience problems.
445 If you have proper color support under cygwin, please post to the IPython
445 If you have proper color support under cygwin, please post to the IPython
446 mailing list so this issue can be resolved for all users.
446 mailing list so this issue can be resolved for all users.
447 \layout Standard
447 \layout Standard
448
448
449
449
450 \series bold
450 \series bold
451 Windows
451 Windows
452 \series default
452 \series default
453 : it works well under Windows XP/2k, and I suspect NT should behave similarly.
453 : it works well under Windows XP/2k, and I suspect NT should behave similarly.
454 Section\SpecialChar ~
454 Section\SpecialChar ~
455
455
456 \begin_inset LatexCommand \ref{sub:Under-Windows}
456 \begin_inset LatexCommand \ref{sub:Under-Windows}
457
457
458 \end_inset
458 \end_inset
459
459
460 describes installation details for Windows, including some additional tools
460 describes installation details for Windows, including some additional tools
461 needed on this platform.
461 needed on this platform.
462 \layout Standard
462 \layout Standard
463
463
464 Windows 9x support is present, and has been reported to work fine (at least
464 Windows 9x support is present, and has been reported to work fine (at least
465 on WinME).
465 on WinME).
466 \layout Standard
466 \layout Standard
467
467
468 Please note, however, that I have very little access to and experience with
468 Please note, however, that I have very little access to and experience with
469 Windows development.
469 Windows development.
470 For this reason, Windows-specific bugs tend to linger far longer than I
470 For this reason, Windows-specific bugs tend to linger far longer than I
471 would like, and often I just can't find a satisfactory solution.
471 would like, and often I just can't find a satisfactory solution.
472 If any Windows user wants to join in with development help, all hands are
472 If any Windows user wants to join in with development help, all hands are
473 always welcome.
473 always welcome.
474 \layout Subsection
474 \layout Subsection
475
475
476 Location
476 Location
477 \layout Standard
477 \layout Standard
478
478
479 IPython is generously hosted at
479 IPython is generously hosted at
480 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
480 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
481
481
482 \end_inset
482 \end_inset
483
483
484 by the SciPy project.
484 by the SciPy project.
485 This site offers downloads, subversion access, mailing lists and a bug
485 This site offers downloads, subversion access, mailing lists and a bug
486 tracking system.
486 tracking system.
487 I am very grateful to Enthought (
487 I am very grateful to Enthought (
488 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
488 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
489
489
490 \end_inset
490 \end_inset
491
491
492 ) and all of the SciPy team for their contribution.
492 ) and all of the SciPy team for their contribution.
493 \layout Section
493 \layout Section
494
494
495
495
496 \begin_inset LatexCommand \label{sec:install}
496 \begin_inset LatexCommand \label{sec:install}
497
497
498 \end_inset
498 \end_inset
499
499
500 Installation
500 Installation
501 \layout Subsection
501 \layout Subsection
502
502
503 Instant instructions
503 Instant instructions
504 \layout Standard
504 \layout Standard
505
505
506 If you are of the impatient kind, under Linux/Unix simply untar/unzip the
506 If you are of the impatient kind, under Linux/Unix simply untar/unzip the
507 download, then install with
507 download, then install with
508 \family typewriter
508 \family typewriter
509 `python setup.py install'
509 `python setup.py install'
510 \family default
510 \family default
511 .
511 .
512 Under Windows, double-click on the provided
512 Under Windows, double-click on the provided
513 \family typewriter
513 \family typewriter
514 .exe
514 .exe
515 \family default
515 \family default
516 binary installer.
516 binary installer.
517 \layout Standard
517 \layout Standard
518
518
519 Then, take a look at Sections
519 Then, take a look at Sections
520 \begin_inset LatexCommand \ref{sec:good_config}
520 \begin_inset LatexCommand \ref{sec:good_config}
521
521
522 \end_inset
522 \end_inset
523
523
524 for configuring things optimally and
524 for configuring things optimally and
525 \begin_inset LatexCommand \ref{sec:quick_tips}
525 \begin_inset LatexCommand \ref{sec:quick_tips}
526
526
527 \end_inset
527 \end_inset
528
528
529 for quick tips on efficient use of IPython.
529 for quick tips on efficient use of IPython.
530 You can later refer to the rest of the manual for all the gory details.
530 You can later refer to the rest of the manual for all the gory details.
531 \layout Standard
531 \layout Standard
532
532
533 See the notes in sec.
533 See the notes in sec.
534
534
535 \begin_inset LatexCommand \ref{sec:upgrade}
535 \begin_inset LatexCommand \ref{sec:upgrade}
536
536
537 \end_inset
537 \end_inset
538
538
539 for upgrading IPython versions.
539 for upgrading IPython versions.
540 \layout Subsection
540 \layout Subsection
541
541
542 Detailed Unix instructions (Linux, Mac OS X, etc.)
542 Detailed Unix instructions (Linux, Mac OS X, etc.)
543 \layout Standard
543 \layout Standard
544
544
545 For RPM based systems, simply install the supplied package in the usual
545 For RPM based systems, simply install the supplied package in the usual
546 manner.
546 manner.
547 If you download the tar archive, the process is:
547 If you download the tar archive, the process is:
548 \layout Enumerate
548 \layout Enumerate
549
549
550 Unzip/untar the
550 Unzip/untar the
551 \family typewriter
551 \family typewriter
552 ipython-XXX.tar.gz
552 ipython-XXX.tar.gz
553 \family default
553 \family default
554 file wherever you want (
554 file wherever you want (
555 \family typewriter
555 \family typewriter
556 XXX
556 XXX
557 \family default
557 \family default
558 is the version number).
558 is the version number).
559 It will make a directory called
559 It will make a directory called
560 \family typewriter
560 \family typewriter
561 ipython-XXX.
561 ipython-XXX.
562
562
563 \family default
563 \family default
564 Change into that directory where you will find the files
564 Change into that directory where you will find the files
565 \family typewriter
565 \family typewriter
566 README
566 README
567 \family default
567 \family default
568 and
568 and
569 \family typewriter
569 \family typewriter
570 setup.py
570 setup.py
571 \family default
571 \family default
572 .
572 .
573
573
574 \family typewriter
574 \family typewriter
575 O
575 O
576 \family default
576 \family default
577 nce you've completed the installation, you can safely remove this directory.
577 nce you've completed the installation, you can safely remove this directory.
578
578
579 \layout Enumerate
579 \layout Enumerate
580
580
581 If you are installing over a previous installation of version 0.2.0 or earlier,
581 If you are installing over a previous installation of version 0.2.0 or earlier,
582 first remove your
582 first remove your
583 \family typewriter
583 \family typewriter
584 $HOME/.ipython
584 $HOME/.ipython
585 \family default
585 \family default
586 directory, since the configuration file format has changed somewhat (the
586 directory, since the configuration file format has changed somewhat (the
587 '=' were removed from all option specifications).
587 '=' were removed from all option specifications).
588 Or you can call ipython with the
588 Or you can call ipython with the
589 \family typewriter
589 \family typewriter
590 -upgrade
590 -upgrade
591 \family default
591 \family default
592 option and it will do this automatically for you.
592 option and it will do this automatically for you.
593 \layout Enumerate
593 \layout Enumerate
594
594
595 IPython uses distutils, so you can install it by simply typing at the system
595 IPython uses distutils, so you can install it by simply typing at the system
596 prompt (don't type the
596 prompt (don't type the
597 \family typewriter
597 \family typewriter
598 $
598 $
599 \family default
599 \family default
600 )
600 )
601 \newline
601 \newline
602
602
603 \family typewriter
603 \family typewriter
604 $ python setup.py install
604 $ python setup.py install
605 \family default
605 \family default
606
606
607 \newline
607 \newline
608 Note that this assumes you have root access to your machine.
608 Note that this assumes you have root access to your machine.
609 If you don't have root access or don't want IPython to go in the default
609 If you don't have root access or don't want IPython to go in the default
610 python directories, you'll need to use the
610 python directories, you'll need to use the
611 \begin_inset ERT
611 \begin_inset ERT
612 status Collapsed
612 status Collapsed
613
613
614 \layout Standard
614 \layout Standard
615
615
616 \backslash
616 \backslash
617 verb|--home|
617 verb|--home|
618 \end_inset
618 \end_inset
619
619
620 option (or
620 option (or
621 \begin_inset ERT
621 \begin_inset ERT
622 status Collapsed
622 status Collapsed
623
623
624 \layout Standard
624 \layout Standard
625
625
626 \backslash
626 \backslash
627 verb|--prefix|
627 verb|--prefix|
628 \end_inset
628 \end_inset
629
629
630 ).
630 ).
631 For example:
631 For example:
632 \newline
632 \newline
633
633
634 \begin_inset ERT
634 \begin_inset ERT
635 status Collapsed
635 status Collapsed
636
636
637 \layout Standard
637 \layout Standard
638
638
639 \backslash
639 \backslash
640 verb|$ python setup.py install --home $HOME/local|
640 verb|$ python setup.py install --home $HOME/local|
641 \end_inset
641 \end_inset
642
642
643
643
644 \newline
644 \newline
645 will install IPython into
645 will install IPython into
646 \family typewriter
646 \family typewriter
647 $HOME/local
647 $HOME/local
648 \family default
648 \family default
649 and its subdirectories (creating them if necessary).
649 and its subdirectories (creating them if necessary).
650 \newline
650 \newline
651 You can type
651 You can type
652 \newline
652 \newline
653
653
654 \begin_inset ERT
654 \begin_inset ERT
655 status Collapsed
655 status Collapsed
656
656
657 \layout Standard
657 \layout Standard
658
658
659 \backslash
659 \backslash
660 verb|$ python setup.py --help|
660 verb|$ python setup.py --help|
661 \end_inset
661 \end_inset
662
662
663
663
664 \newline
664 \newline
665 for more details.
665 for more details.
666 \newline
666 \newline
667 Note that if you change the default location for
667 Note that if you change the default location for
668 \begin_inset ERT
668 \begin_inset ERT
669 status Collapsed
669 status Collapsed
670
670
671 \layout Standard
671 \layout Standard
672
672
673 \backslash
673 \backslash
674 verb|--home|
674 verb|--home|
675 \end_inset
675 \end_inset
676
676
677 at installation, IPython may end up installed at a location which is not
677 at installation, IPython may end up installed at a location which is not
678 part of your
678 part of your
679 \family typewriter
679 \family typewriter
680 $PYTHONPATH
680 $PYTHONPATH
681 \family default
681 \family default
682 environment variable.
682 environment variable.
683 In this case, you'll need to configure this variable to include the actual
683 In this case, you'll need to configure this variable to include the actual
684 directory where the
684 directory where the
685 \family typewriter
685 \family typewriter
686 IPython/
686 IPython/
687 \family default
687 \family default
688 directory ended (typically the value you give to
688 directory ended (typically the value you give to
689 \begin_inset ERT
689 \begin_inset ERT
690 status Collapsed
690 status Collapsed
691
691
692 \layout Standard
692 \layout Standard
693
693
694 \backslash
694 \backslash
695 verb|--home|
695 verb|--home|
696 \end_inset
696 \end_inset
697
697
698 plus
698 plus
699 \family typewriter
699 \family typewriter
700 /lib/python
700 /lib/python
701 \family default
701 \family default
702 ).
702 ).
703 \layout Subsubsection
703 \layout Subsubsection
704
704
705 Mac OSX information
705 Mac OSX information
706 \layout Standard
706 \layout Standard
707
707
708 Under OSX, there is a choice you need to make.
708 Under OSX, there is a choice you need to make.
709 Apple ships its own build of Python, which lives in the core OSX filesystem
709 Apple ships its own build of Python, which lives in the core OSX filesystem
710 hierarchy.
710 hierarchy.
711 You can also manually install a separate Python, either purely by hand
711 You can also manually install a separate Python, either purely by hand
712 (typically in
712 (typically in
713 \family typewriter
713 \family typewriter
714 /usr/local
714 /usr/local
715 \family default
715 \family default
716 ) or by using Fink, which puts everything under
716 ) or by using Fink, which puts everything under
717 \family typewriter
717 \family typewriter
718 /sw
718 /sw
719 \family default
719 \family default
720 .
720 .
721 Which route to follow is a matter of personal preference, as I've seen
721 Which route to follow is a matter of personal preference, as I've seen
722 users who favor each of the approaches.
722 users who favor each of the approaches.
723 Here I will simply list the known installation issues under OSX, along
723 Here I will simply list the known installation issues under OSX, along
724 with their solutions.
724 with their solutions.
725 \layout Standard
725 \layout Standard
726
726
727 This page:
727 This page:
728 \begin_inset LatexCommand \htmlurl{http://geosci.uchicago.edu/~tobis/pylab.html}
728 \begin_inset LatexCommand \htmlurl{http://geosci.uchicago.edu/~tobis/pylab.html}
729
729
730 \end_inset
730 \end_inset
731
731
732 contains information on this topic, with additional details on how to make
732 contains information on this topic, with additional details on how to make
733 IPython and matplotlib play nicely under OSX.
733 IPython and matplotlib play nicely under OSX.
734 \layout Subsubsection*
734 \layout Subsubsection*
735
735
736 GUI problems
736 GUI problems
737 \layout Standard
737 \layout Standard
738
738
739 The following instructions apply to an install of IPython under OSX from
739 The following instructions apply to an install of IPython under OSX from
740 unpacking the
740 unpacking the
741 \family typewriter
741 \family typewriter
742 .tar.gz
742 .tar.gz
743 \family default
743 \family default
744 distribution and installing it for the default Python interpreter shipped
744 distribution and installing it for the default Python interpreter shipped
745 by Apple.
745 by Apple.
746 If you are using a fink install, fink will take care of these details for
746 If you are using a fink install, fink will take care of these details for
747 you, by installing IPython against fink's Python.
747 you, by installing IPython against fink's Python.
748 \layout Standard
748 \layout Standard
749
749
750 IPython offers various forms of support for interacting with graphical applicati
750 IPython offers various forms of support for interacting with graphical applicati
751 ons from the command line, from simple Tk apps (which are in principle always
751 ons from the command line, from simple Tk apps (which are in principle always
752 supported by Python) to interactive control of WX, Qt and GTK apps.
752 supported by Python) to interactive control of WX, Qt and GTK apps.
753 Under OSX, however, this requires that ipython is installed by calling
753 Under OSX, however, this requires that ipython is installed by calling
754 the special
754 the special
755 \family typewriter
755 \family typewriter
756 pythonw
756 pythonw
757 \family default
757 \family default
758 script at installation time, which takes care of coordinating things with
758 script at installation time, which takes care of coordinating things with
759 Apple's graphical environment.
759 Apple's graphical environment.
760 \layout Standard
760 \layout Standard
761
761
762 So when installing under OSX, it is best to use the following command:
762 So when installing under OSX, it is best to use the following command:
763 \family typewriter
763 \family typewriter
764
764
765 \newline
765 \newline
766
766
767 \family default
767 \family default
768
768
769 \begin_inset ERT
769 \begin_inset ERT
770 status Collapsed
770 status Collapsed
771
771
772 \layout Standard
772 \layout Standard
773
773
774 \backslash
774 \backslash
775 verb| $ sudo pythonw setup.py install --install-scripts=/usr/local/bin|
775 verb| $ sudo pythonw setup.py install --install-scripts=/usr/local/bin|
776 \end_inset
776 \end_inset
777
777
778
778
779 \newline
779 \newline
780 or
780 or
781 \newline
781 \newline
782
782
783 \begin_inset ERT
783 \begin_inset ERT
784 status Open
784 status Open
785
785
786 \layout Standard
786 \layout Standard
787
787
788 \backslash
788 \backslash
789 verb| $ sudo pythonw setup.py install --install-scripts=/usr/bin|
789 verb| $ sudo pythonw setup.py install --install-scripts=/usr/bin|
790 \end_inset
790 \end_inset
791
791
792
792
793 \newline
793 \newline
794 depending on where you like to keep hand-installed executables.
794 depending on where you like to keep hand-installed executables.
795 \layout Standard
795 \layout Standard
796
796
797 The resulting script will have an appropriate shebang line (the first line
797 The resulting script will have an appropriate shebang line (the first line
798 in the script whic begins with
798 in the script whic begins with
799 \family typewriter
799 \family typewriter
800 #!...
800 #!...
801 \family default
801 \family default
802 ) such that the ipython interpreter can interact with the OS X GUI.
802 ) such that the ipython interpreter can interact with the OS X GUI.
803 If the installed version does not work and has a shebang line that points
803 If the installed version does not work and has a shebang line that points
804 to, for example, just
804 to, for example, just
805 \family typewriter
805 \family typewriter
806 /usr/bin/python
806 /usr/bin/python
807 \family default
807 \family default
808 , then you might have a stale, cached version in your
808 , then you might have a stale, cached version in your
809 \family typewriter
809 \family typewriter
810 build/scripts-<python-version>
810 build/scripts-<python-version>
811 \family default
811 \family default
812 directory.
812 directory.
813 Delete that directory and rerun the
813 Delete that directory and rerun the
814 \family typewriter
814 \family typewriter
815 setup.py
815 setup.py
816 \family default
816 \family default
817 .
817 .
818
818
819 \layout Standard
819 \layout Standard
820
820
821 It is also a good idea to use the special flag
821 It is also a good idea to use the special flag
822 \begin_inset ERT
822 \begin_inset ERT
823 status Collapsed
823 status Collapsed
824
824
825 \layout Standard
825 \layout Standard
826
826
827 \backslash
827 \backslash
828 verb|--install-scripts|
828 verb|--install-scripts|
829 \end_inset
829 \end_inset
830
830
831 as indicated above, to ensure that the ipython scripts end up in a location
831 as indicated above, to ensure that the ipython scripts end up in a location
832 which is part of your
832 which is part of your
833 \family typewriter
833 \family typewriter
834 $PATH
834 $PATH
835 \family default
835 \family default
836 .
836 .
837 Otherwise Apple's Python will put the scripts in an internal directory
837 Otherwise Apple's Python will put the scripts in an internal directory
838 not available by default at the command line (if you use
838 not available by default at the command line (if you use
839 \family typewriter
839 \family typewriter
840 /usr/local/bin
840 /usr/local/bin
841 \family default
841 \family default
842 , you need to make sure this is in your
842 , you need to make sure this is in your
843 \family typewriter
843 \family typewriter
844 $PATH
844 $PATH
845 \family default
845 \family default
846 , which may not be true by default).
846 , which may not be true by default).
847 \layout Subsubsection*
847 \layout Subsubsection*
848
848
849 Readline problems
849 Readline problems
850 \layout Standard
850 \layout Standard
851
851
852 By default, the Python version shipped by Apple does
852 By default, the Python version shipped by Apple does
853 \emph on
853 \emph on
854 not
854 not
855 \emph default
855 \emph default
856 include the readline library, so central to IPython's behavior.
856 include the readline library, so central to IPython's behavior.
857 If you install IPython against Apple's Python, you will not have arrow
857 If you install IPython against Apple's Python, you will not have arrow
858 keys, tab completion, etc.
858 keys, tab completion, etc.
859 For Mac OSX 10.3 (Panther), you can find a prebuilt readline library here:
859 For Mac OSX 10.3 (Panther), you can find a prebuilt readline library here:
860 \newline
860 \newline
861
861
862 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip}
862 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip}
863
863
864 \end_inset
864 \end_inset
865
865
866
866
867 \layout Standard
867 \layout Standard
868
868
869 If you are using OSX 10.4 (Tiger), after installing this package you need
869 If you are using OSX 10.4 (Tiger), after installing this package you need
870 to either:
870 to either:
871 \layout Enumerate
871 \layout Enumerate
872
872
873 move
873 move
874 \family typewriter
874 \family typewriter
875 readline.so
875 readline.so
876 \family default
876 \family default
877 from
877 from
878 \family typewriter
878 \family typewriter
879 /Library/Python/2.3
879 /Library/Python/2.3
880 \family default
880 \family default
881 to
881 to
882 \family typewriter
882 \family typewriter
883 /Library/Python/2.3/site-packages
883 /Library/Python/2.3/site-packages
884 \family default
884 \family default
885 , or
885 , or
886 \layout Enumerate
886 \layout Enumerate
887
887
888 install
888 install
889 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/TigerPython23Compat.pkg.zip}
889 \begin_inset LatexCommand \htmlurl{http://pythonmac.org/packages/TigerPython23Compat.pkg.zip}
890
890
891 \end_inset
891 \end_inset
892
892
893
893
894 \layout Standard
894 \layout Standard
895
895
896 Users installing against Fink's Python or a properly hand-built one should
896 Users installing against Fink's Python or a properly hand-built one should
897 not have this problem.
897 not have this problem.
898 \layout Subsubsection*
898 \layout Subsubsection*
899
899
900 DarwinPorts
900 DarwinPorts
901 \layout Standard
901 \layout Standard
902
902
903 I report here a message from an OSX user, who suggests an alternative means
903 I report here a message from an OSX user, who suggests an alternative means
904 of using IPython under this operating system with good results.
904 of using IPython under this operating system with good results.
905 Please let me know of any updates that may be useful for this section.
905 Please let me know of any updates that may be useful for this section.
906 His message is reproduced verbatim below:
906 His message is reproduced verbatim below:
907 \layout Quote
907 \layout Quote
908
908
909 From: Markus Banfi
909 From: Markus Banfi
910 \family typewriter
910 \family typewriter
911 <markus.banfi-AT-mospheira.net>
911 <markus.banfi-AT-mospheira.net>
912 \layout Quote
912 \layout Quote
913
913
914 As a MacOS X (10.4.2) user I prefer to install software using DawinPorts instead
914 As a MacOS X (10.4.2) user I prefer to install software using DawinPorts instead
915 of Fink.
915 of Fink.
916 I had no problems installing ipython with DarwinPorts.
916 I had no problems installing ipython with DarwinPorts.
917 It's just:
917 It's just:
918 \layout Quote
918 \layout Quote
919
919
920
920
921 \family typewriter
921 \family typewriter
922 sudo port install py-ipython
922 sudo port install py-ipython
923 \layout Quote
923 \layout Quote
924
924
925 It automatically resolved all dependencies (python24, readline, py-readline).
925 It automatically resolved all dependencies (python24, readline, py-readline).
926 So far I did not encounter any problems with the DarwinPorts port of ipython.
926 So far I did not encounter any problems with the DarwinPorts port of ipython.
927
927
928 \layout Subsection
928 \layout Subsection
929
929
930
930
931 \begin_inset LatexCommand \label{sub:Under-Windows}
931 \begin_inset LatexCommand \label{sub:Under-Windows}
932
932
933 \end_inset
933 \end_inset
934
934
935 Windows instructions
935 Windows instructions
936 \layout Standard
936 \layout Standard
937
937
938 Some of IPython's very useful features are:
938 Some of IPython's very useful features are:
939 \layout Itemize
939 \layout Itemize
940
940
941 Integrated readline support (Tab-based file, object and attribute completion,
941 Integrated readline support (Tab-based file, object and attribute completion,
942 input history across sessions, editable command line, etc.)
942 input history across sessions, editable command line, etc.)
943 \layout Itemize
943 \layout Itemize
944
944
945 Coloring of prompts, code and tracebacks.
945 Coloring of prompts, code and tracebacks.
946 \layout Standard
946 \layout Standard
947
947
948 These, by default, are only available under Unix-like operating systems.
948 These, by default, are only available under Unix-like operating systems.
949 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
949 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
950 from them.
950 from them.
951 His readline library implements both GNU readline functionality and color
951 His readline library implements both GNU readline functionality and color
952 support, so that IPython under Windows XP/2k can be as friendly and powerful
952 support, so that IPython under Windows XP/2k can be as friendly and powerful
953 as under Unix-like environments.
953 as under Unix-like environments.
954 \layout Standard
954 \layout Standard
955
955
956 The
956 The
957 \family typewriter
957 \family typewriter
958 readline
958 readline
959 \family default
959 \family default
960 extension needs two other libraries to work, so in all you need:
960 extension needs two other libraries to work, so in all you need:
961 \layout Enumerate
961 \layout Enumerate
962
962
963
963
964 \family typewriter
964 \family typewriter
965 PyWin32
965 PyWin32
966 \family default
966 \family default
967 from
967 from
968 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
968 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
969
969
970 \end_inset
970 \end_inset
971
971
972 .
972 .
973 \layout Enumerate
973 \layout Enumerate
974
974
975
975
976 \family typewriter
976 \family typewriter
977 CTypes
977 CTypes
978 \family default
978 \family default
979 from
979 from
980 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
980 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
981
981
982 \end_inset
982 \end_inset
983
983
984 (you
984 (you
985 \emph on
985 \emph on
986 must
986 must
987 \emph default
987 \emph default
988 use version 0.9.1 or newer).
988 use version 0.9.1 or newer).
989 \layout Enumerate
989 \layout Enumerate
990
990
991
991
992 \family typewriter
992 \family typewriter
993 Readline
993 Readline
994 \family default
994 \family default
995 for Windows from
995 for Windows from
996 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
996 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
997
997
998 \end_inset
998 \end_inset
999
999
1000 .
1000 .
1001 \layout Standard
1001 \layout Standard
1002
1002
1003
1003
1004 \series bold
1004 \series bold
1005 Warning about a broken readline-like library:
1005 Warning about a broken readline-like library:
1006 \series default
1006 \series default
1007 several users have reported problems stemming from using the pseudo-readline
1007 several users have reported problems stemming from using the pseudo-readline
1008 library at
1008 library at
1009 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1009 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1010
1010
1011 \end_inset
1011 \end_inset
1012
1012
1013 .
1013 .
1014 This is a broken library which, while called readline, only implements
1014 This is a broken library which, while called readline, only implements
1015 an incomplete subset of the readline API.
1015 an incomplete subset of the readline API.
1016 Since it is still called readline, it fools IPython's detection mechanisms
1016 Since it is still called readline, it fools IPython's detection mechanisms
1017 and causes unpredictable crashes later.
1017 and causes unpredictable crashes later.
1018 If you wish to use IPython under Windows, you must NOT use this library,
1018 If you wish to use IPython under Windows, you must NOT use this library,
1019 which for all purposes is (at least as of version 1.6) terminally broken.
1019 which for all purposes is (at least as of version 1.6) terminally broken.
1020 \layout Subsubsection
1020 \layout Subsubsection
1021
1021
1022 Installation procedure
1022 Installation procedure
1023 \layout Standard
1023 \layout Standard
1024
1024
1025 Once you have the above installed, from the IPython download directory grab
1025 Once you have the above installed, from the IPython download directory grab
1026 the
1026 the
1027 \family typewriter
1027 \family typewriter
1028 ipython-XXX.win32.exe
1028 ipython-XXX.win32.exe
1029 \family default
1029 \family default
1030 file, where
1030 file, where
1031 \family typewriter
1031 \family typewriter
1032 XXX
1032 XXX
1033 \family default
1033 \family default
1034 represents the version number.
1034 represents the version number.
1035 This is a regular windows executable installer, which you can simply double-cli
1035 This is a regular windows executable installer, which you can simply double-cli
1036 ck to install.
1036 ck to install.
1037 It will add an entry for IPython to your Start Menu, as well as registering
1037 It will add an entry for IPython to your Start Menu, as well as registering
1038 IPython in the Windows list of applications, so you can later uninstall
1038 IPython in the Windows list of applications, so you can later uninstall
1039 it from the Control Panel.
1039 it from the Control Panel.
1040
1040
1041 \layout Standard
1041 \layout Standard
1042
1042
1043 IPython tries to install the configuration information in a directory named
1043 IPython tries to install the configuration information in a directory named
1044
1044
1045 \family typewriter
1045 \family typewriter
1046 .ipython
1046 .ipython
1047 \family default
1047 \family default
1048 (
1048 (
1049 \family typewriter
1049 \family typewriter
1050 _ipython
1050 _ipython
1051 \family default
1051 \family default
1052 under Windows) located in your `home' directory.
1052 under Windows) located in your `home' directory.
1053 IPython sets this directory by looking for a
1053 IPython sets this directory by looking for a
1054 \family typewriter
1054 \family typewriter
1055 HOME
1055 HOME
1056 \family default
1056 \family default
1057 environment variable; if such a variable does not exist, it uses
1057 environment variable; if such a variable does not exist, it uses
1058 \family typewriter
1058 \family typewriter
1059 HOMEDRIVE
1059 HOMEDRIVE
1060 \backslash
1060 \backslash
1061 HOMEPATH
1061 HOMEPATH
1062 \family default
1062 \family default
1063 (these are always defined by Windows).
1063 (these are always defined by Windows).
1064 This typically gives something like
1064 This typically gives something like
1065 \family typewriter
1065 \family typewriter
1066 C:
1066 C:
1067 \backslash
1067 \backslash
1068 Documents and Settings
1068 Documents and Settings
1069 \backslash
1069 \backslash
1070 YourUserName
1070 YourUserName
1071 \family default
1071 \family default
1072 , but your local details may vary.
1072 , but your local details may vary.
1073 In this directory you will find all the files that configure IPython's
1073 In this directory you will find all the files that configure IPython's
1074 defaults, and you can put there your profiles and extensions.
1074 defaults, and you can put there your profiles and extensions.
1075 This directory is automatically added by IPython to
1075 This directory is automatically added by IPython to
1076 \family typewriter
1076 \family typewriter
1077 sys.path
1077 sys.path
1078 \family default
1078 \family default
1079 , so anything you place there can be found by
1079 , so anything you place there can be found by
1080 \family typewriter
1080 \family typewriter
1081 import
1081 import
1082 \family default
1082 \family default
1083 statements.
1083 statements.
1084 \layout Paragraph
1084 \layout Paragraph
1085
1085
1086 Upgrading
1086 Upgrading
1087 \layout Standard
1087 \layout Standard
1088
1088
1089 For an IPython upgrade, you should first uninstall the previous version.
1089 For an IPython upgrade, you should first uninstall the previous version.
1090 This will ensure that all files and directories (such as the documentation)
1090 This will ensure that all files and directories (such as the documentation)
1091 which carry embedded version strings in their names are properly removed.
1091 which carry embedded version strings in their names are properly removed.
1092 \layout Paragraph
1092 \layout Paragraph
1093
1093
1094 Manual installation under Win32
1094 Manual installation under Win32
1095 \layout Standard
1095 \layout Standard
1096
1096
1097 In case the automatic installer does not work for some reason, you can download
1097 In case the automatic installer does not work for some reason, you can download
1098 the
1098 the
1099 \family typewriter
1099 \family typewriter
1100 ipython-XXX.tar.gz
1100 ipython-XXX.tar.gz
1101 \family default
1101 \family default
1102 file, which contains the full IPython source distribution (the popular
1102 file, which contains the full IPython source distribution (the popular
1103 WinZip can read
1103 WinZip can read
1104 \family typewriter
1104 \family typewriter
1105 .tar.gz
1105 .tar.gz
1106 \family default
1106 \family default
1107 files).
1107 files).
1108 After uncompressing the archive, you can install it at a command terminal
1108 After uncompressing the archive, you can install it at a command terminal
1109 just like any other Python module, by using
1109 just like any other Python module, by using
1110 \family typewriter
1110 \family typewriter
1111 `python setup.py install'
1111 `python setup.py install'
1112 \family default
1112 \family default
1113 .
1113 .
1114
1114
1115 \layout Standard
1115 \layout Standard
1116
1116
1117 After the installation, run the supplied
1117 After the installation, run the supplied
1118 \family typewriter
1118 \family typewriter
1119 win32_manual_post_install.py
1119 win32_manual_post_install.py
1120 \family default
1120 \family default
1121 script, which creates the necessary Start Menu shortcuts for you.
1121 script, which creates the necessary Start Menu shortcuts for you.
1122 \layout Subsection
1122 \layout Subsection
1123
1123
1124
1124
1125 \begin_inset LatexCommand \label{sec:upgrade}
1125 \begin_inset LatexCommand \label{sec:upgrade}
1126
1126
1127 \end_inset
1127 \end_inset
1128
1128
1129 Upgrading from a previous version
1129 Upgrading from a previous version
1130 \layout Standard
1130 \layout Standard
1131
1131
1132 If you are upgrading from a previous version of IPython, after doing the
1132 If you are upgrading from a previous version of IPython, after doing the
1133 routine installation described above, you should call IPython with the
1133 routine installation described above, you should call IPython with the
1134
1134
1135 \family typewriter
1135 \family typewriter
1136 -upgrade
1136 -upgrade
1137 \family default
1137 \family default
1138 option the first time you run your new copy.
1138 option the first time you run your new copy.
1139 This will automatically update your configuration directory while preserving
1139 This will automatically update your configuration directory while preserving
1140 copies of your old files.
1140 copies of your old files.
1141 You can then later merge back any personal customizations you may have
1141 You can then later merge back any personal customizations you may have
1142 made into the new files.
1142 made into the new files.
1143 It is a good idea to do this as there may be new options available in the
1143 It is a good idea to do this as there may be new options available in the
1144 new configuration files which you will not have.
1144 new configuration files which you will not have.
1145 \layout Standard
1145 \layout Standard
1146
1146
1147 Under Windows, if you don't know how to call python scripts with arguments
1147 Under Windows, if you don't know how to call python scripts with arguments
1148 from a command line, simply delete the old config directory and IPython
1148 from a command line, simply delete the old config directory and IPython
1149 will make a new one.
1149 will make a new one.
1150 Win2k and WinXP users will find it in
1150 Win2k and WinXP users will find it in
1151 \family typewriter
1151 \family typewriter
1152 C:
1152 C:
1153 \backslash
1153 \backslash
1154 Documents and Settings
1154 Documents and Settings
1155 \backslash
1155 \backslash
1156 YourUserName
1156 YourUserName
1157 \backslash
1157 \backslash
1158 _ipython
1158 _ipython
1159 \family default
1159 \family default
1160 , and Win 9x users under
1160 , and Win 9x users under
1161 \family typewriter
1161 \family typewriter
1162 C:
1162 C:
1163 \backslash
1163 \backslash
1164 Program Files
1164 Program Files
1165 \backslash
1165 \backslash
1166 IPython
1166 IPython
1167 \backslash
1167 \backslash
1168 _ipython.
1168 _ipython.
1169 \layout Section
1169 \layout Section
1170
1170
1171
1171
1172 \begin_inset LatexCommand \label{sec:good_config}
1172 \begin_inset LatexCommand \label{sec:good_config}
1173
1173
1174 \end_inset
1174 \end_inset
1175
1175
1176
1176
1177 \begin_inset OptArg
1177 \begin_inset OptArg
1178 collapsed true
1178 collapsed true
1179
1179
1180 \layout Standard
1180 \layout Standard
1181
1181
1182 Initial configuration
1182 Initial configuration
1183 \begin_inset ERT
1183 \begin_inset ERT
1184 status Collapsed
1184 status Collapsed
1185
1185
1186 \layout Standard
1186 \layout Standard
1187
1187
1188 \backslash
1188 \backslash
1189 ldots
1189 ldots
1190 \end_inset
1190 \end_inset
1191
1191
1192
1192
1193 \end_inset
1193 \end_inset
1194
1194
1195 Initial configuration of your environment
1195 Initial configuration of your environment
1196 \layout Standard
1196 \layout Standard
1197
1197
1198 This section will help you set various things in your environment for your
1198 This section will help you set various things in your environment for your
1199 IPython sessions to be as efficient as possible.
1199 IPython sessions to be as efficient as possible.
1200 All of IPython's configuration information, along with several example
1200 All of IPython's configuration information, along with several example
1201 files, is stored in a directory named by default
1201 files, is stored in a directory named by default
1202 \family typewriter
1202 \family typewriter
1203 $HOME/.ipython
1203 $HOME/.ipython
1204 \family default
1204 \family default
1205 .
1205 .
1206 You can change this by defining the environment variable
1206 You can change this by defining the environment variable
1207 \family typewriter
1207 \family typewriter
1208 IPYTHONDIR
1208 IPYTHONDIR
1209 \family default
1209 \family default
1210 , or at runtime with the command line option
1210 , or at runtime with the command line option
1211 \family typewriter
1211 \family typewriter
1212 -ipythondir
1212 -ipythondir
1213 \family default
1213 \family default
1214 .
1214 .
1215 \layout Standard
1215 \layout Standard
1216
1216
1217 If all goes well, the first time you run IPython it should automatically
1217 If all goes well, the first time you run IPython it should automatically
1218 create a user copy of the config directory for you, based on its builtin
1218 create a user copy of the config directory for you, based on its builtin
1219 defaults.
1219 defaults.
1220 You can look at the files it creates to learn more about configuring the
1220 You can look at the files it creates to learn more about configuring the
1221 system.
1221 system.
1222 The main file you will modify to configure IPython's behavior is called
1222 The main file you will modify to configure IPython's behavior is called
1223
1223
1224 \family typewriter
1224 \family typewriter
1225 ipythonrc
1225 ipythonrc
1226 \family default
1226 \family default
1227 (with a
1227 (with a
1228 \family typewriter
1228 \family typewriter
1229 .ini
1229 .ini
1230 \family default
1230 \family default
1231 extension under Windows), included for reference in Sec.
1231 extension under Windows), included for reference in Sec.
1232
1232
1233 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1233 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1234
1234
1235 \end_inset
1235 \end_inset
1236
1236
1237 .
1237 .
1238 This file is very commented and has many variables you can change to suit
1238 This file is very commented and has many variables you can change to suit
1239 your taste, you can find more details in Sec.
1239 your taste, you can find more details in Sec.
1240
1240
1241 \begin_inset LatexCommand \ref{sec:customization}
1241 \begin_inset LatexCommand \ref{sec:customization}
1242
1242
1243 \end_inset
1243 \end_inset
1244
1244
1245 .
1245 .
1246 Here we discuss the basic things you will want to make sure things are
1246 Here we discuss the basic things you will want to make sure things are
1247 working properly from the beginning.
1247 working properly from the beginning.
1248 \layout Subsection
1248 \layout Subsection
1249
1249
1250
1250
1251 \begin_inset LatexCommand \label{sec:help-access}
1251 \begin_inset LatexCommand \label{sec:help-access}
1252
1252
1253 \end_inset
1253 \end_inset
1254
1254
1255 Access to the Python help system
1255 Access to the Python help system
1256 \layout Standard
1256 \layout Standard
1257
1257
1258 This is true for Python in general (not just for IPython): you should have
1258 This is true for Python in general (not just for IPython): you should have
1259 an environment variable called
1259 an environment variable called
1260 \family typewriter
1260 \family typewriter
1261 PYTHONDOCS
1261 PYTHONDOCS
1262 \family default
1262 \family default
1263 pointing to the directory where your HTML Python documentation lives.
1263 pointing to the directory where your HTML Python documentation lives.
1264 In my system it's
1264 In my system it's
1265 \family typewriter
1265 \family typewriter
1266 /usr/share/doc/python-docs-2.3.4/html
1266 /usr/share/doc/python-docs-2.3.4/html
1267 \family default
1267 \family default
1268 , check your local details or ask your systems administrator.
1268 , check your local details or ask your systems administrator.
1269
1269
1270 \layout Standard
1270 \layout Standard
1271
1271
1272 This is the directory which holds the HTML version of the Python manuals.
1272 This is the directory which holds the HTML version of the Python manuals.
1273 Unfortunately it seems that different Linux distributions package these
1273 Unfortunately it seems that different Linux distributions package these
1274 files differently, so you may have to look around a bit.
1274 files differently, so you may have to look around a bit.
1275 Below I show the contents of this directory on my system for reference:
1275 Below I show the contents of this directory on my system for reference:
1276 \layout Standard
1276 \layout Standard
1277
1277
1278
1278
1279 \family typewriter
1279 \family typewriter
1280 [html]> ls
1280 [html]> ls
1281 \newline
1281 \newline
1282 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1282 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1283 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1283 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1284 \layout Standard
1284 \layout Standard
1285
1285
1286 You should really make sure this variable is correctly set so that Python's
1286 You should really make sure this variable is correctly set so that Python's
1287 pydoc-based help system works.
1287 pydoc-based help system works.
1288 It is a powerful and convenient system with full access to the Python manuals
1288 It is a powerful and convenient system with full access to the Python manuals
1289 and all modules accessible to you.
1289 and all modules accessible to you.
1290 \layout Standard
1290 \layout Standard
1291
1291
1292 Under Windows it seems that pydoc finds the documentation automatically,
1292 Under Windows it seems that pydoc finds the documentation automatically,
1293 so no extra setup appears necessary.
1293 so no extra setup appears necessary.
1294 \layout Subsection
1294 \layout Subsection
1295
1295
1296 Editor
1296 Editor
1297 \layout Standard
1297 \layout Standard
1298
1298
1299 The
1299 The
1300 \family typewriter
1300 \family typewriter
1301 %edit
1301 %edit
1302 \family default
1302 \family default
1303 command (and its alias
1303 command (and its alias
1304 \family typewriter
1304 \family typewriter
1305 %ed
1305 %ed
1306 \family default
1306 \family default
1307 ) will invoke the editor set in your environment as
1307 ) will invoke the editor set in your environment as
1308 \family typewriter
1308 \family typewriter
1309 EDITOR
1309 EDITOR
1310 \family default
1310 \family default
1311 .
1311 .
1312 If this variable is not set, it will default to
1312 If this variable is not set, it will default to
1313 \family typewriter
1313 \family typewriter
1314 vi
1314 vi
1315 \family default
1315 \family default
1316 under Linux/Unix and to
1316 under Linux/Unix and to
1317 \family typewriter
1317 \family typewriter
1318 notepad
1318 notepad
1319 \family default
1319 \family default
1320 under Windows.
1320 under Windows.
1321 You may want to set this variable properly and to a lightweight editor
1321 You may want to set this variable properly and to a lightweight editor
1322 which doesn't take too long to start (that is, something other than a new
1322 which doesn't take too long to start (that is, something other than a new
1323 instance of
1323 instance of
1324 \family typewriter
1324 \family typewriter
1325 Emacs
1325 Emacs
1326 \family default
1326 \family default
1327 ).
1327 ).
1328 This way you can edit multi-line code quickly and with the power of a real
1328 This way you can edit multi-line code quickly and with the power of a real
1329 editor right inside IPython.
1329 editor right inside IPython.
1330
1330
1331 \layout Standard
1331 \layout Standard
1332
1332
1333 If you are a dedicated
1333 If you are a dedicated
1334 \family typewriter
1334 \family typewriter
1335 Emacs
1335 Emacs
1336 \family default
1336 \family default
1337 user, you should set up the
1337 user, you should set up the
1338 \family typewriter
1338 \family typewriter
1339 Emacs
1339 Emacs
1340 \family default
1340 \family default
1341 server so that new requests are handled by the original process.
1341 server so that new requests are handled by the original process.
1342 This means that almost no time is spent in handling the request (assuming
1342 This means that almost no time is spent in handling the request (assuming
1343 an
1343 an
1344 \family typewriter
1344 \family typewriter
1345 Emacs
1345 Emacs
1346 \family default
1346 \family default
1347 process is already running).
1347 process is already running).
1348 For this to work, you need to set your
1348 For this to work, you need to set your
1349 \family typewriter
1349 \family typewriter
1350 EDITOR
1350 EDITOR
1351 \family default
1351 \family default
1352 environment variable to
1352 environment variable to
1353 \family typewriter
1353 \family typewriter
1354 'emacsclient'
1354 'emacsclient'
1355 \family default
1355 \family default
1356 .
1356 .
1357
1357
1358 \family typewriter
1358 \family typewriter
1359
1359
1360 \family default
1360 \family default
1361 The code below, supplied by Francois Pinard, can then be used in your
1361 The code below, supplied by Francois Pinard, can then be used in your
1362 \family typewriter
1362 \family typewriter
1363 .emacs
1363 .emacs
1364 \family default
1364 \family default
1365 file to enable the server:
1365 file to enable the server:
1366 \layout Standard
1366 \layout Standard
1367
1367
1368
1368
1369 \family typewriter
1369 \family typewriter
1370 (defvar server-buffer-clients)
1370 (defvar server-buffer-clients)
1371 \newline
1371 \newline
1372 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1372 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1373 \newline
1373 \newline
1374
1374
1375 \begin_inset ERT
1375 \begin_inset ERT
1376 status Collapsed
1376 status Collapsed
1377
1377
1378 \layout Standard
1378 \layout Standard
1379
1379
1380 \backslash
1380 \backslash
1381 hspace*{0mm}
1381 hspace*{0mm}
1382 \end_inset
1382 \end_inset
1383
1383
1384 \SpecialChar ~
1384 \SpecialChar ~
1385 \SpecialChar ~
1385 \SpecialChar ~
1386 (server-start)
1386 (server-start)
1387 \newline
1387 \newline
1388
1388
1389 \begin_inset ERT
1389 \begin_inset ERT
1390 status Collapsed
1390 status Collapsed
1391
1391
1392 \layout Standard
1392 \layout Standard
1393
1393
1394 \backslash
1394 \backslash
1395 hspace*{0mm}
1395 hspace*{0mm}
1396 \end_inset
1396 \end_inset
1397
1397
1398 \SpecialChar ~
1398 \SpecialChar ~
1399 \SpecialChar ~
1399 \SpecialChar ~
1400 (defun fp-kill-server-with-buffer-routine ()
1400 (defun fp-kill-server-with-buffer-routine ()
1401 \newline
1401 \newline
1402
1402
1403 \begin_inset ERT
1403 \begin_inset ERT
1404 status Collapsed
1404 status Collapsed
1405
1405
1406 \layout Standard
1406 \layout Standard
1407
1407
1408 \backslash
1408 \backslash
1409 hspace*{0mm}
1409 hspace*{0mm}
1410 \end_inset
1410 \end_inset
1411
1411
1412 \SpecialChar ~
1412 \SpecialChar ~
1413 \SpecialChar ~
1413 \SpecialChar ~
1414 \SpecialChar ~
1414 \SpecialChar ~
1415 \SpecialChar ~
1415 \SpecialChar ~
1416 (and server-buffer-clients (server-done)))
1416 (and server-buffer-clients (server-done)))
1417 \newline
1417 \newline
1418
1418
1419 \begin_inset ERT
1419 \begin_inset ERT
1420 status Collapsed
1420 status Collapsed
1421
1421
1422 \layout Standard
1422 \layout Standard
1423
1423
1424 \backslash
1424 \backslash
1425 hspace*{0mm}
1425 hspace*{0mm}
1426 \end_inset
1426 \end_inset
1427
1427
1428 \SpecialChar ~
1428 \SpecialChar ~
1429 \SpecialChar ~
1429 \SpecialChar ~
1430 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1430 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1431 \layout Standard
1431 \layout Standard
1432
1432
1433 You can also set the value of this editor via the commmand-line option '-
1433 You can also set the value of this editor via the commmand-line option '-
1434 \family typewriter
1434 \family typewriter
1435 editor'
1435 editor'
1436 \family default
1436 \family default
1437 or in your
1437 or in your
1438 \family typewriter
1438 \family typewriter
1439 ipythonrc
1439 ipythonrc
1440 \family default
1440 \family default
1441 file.
1441 file.
1442 This is useful if you wish to use specifically for IPython an editor different
1442 This is useful if you wish to use specifically for IPython an editor different
1443 from your typical default (and for Windows users who tend to use fewer
1443 from your typical default (and for Windows users who tend to use fewer
1444 environment variables).
1444 environment variables).
1445 \layout Subsection
1445 \layout Subsection
1446
1446
1447 Color
1447 Color
1448 \layout Standard
1448 \layout Standard
1449
1449
1450 The default IPython configuration has most bells and whistles turned on
1450 The default IPython configuration has most bells and whistles turned on
1451 (they're pretty safe).
1451 (they're pretty safe).
1452 But there's one that
1452 But there's one that
1453 \emph on
1453 \emph on
1454 may
1454 may
1455 \emph default
1455 \emph default
1456 cause problems on some systems: the use of color on screen for displaying
1456 cause problems on some systems: the use of color on screen for displaying
1457 information.
1457 information.
1458 This is very useful, since IPython can show prompts and exception tracebacks
1458 This is very useful, since IPython can show prompts and exception tracebacks
1459 with various colors, display syntax-highlighted source code, and in general
1459 with various colors, display syntax-highlighted source code, and in general
1460 make it easier to visually parse information.
1460 make it easier to visually parse information.
1461 \layout Standard
1461 \layout Standard
1462
1462
1463 The following terminals seem to handle the color sequences fine:
1463 The following terminals seem to handle the color sequences fine:
1464 \layout Itemize
1464 \layout Itemize
1465
1465
1466 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1466 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1467 \layout Itemize
1467 \layout Itemize
1468
1468
1469 CDE terminal (tested under Solaris).
1469 CDE terminal (tested under Solaris).
1470 This one boldfaces light colors.
1470 This one boldfaces light colors.
1471 \layout Itemize
1471 \layout Itemize
1472
1472
1473 (X)Emacs buffers.
1473 (X)Emacs buffers.
1474 See sec.
1474 See sec.
1475 \begin_inset LatexCommand \ref{sec:emacs}
1475 \begin_inset LatexCommand \ref{sec:emacs}
1476
1476
1477 \end_inset
1477 \end_inset
1478
1478
1479 for more details on using IPython with (X)Emacs.
1479 for more details on using IPython with (X)Emacs.
1480 \layout Itemize
1480 \layout Itemize
1481
1481
1482 A Windows (XP/2k) command prompt
1482 A Windows (XP/2k) command prompt
1483 \emph on
1483 \emph on
1484 with Gary Bishop's support extensions
1484 with Gary Bishop's support extensions
1485 \emph default
1485 \emph default
1486 .
1486 .
1487 Gary's extensions are discussed in Sec.\SpecialChar ~
1487 Gary's extensions are discussed in Sec.\SpecialChar ~
1488
1488
1489 \begin_inset LatexCommand \ref{sub:Under-Windows}
1489 \begin_inset LatexCommand \ref{sub:Under-Windows}
1490
1490
1491 \end_inset
1491 \end_inset
1492
1492
1493 .
1493 .
1494 \layout Itemize
1494 \layout Itemize
1495
1495
1496 A Windows (XP/2k) CygWin shell.
1496 A Windows (XP/2k) CygWin shell.
1497 Although some users have reported problems; it is not clear whether there
1497 Although some users have reported problems; it is not clear whether there
1498 is an issue for everyone or only under specific configurations.
1498 is an issue for everyone or only under specific configurations.
1499 If you have full color support under cygwin, please post to the IPython
1499 If you have full color support under cygwin, please post to the IPython
1500 mailing list so this issue can be resolved for all users.
1500 mailing list so this issue can be resolved for all users.
1501 \layout Standard
1501 \layout Standard
1502
1502
1503 These have shown problems:
1503 These have shown problems:
1504 \layout Itemize
1504 \layout Itemize
1505
1505
1506 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1506 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1507 or ssh.
1507 or ssh.
1508 \layout Itemize
1508 \layout Itemize
1509
1509
1510 Windows native command prompt in WinXP/2k,
1510 Windows native command prompt in WinXP/2k,
1511 \emph on
1511 \emph on
1512 without
1512 without
1513 \emph default
1513 \emph default
1514 Gary Bishop's extensions.
1514 Gary Bishop's extensions.
1515 Once Gary's readline library is installed, the normal WinXP/2k command
1515 Once Gary's readline library is installed, the normal WinXP/2k command
1516 prompt works perfectly.
1516 prompt works perfectly.
1517 \layout Standard
1517 \layout Standard
1518
1518
1519 Currently the following color schemes are available:
1519 Currently the following color schemes are available:
1520 \layout Itemize
1520 \layout Itemize
1521
1521
1522
1522
1523 \family typewriter
1523 \family typewriter
1524 NoColor
1524 NoColor
1525 \family default
1525 \family default
1526 : uses no color escapes at all (all escapes are empty
1526 : uses no color escapes at all (all escapes are empty
1527 \begin_inset Quotes eld
1527 \begin_inset Quotes eld
1528 \end_inset
1528 \end_inset
1529
1529
1530
1530
1531 \begin_inset Quotes eld
1531 \begin_inset Quotes eld
1532 \end_inset
1532 \end_inset
1533
1533
1534 strings).
1534 strings).
1535 This 'scheme' is thus fully safe to use in any terminal.
1535 This 'scheme' is thus fully safe to use in any terminal.
1536 \layout Itemize
1536 \layout Itemize
1537
1537
1538
1538
1539 \family typewriter
1539 \family typewriter
1540 Linux
1540 Linux
1541 \family default
1541 \family default
1542 : works well in Linux console type environments: dark background with light
1542 : works well in Linux console type environments: dark background with light
1543 fonts.
1543 fonts.
1544 It uses bright colors for information, so it is difficult to read if you
1544 It uses bright colors for information, so it is difficult to read if you
1545 have a light colored background.
1545 have a light colored background.
1546 \layout Itemize
1546 \layout Itemize
1547
1547
1548
1548
1549 \family typewriter
1549 \family typewriter
1550 LightBG
1550 LightBG
1551 \family default
1551 \family default
1552 : the basic colors are similar to those in the
1552 : the basic colors are similar to those in the
1553 \family typewriter
1553 \family typewriter
1554 Linux
1554 Linux
1555 \family default
1555 \family default
1556 scheme but darker.
1556 scheme but darker.
1557 It is easy to read in terminals with light backgrounds.
1557 It is easy to read in terminals with light backgrounds.
1558 \layout Standard
1558 \layout Standard
1559
1559
1560 IPython uses colors for two main groups of things: prompts and tracebacks
1560 IPython uses colors for two main groups of things: prompts and tracebacks
1561 which are directly printed to the terminal, and the object introspection
1561 which are directly printed to the terminal, and the object introspection
1562 system which passes large sets of data through a pager.
1562 system which passes large sets of data through a pager.
1563 \layout Subsubsection
1563 \layout Subsubsection
1564
1564
1565 Input/Output prompts and exception tracebacks
1565 Input/Output prompts and exception tracebacks
1566 \layout Standard
1566 \layout Standard
1567
1567
1568 You can test whether the colored prompts and tracebacks work on your system
1568 You can test whether the colored prompts and tracebacks work on your system
1569 interactively by typing
1569 interactively by typing
1570 \family typewriter
1570 \family typewriter
1571 '%colors Linux'
1571 '%colors Linux'
1572 \family default
1572 \family default
1573 at the prompt (use '
1573 at the prompt (use '
1574 \family typewriter
1574 \family typewriter
1575 %colors LightBG'
1575 %colors LightBG'
1576 \family default
1576 \family default
1577 if your terminal has a light background).
1577 if your terminal has a light background).
1578 If the input prompt shows garbage like:
1578 If the input prompt shows garbage like:
1579 \newline
1579 \newline
1580
1580
1581 \family typewriter
1581 \family typewriter
1582 [0;32mIn [[1;32m1[0;32m]: [0;00m
1582 [0;32mIn [[1;32m1[0;32m]: [0;00m
1583 \family default
1583 \family default
1584
1584
1585 \newline
1585 \newline
1586 instead of (in color) something like:
1586 instead of (in color) something like:
1587 \newline
1587 \newline
1588
1588
1589 \family typewriter
1589 \family typewriter
1590 In [1]:
1590 In [1]:
1591 \family default
1591 \family default
1592
1592
1593 \newline
1593 \newline
1594 this means that your terminal doesn't properly handle color escape sequences.
1594 this means that your terminal doesn't properly handle color escape sequences.
1595 You can go to a 'no color' mode by typing '
1595 You can go to a 'no color' mode by typing '
1596 \family typewriter
1596 \family typewriter
1597 %colors NoColor
1597 %colors NoColor
1598 \family default
1598 \family default
1599 '.
1599 '.
1600
1600
1601 \layout Standard
1601 \layout Standard
1602
1602
1603 You can try using a different terminal emulator program.
1603 You can try using a different terminal emulator program.
1604 To permanently set your color preferences, edit the file
1604 To permanently set your color preferences, edit the file
1605 \family typewriter
1605 \family typewriter
1606 $HOME/.ipython/ipythonrc
1606 $HOME/.ipython/ipythonrc
1607 \family default
1607 \family default
1608 and set the
1608 and set the
1609 \family typewriter
1609 \family typewriter
1610 colors
1610 colors
1611 \family default
1611 \family default
1612 option to the desired value.
1612 option to the desired value.
1613 \layout Subsubsection
1613 \layout Subsubsection
1614
1614
1615 Object details (types, docstrings, source code, etc.)
1615 Object details (types, docstrings, source code, etc.)
1616 \layout Standard
1616 \layout Standard
1617
1617
1618 IPython has a set of special functions for studying the objects you are
1618 IPython has a set of special functions for studying the objects you are
1619 working with, discussed in detail in Sec.
1619 working with, discussed in detail in Sec.
1620
1620
1621 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1621 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1622
1622
1623 \end_inset
1623 \end_inset
1624
1624
1625 .
1625 .
1626 But this system relies on passing information which is longer than your
1626 But this system relies on passing information which is longer than your
1627 screen through a data pager, such as the common Unix
1627 screen through a data pager, such as the common Unix
1628 \family typewriter
1628 \family typewriter
1629 less
1629 less
1630 \family default
1630 \family default
1631 and
1631 and
1632 \family typewriter
1632 \family typewriter
1633 more
1633 more
1634 \family default
1634 \family default
1635 programs.
1635 programs.
1636 In order to be able to see this information in color, your pager needs
1636 In order to be able to see this information in color, your pager needs
1637 to be properly configured.
1637 to be properly configured.
1638 I strongly recommend using
1638 I strongly recommend using
1639 \family typewriter
1639 \family typewriter
1640 less
1640 less
1641 \family default
1641 \family default
1642 instead of
1642 instead of
1643 \family typewriter
1643 \family typewriter
1644 more
1644 more
1645 \family default
1645 \family default
1646 , as it seems that
1646 , as it seems that
1647 \family typewriter
1647 \family typewriter
1648 more
1648 more
1649 \family default
1649 \family default
1650 simply can not understand colored text correctly.
1650 simply can not understand colored text correctly.
1651 \layout Standard
1651 \layout Standard
1652
1652
1653 In order to configure
1653 In order to configure
1654 \family typewriter
1654 \family typewriter
1655 less
1655 less
1656 \family default
1656 \family default
1657 as your default pager, do the following:
1657 as your default pager, do the following:
1658 \layout Enumerate
1658 \layout Enumerate
1659
1659
1660 Set the environment
1660 Set the environment
1661 \family typewriter
1661 \family typewriter
1662 PAGER
1662 PAGER
1663 \family default
1663 \family default
1664 variable to
1664 variable to
1665 \family typewriter
1665 \family typewriter
1666 less
1666 less
1667 \family default
1667 \family default
1668 .
1668 .
1669 \layout Enumerate
1669 \layout Enumerate
1670
1670
1671 Set the environment
1671 Set the environment
1672 \family typewriter
1672 \family typewriter
1673 LESS
1673 LESS
1674 \family default
1674 \family default
1675 variable to
1675 variable to
1676 \family typewriter
1676 \family typewriter
1677 -r
1677 -r
1678 \family default
1678 \family default
1679 (plus any other options you always want to pass to
1679 (plus any other options you always want to pass to
1680 \family typewriter
1680 \family typewriter
1681 less
1681 less
1682 \family default
1682 \family default
1683 by default).
1683 by default).
1684 This tells
1684 This tells
1685 \family typewriter
1685 \family typewriter
1686 less
1686 less
1687 \family default
1687 \family default
1688 to properly interpret control sequences, which is how color information
1688 to properly interpret control sequences, which is how color information
1689 is given to your terminal.
1689 is given to your terminal.
1690 \layout Standard
1690 \layout Standard
1691
1691
1692 For the
1692 For the
1693 \family typewriter
1693 \family typewriter
1694 csh
1694 csh
1695 \family default
1695 \family default
1696 or
1696 or
1697 \family typewriter
1697 \family typewriter
1698 tcsh
1698 tcsh
1699 \family default
1699 \family default
1700 shells, add to your
1700 shells, add to your
1701 \family typewriter
1701 \family typewriter
1702 ~/.cshrc
1702 ~/.cshrc
1703 \family default
1703 \family default
1704 file the lines:
1704 file the lines:
1705 \layout Standard
1705 \layout Standard
1706
1706
1707
1707
1708 \family typewriter
1708 \family typewriter
1709 setenv PAGER less
1709 setenv PAGER less
1710 \newline
1710 \newline
1711 setenv LESS -r
1711 setenv LESS -r
1712 \layout Standard
1712 \layout Standard
1713
1713
1714 There is similar syntax for other Unix shells, look at your system documentation
1714 There is similar syntax for other Unix shells, look at your system documentation
1715 for details.
1715 for details.
1716 \layout Standard
1716 \layout Standard
1717
1717
1718 If you are on a system which lacks proper data pagers (such as Windows),
1718 If you are on a system which lacks proper data pagers (such as Windows),
1719 IPython will use a very limited builtin pager.
1719 IPython will use a very limited builtin pager.
1720 \layout Subsection
1720 \layout Subsection
1721
1721
1722
1722
1723 \begin_inset LatexCommand \label{sec:emacs}
1723 \begin_inset LatexCommand \label{sec:emacs}
1724
1724
1725 \end_inset
1725 \end_inset
1726
1726
1727 (X)Emacs configuration
1727 (X)Emacs configuration
1728 \layout Standard
1728 \layout Standard
1729
1729
1730 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1730 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1731 (X)Emacs and IPython get along very well.
1731 (X)Emacs and IPython get along very well.
1732
1732
1733 \layout Standard
1733 \layout Standard
1734
1734
1735
1735
1736 \series bold
1736 \series bold
1737 Important note:
1737 Important note:
1738 \series default
1738 \series default
1739 You will need to use a recent enough version of
1739 You will need to use a recent enough version of
1740 \family typewriter
1740 \family typewriter
1741 python-mode.el
1741 python-mode.el
1742 \family default
1742 \family default
1743 , along with the file
1743 , along with the file
1744 \family typewriter
1744 \family typewriter
1745 ipython.el
1745 ipython.el
1746 \family default
1746 \family default
1747 .
1747 .
1748 You can check that the version you have of
1748 You can check that the version you have of
1749 \family typewriter
1749 \family typewriter
1750 python-mode.el
1750 python-mode.el
1751 \family default
1751 \family default
1752 is new enough by either looking at the revision number in the file itself,
1752 is new enough by either looking at the revision number in the file itself,
1753 or asking for it in (X)Emacs via
1753 or asking for it in (X)Emacs via
1754 \family typewriter
1754 \family typewriter
1755 M-x py-version
1755 M-x py-version
1756 \family default
1756 \family default
1757 .
1757 .
1758 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1758 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1759 \layout Standard
1759 \layout Standard
1760
1760
1761 The file
1761 The file
1762 \family typewriter
1762 \family typewriter
1763 ipython.el
1763 ipython.el
1764 \family default
1764 \family default
1765 is included with the IPython distribution, in the documentation directory
1765 is included with the IPython distribution, in the documentation directory
1766 (where this manual resides in PDF and HTML formats).
1766 (where this manual resides in PDF and HTML formats).
1767 \layout Standard
1767 \layout Standard
1768
1768
1769 Once you put these files in your Emacs path, all you need in your
1769 Once you put these files in your Emacs path, all you need in your
1770 \family typewriter
1770 \family typewriter
1771 .emacs
1771 .emacs
1772 \family default
1772 \family default
1773 file is:
1773 file is:
1774 \layout Standard
1774 \layout Standard
1775
1775
1776
1776
1777 \family typewriter
1777 \family typewriter
1778 (require 'ipython)
1778 (require 'ipython)
1779 \layout Standard
1779 \layout Standard
1780
1780
1781 This should give you full support for executing code snippets via IPython,
1781 This should give you full support for executing code snippets via IPython,
1782 opening IPython as your Python shell via
1782 opening IPython as your Python shell via
1783 \family typewriter
1783 \family typewriter
1784 C-c\SpecialChar ~
1784 C-c\SpecialChar ~
1785 !
1785 !
1786 \family default
1786 \family default
1787 , etc.
1787 , etc.
1788
1788
1789 \layout Subsubsection*
1789 \layout Subsubsection*
1790
1790
1791 Notes
1791 Notes
1792 \layout Itemize
1792 \layout Itemize
1793
1793
1794 There is one caveat you should be aware of: you must start the IPython shell
1794 There is one caveat you should be aware of: you must start the IPython shell
1795
1795
1796 \emph on
1796 \emph on
1797 before
1797 before
1798 \emph default
1798 \emph default
1799 attempting to execute any code regions via
1799 attempting to execute any code regions via
1800 \family typewriter
1800 \family typewriter
1801 C-c\SpecialChar ~
1801 C-c\SpecialChar ~
1802 |
1802 |
1803 \family default
1803 \family default
1804 .
1804 .
1805 Simply type
1805 Simply type
1806 \family typewriter
1806 \family typewriter
1807 C-c\SpecialChar ~
1807 C-c\SpecialChar ~
1808 !
1808 !
1809 \family default
1809 \family default
1810 to start IPython before passing any code regions to the interpreter, and
1810 to start IPython before passing any code regions to the interpreter, and
1811 you shouldn't experience any problems.
1811 you shouldn't experience any problems.
1812 \newline
1812 \newline
1813 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1813 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1814 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1814 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1815 \layout Itemize
1815 \layout Itemize
1816
1816
1817 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1817 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1818 ts should be directed to him through the IPython mailing lists.
1818 ts should be directed to him through the IPython mailing lists.
1819
1819
1820 \layout Itemize
1820 \layout Itemize
1821
1821
1822 This code is still somewhat experimental so it's a bit rough around the
1822 This code is still somewhat experimental so it's a bit rough around the
1823 edges (although in practice, it works quite well).
1823 edges (although in practice, it works quite well).
1824 \layout Itemize
1824 \layout Itemize
1825
1825
1826 Be aware that if you customize
1826 Be aware that if you customize
1827 \family typewriter
1827 \family typewriter
1828 py-python-command
1828 py-python-command
1829 \family default
1829 \family default
1830 previously, this value will override what
1830 previously, this value will override what
1831 \family typewriter
1831 \family typewriter
1832 ipython.el
1832 ipython.el
1833 \family default
1833 \family default
1834 does (because loading the customization variables comes later).
1834 does (because loading the customization variables comes later).
1835 \layout Section
1835 \layout Section
1836
1836
1837
1837
1838 \begin_inset LatexCommand \label{sec:quick_tips}
1838 \begin_inset LatexCommand \label{sec:quick_tips}
1839
1839
1840 \end_inset
1840 \end_inset
1841
1841
1842 Quick tips
1842 Quick tips
1843 \layout Standard
1843 \layout Standard
1844
1844
1845 IPython can be used as an improved replacement for the Python prompt, and
1845 IPython can be used as an improved replacement for the Python prompt, and
1846 for that you don't really need to read any more of this manual.
1846 for that you don't really need to read any more of this manual.
1847 But in this section we'll try to summarize a few tips on how to make the
1847 But in this section we'll try to summarize a few tips on how to make the
1848 most effective use of it for everyday Python development, highlighting
1848 most effective use of it for everyday Python development, highlighting
1849 things you might miss in the rest of the manual (which is getting long).
1849 things you might miss in the rest of the manual (which is getting long).
1850 We'll give references to parts in the manual which provide more detail
1850 We'll give references to parts in the manual which provide more detail
1851 when appropriate.
1851 when appropriate.
1852 \layout Standard
1852 \layout Standard
1853
1853
1854 The following article by Jeremy Jones provides an introductory tutorial
1854 The following article by Jeremy Jones provides an introductory tutorial
1855 about IPython:
1855 about IPython:
1856 \newline
1856 \newline
1857
1857
1858 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1858 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1859
1859
1860 \end_inset
1860 \end_inset
1861
1861
1862
1862
1863 \layout Itemize
1863 \layout Itemize
1864
1864
1865 The TAB key.
1865 The TAB key.
1866 TAB-completion, especially for attributes, is a convenient way to explore
1866 TAB-completion, especially for attributes, is a convenient way to explore
1867 the structure of any object you're dealing with.
1867 the structure of any object you're dealing with.
1868 Simply type
1868 Simply type
1869 \family typewriter
1869 \family typewriter
1870 object_name.<TAB>
1870 object_name.<TAB>
1871 \family default
1871 \family default
1872 and a list of the object's attributes will be printed (see sec.
1872 and a list of the object's attributes will be printed (see sec.
1873
1873
1874 \begin_inset LatexCommand \ref{sec:readline}
1874 \begin_inset LatexCommand \ref{sec:readline}
1875
1875
1876 \end_inset
1876 \end_inset
1877
1877
1878 for more).
1878 for more).
1879 Tab completion also works on file and directory names, which combined with
1879 Tab completion also works on file and directory names, which combined with
1880 IPython's alias system allows you to do from within IPython many of the
1880 IPython's alias system allows you to do from within IPython many of the
1881 things you normally would need the system shell for.
1881 things you normally would need the system shell for.
1882
1882
1883 \layout Itemize
1883 \layout Itemize
1884
1884
1885 Explore your objects.
1885 Explore your objects.
1886 Typing
1886 Typing
1887 \family typewriter
1887 \family typewriter
1888 object_name?
1888 object_name?
1889 \family default
1889 \family default
1890 will print all sorts of details about any object, including docstrings,
1890 will print all sorts of details about any object, including docstrings,
1891 function definition lines (for call arguments) and constructor details
1891 function definition lines (for call arguments) and constructor details
1892 for classes.
1892 for classes.
1893 The magic commands
1893 The magic commands
1894 \family typewriter
1894 \family typewriter
1895 %pdoc
1895 %pdoc
1896 \family default
1896 \family default
1897 ,
1897 ,
1898 \family typewriter
1898 \family typewriter
1899 %pdef
1899 %pdef
1900 \family default
1900 \family default
1901 ,
1901 ,
1902 \family typewriter
1902 \family typewriter
1903 %psource
1903 %psource
1904 \family default
1904 \family default
1905 and
1905 and
1906 \family typewriter
1906 \family typewriter
1907 %pfile
1907 %pfile
1908 \family default
1908 \family default
1909 will respectively print the docstring, function definition line, full source
1909 will respectively print the docstring, function definition line, full source
1910 code and the complete file for any object (when they can be found).
1910 code and the complete file for any object (when they can be found).
1911 If automagic is on (it is by default), you don't need to type the '
1911 If automagic is on (it is by default), you don't need to type the '
1912 \family typewriter
1912 \family typewriter
1913 %
1913 %
1914 \family default
1914 \family default
1915 ' explicitly.
1915 ' explicitly.
1916 See sec.
1916 See sec.
1917
1917
1918 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1918 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1919
1919
1920 \end_inset
1920 \end_inset
1921
1921
1922 for more.
1922 for more.
1923 \layout Itemize
1923 \layout Itemize
1924
1924
1925 The
1925 The
1926 \family typewriter
1926 \family typewriter
1927 %run
1927 %run
1928 \family default
1928 \family default
1929 magic command allows you to run any python script and load all of its data
1929 magic command allows you to run any python script and load all of its data
1930 directly into the interactive namespace.
1930 directly into the interactive namespace.
1931 Since the file is re-read from disk each time, changes you make to it are
1931 Since the file is re-read from disk each time, changes you make to it are
1932 reflected immediately (in contrast to the behavior of
1932 reflected immediately (in contrast to the behavior of
1933 \family typewriter
1933 \family typewriter
1934 import
1934 import
1935 \family default
1935 \family default
1936 ).
1936 ).
1937 I rarely use
1937 I rarely use
1938 \family typewriter
1938 \family typewriter
1939 import
1939 import
1940 \family default
1940 \family default
1941 for code I am testing, relying on
1941 for code I am testing, relying on
1942 \family typewriter
1942 \family typewriter
1943 %run
1943 %run
1944 \family default
1944 \family default
1945 instead.
1945 instead.
1946 See sec.
1946 See sec.
1947
1947
1948 \begin_inset LatexCommand \ref{sec:magic}
1948 \begin_inset LatexCommand \ref{sec:magic}
1949
1949
1950 \end_inset
1950 \end_inset
1951
1951
1952 for more on this and other magic commands, or type the name of any magic
1952 for more on this and other magic commands, or type the name of any magic
1953 command and ? to get details on it.
1953 command and ? to get details on it.
1954 See also sec.
1954 See also sec.
1955
1955
1956 \begin_inset LatexCommand \ref{sec:dreload}
1956 \begin_inset LatexCommand \ref{sec:dreload}
1957
1957
1958 \end_inset
1958 \end_inset
1959
1959
1960 for a recursive reload command.
1960 for a recursive reload command.
1961 \newline
1961 \newline
1962
1962
1963 \family typewriter
1963 \family typewriter
1964 %run
1964 %run
1965 \family default
1965 \family default
1966 also has special flags for timing the execution of your scripts (
1966 also has special flags for timing the execution of your scripts (
1967 \family typewriter
1967 \family typewriter
1968 -t
1968 -t
1969 \family default
1969 \family default
1970 ) and for executing them under the control of either Python's
1970 ) and for executing them under the control of either Python's
1971 \family typewriter
1971 \family typewriter
1972 pdb
1972 pdb
1973 \family default
1973 \family default
1974 debugger (
1974 debugger (
1975 \family typewriter
1975 \family typewriter
1976 -d
1976 -d
1977 \family default
1977 \family default
1978 ) or profiler (
1978 ) or profiler (
1979 \family typewriter
1979 \family typewriter
1980 -p
1980 -p
1981 \family default
1981 \family default
1982 ).
1982 ).
1983 With all of these,
1983 With all of these,
1984 \family typewriter
1984 \family typewriter
1985 %run
1985 %run
1986 \family default
1986 \family default
1987 can be used as the main tool for efficient interactive development of code
1987 can be used as the main tool for efficient interactive development of code
1988 which you write in your editor of choice.
1988 which you write in your editor of choice.
1989 \layout Itemize
1989 \layout Itemize
1990
1990
1991 Use the Python debugger,
1991 Use the Python debugger,
1992 \family typewriter
1992 \family typewriter
1993 pdb
1993 pdb
1994 \family default
1994 \family default
1995
1995
1996 \begin_inset Foot
1996 \begin_inset Foot
1997 collapsed true
1997 collapsed true
1998
1998
1999 \layout Standard
1999 \layout Standard
2000
2000
2001 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2001 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2002 to IPython's improved debugger and profiler support.
2002 to IPython's improved debugger and profiler support.
2003 \end_inset
2003 \end_inset
2004
2004
2005 .
2005 .
2006 The
2006 The
2007 \family typewriter
2007 \family typewriter
2008 %pdb
2008 %pdb
2009 \family default
2009 \family default
2010 command allows you to toggle on and off the automatic invocation of an
2010 command allows you to toggle on and off the automatic invocation of an
2011 IPython-enhanced
2011 IPython-enhanced
2012 \family typewriter
2012 \family typewriter
2013 pdb
2013 pdb
2014 \family default
2014 \family default
2015 debugger (with coloring, tab completion and more) at any uncaught exception.
2015 debugger (with coloring, tab completion and more) at any uncaught exception.
2016 The advantage of this is that
2016 The advantage of this is that
2017 \family typewriter
2017 \family typewriter
2018 pdb
2018 pdb
2019 \family default
2019 \family default
2020 starts
2020 starts
2021 \emph on
2021 \emph on
2022 inside
2022 inside
2023 \emph default
2023 \emph default
2024 the function where the exception occurred, with all data still available.
2024 the function where the exception occurred, with all data still available.
2025 You can print variables, see code, execute statements and even walk up
2025 You can print variables, see code, execute statements and even walk up
2026 and down the call stack to track down the true source of the problem (which
2026 and down the call stack to track down the true source of the problem (which
2027 often is many layers in the stack above where the exception gets triggered).
2027 often is many layers in the stack above where the exception gets triggered).
2028 \newline
2028 \newline
2029 Running programs with
2029 Running programs with
2030 \family typewriter
2030 \family typewriter
2031 %run
2031 %run
2032 \family default
2032 \family default
2033 and pdb active can be an efficient to develop and debug code, in many cases
2033 and pdb active can be an efficient to develop and debug code, in many cases
2034 eliminating the need for
2034 eliminating the need for
2035 \family typewriter
2035 \family typewriter
2036 print
2036 print
2037 \family default
2037 \family default
2038 statements or external debugging tools.
2038 statements or external debugging tools.
2039 I often simply put a
2039 I often simply put a
2040 \family typewriter
2040 \family typewriter
2041 1/0
2041 1/0
2042 \family default
2042 \family default
2043 in a place where I want to take a look so that pdb gets called, quickly
2043 in a place where I want to take a look so that pdb gets called, quickly
2044 view whatever variables I need to or test various pieces of code and then
2044 view whatever variables I need to or test various pieces of code and then
2045 remove the
2045 remove the
2046 \family typewriter
2046 \family typewriter
2047 1/0
2047 1/0
2048 \family default
2048 \family default
2049 .
2049 .
2050 \newline
2050 \newline
2051 Note also that `
2051 Note also that `
2052 \family typewriter
2052 \family typewriter
2053 %run -d
2053 %run -d
2054 \family default
2054 \family default
2055 ' activates
2055 ' activates
2056 \family typewriter
2056 \family typewriter
2057 pdb
2057 pdb
2058 \family default
2058 \family default
2059 and automatically sets initial breakpoints for you to step through your
2059 and automatically sets initial breakpoints for you to step through your
2060 code, watch variables, etc.
2060 code, watch variables, etc.
2061 See Sec.\SpecialChar ~
2061 See Sec.\SpecialChar ~
2062
2062
2063 \begin_inset LatexCommand \ref{sec:cache_output}
2063 \begin_inset LatexCommand \ref{sec:cache_output}
2064
2064
2065 \end_inset
2065 \end_inset
2066
2066
2067 for details.
2067 for details.
2068 \layout Itemize
2068 \layout Itemize
2069
2069
2070 Use the output cache.
2070 Use the output cache.
2071 All output results are automatically stored in a global dictionary named
2071 All output results are automatically stored in a global dictionary named
2072
2072
2073 \family typewriter
2073 \family typewriter
2074 Out
2074 Out
2075 \family default
2075 \family default
2076 and variables named
2076 and variables named
2077 \family typewriter
2077 \family typewriter
2078 _1
2078 _1
2079 \family default
2079 \family default
2080 ,
2080 ,
2081 \family typewriter
2081 \family typewriter
2082 _2
2082 _2
2083 \family default
2083 \family default
2084 , etc.
2084 , etc.
2085 alias them.
2085 alias them.
2086 For example, the result of input line 4 is available either as
2086 For example, the result of input line 4 is available either as
2087 \family typewriter
2087 \family typewriter
2088 Out[4]
2088 Out[4]
2089 \family default
2089 \family default
2090 or as
2090 or as
2091 \family typewriter
2091 \family typewriter
2092 _4
2092 _4
2093 \family default
2093 \family default
2094 .
2094 .
2095 Additionally, three variables named
2095 Additionally, three variables named
2096 \family typewriter
2096 \family typewriter
2097 _
2097 _
2098 \family default
2098 \family default
2099 ,
2099 ,
2100 \family typewriter
2100 \family typewriter
2101 __
2101 __
2102 \family default
2102 \family default
2103 and
2103 and
2104 \family typewriter
2104 \family typewriter
2105 ___
2105 ___
2106 \family default
2106 \family default
2107 are always kept updated with the for the last three results.
2107 are always kept updated with the for the last three results.
2108 This allows you to recall any previous result and further use it for new
2108 This allows you to recall any previous result and further use it for new
2109 calculations.
2109 calculations.
2110 See Sec.\SpecialChar ~
2110 See Sec.\SpecialChar ~
2111
2111
2112 \begin_inset LatexCommand \ref{sec:cache_output}
2112 \begin_inset LatexCommand \ref{sec:cache_output}
2113
2113
2114 \end_inset
2114 \end_inset
2115
2115
2116 for more.
2116 for more.
2117 \layout Itemize
2117 \layout Itemize
2118
2118
2119 Put a '
2119 Put a '
2120 \family typewriter
2120 \family typewriter
2121 ;
2121 ;
2122 \family default
2122 \family default
2123 ' at the end of a line to supress the printing of output.
2123 ' at the end of a line to supress the printing of output.
2124 This is useful when doing calculations which generate long output you are
2124 This is useful when doing calculations which generate long output you are
2125 not interested in seeing.
2125 not interested in seeing.
2126 The
2126 The
2127 \family typewriter
2127 \family typewriter
2128 _*
2128 _*
2129 \family default
2129 \family default
2130 variables and the
2130 variables and the
2131 \family typewriter
2131 \family typewriter
2132 Out[]
2132 Out[]
2133 \family default
2133 \family default
2134 list do get updated with the contents of the output, even if it is not
2134 list do get updated with the contents of the output, even if it is not
2135 printed.
2135 printed.
2136 You can thus still access the generated results this way for further processing.
2136 You can thus still access the generated results this way for further processing.
2137 \layout Itemize
2137 \layout Itemize
2138
2138
2139 A similar system exists for caching input.
2139 A similar system exists for caching input.
2140 All input is stored in a global list called
2140 All input is stored in a global list called
2141 \family typewriter
2141 \family typewriter
2142 In
2142 In
2143 \family default
2143 \family default
2144 , so you can re-execute lines 22 through 28 plus line 34 by typing
2144 , so you can re-execute lines 22 through 28 plus line 34 by typing
2145 \family typewriter
2145 \family typewriter
2146 'exec In[22:29]+In[34]'
2146 'exec In[22:29]+In[34]'
2147 \family default
2147 \family default
2148 (using Python slicing notation).
2148 (using Python slicing notation).
2149 If you need to execute the same set of lines often, you can assign them
2149 If you need to execute the same set of lines often, you can assign them
2150 to a macro with the
2150 to a macro with the
2151 \family typewriter
2151 \family typewriter
2152 %macro
2152 %macro
2153 \family default
2153 \family default
2154
2154
2155 \family typewriter
2155 \family typewriter
2156 function.
2156 function.
2157
2157
2158 \family default
2158 \family default
2159 See sec.
2159 See sec.
2160
2160
2161 \begin_inset LatexCommand \ref{sec:cache_input}
2161 \begin_inset LatexCommand \ref{sec:cache_input}
2162
2162
2163 \end_inset
2163 \end_inset
2164
2164
2165 for more.
2165 for more.
2166 \layout Itemize
2166 \layout Itemize
2167
2167
2168 Use your input history.
2168 Use your input history.
2169 The
2169 The
2170 \family typewriter
2170 \family typewriter
2171 %hist
2171 %hist
2172 \family default
2172 \family default
2173 command can show you all previous input, without line numbers if desired
2173 command can show you all previous input, without line numbers if desired
2174 (option
2174 (option
2175 \family typewriter
2175 \family typewriter
2176 -n
2176 -n
2177 \family default
2177 \family default
2178 ) so you can directly copy and paste code either back in IPython or in a
2178 ) so you can directly copy and paste code either back in IPython or in a
2179 text editor.
2179 text editor.
2180 You can also save all your history by turning on logging via
2180 You can also save all your history by turning on logging via
2181 \family typewriter
2181 \family typewriter
2182 %logstart
2182 %logstart
2183 \family default
2183 \family default
2184 ; these logs can later be either reloaded as IPython sessions or used as
2184 ; these logs can later be either reloaded as IPython sessions or used as
2185 code for your programs.
2185 code for your programs.
2186 \layout Itemize
2186 \layout Itemize
2187
2187
2188 Define your own macros with
2188 Define your own macros with
2189 \family typewriter
2189 \family typewriter
2190 %macro
2190 %macro
2191 \family default
2191 \family default
2192 .
2192 .
2193 This can be useful for automating sequences of expressions when working
2193 This can be useful for automating sequences of expressions when working
2194 interactively.
2194 interactively.
2195 \layout Itemize
2195 \layout Itemize
2196
2196
2197 Define your own system aliases.
2197 Define your own system aliases.
2198 Even though IPython gives you access to your system shell via the
2198 Even though IPython gives you access to your system shell via the
2199 \family typewriter
2199 \family typewriter
2200 !
2200 !
2201 \family default
2201 \family default
2202 prefix, it is convenient to have aliases to the system commands you use
2202 prefix, it is convenient to have aliases to the system commands you use
2203 most often.
2203 most often.
2204 This allows you to work seamlessly from inside IPython with the same commands
2204 This allows you to work seamlessly from inside IPython with the same commands
2205 you are used to in your system shell.
2205 you are used to in your system shell.
2206 \newline
2206 \newline
2207 IPython comes with some pre-defined aliases and a complete system for changing
2207 IPython comes with some pre-defined aliases and a complete system for changing
2208 directories, both via a stack (see
2208 directories, both via a stack (see
2209 \family typewriter
2209 \family typewriter
2210 %pushd
2210 %pushd
2211 \family default
2211 \family default
2212 ,
2212 ,
2213 \family typewriter
2213 \family typewriter
2214 %popd
2214 %popd
2215 \family default
2215 \family default
2216 and
2216 and
2217 \family typewriter
2217 \family typewriter
2218 %ds
2218 %ds
2219 \family default
2219 \family default
2220 ) and via direct
2220 ) and via direct
2221 \family typewriter
2221 \family typewriter
2222 %cd
2222 %cd
2223 \family default
2223 \family default
2224 .
2224 .
2225 The latter keeps a history of visited directories and allows you to go
2225 The latter keeps a history of visited directories and allows you to go
2226 to any previously visited one.
2226 to any previously visited one.
2227 \layout Itemize
2227 \layout Itemize
2228
2228
2229 Use Python to manipulate the results of system commands.
2229 Use Python to manipulate the results of system commands.
2230 The `
2230 The `
2231 \family typewriter
2231 \family typewriter
2232 !!
2232 !!
2233 \family default
2233 \family default
2234 ' special syntax, and the
2234 ' special syntax, and the
2235 \family typewriter
2235 \family typewriter
2236 %sc
2236 %sc
2237 \family default
2237 \family default
2238 and
2238 and
2239 \family typewriter
2239 \family typewriter
2240 %sx
2240 %sx
2241 \family default
2241 \family default
2242 magic commands allow you to capture system output into Python variables.
2242 magic commands allow you to capture system output into Python variables.
2243 \layout Itemize
2243 \layout Itemize
2244
2244
2245 Expand python variables when calling the shell (either via
2245 Expand python variables when calling the shell (either via
2246 \family typewriter
2246 \family typewriter
2247 `!'
2247 `!'
2248 \family default
2248 \family default
2249 and
2249 and
2250 \family typewriter
2250 \family typewriter
2251 `!!'
2251 `!!'
2252 \family default
2252 \family default
2253 or via aliases) by prepending a
2253 or via aliases) by prepending a
2254 \family typewriter
2254 \family typewriter
2255 $
2255 $
2256 \family default
2256 \family default
2257 in front of them.
2257 in front of them.
2258 You can also expand complete python expressions.
2258 You can also expand complete python expressions.
2259 See sec.\SpecialChar ~
2259 See sec.\SpecialChar ~
2260
2260
2261 \begin_inset LatexCommand \ref{sub:System-shell-access}
2261 \begin_inset LatexCommand \ref{sub:System-shell-access}
2262
2262
2263 \end_inset
2263 \end_inset
2264
2264
2265 for more.
2265 for more.
2266 \layout Itemize
2266 \layout Itemize
2267
2267
2268 Use profiles to maintain different configurations (modules to load, function
2268 Use profiles to maintain different configurations (modules to load, function
2269 definitions, option settings) for particular tasks.
2269 definitions, option settings) for particular tasks.
2270 You can then have customized versions of IPython for specific purposes.
2270 You can then have customized versions of IPython for specific purposes.
2271 See sec.\SpecialChar ~
2271 See sec.\SpecialChar ~
2272
2272
2273 \begin_inset LatexCommand \ref{sec:profiles}
2273 \begin_inset LatexCommand \ref{sec:profiles}
2274
2274
2275 \end_inset
2275 \end_inset
2276
2276
2277 for more.
2277 for more.
2278 \layout Itemize
2278 \layout Itemize
2279
2279
2280 Embed IPython in your programs.
2280 Embed IPython in your programs.
2281 A few lines of code are enough to load a complete IPython inside your own
2281 A few lines of code are enough to load a complete IPython inside your own
2282 programs, giving you the ability to work with your data interactively after
2282 programs, giving you the ability to work with your data interactively after
2283 automatic processing has been completed.
2283 automatic processing has been completed.
2284 See sec.\SpecialChar ~
2284 See sec.\SpecialChar ~
2285
2285
2286 \begin_inset LatexCommand \ref{sec:embed}
2286 \begin_inset LatexCommand \ref{sec:embed}
2287
2287
2288 \end_inset
2288 \end_inset
2289
2289
2290 for more.
2290 for more.
2291 \layout Itemize
2291 \layout Itemize
2292
2292
2293 Use the Python profiler.
2293 Use the Python profiler.
2294 When dealing with performance issues, the
2294 When dealing with performance issues, the
2295 \family typewriter
2295 \family typewriter
2296 %run
2296 %run
2297 \family default
2297 \family default
2298 command with a
2298 command with a
2299 \family typewriter
2299 \family typewriter
2300 -p
2300 -p
2301 \family default
2301 \family default
2302 option allows you to run complete programs under the control of the Python
2302 option allows you to run complete programs under the control of the Python
2303 profiler.
2303 profiler.
2304 The
2304 The
2305 \family typewriter
2305 \family typewriter
2306 %prun
2306 %prun
2307 \family default
2307 \family default
2308 command does a similar job for single Python expressions (like function
2308 command does a similar job for single Python expressions (like function
2309 calls).
2309 calls).
2310 \layout Itemize
2310 \layout Itemize
2311
2311
2312 Use
2312 Use
2313 \family typewriter
2313 \family typewriter
2314 %edit
2314 %edit
2315 \family default
2315 \family default
2316 to have almost multiline editing.
2316 to have almost multiline editing.
2317 While IPython doesn't support true multiline editing, this command allows
2317 While IPython doesn't support true multiline editing, this command allows
2318 you to call an editor on the spot, and IPython will execute the code you
2318 you to call an editor on the spot, and IPython will execute the code you
2319 type in there as if it were typed interactively.
2319 type in there as if it were typed interactively.
2320 \layout Itemize
2320 \layout Itemize
2321
2321
2322 Use the IPython.demo.Demo class to load any Python script as an interactive
2322 Use the IPython.demo.Demo class to load any Python script as an interactive
2323 demo.
2323 demo.
2324 With a minimal amount of simple markup, you can control the execution of
2324 With a minimal amount of simple markup, you can control the execution of
2325 the script, stopping as needed.
2325 the script, stopping as needed.
2326 See sec.\SpecialChar ~
2326 See sec.\SpecialChar ~
2327
2327
2328 \begin_inset LatexCommand \ref{sec:interactive-demos}
2328 \begin_inset LatexCommand \ref{sec:interactive-demos}
2329
2329
2330 \end_inset
2330 \end_inset
2331
2331
2332 for more.
2332 for more.
2333 \layout Standard
2333 \layout Standard
2334
2334
2335
2335
2336 \series bold
2336 \series bold
2337 Effective logging:
2337 Effective logging:
2338 \series default
2338 \series default
2339 a very useful suggestion sent in by Robert Kern follows
2339 a very useful suggestion sent in by Robert Kern follows
2340 \layout Standard
2340 \layout Standard
2341
2341
2342 I recently happened on a nifty way to keep tidy per-project log files.
2342 I recently happened on a nifty way to keep tidy per-project log files.
2343 I made a profile for my project (which is called "parkfield").
2343 I made a profile for my project (which is called "parkfield").
2344 \layout LyX-Code
2344 \layout LyX-Code
2345
2345
2346 include ipythonrc
2346 include ipythonrc
2347 \layout LyX-Code
2347 \layout LyX-Code
2348
2348
2349 logfile '' # cancel earlier logfile invocation
2349 logfile '' # cancel earlier logfile invocation
2350 \layout LyX-Code
2350 \layout LyX-Code
2351
2351
2352 execute import time
2352 execute import time
2353 \layout LyX-Code
2353 \layout LyX-Code
2354
2354
2355 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
2355 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
2356 \layout LyX-Code
2356 \layout LyX-Code
2357
2357
2358 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
2358 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
2359 \layout Standard
2359 \layout Standard
2360
2360
2361 I also added a shell alias for convenience:
2361 I also added a shell alias for convenience:
2362 \layout LyX-Code
2362 \layout LyX-Code
2363
2363
2364 alias parkfield="ipython -pylab -profile parkfield"
2364 alias parkfield="ipython -pylab -profile parkfield"
2365 \layout Standard
2365 \layout Standard
2366
2366
2367 Now I have a nice little directory with everything I ever type in, organized
2367 Now I have a nice little directory with everything I ever type in, organized
2368 by project and date.
2368 by project and date.
2369 \layout Standard
2369 \layout Standard
2370
2370
2371
2371
2372 \series bold
2372 \series bold
2373 Contribute your own:
2373 Contribute your own:
2374 \series default
2374 \series default
2375 If you have your own favorite tip on using IPython efficiently for a certain
2375 If you have your own favorite tip on using IPython efficiently for a certain
2376 task (especially things which can't be done in the normal Python interpreter),
2376 task (especially things which can't be done in the normal Python interpreter),
2377 don't hesitate to send it!
2377 don't hesitate to send it!
2378 \layout Section
2378 \layout Section
2379
2379
2380 Command-line use
2380 Command-line use
2381 \layout Standard
2381 \layout Standard
2382
2382
2383 You start IPython with the command:
2383 You start IPython with the command:
2384 \layout Standard
2384 \layout Standard
2385
2385
2386
2386
2387 \family typewriter
2387 \family typewriter
2388 $ ipython [options] files
2388 $ ipython [options] files
2389 \layout Standard
2389 \layout Standard
2390
2390
2391 If invoked with no options, it executes all the files listed in sequence
2391 If invoked with no options, it executes all the files listed in sequence
2392 and drops you into the interpreter while still acknowledging any options
2392 and drops you into the interpreter while still acknowledging any options
2393 you may have set in your ipythonrc file.
2393 you may have set in your ipythonrc file.
2394 This behavior is different from standard Python, which when called as
2394 This behavior is different from standard Python, which when called as
2395 \family typewriter
2395 \family typewriter
2396 python -i
2396 python -i
2397 \family default
2397 \family default
2398 will only execute one file and ignore your configuration setup.
2398 will only execute one file and ignore your configuration setup.
2399 \layout Standard
2399 \layout Standard
2400
2400
2401 Please note that some of the configuration options are not available at
2401 Please note that some of the configuration options are not available at
2402 the command line, simply because they are not practical here.
2402 the command line, simply because they are not practical here.
2403 Look into your ipythonrc configuration file for details on those.
2403 Look into your ipythonrc configuration file for details on those.
2404 This file typically installed in the
2404 This file typically installed in the
2405 \family typewriter
2405 \family typewriter
2406 $HOME/.ipython
2406 $HOME/.ipython
2407 \family default
2407 \family default
2408 directory.
2408 directory.
2409 For Windows users,
2409 For Windows users,
2410 \family typewriter
2410 \family typewriter
2411 $HOME
2411 $HOME
2412 \family default
2412 \family default
2413 resolves to
2413 resolves to
2414 \family typewriter
2414 \family typewriter
2415 C:
2415 C:
2416 \backslash
2416 \backslash
2417
2417
2418 \backslash
2418 \backslash
2419 Documents and Settings
2419 Documents and Settings
2420 \backslash
2420 \backslash
2421
2421
2422 \backslash
2422 \backslash
2423 YourUserName
2423 YourUserName
2424 \family default
2424 \family default
2425 in most instances.
2425 in most instances.
2426 In the rest of this text, we will refer to this directory as
2426 In the rest of this text, we will refer to this directory as
2427 \family typewriter
2427 \family typewriter
2428 IPYTHONDIR
2428 IPYTHONDIR
2429 \family default
2429 \family default
2430 .
2430 .
2431 \layout Subsection
2431 \layout Subsection
2432
2432
2433
2433
2434 \begin_inset LatexCommand \label{sec:threading-opts}
2434 \begin_inset LatexCommand \label{sec:threading-opts}
2435
2435
2436 \end_inset
2436 \end_inset
2437
2437
2438 Special Threading Options
2438 Special Threading Options
2439 \layout Standard
2439 \layout Standard
2440
2440
2441 The following special options are ONLY valid at the beginning of the command
2441 The following special options are ONLY valid at the beginning of the command
2442 line, and not later.
2442 line, and not later.
2443 This is because they control the initial- ization of ipython itself, before
2443 This is because they control the initial- ization of ipython itself, before
2444 the normal option-handling mechanism is active.
2444 the normal option-handling mechanism is active.
2445 \layout List
2445 \layout List
2446 \labelwidthstring 00.00.0000
2446 \labelwidthstring 00.00.0000
2447
2447
2448
2448
2449 \family typewriter
2449 \family typewriter
2450 \series bold
2450 \series bold
2451 -gthread,\SpecialChar ~
2451 -gthread,\SpecialChar ~
2452 -qthread,\SpecialChar ~
2452 -qthread,\SpecialChar ~
2453 -wthread,\SpecialChar ~
2453 -wthread,\SpecialChar ~
2454 -pylab:
2454 -pylab:
2455 \family default
2455 \family default
2456 \series default
2456 \series default
2457 Only
2457 Only
2458 \emph on
2458 \emph on
2459 one
2459 one
2460 \emph default
2460 \emph default
2461 of these can be given, and it can only be given as the first option passed
2461 of these can be given, and it can only be given as the first option passed
2462 to IPython (it will have no effect in any other position).
2462 to IPython (it will have no effect in any other position).
2463 They provide threading support for the GTK Qt and WXPython toolkits, and
2463 They provide threading support for the GTK Qt and WXPython toolkits, and
2464 for the matplotlib library.
2464 for the matplotlib library.
2465 \layout List
2465 \layout List
2466 \labelwidthstring 00.00.0000
2466 \labelwidthstring 00.00.0000
2467
2467
2468 \SpecialChar ~
2468 \SpecialChar ~
2469 With any of the first three options, IPython starts running a separate
2469 With any of the first three options, IPython starts running a separate
2470 thread for the graphical toolkit's operation, so that you can open and
2470 thread for the graphical toolkit's operation, so that you can open and
2471 control graphical elements from within an IPython command line, without
2471 control graphical elements from within an IPython command line, without
2472 blocking.
2472 blocking.
2473 All three provide essentially the same functionality, respectively for
2473 All three provide essentially the same functionality, respectively for
2474 GTK, QT and WXWidgets (via their Python interfaces).
2474 GTK, QT and WXWidgets (via their Python interfaces).
2475 \layout List
2475 \layout List
2476 \labelwidthstring 00.00.0000
2476 \labelwidthstring 00.00.0000
2477
2477
2478 \SpecialChar ~
2478 \SpecialChar ~
2479 If
2479 If
2480 \family typewriter
2480 \family typewriter
2481 -pylab
2481 -pylab
2482 \family default
2482 \family default
2483 is given, IPython loads special support for the mat plotlib library (
2483 is given, IPython loads special support for the mat plotlib library (
2484 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2484 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2485
2485
2486 \end_inset
2486 \end_inset
2487
2487
2488 ), allowing interactive usage of any of its backends as defined in the user's
2488 ), allowing interactive usage of any of its backends as defined in the user's
2489
2489
2490 \family typewriter
2490 \family typewriter
2491 ~/.matplotlib/matplotlibrc
2491 ~/.matplotlib/matplotlibrc
2492 \family default
2492 \family default
2493 file.
2493 file.
2494 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2494 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2495 of matplotlib backend requires it.
2495 of matplotlib backend requires it.
2496 It also modifies the
2496 It also modifies the
2497 \family typewriter
2497 \family typewriter
2498 %run
2498 %run
2499 \family default
2499 \family default
2500 command to correctly execute (without blocking) any matplotlib-based script
2500 command to correctly execute (without blocking) any matplotlib-based script
2501 which calls
2501 which calls
2502 \family typewriter
2502 \family typewriter
2503 show()
2503 show()
2504 \family default
2504 \family default
2505 at the end.
2505 at the end.
2506
2506
2507 \layout List
2507 \layout List
2508 \labelwidthstring 00.00.0000
2508 \labelwidthstring 00.00.0000
2509
2509
2510
2510
2511 \family typewriter
2511 \family typewriter
2512 \series bold
2512 \series bold
2513 -tk
2513 -tk
2514 \family default
2514 \family default
2515 \series default
2515 \series default
2516 The
2516 The
2517 \family typewriter
2517 \family typewriter
2518 -g/q/wthread
2518 -g/q/wthread
2519 \family default
2519 \family default
2520 options, and
2520 options, and
2521 \family typewriter
2521 \family typewriter
2522 -pylab
2522 -pylab
2523 \family default
2523 \family default
2524 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2524 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2525 Tk graphical interfaces.
2525 Tk graphical interfaces.
2526 This means that when either GTK, Qt or WX threading is active, any attempt
2526 This means that when either GTK, Qt or WX threading is active, any attempt
2527 to open a Tk GUI will result in a dead window, and possibly cause the Python
2527 to open a Tk GUI will result in a dead window, and possibly cause the Python
2528 interpreter to crash.
2528 interpreter to crash.
2529 An extra option,
2529 An extra option,
2530 \family typewriter
2530 \family typewriter
2531 -tk
2531 -tk
2532 \family default
2532 \family default
2533 , is available to address this issue.
2533 , is available to address this issue.
2534 It can
2534 It can
2535 \emph on
2535 \emph on
2536 only
2536 only
2537 \emph default
2537 \emph default
2538 be given as a
2538 be given as a
2539 \emph on
2539 \emph on
2540 second
2540 second
2541 \emph default
2541 \emph default
2542 option after any of the above (
2542 option after any of the above (
2543 \family typewriter
2543 \family typewriter
2544 -gthread
2544 -gthread
2545 \family default
2545 \family default
2546 ,
2546 ,
2547 \family typewriter
2547 \family typewriter
2548 -wthread
2548 -wthread
2549 \family default
2549 \family default
2550 or
2550 or
2551 \family typewriter
2551 \family typewriter
2552 -pylab
2552 -pylab
2553 \family default
2553 \family default
2554 ).
2554 ).
2555 \layout List
2555 \layout List
2556 \labelwidthstring 00.00.0000
2556 \labelwidthstring 00.00.0000
2557
2557
2558 \SpecialChar ~
2558 \SpecialChar ~
2559 If
2559 If
2560 \family typewriter
2560 \family typewriter
2561 -tk
2561 -tk
2562 \family default
2562 \family default
2563 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2563 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2564 This is however potentially unreliable, and you will have to test on your
2564 This is however potentially unreliable, and you will have to test on your
2565 platform and Python configuration to determine whether it works for you.
2565 platform and Python configuration to determine whether it works for you.
2566 Debian users have reported success, apparently due to the fact that Debian
2566 Debian users have reported success, apparently due to the fact that Debian
2567 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2567 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2568 Under other Linux environments (such as Fedora Core 2/3), this option has
2568 Under other Linux environments (such as Fedora Core 2/3), this option has
2569 caused random crashes and lockups of the Python interpreter.
2569 caused random crashes and lockups of the Python interpreter.
2570 Under other operating systems (Mac OSX and Windows), you'll need to try
2570 Under other operating systems (Mac OSX and Windows), you'll need to try
2571 it to find out, since currently no user reports are available.
2571 it to find out, since currently no user reports are available.
2572 \layout List
2572 \layout List
2573 \labelwidthstring 00.00.0000
2573 \labelwidthstring 00.00.0000
2574
2574
2575 \SpecialChar ~
2575 \SpecialChar ~
2576 There is unfortunately no way for IPython to determine at run time whether
2576 There is unfortunately no way for IPython to determine at run time whether
2577
2577
2578 \family typewriter
2578 \family typewriter
2579 -tk
2579 -tk
2580 \family default
2580 \family default
2581 will work reliably or not, so you will need to do some experiments before
2581 will work reliably or not, so you will need to do some experiments before
2582 relying on it for regular work.
2582 relying on it for regular work.
2583
2583
2584 \layout Subsection
2584 \layout Subsection
2585
2585
2586
2586
2587 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2587 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2588
2588
2589 \end_inset
2589 \end_inset
2590
2590
2591 Regular Options
2591 Regular Options
2592 \layout Standard
2592 \layout Standard
2593
2593
2594 After the above threading options have been given, regular options can follow
2594 After the above threading options have been given, regular options can follow
2595 in any order.
2595 in any order.
2596 All options can be abbreviated to their shortest non-ambiguous form and
2596 All options can be abbreviated to their shortest non-ambiguous form and
2597 are case-sensitive.
2597 are case-sensitive.
2598 One or two dashes can be used.
2598 One or two dashes can be used.
2599 Some options have an alternate short form, indicated after a
2599 Some options have an alternate short form, indicated after a
2600 \family typewriter
2600 \family typewriter
2601 |
2601 |
2602 \family default
2602 \family default
2603 .
2603 .
2604 \layout Standard
2604 \layout Standard
2605
2605
2606 Most options can also be set from your ipythonrc configuration file.
2606 Most options can also be set from your ipythonrc configuration file.
2607 See the provided example for more details on what the options do.
2607 See the provided example for more details on what the options do.
2608 Options given at the command line override the values set in the ipythonrc
2608 Options given at the command line override the values set in the ipythonrc
2609 file.
2609 file.
2610 \layout Standard
2610 \layout Standard
2611
2611
2612 All options with a
2612 All options with a
2613 \family typewriter
2613 \family typewriter
2614 [no]
2614 [no]
2615 \family default
2615 \family default
2616 prepended can be specified in negated form (
2616 prepended can be specified in negated form (
2617 \family typewriter
2617 \family typewriter
2618 -nooption
2618 -nooption
2619 \family default
2619 \family default
2620 instead of
2620 instead of
2621 \family typewriter
2621 \family typewriter
2622 -option
2622 -option
2623 \family default
2623 \family default
2624 ) to turn the feature off.
2624 ) to turn the feature off.
2625 \layout List
2625 \layout List
2626 \labelwidthstring 00.00.0000
2626 \labelwidthstring 00.00.0000
2627
2627
2628
2628
2629 \family typewriter
2629 \family typewriter
2630 \series bold
2630 \series bold
2631 -help
2631 -help
2632 \family default
2632 \family default
2633 \series default
2633 \series default
2634 : print a help message and exit.
2634 : print a help message and exit.
2635 \layout List
2635 \layout List
2636 \labelwidthstring 00.00.0000
2636 \labelwidthstring 00.00.0000
2637
2637
2638
2638
2639 \family typewriter
2639 \family typewriter
2640 \series bold
2640 \series bold
2641 -pylab:
2641 -pylab:
2642 \family default
2642 \family default
2643 \series default
2643 \series default
2644 this can
2644 this can
2645 \emph on
2645 \emph on
2646 only
2646 only
2647 \emph default
2647 \emph default
2648 be given as the
2648 be given as the
2649 \emph on
2649 \emph on
2650 first
2650 first
2651 \emph default
2651 \emph default
2652 option passed to IPython (it will have no effect in any other position).
2652 option passed to IPython (it will have no effect in any other position).
2653 It adds special support for the matplotlib library (
2653 It adds special support for the matplotlib library (
2654 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2654 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2655
2655
2656 \end_inset
2656 \end_inset
2657
2657
2658 ), allowing interactive usage of any of its backends as defined in the user's
2658 ), allowing interactive usage of any of its backends as defined in the user's
2659
2659
2660 \family typewriter
2660 \family typewriter
2661 .matplotlibrc
2661 .matplotlibrc
2662 \family default
2662 \family default
2663 file.
2663 file.
2664 It automatically activates GTK or WX threading for IPyhton if the choice
2664 It automatically activates GTK or WX threading for IPyhton if the choice
2665 of matplotlib backend requires it.
2665 of matplotlib backend requires it.
2666 It also modifies the
2666 It also modifies the
2667 \family typewriter
2667 \family typewriter
2668 %run
2668 %run
2669 \family default
2669 \family default
2670 command to correctly execute (without blocking) any matplotlib-based script
2670 command to correctly execute (without blocking) any matplotlib-based script
2671 which calls
2671 which calls
2672 \family typewriter
2672 \family typewriter
2673 show()
2673 show()
2674 \family default
2674 \family default
2675 at the end.
2675 at the end.
2676 See Sec.\SpecialChar ~
2676 See Sec.\SpecialChar ~
2677
2677
2678 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2678 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2679
2679
2680 \end_inset
2680 \end_inset
2681
2681
2682 for more details.
2682 for more details.
2683 \layout List
2683 \layout List
2684 \labelwidthstring 00.00.0000
2684 \labelwidthstring 00.00.0000
2685
2685
2686
2686
2687 \family typewriter
2687 \family typewriter
2688 \series bold
2688 \series bold
2689 -[no]autocall:
2689 -autocall <val>:
2690 \family default
2690 \family default
2691 \series default
2691 \series default
2692 Make IPython automatically call any callable object even if you didn't
2692 Make IPython automatically call any callable object even if you didn't
2693 type explicit parentheses.
2693 type explicit parentheses.
2694 For example, `str 43' becomes `str(43)' automatically.
2694 For example, `str 43' becomes `str(43)' automatically.
2695 The value can be `0' to disable the feature, `1' for
2696 \emph on
2697 smart
2698 \emph default
2699 autocall, where it is not applied if there are no more arguments on the
2700 line, and `2' for
2701 \emph on
2702 full
2703 \emph default
2704 autocall, where all callable objects are automatically called (even if
2705 no arguments are present).
2706 The default is `1'.
2695 \layout List
2707 \layout List
2696 \labelwidthstring 00.00.0000
2708 \labelwidthstring 00.00.0000
2697
2709
2698
2710
2699 \family typewriter
2711 \family typewriter
2700 \series bold
2712 \series bold
2701 -[no]autoindent:
2713 -[no]autoindent:
2702 \family default
2714 \family default
2703 \series default
2715 \series default
2704 Turn automatic indentation on/off.
2716 Turn automatic indentation on/off.
2705 \layout List
2717 \layout List
2706 \labelwidthstring 00.00.0000
2718 \labelwidthstring 00.00.0000
2707
2719
2708
2720
2709 \family typewriter
2721 \family typewriter
2710 \series bold
2722 \series bold
2711 -[no]automagic
2723 -[no]automagic
2712 \series default
2724 \series default
2713 :
2725 :
2714 \family default
2726 \family default
2715 make magic commands automatic (without needing their first character to
2727 make magic commands automatic (without needing their first character to
2716 be
2728 be
2717 \family typewriter
2729 \family typewriter
2718 %
2730 %
2719 \family default
2731 \family default
2720 ).
2732 ).
2721 Type
2733 Type
2722 \family typewriter
2734 \family typewriter
2723 %magic
2735 %magic
2724 \family default
2736 \family default
2725 at the IPython prompt for more information.
2737 at the IPython prompt for more information.
2726 \layout List
2738 \layout List
2727 \labelwidthstring 00.00.0000
2739 \labelwidthstring 00.00.0000
2728
2740
2729
2741
2730 \family typewriter
2742 \family typewriter
2731 \series bold
2743 \series bold
2732 -[no]autoedit_syntax:
2744 -[no]autoedit_syntax:
2733 \family default
2745 \family default
2734 \series default
2746 \series default
2735 When a syntax error occurs after editing a file, automatically open the
2747 When a syntax error occurs after editing a file, automatically open the
2736 file to the trouble causing line for convenient fixing.
2748 file to the trouble causing line for convenient fixing.
2737
2749
2738 \layout List
2750 \layout List
2739 \labelwidthstring 00.00.0000
2751 \labelwidthstring 00.00.0000
2740
2752
2741
2753
2742 \family typewriter
2754 \family typewriter
2743 \series bold
2755 \series bold
2744 -[no]banner
2756 -[no]banner
2745 \series default
2757 \series default
2746 :
2758 :
2747 \family default
2759 \family default
2748 Print the initial information banner (default on).
2760 Print the initial information banner (default on).
2749 \layout List
2761 \layout List
2750 \labelwidthstring 00.00.0000
2762 \labelwidthstring 00.00.0000
2751
2763
2752
2764
2753 \family typewriter
2765 \family typewriter
2754 \series bold
2766 \series bold
2755 -c\SpecialChar ~
2767 -c\SpecialChar ~
2756 <command>:
2768 <command>:
2757 \family default
2769 \family default
2758 \series default
2770 \series default
2759 execute the given command string, and set sys.argv to
2771 execute the given command string, and set sys.argv to
2760 \family typewriter
2772 \family typewriter
2761 ['c']
2773 ['c']
2762 \family default
2774 \family default
2763 .
2775 .
2764 This is similar to the
2776 This is similar to the
2765 \family typewriter
2777 \family typewriter
2766 -c
2778 -c
2767 \family default
2779 \family default
2768 option in the normal Python interpreter.
2780 option in the normal Python interpreter.
2769
2781
2770 \layout List
2782 \layout List
2771 \labelwidthstring 00.00.0000
2783 \labelwidthstring 00.00.0000
2772
2784
2773
2785
2774 \family typewriter
2786 \family typewriter
2775 \series bold
2787 \series bold
2776 -cache_size|cs\SpecialChar ~
2788 -cache_size|cs\SpecialChar ~
2777 <n>
2789 <n>
2778 \series default
2790 \series default
2779 :
2791 :
2780 \family default
2792 \family default
2781 size of the output cache (maximum number of entries to hold in memory).
2793 size of the output cache (maximum number of entries to hold in memory).
2782 The default is 1000, you can change it permanently in your config file.
2794 The default is 1000, you can change it permanently in your config file.
2783 Setting it to 0 completely disables the caching system, and the minimum
2795 Setting it to 0 completely disables the caching system, and the minimum
2784 value accepted is 20 (if you provide a value less than 20, it is reset
2796 value accepted is 20 (if you provide a value less than 20, it is reset
2785 to 0 and a warning is issued) This limit is defined because otherwise you'll
2797 to 0 and a warning is issued) This limit is defined because otherwise you'll
2786 spend more time re-flushing a too small cache than working.
2798 spend more time re-flushing a too small cache than working.
2787 \layout List
2799 \layout List
2788 \labelwidthstring 00.00.0000
2800 \labelwidthstring 00.00.0000
2789
2801
2790
2802
2791 \family typewriter
2803 \family typewriter
2792 \series bold
2804 \series bold
2793 -classic|cl
2805 -classic|cl
2794 \series default
2806 \series default
2795 :
2807 :
2796 \family default
2808 \family default
2797 Gives IPython a similar feel to the classic Python prompt.
2809 Gives IPython a similar feel to the classic Python prompt.
2798 \layout List
2810 \layout List
2799 \labelwidthstring 00.00.0000
2811 \labelwidthstring 00.00.0000
2800
2812
2801
2813
2802 \family typewriter
2814 \family typewriter
2803 \series bold
2815 \series bold
2804 -colors\SpecialChar ~
2816 -colors\SpecialChar ~
2805 <scheme>:
2817 <scheme>:
2806 \family default
2818 \family default
2807 \series default
2819 \series default
2808 Color scheme for prompts and exception reporting.
2820 Color scheme for prompts and exception reporting.
2809 Currently implemented: NoColor, Linux and LightBG.
2821 Currently implemented: NoColor, Linux and LightBG.
2810 \layout List
2822 \layout List
2811 \labelwidthstring 00.00.0000
2823 \labelwidthstring 00.00.0000
2812
2824
2813
2825
2814 \family typewriter
2826 \family typewriter
2815 \series bold
2827 \series bold
2816 -[no]color_info:
2828 -[no]color_info:
2817 \family default
2829 \family default
2818 \series default
2830 \series default
2819 IPython can display information about objects via a set of functions, and
2831 IPython can display information about objects via a set of functions, and
2820 optionally can use colors for this, syntax highlighting source code and
2832 optionally can use colors for this, syntax highlighting source code and
2821 various other elements.
2833 various other elements.
2822 However, because this information is passed through a pager (like 'less')
2834 However, because this information is passed through a pager (like 'less')
2823 and many pagers get confused with color codes, this option is off by default.
2835 and many pagers get confused with color codes, this option is off by default.
2824 You can test it and turn it on permanently in your ipythonrc file if it
2836 You can test it and turn it on permanently in your ipythonrc file if it
2825 works for you.
2837 works for you.
2826 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
2838 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
2827 that in RedHat 7.2 doesn't.
2839 that in RedHat 7.2 doesn't.
2828 \layout List
2840 \layout List
2829 \labelwidthstring 00.00.0000
2841 \labelwidthstring 00.00.0000
2830
2842
2831 \SpecialChar ~
2843 \SpecialChar ~
2832 Test it and turn it on permanently if it works with your system.
2844 Test it and turn it on permanently if it works with your system.
2833 The magic function
2845 The magic function
2834 \family typewriter
2846 \family typewriter
2835 %color_info
2847 %color_info
2836 \family default
2848 \family default
2837 allows you to toggle this interactively for testing.
2849 allows you to toggle this interactively for testing.
2838 \layout List
2850 \layout List
2839 \labelwidthstring 00.00.0000
2851 \labelwidthstring 00.00.0000
2840
2852
2841
2853
2842 \family typewriter
2854 \family typewriter
2843 \series bold
2855 \series bold
2844 -[no]debug
2856 -[no]debug
2845 \family default
2857 \family default
2846 \series default
2858 \series default
2847 : Show information about the loading process.
2859 : Show information about the loading process.
2848 Very useful to pin down problems with your configuration files or to get
2860 Very useful to pin down problems with your configuration files or to get
2849 details about session restores.
2861 details about session restores.
2850 \layout List
2862 \layout List
2851 \labelwidthstring 00.00.0000
2863 \labelwidthstring 00.00.0000
2852
2864
2853
2865
2854 \family typewriter
2866 \family typewriter
2855 \series bold
2867 \series bold
2856 -[no]deep_reload
2868 -[no]deep_reload
2857 \series default
2869 \series default
2858 :
2870 :
2859 \family default
2871 \family default
2860 IPython can use the
2872 IPython can use the
2861 \family typewriter
2873 \family typewriter
2862 deep_reload
2874 deep_reload
2863 \family default
2875 \family default
2864 module which reloads changes in modules recursively (it replaces the
2876 module which reloads changes in modules recursively (it replaces the
2865 \family typewriter
2877 \family typewriter
2866 reload()
2878 reload()
2867 \family default
2879 \family default
2868 function, so you don't need to change anything to use it).
2880 function, so you don't need to change anything to use it).
2869
2881
2870 \family typewriter
2882 \family typewriter
2871 deep_reload()
2883 deep_reload()
2872 \family default
2884 \family default
2873 forces a full reload of modules whose code may have changed, which the
2885 forces a full reload of modules whose code may have changed, which the
2874 default
2886 default
2875 \family typewriter
2887 \family typewriter
2876 reload()
2888 reload()
2877 \family default
2889 \family default
2878 function does not.
2890 function does not.
2879 \layout List
2891 \layout List
2880 \labelwidthstring 00.00.0000
2892 \labelwidthstring 00.00.0000
2881
2893
2882 \SpecialChar ~
2894 \SpecialChar ~
2883 When deep_reload is off, IPython will use the normal
2895 When deep_reload is off, IPython will use the normal
2884 \family typewriter
2896 \family typewriter
2885 reload()
2897 reload()
2886 \family default
2898 \family default
2887 , but deep_reload will still be available as
2899 , but deep_reload will still be available as
2888 \family typewriter
2900 \family typewriter
2889 dreload()
2901 dreload()
2890 \family default
2902 \family default
2891 .
2903 .
2892 This feature is off by default [which means that you have both normal
2904 This feature is off by default [which means that you have both normal
2893 \family typewriter
2905 \family typewriter
2894 reload()
2906 reload()
2895 \family default
2907 \family default
2896 and
2908 and
2897 \family typewriter
2909 \family typewriter
2898 dreload()
2910 dreload()
2899 \family default
2911 \family default
2900 ].
2912 ].
2901 \layout List
2913 \layout List
2902 \labelwidthstring 00.00.0000
2914 \labelwidthstring 00.00.0000
2903
2915
2904
2916
2905 \family typewriter
2917 \family typewriter
2906 \series bold
2918 \series bold
2907 -editor\SpecialChar ~
2919 -editor\SpecialChar ~
2908 <name>
2920 <name>
2909 \family default
2921 \family default
2910 \series default
2922 \series default
2911 : Which editor to use with the
2923 : Which editor to use with the
2912 \family typewriter
2924 \family typewriter
2913 %edit
2925 %edit
2914 \family default
2926 \family default
2915 command.
2927 command.
2916 By default, IPython will honor your
2928 By default, IPython will honor your
2917 \family typewriter
2929 \family typewriter
2918 EDITOR
2930 EDITOR
2919 \family default
2931 \family default
2920 environment variable (if not set, vi is the Unix default and notepad the
2932 environment variable (if not set, vi is the Unix default and notepad the
2921 Windows one).
2933 Windows one).
2922 Since this editor is invoked on the fly by IPython and is meant for editing
2934 Since this editor is invoked on the fly by IPython and is meant for editing
2923 small code snippets, you may want to use a small, lightweight editor here
2935 small code snippets, you may want to use a small, lightweight editor here
2924 (in case your default
2936 (in case your default
2925 \family typewriter
2937 \family typewriter
2926 EDITOR
2938 EDITOR
2927 \family default
2939 \family default
2928 is something like Emacs).
2940 is something like Emacs).
2929 \layout List
2941 \layout List
2930 \labelwidthstring 00.00.0000
2942 \labelwidthstring 00.00.0000
2931
2943
2932
2944
2933 \family typewriter
2945 \family typewriter
2934 \series bold
2946 \series bold
2935 -ipythondir\SpecialChar ~
2947 -ipythondir\SpecialChar ~
2936 <name>
2948 <name>
2937 \series default
2949 \series default
2938 :
2950 :
2939 \family default
2951 \family default
2940 name of your IPython configuration directory
2952 name of your IPython configuration directory
2941 \family typewriter
2953 \family typewriter
2942 IPYTHONDIR
2954 IPYTHONDIR
2943 \family default
2955 \family default
2944 .
2956 .
2945 This can also be specified through the environment variable
2957 This can also be specified through the environment variable
2946 \family typewriter
2958 \family typewriter
2947 IPYTHONDIR
2959 IPYTHONDIR
2948 \family default
2960 \family default
2949 .
2961 .
2950 \layout List
2962 \layout List
2951 \labelwidthstring 00.00.0000
2963 \labelwidthstring 00.00.0000
2952
2964
2953
2965
2954 \family typewriter
2966 \family typewriter
2955 \series bold
2967 \series bold
2956 -log|l
2968 -log|l
2957 \family default
2969 \family default
2958 \series default
2970 \series default
2959 : generate a log file of all input.
2971 : generate a log file of all input.
2960 The file is named
2972 The file is named
2961 \family typewriter
2973 \family typewriter
2962 ipython_log.py
2974 ipython_log.py
2963 \family default
2975 \family default
2964 in your current directory (which prevents logs from multiple IPython sessions
2976 in your current directory (which prevents logs from multiple IPython sessions
2965 from trampling each other).
2977 from trampling each other).
2966 You can use this to later restore a session by loading your logfile as
2978 You can use this to later restore a session by loading your logfile as
2967 a file to be executed with option
2979 a file to be executed with option
2968 \family typewriter
2980 \family typewriter
2969 -logplay
2981 -logplay
2970 \family default
2982 \family default
2971 (see below).
2983 (see below).
2972 \layout List
2984 \layout List
2973 \labelwidthstring 00.00.0000
2985 \labelwidthstring 00.00.0000
2974
2986
2975
2987
2976 \family typewriter
2988 \family typewriter
2977 \series bold
2989 \series bold
2978 -logfile|lf\SpecialChar ~
2990 -logfile|lf\SpecialChar ~
2979 <name>
2991 <name>
2980 \series default
2992 \series default
2981 :
2993 :
2982 \family default
2994 \family default
2983 specify the name of your logfile.
2995 specify the name of your logfile.
2984 \layout List
2996 \layout List
2985 \labelwidthstring 00.00.0000
2997 \labelwidthstring 00.00.0000
2986
2998
2987
2999
2988 \family typewriter
3000 \family typewriter
2989 \series bold
3001 \series bold
2990 -logplay|lp\SpecialChar ~
3002 -logplay|lp\SpecialChar ~
2991 <name>
3003 <name>
2992 \series default
3004 \series default
2993 :
3005 :
2994 \family default
3006 \family default
2995 you can replay a previous log.
3007 you can replay a previous log.
2996 For restoring a session as close as possible to the state you left it in,
3008 For restoring a session as close as possible to the state you left it in,
2997 use this option (don't just run the logfile).
3009 use this option (don't just run the logfile).
2998 With
3010 With
2999 \family typewriter
3011 \family typewriter
3000 -logplay
3012 -logplay
3001 \family default
3013 \family default
3002 , IPython will try to reconstruct the previous working environment in full,
3014 , IPython will try to reconstruct the previous working environment in full,
3003 not just execute the commands in the logfile.
3015 not just execute the commands in the logfile.
3004 \layout List
3016 \layout List
3005 \labelwidthstring 00.00.0000
3017 \labelwidthstring 00.00.0000
3006
3018
3007 \SpecialChar ~
3019 \SpecialChar ~
3008 When a session is restored, logging is automatically turned on again with
3020 When a session is restored, logging is automatically turned on again with
3009 the name of the logfile it was invoked with (it is read from the log header).
3021 the name of the logfile it was invoked with (it is read from the log header).
3010 So once you've turned logging on for a session, you can quit IPython and
3022 So once you've turned logging on for a session, you can quit IPython and
3011 reload it as many times as you want and it will continue to log its history
3023 reload it as many times as you want and it will continue to log its history
3012 and restore from the beginning every time.
3024 and restore from the beginning every time.
3013 \layout List
3025 \layout List
3014 \labelwidthstring 00.00.0000
3026 \labelwidthstring 00.00.0000
3015
3027
3016 \SpecialChar ~
3028 \SpecialChar ~
3017 Caveats: there are limitations in this option.
3029 Caveats: there are limitations in this option.
3018 The history variables
3030 The history variables
3019 \family typewriter
3031 \family typewriter
3020 _i*
3032 _i*
3021 \family default
3033 \family default
3022 ,
3034 ,
3023 \family typewriter
3035 \family typewriter
3024 _*
3036 _*
3025 \family default
3037 \family default
3026 and
3038 and
3027 \family typewriter
3039 \family typewriter
3028 _dh
3040 _dh
3029 \family default
3041 \family default
3030 don't get restored properly.
3042 don't get restored properly.
3031 In the future we will try to implement full session saving by writing and
3043 In the future we will try to implement full session saving by writing and
3032 retrieving a 'snapshot' of the memory state of IPython.
3044 retrieving a 'snapshot' of the memory state of IPython.
3033 But our first attempts failed because of inherent limitations of Python's
3045 But our first attempts failed because of inherent limitations of Python's
3034 Pickle module, so this may have to wait.
3046 Pickle module, so this may have to wait.
3035 \layout List
3047 \layout List
3036 \labelwidthstring 00.00.0000
3048 \labelwidthstring 00.00.0000
3037
3049
3038
3050
3039 \family typewriter
3051 \family typewriter
3040 \series bold
3052 \series bold
3041 -[no]messages
3053 -[no]messages
3042 \series default
3054 \series default
3043 :
3055 :
3044 \family default
3056 \family default
3045 Print messages which IPython collects about its startup process (default
3057 Print messages which IPython collects about its startup process (default
3046 on).
3058 on).
3047 \layout List
3059 \layout List
3048 \labelwidthstring 00.00.0000
3060 \labelwidthstring 00.00.0000
3049
3061
3050
3062
3051 \family typewriter
3063 \family typewriter
3052 \series bold
3064 \series bold
3053 -[no]pdb
3065 -[no]pdb
3054 \family default
3066 \family default
3055 \series default
3067 \series default
3056 : Automatically call the pdb debugger after every uncaught exception.
3068 : Automatically call the pdb debugger after every uncaught exception.
3057 If you are used to debugging using pdb, this puts you automatically inside
3069 If you are used to debugging using pdb, this puts you automatically inside
3058 of it after any call (either in IPython or in code called by it) which
3070 of it after any call (either in IPython or in code called by it) which
3059 triggers an exception which goes uncaught.
3071 triggers an exception which goes uncaught.
3060 \layout List
3072 \layout List
3061 \labelwidthstring 00.00.0000
3073 \labelwidthstring 00.00.0000
3062
3074
3063
3075
3064 \family typewriter
3076 \family typewriter
3065 \series bold
3077 \series bold
3066 -[no]pprint
3078 -[no]pprint
3067 \series default
3079 \series default
3068 :
3080 :
3069 \family default
3081 \family default
3070 ipython can optionally use the pprint (pretty printer) module for displaying
3082 ipython can optionally use the pprint (pretty printer) module for displaying
3071 results.
3083 results.
3072 pprint tends to give a nicer display of nested data structures.
3084 pprint tends to give a nicer display of nested data structures.
3073 If you like it, you can turn it on permanently in your config file (default
3085 If you like it, you can turn it on permanently in your config file (default
3074 off).
3086 off).
3075 \layout List
3087 \layout List
3076 \labelwidthstring 00.00.0000
3088 \labelwidthstring 00.00.0000
3077
3089
3078
3090
3079 \family typewriter
3091 \family typewriter
3080 \series bold
3092 \series bold
3081 -profile|p <name>
3093 -profile|p <name>
3082 \series default
3094 \series default
3083 :
3095 :
3084 \family default
3096 \family default
3085 assume that your config file is
3097 assume that your config file is
3086 \family typewriter
3098 \family typewriter
3087 ipythonrc-<name>
3099 ipythonrc-<name>
3088 \family default
3100 \family default
3089 (looks in current dir first, then in
3101 (looks in current dir first, then in
3090 \family typewriter
3102 \family typewriter
3091 IPYTHONDIR
3103 IPYTHONDIR
3092 \family default
3104 \family default
3093 ).
3105 ).
3094 This is a quick way to keep and load multiple config files for different
3106 This is a quick way to keep and load multiple config files for different
3095 tasks, especially if you use the include option of config files.
3107 tasks, especially if you use the include option of config files.
3096 You can keep a basic
3108 You can keep a basic
3097 \family typewriter
3109 \family typewriter
3098 IPYTHONDIR/ipythonrc
3110 IPYTHONDIR/ipythonrc
3099 \family default
3111 \family default
3100 file and then have other 'profiles' which include this one and load extra
3112 file and then have other 'profiles' which include this one and load extra
3101 things for particular tasks.
3113 things for particular tasks.
3102 For example:
3114 For example:
3103 \layout List
3115 \layout List
3104 \labelwidthstring 00.00.0000
3116 \labelwidthstring 00.00.0000
3105
3117
3106
3118
3107 \family typewriter
3119 \family typewriter
3108 \SpecialChar ~
3120 \SpecialChar ~
3109
3121
3110 \family default
3122 \family default
3111 1.
3123 1.
3112
3124
3113 \family typewriter
3125 \family typewriter
3114 $HOME/.ipython/ipythonrc
3126 $HOME/.ipython/ipythonrc
3115 \family default
3127 \family default
3116 : load basic things you always want.
3128 : load basic things you always want.
3117 \layout List
3129 \layout List
3118 \labelwidthstring 00.00.0000
3130 \labelwidthstring 00.00.0000
3119
3131
3120
3132
3121 \family typewriter
3133 \family typewriter
3122 \SpecialChar ~
3134 \SpecialChar ~
3123
3135
3124 \family default
3136 \family default
3125 2.
3137 2.
3126
3138
3127 \family typewriter
3139 \family typewriter
3128 $HOME/.ipython/ipythonrc-math
3140 $HOME/.ipython/ipythonrc-math
3129 \family default
3141 \family default
3130 : load (1) and basic math-related modules.
3142 : load (1) and basic math-related modules.
3131
3143
3132 \layout List
3144 \layout List
3133 \labelwidthstring 00.00.0000
3145 \labelwidthstring 00.00.0000
3134
3146
3135
3147
3136 \family typewriter
3148 \family typewriter
3137 \SpecialChar ~
3149 \SpecialChar ~
3138
3150
3139 \family default
3151 \family default
3140 3.
3152 3.
3141
3153
3142 \family typewriter
3154 \family typewriter
3143 $HOME/.ipython/ipythonrc-numeric
3155 $HOME/.ipython/ipythonrc-numeric
3144 \family default
3156 \family default
3145 : load (1) and Numeric and plotting modules.
3157 : load (1) and Numeric and plotting modules.
3146 \layout List
3158 \layout List
3147 \labelwidthstring 00.00.0000
3159 \labelwidthstring 00.00.0000
3148
3160
3149 \SpecialChar ~
3161 \SpecialChar ~
3150 Since it is possible to create an endless loop by having circular file
3162 Since it is possible to create an endless loop by having circular file
3151 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3163 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3152 \layout List
3164 \layout List
3153 \labelwidthstring 00.00.0000
3165 \labelwidthstring 00.00.0000
3154
3166
3155
3167
3156 \family typewriter
3168 \family typewriter
3157 \series bold
3169 \series bold
3158 -prompt_in1|pi1\SpecialChar ~
3170 -prompt_in1|pi1\SpecialChar ~
3159 <string>:
3171 <string>:
3160 \family default
3172 \family default
3161 \series default
3173 \series default
3162 Specify the string used for input prompts.
3174 Specify the string used for input prompts.
3163 Note that if you are using numbered prompts, the number is represented
3175 Note that if you are using numbered prompts, the number is represented
3164 with a '
3176 with a '
3165 \backslash
3177 \backslash
3166 #' in the string.
3178 #' in the string.
3167 Don't forget to quote strings with spaces embedded in them.
3179 Don't forget to quote strings with spaces embedded in them.
3168 Default: '
3180 Default: '
3169 \family typewriter
3181 \family typewriter
3170 In\SpecialChar ~
3182 In\SpecialChar ~
3171 [
3183 [
3172 \backslash
3184 \backslash
3173 #]:
3185 #]:
3174 \family default
3186 \family default
3175 '.
3187 '.
3176 Sec.\SpecialChar ~
3188 Sec.\SpecialChar ~
3177
3189
3178 \begin_inset LatexCommand \ref{sec:prompts}
3190 \begin_inset LatexCommand \ref{sec:prompts}
3179
3191
3180 \end_inset
3192 \end_inset
3181
3193
3182 discusses in detail all the available escapes to customize your prompts.
3194 discusses in detail all the available escapes to customize your prompts.
3183 \layout List
3195 \layout List
3184 \labelwidthstring 00.00.0000
3196 \labelwidthstring 00.00.0000
3185
3197
3186
3198
3187 \family typewriter
3199 \family typewriter
3188 \series bold
3200 \series bold
3189 -prompt_in2|pi2\SpecialChar ~
3201 -prompt_in2|pi2\SpecialChar ~
3190 <string>:
3202 <string>:
3191 \family default
3203 \family default
3192 \series default
3204 \series default
3193 Similar to the previous option, but used for the continuation prompts.
3205 Similar to the previous option, but used for the continuation prompts.
3194 The special sequence '
3206 The special sequence '
3195 \family typewriter
3207 \family typewriter
3196
3208
3197 \backslash
3209 \backslash
3198 D
3210 D
3199 \family default
3211 \family default
3200 ' is similar to '
3212 ' is similar to '
3201 \family typewriter
3213 \family typewriter
3202
3214
3203 \backslash
3215 \backslash
3204 #
3216 #
3205 \family default
3217 \family default
3206 ', but with all digits replaced dots (so you can have your continuation
3218 ', but with all digits replaced dots (so you can have your continuation
3207 prompt aligned with your input prompt).
3219 prompt aligned with your input prompt).
3208 Default: '
3220 Default: '
3209 \family typewriter
3221 \family typewriter
3210 \SpecialChar ~
3222 \SpecialChar ~
3211 \SpecialChar ~
3223 \SpecialChar ~
3212 \SpecialChar ~
3224 \SpecialChar ~
3213 .
3225 .
3214 \backslash
3226 \backslash
3215 D.:
3227 D.:
3216 \family default
3228 \family default
3217 ' (note three spaces at the start for alignment with '
3229 ' (note three spaces at the start for alignment with '
3218 \family typewriter
3230 \family typewriter
3219 In\SpecialChar ~
3231 In\SpecialChar ~
3220 [
3232 [
3221 \backslash
3233 \backslash
3222 #]
3234 #]
3223 \family default
3235 \family default
3224 ').
3236 ').
3225 \layout List
3237 \layout List
3226 \labelwidthstring 00.00.0000
3238 \labelwidthstring 00.00.0000
3227
3239
3228
3240
3229 \family typewriter
3241 \family typewriter
3230 \series bold
3242 \series bold
3231 -prompt_out|po\SpecialChar ~
3243 -prompt_out|po\SpecialChar ~
3232 <string>:
3244 <string>:
3233 \family default
3245 \family default
3234 \series default
3246 \series default
3235 String used for output prompts, also uses numbers like
3247 String used for output prompts, also uses numbers like
3236 \family typewriter
3248 \family typewriter
3237 prompt_in1
3249 prompt_in1
3238 \family default
3250 \family default
3239 .
3251 .
3240 Default: '
3252 Default: '
3241 \family typewriter
3253 \family typewriter
3242 Out[
3254 Out[
3243 \backslash
3255 \backslash
3244 #]:
3256 #]:
3245 \family default
3257 \family default
3246 '
3258 '
3247 \layout List
3259 \layout List
3248 \labelwidthstring 00.00.0000
3260 \labelwidthstring 00.00.0000
3249
3261
3250
3262
3251 \family typewriter
3263 \family typewriter
3252 \series bold
3264 \series bold
3253 -quick
3265 -quick
3254 \family default
3266 \family default
3255 \series default
3267 \series default
3256 : start in bare bones mode (no config file loaded).
3268 : start in bare bones mode (no config file loaded).
3257 \layout List
3269 \layout List
3258 \labelwidthstring 00.00.0000
3270 \labelwidthstring 00.00.0000
3259
3271
3260
3272
3261 \family typewriter
3273 \family typewriter
3262 \series bold
3274 \series bold
3263 -rcfile\SpecialChar ~
3275 -rcfile\SpecialChar ~
3264 <name>
3276 <name>
3265 \series default
3277 \series default
3266 :
3278 :
3267 \family default
3279 \family default
3268 name of your IPython resource configuration file.
3280 name of your IPython resource configuration file.
3269 Normally IPython loads ipythonrc (from current directory) or
3281 Normally IPython loads ipythonrc (from current directory) or
3270 \family typewriter
3282 \family typewriter
3271 IPYTHONDIR/ipythonrc
3283 IPYTHONDIR/ipythonrc
3272 \family default
3284 \family default
3273 .
3285 .
3274 \layout List
3286 \layout List
3275 \labelwidthstring 00.00.0000
3287 \labelwidthstring 00.00.0000
3276
3288
3277 \SpecialChar ~
3289 \SpecialChar ~
3278 If the loading of your config file fails, IPython starts with a bare bones
3290 If the loading of your config file fails, IPython starts with a bare bones
3279 configuration (no modules loaded at all).
3291 configuration (no modules loaded at all).
3280 \layout List
3292 \layout List
3281 \labelwidthstring 00.00.0000
3293 \labelwidthstring 00.00.0000
3282
3294
3283
3295
3284 \family typewriter
3296 \family typewriter
3285 \series bold
3297 \series bold
3286 -[no]readline
3298 -[no]readline
3287 \family default
3299 \family default
3288 \series default
3300 \series default
3289 : use the readline library, which is needed to support name completion and
3301 : use the readline library, which is needed to support name completion and
3290 command history, among other things.
3302 command history, among other things.
3291 It is enabled by default, but may cause problems for users of X/Emacs in
3303 It is enabled by default, but may cause problems for users of X/Emacs in
3292 Python comint or shell buffers.
3304 Python comint or shell buffers.
3293 \layout List
3305 \layout List
3294 \labelwidthstring 00.00.0000
3306 \labelwidthstring 00.00.0000
3295
3307
3296 \SpecialChar ~
3308 \SpecialChar ~
3297 Note that X/Emacs 'eterm' buffers (opened with
3309 Note that X/Emacs 'eterm' buffers (opened with
3298 \family typewriter
3310 \family typewriter
3299 M-x\SpecialChar ~
3311 M-x\SpecialChar ~
3300 term
3312 term
3301 \family default
3313 \family default
3302 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3314 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3303 \family typewriter
3315 \family typewriter
3304 M-x\SpecialChar ~
3316 M-x\SpecialChar ~
3305 shell
3317 shell
3306 \family default
3318 \family default
3307 and
3319 and
3308 \family typewriter
3320 \family typewriter
3309 C-c\SpecialChar ~
3321 C-c\SpecialChar ~
3310 !
3322 !
3311 \family default
3323 \family default
3312 ) buffers do not.
3324 ) buffers do not.
3313 \layout List
3325 \layout List
3314 \labelwidthstring 00.00.0000
3326 \labelwidthstring 00.00.0000
3315
3327
3316
3328
3317 \family typewriter
3329 \family typewriter
3318 \series bold
3330 \series bold
3319 -screen_length|sl\SpecialChar ~
3331 -screen_length|sl\SpecialChar ~
3320 <n>
3332 <n>
3321 \series default
3333 \series default
3322 :
3334 :
3323 \family default
3335 \family default
3324 number of lines of your screen.
3336 number of lines of your screen.
3325 This is used to control printing of very long strings.
3337 This is used to control printing of very long strings.
3326 Strings longer than this number of lines will be sent through a pager instead
3338 Strings longer than this number of lines will be sent through a pager instead
3327 of directly printed.
3339 of directly printed.
3328 \layout List
3340 \layout List
3329 \labelwidthstring 00.00.0000
3341 \labelwidthstring 00.00.0000
3330
3342
3331 \SpecialChar ~
3343 \SpecialChar ~
3332 The default value for this is 0, which means IPython will auto-detect your
3344 The default value for this is 0, which means IPython will auto-detect your
3333 screen size every time it needs to print certain potentially long strings
3345 screen size every time it needs to print certain potentially long strings
3334 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3346 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3335 internally).
3347 internally).
3336 If for some reason this isn't working well (it needs curses support), specify
3348 If for some reason this isn't working well (it needs curses support), specify
3337 it yourself.
3349 it yourself.
3338 Otherwise don't change the default.
3350 Otherwise don't change the default.
3339 \layout List
3351 \layout List
3340 \labelwidthstring 00.00.0000
3352 \labelwidthstring 00.00.0000
3341
3353
3342
3354
3343 \family typewriter
3355 \family typewriter
3344 \series bold
3356 \series bold
3345 -separate_in|si\SpecialChar ~
3357 -separate_in|si\SpecialChar ~
3346 <string>
3358 <string>
3347 \series default
3359 \series default
3348 :
3360 :
3349 \family default
3361 \family default
3350 separator before input prompts.
3362 separator before input prompts.
3351 Default: '
3363 Default: '
3352 \family typewriter
3364 \family typewriter
3353
3365
3354 \backslash
3366 \backslash
3355 n
3367 n
3356 \family default
3368 \family default
3357 '
3369 '
3358 \layout List
3370 \layout List
3359 \labelwidthstring 00.00.0000
3371 \labelwidthstring 00.00.0000
3360
3372
3361
3373
3362 \family typewriter
3374 \family typewriter
3363 \series bold
3375 \series bold
3364 -separate_out|so\SpecialChar ~
3376 -separate_out|so\SpecialChar ~
3365 <string>
3377 <string>
3366 \family default
3378 \family default
3367 \series default
3379 \series default
3368 : separator before output prompts.
3380 : separator before output prompts.
3369 Default: nothing.
3381 Default: nothing.
3370 \layout List
3382 \layout List
3371 \labelwidthstring 00.00.0000
3383 \labelwidthstring 00.00.0000
3372
3384
3373
3385
3374 \family typewriter
3386 \family typewriter
3375 \series bold
3387 \series bold
3376 -separate_out2|so2\SpecialChar ~
3388 -separate_out2|so2\SpecialChar ~
3377 <string>
3389 <string>
3378 \series default
3390 \series default
3379 :
3391 :
3380 \family default
3392 \family default
3381 separator after output prompts.
3393 separator after output prompts.
3382 Default: nothing.
3394 Default: nothing.
3383 \layout List
3395 \layout List
3384 \labelwidthstring 00.00.0000
3396 \labelwidthstring 00.00.0000
3385
3397
3386 \SpecialChar ~
3398 \SpecialChar ~
3387 For these three options, use the value 0 to specify no separator.
3399 For these three options, use the value 0 to specify no separator.
3388 \layout List
3400 \layout List
3389 \labelwidthstring 00.00.0000
3401 \labelwidthstring 00.00.0000
3390
3402
3391
3403
3392 \family typewriter
3404 \family typewriter
3393 \series bold
3405 \series bold
3394 -nosep
3406 -nosep
3395 \series default
3407 \series default
3396 :
3408 :
3397 \family default
3409 \family default
3398 shorthand for
3410 shorthand for
3399 \family typewriter
3411 \family typewriter
3400 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3412 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3401 \family default
3413 \family default
3402 .
3414 .
3403 Simply removes all input/output separators.
3415 Simply removes all input/output separators.
3404 \layout List
3416 \layout List
3405 \labelwidthstring 00.00.0000
3417 \labelwidthstring 00.00.0000
3406
3418
3407
3419
3408 \family typewriter
3420 \family typewriter
3409 \series bold
3421 \series bold
3410 -upgrade
3422 -upgrade
3411 \family default
3423 \family default
3412 \series default
3424 \series default
3413 : allows you to upgrade your
3425 : allows you to upgrade your
3414 \family typewriter
3426 \family typewriter
3415 IPYTHONDIR
3427 IPYTHONDIR
3416 \family default
3428 \family default
3417 configuration when you install a new version of IPython.
3429 configuration when you install a new version of IPython.
3418 Since new versions may include new command line options or example files,
3430 Since new versions may include new command line options or example files,
3419 this copies updated ipythonrc-type files.
3431 this copies updated ipythonrc-type files.
3420 However, it backs up (with a
3432 However, it backs up (with a
3421 \family typewriter
3433 \family typewriter
3422 .old
3434 .old
3423 \family default
3435 \family default
3424 extension) all files which it overwrites so that you can merge back any
3436 extension) all files which it overwrites so that you can merge back any
3425 customizations you might have in your personal files.
3437 customizations you might have in your personal files.
3426 \layout List
3438 \layout List
3427 \labelwidthstring 00.00.0000
3439 \labelwidthstring 00.00.0000
3428
3440
3429
3441
3430 \family typewriter
3442 \family typewriter
3431 \series bold
3443 \series bold
3432 -Version
3444 -Version
3433 \series default
3445 \series default
3434 :
3446 :
3435 \family default
3447 \family default
3436 print version information and exit.
3448 print version information and exit.
3437 \layout List
3449 \layout List
3438 \labelwidthstring 00.00.0000
3450 \labelwidthstring 00.00.0000
3439
3451
3440
3452
3441 \family typewriter
3453 \family typewriter
3442 \series bold
3454 \series bold
3443 -xmode <modename>
3455 -xmode <modename>
3444 \series default
3456 \series default
3445 :
3457 :
3446 \family default
3458 \family default
3447 Mode for exception reporting.
3459 Mode for exception reporting.
3448 \layout List
3460 \layout List
3449 \labelwidthstring 00.00.0000
3461 \labelwidthstring 00.00.0000
3450
3462
3451 \SpecialChar ~
3463 \SpecialChar ~
3452 Valid modes: Plain, Context and Verbose.
3464 Valid modes: Plain, Context and Verbose.
3453 \layout List
3465 \layout List
3454 \labelwidthstring 00.00.0000
3466 \labelwidthstring 00.00.0000
3455
3467
3456 \SpecialChar ~
3468 \SpecialChar ~
3457 Plain: similar to python's normal traceback printing.
3469 Plain: similar to python's normal traceback printing.
3458 \layout List
3470 \layout List
3459 \labelwidthstring 00.00.0000
3471 \labelwidthstring 00.00.0000
3460
3472
3461 \SpecialChar ~
3473 \SpecialChar ~
3462 Context: prints 5 lines of context source code around each line in the
3474 Context: prints 5 lines of context source code around each line in the
3463 traceback.
3475 traceback.
3464 \layout List
3476 \layout List
3465 \labelwidthstring 00.00.0000
3477 \labelwidthstring 00.00.0000
3466
3478
3467 \SpecialChar ~
3479 \SpecialChar ~
3468 Verbose: similar to Context, but additionally prints the variables currently
3480 Verbose: similar to Context, but additionally prints the variables currently
3469 visible where the exception happened (shortening their strings if too long).
3481 visible where the exception happened (shortening their strings if too long).
3470 This can potentially be very slow, if you happen to have a huge data structure
3482 This can potentially be very slow, if you happen to have a huge data structure
3471 whose string representation is complex to compute.
3483 whose string representation is complex to compute.
3472 Your computer may appear to freeze for a while with cpu usage at 100%.
3484 Your computer may appear to freeze for a while with cpu usage at 100%.
3473 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3485 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3474 it more than once).
3486 it more than once).
3475 \layout Section
3487 \layout Section
3476
3488
3477 Interactive use
3489 Interactive use
3478 \layout Standard
3490 \layout Standard
3479
3491
3480
3492
3481 \series bold
3493 \series bold
3482 Warning
3494 Warning
3483 \series default
3495 \series default
3484 : IPython relies on the existence of a global variable called
3496 : IPython relies on the existence of a global variable called
3485 \family typewriter
3497 \family typewriter
3486 __IP
3498 __IP
3487 \family default
3499 \family default
3488 which controls the shell itself.
3500 which controls the shell itself.
3489 If you redefine
3501 If you redefine
3490 \family typewriter
3502 \family typewriter
3491 __IP
3503 __IP
3492 \family default
3504 \family default
3493 to anything, bizarre behavior will quickly occur.
3505 to anything, bizarre behavior will quickly occur.
3494 \layout Standard
3506 \layout Standard
3495
3507
3496 Other than the above warning, IPython is meant to work as a drop-in replacement
3508 Other than the above warning, IPython is meant to work as a drop-in replacement
3497 for the standard interactive interpreter.
3509 for the standard interactive interpreter.
3498 As such, any code which is valid python should execute normally under IPython
3510 As such, any code which is valid python should execute normally under IPython
3499 (cases where this is not true should be reported as bugs).
3511 (cases where this is not true should be reported as bugs).
3500 It does, however, offer many features which are not available at a standard
3512 It does, however, offer many features which are not available at a standard
3501 python prompt.
3513 python prompt.
3502 What follows is a list of these.
3514 What follows is a list of these.
3503 \layout Subsection
3515 \layout Subsection
3504
3516
3505 Caution for Windows users
3517 Caution for Windows users
3506 \layout Standard
3518 \layout Standard
3507
3519
3508 Windows, unfortunately, uses the `
3520 Windows, unfortunately, uses the `
3509 \family typewriter
3521 \family typewriter
3510
3522
3511 \backslash
3523 \backslash
3512
3524
3513 \family default
3525 \family default
3514 ' character as a path separator.
3526 ' character as a path separator.
3515 This is a terrible choice, because `
3527 This is a terrible choice, because `
3516 \family typewriter
3528 \family typewriter
3517
3529
3518 \backslash
3530 \backslash
3519
3531
3520 \family default
3532 \family default
3521 ' also represents the escape character in most modern programming languages,
3533 ' also represents the escape character in most modern programming languages,
3522 including Python.
3534 including Python.
3523 For this reason, issuing many of the commands discussed below (especially
3535 For this reason, issuing many of the commands discussed below (especially
3524 magics which affect the filesystem) with `
3536 magics which affect the filesystem) with `
3525 \family typewriter
3537 \family typewriter
3526
3538
3527 \backslash
3539 \backslash
3528
3540
3529 \family default
3541 \family default
3530 ' in them will cause strange errors.
3542 ' in them will cause strange errors.
3531 \layout Standard
3543 \layout Standard
3532
3544
3533 A partial solution is to use instead the `
3545 A partial solution is to use instead the `
3534 \family typewriter
3546 \family typewriter
3535 /
3547 /
3536 \family default
3548 \family default
3537 ' character as a path separator, which Windows recognizes in
3549 ' character as a path separator, which Windows recognizes in
3538 \emph on
3550 \emph on
3539 most
3551 most
3540 \emph default
3552 \emph default
3541 situations.
3553 situations.
3542 However, in Windows commands `
3554 However, in Windows commands `
3543 \family typewriter
3555 \family typewriter
3544 /
3556 /
3545 \family default
3557 \family default
3546 ' flags options, so you can not use it for the root directory.
3558 ' flags options, so you can not use it for the root directory.
3547 This means that paths beginning at the root must be typed in a contrived
3559 This means that paths beginning at the root must be typed in a contrived
3548 manner like:
3560 manner like:
3549 \newline
3561 \newline
3550
3562
3551 \family typewriter
3563 \family typewriter
3552 %copy
3564 %copy
3553 \backslash
3565 \backslash
3554 opt/foo/bar.txt
3566 opt/foo/bar.txt
3555 \backslash
3567 \backslash
3556 tmp
3568 tmp
3557 \layout Standard
3569 \layout Standard
3558
3570
3559 There is no sensible thing IPython can do to truly work around this flaw
3571 There is no sensible thing IPython can do to truly work around this flaw
3560 in Windows
3572 in Windows
3561 \begin_inset Foot
3573 \begin_inset Foot
3562 collapsed true
3574 collapsed true
3563
3575
3564 \layout Standard
3576 \layout Standard
3565
3577
3566 If anyone comes up with a
3578 If anyone comes up with a
3567 \emph on
3579 \emph on
3568 clean
3580 clean
3569 \emph default
3581 \emph default
3570 solution which works consistently and does not negatively impact other
3582 solution which works consistently and does not negatively impact other
3571 platforms at all, I'll gladly accept a patch.
3583 platforms at all, I'll gladly accept a patch.
3572 \end_inset
3584 \end_inset
3573
3585
3574 .
3586 .
3575 \layout Subsection
3587 \layout Subsection
3576
3588
3577
3589
3578 \begin_inset LatexCommand \label{sec:magic}
3590 \begin_inset LatexCommand \label{sec:magic}
3579
3591
3580 \end_inset
3592 \end_inset
3581
3593
3582 Magic command system
3594 Magic command system
3583 \layout Standard
3595 \layout Standard
3584
3596
3585 IPython will treat any line whose first character is a
3597 IPython will treat any line whose first character is a
3586 \family typewriter
3598 \family typewriter
3587 %
3599 %
3588 \family default
3600 \family default
3589 as a special call to a 'magic' function.
3601 as a special call to a 'magic' function.
3590 These allow you to control the behavior of IPython itself, plus a lot of
3602 These allow you to control the behavior of IPython itself, plus a lot of
3591 system-type features.
3603 system-type features.
3592 They are all prefixed with a
3604 They are all prefixed with a
3593 \family typewriter
3605 \family typewriter
3594 %
3606 %
3595 \family default
3607 \family default
3596 character, but parameters are given without parentheses or quotes.
3608 character, but parameters are given without parentheses or quotes.
3597 \layout Standard
3609 \layout Standard
3598
3610
3599 Example: typing
3611 Example: typing
3600 \family typewriter
3612 \family typewriter
3601 '%cd mydir'
3613 '%cd mydir'
3602 \family default
3614 \family default
3603 (without the quotes) changes you working directory to
3615 (without the quotes) changes you working directory to
3604 \family typewriter
3616 \family typewriter
3605 'mydir'
3617 'mydir'
3606 \family default
3618 \family default
3607 , if it exists.
3619 , if it exists.
3608 \layout Standard
3620 \layout Standard
3609
3621
3610 If you have 'automagic' enabled (in your
3622 If you have 'automagic' enabled (in your
3611 \family typewriter
3623 \family typewriter
3612 ipythonrc
3624 ipythonrc
3613 \family default
3625 \family default
3614 file, via the command line option
3626 file, via the command line option
3615 \family typewriter
3627 \family typewriter
3616 -automagic
3628 -automagic
3617 \family default
3629 \family default
3618 or with the
3630 or with the
3619 \family typewriter
3631 \family typewriter
3620 %automagic
3632 %automagic
3621 \family default
3633 \family default
3622 function), you don't need to type in the
3634 function), you don't need to type in the
3623 \family typewriter
3635 \family typewriter
3624 %
3636 %
3625 \family default
3637 \family default
3626 explicitly.
3638 explicitly.
3627 IPython will scan its internal list of magic functions and call one if
3639 IPython will scan its internal list of magic functions and call one if
3628 it exists.
3640 it exists.
3629 With automagic on you can then just type '
3641 With automagic on you can then just type '
3630 \family typewriter
3642 \family typewriter
3631 cd mydir
3643 cd mydir
3632 \family default
3644 \family default
3633 ' to go to directory '
3645 ' to go to directory '
3634 \family typewriter
3646 \family typewriter
3635 mydir
3647 mydir
3636 \family default
3648 \family default
3637 '.
3649 '.
3638 The automagic system has the lowest possible precedence in name searches,
3650 The automagic system has the lowest possible precedence in name searches,
3639 so defining an identifier with the same name as an existing magic function
3651 so defining an identifier with the same name as an existing magic function
3640 will shadow it for automagic use.
3652 will shadow it for automagic use.
3641 You can still access the shadowed magic function by explicitly using the
3653 You can still access the shadowed magic function by explicitly using the
3642
3654
3643 \family typewriter
3655 \family typewriter
3644 %
3656 %
3645 \family default
3657 \family default
3646 character at the beginning of the line.
3658 character at the beginning of the line.
3647 \layout Standard
3659 \layout Standard
3648
3660
3649 An example (with automagic on) should clarify all this:
3661 An example (with automagic on) should clarify all this:
3650 \layout LyX-Code
3662 \layout LyX-Code
3651
3663
3652 In [1]: cd ipython # %cd is called by automagic
3664 In [1]: cd ipython # %cd is called by automagic
3653 \layout LyX-Code
3665 \layout LyX-Code
3654
3666
3655 /home/fperez/ipython
3667 /home/fperez/ipython
3656 \layout LyX-Code
3668 \layout LyX-Code
3657
3669
3658 In [2]: cd=1 # now cd is just a variable
3670 In [2]: cd=1 # now cd is just a variable
3659 \layout LyX-Code
3671 \layout LyX-Code
3660
3672
3661 In [3]: cd ..
3673 In [3]: cd ..
3662 # and doesn't work as a function anymore
3674 # and doesn't work as a function anymore
3663 \layout LyX-Code
3675 \layout LyX-Code
3664
3676
3665 ------------------------------------------------------------
3677 ------------------------------------------------------------
3666 \layout LyX-Code
3678 \layout LyX-Code
3667
3679
3668 File "<console>", line 1
3680 File "<console>", line 1
3669 \layout LyX-Code
3681 \layout LyX-Code
3670
3682
3671 cd ..
3683 cd ..
3672 \layout LyX-Code
3684 \layout LyX-Code
3673
3685
3674 ^
3686 ^
3675 \layout LyX-Code
3687 \layout LyX-Code
3676
3688
3677 SyntaxError: invalid syntax
3689 SyntaxError: invalid syntax
3678 \layout LyX-Code
3690 \layout LyX-Code
3679
3691
3680 \layout LyX-Code
3692 \layout LyX-Code
3681
3693
3682 In [4]: %cd ..
3694 In [4]: %cd ..
3683 # but %cd always works
3695 # but %cd always works
3684 \layout LyX-Code
3696 \layout LyX-Code
3685
3697
3686 /home/fperez
3698 /home/fperez
3687 \layout LyX-Code
3699 \layout LyX-Code
3688
3700
3689 In [5]: del cd # if you remove the cd variable
3701 In [5]: del cd # if you remove the cd variable
3690 \layout LyX-Code
3702 \layout LyX-Code
3691
3703
3692 In [6]: cd ipython # automagic can work again
3704 In [6]: cd ipython # automagic can work again
3693 \layout LyX-Code
3705 \layout LyX-Code
3694
3706
3695 /home/fperez/ipython
3707 /home/fperez/ipython
3696 \layout Standard
3708 \layout Standard
3697
3709
3698 You can define your own magic functions to extend the system.
3710 You can define your own magic functions to extend the system.
3699 The following is a snippet of code which shows how to do it.
3711 The following is a snippet of code which shows how to do it.
3700 It is provided as file
3712 It is provided as file
3701 \family typewriter
3713 \family typewriter
3702 example-magic.py
3714 example-magic.py
3703 \family default
3715 \family default
3704 in the examples directory:
3716 in the examples directory:
3705 \layout Standard
3717 \layout Standard
3706
3718
3707
3719
3708 \begin_inset ERT
3720 \begin_inset ERT
3709 status Open
3721 status Open
3710
3722
3711 \layout Standard
3723 \layout Standard
3712
3724
3713 \backslash
3725 \backslash
3714 codelist{examples/example-magic.py}
3726 codelist{examples/example-magic.py}
3715 \end_inset
3727 \end_inset
3716
3728
3717
3729
3718 \layout Standard
3730 \layout Standard
3719
3731
3720 You can also define your own aliased names for magic functions.
3732 You can also define your own aliased names for magic functions.
3721 In your
3733 In your
3722 \family typewriter
3734 \family typewriter
3723 ipythonrc
3735 ipythonrc
3724 \family default
3736 \family default
3725 file, placing a line like:
3737 file, placing a line like:
3726 \layout Standard
3738 \layout Standard
3727
3739
3728
3740
3729 \family typewriter
3741 \family typewriter
3730 execute __IP.magic_cl = __IP.magic_clear
3742 execute __IP.magic_cl = __IP.magic_clear
3731 \layout Standard
3743 \layout Standard
3732
3744
3733 will define
3745 will define
3734 \family typewriter
3746 \family typewriter
3735 %cl
3747 %cl
3736 \family default
3748 \family default
3737 as a new name for
3749 as a new name for
3738 \family typewriter
3750 \family typewriter
3739 %clear
3751 %clear
3740 \family default
3752 \family default
3741 .
3753 .
3742 \layout Standard
3754 \layout Standard
3743
3755
3744 Type
3756 Type
3745 \family typewriter
3757 \family typewriter
3746 %magic
3758 %magic
3747 \family default
3759 \family default
3748 for more information, including a list of all available magic functions
3760 for more information, including a list of all available magic functions
3749 at any time and their docstrings.
3761 at any time and their docstrings.
3750 You can also type
3762 You can also type
3751 \family typewriter
3763 \family typewriter
3752 %magic_function_name?
3764 %magic_function_name?
3753 \family default
3765 \family default
3754 (see sec.
3766 (see sec.
3755
3767
3756 \begin_inset LatexCommand \ref{sec:dyn-object-info}
3768 \begin_inset LatexCommand \ref{sec:dyn-object-info}
3757
3769
3758 \end_inset
3770 \end_inset
3759
3771
3760 for information on the
3772 for information on the
3761 \family typewriter
3773 \family typewriter
3762 '?'
3774 '?'
3763 \family default
3775 \family default
3764 system) to get information about any particular magic function you are
3776 system) to get information about any particular magic function you are
3765 interested in.
3777 interested in.
3766 \layout Subsubsection
3778 \layout Subsubsection
3767
3779
3768 Magic commands
3780 Magic commands
3769 \layout Standard
3781 \layout Standard
3770
3782
3771 The rest of this section is automatically generated for each release from
3783 The rest of this section is automatically generated for each release from
3772 the docstrings in the IPython code.
3784 the docstrings in the IPython code.
3773 Therefore the formatting is somewhat minimal, but this method has the advantage
3785 Therefore the formatting is somewhat minimal, but this method has the advantage
3774 of having information always in sync with the code.
3786 of having information always in sync with the code.
3775 \layout Standard
3787 \layout Standard
3776
3788
3777 A list of all the magic commands available in IPython's
3789 A list of all the magic commands available in IPython's
3778 \emph on
3790 \emph on
3779 default
3791 default
3780 \emph default
3792 \emph default
3781 installation follows.
3793 installation follows.
3782 This is similar to what you'll see by simply typing
3794 This is similar to what you'll see by simply typing
3783 \family typewriter
3795 \family typewriter
3784 %magic
3796 %magic
3785 \family default
3797 \family default
3786 at the prompt, but that will also give you information about magic commands
3798 at the prompt, but that will also give you information about magic commands
3787 you may have added as part of your personal customizations.
3799 you may have added as part of your personal customizations.
3788 \layout Standard
3800 \layout Standard
3789
3801
3790
3802
3791 \begin_inset Include \input{magic.tex}
3803 \begin_inset Include \input{magic.tex}
3792 preview false
3804 preview false
3793
3805
3794 \end_inset
3806 \end_inset
3795
3807
3796
3808
3797 \layout Subsection
3809 \layout Subsection
3798
3810
3799 Access to the standard Python help
3811 Access to the standard Python help
3800 \layout Standard
3812 \layout Standard
3801
3813
3802 As of Python 2.1, a help system is available with access to object docstrings
3814 As of Python 2.1, a help system is available with access to object docstrings
3803 and the Python manuals.
3815 and the Python manuals.
3804 Simply type
3816 Simply type
3805 \family typewriter
3817 \family typewriter
3806 'help'
3818 'help'
3807 \family default
3819 \family default
3808 (no quotes) to access it.
3820 (no quotes) to access it.
3809 You can also type
3821 You can also type
3810 \family typewriter
3822 \family typewriter
3811 help(object)
3823 help(object)
3812 \family default
3824 \family default
3813 to obtain information about a given object, and
3825 to obtain information about a given object, and
3814 \family typewriter
3826 \family typewriter
3815 help('keyword')
3827 help('keyword')
3816 \family default
3828 \family default
3817 for information on a keyword.
3829 for information on a keyword.
3818 As noted in sec.
3830 As noted in sec.
3819
3831
3820 \begin_inset LatexCommand \ref{sec:help-access}
3832 \begin_inset LatexCommand \ref{sec:help-access}
3821
3833
3822 \end_inset
3834 \end_inset
3823
3835
3824 , you need to properly configure your environment variable
3836 , you need to properly configure your environment variable
3825 \family typewriter
3837 \family typewriter
3826 PYTHONDOCS
3838 PYTHONDOCS
3827 \family default
3839 \family default
3828 for this feature to work correctly.
3840 for this feature to work correctly.
3829 \layout Subsection
3841 \layout Subsection
3830
3842
3831
3843
3832 \begin_inset LatexCommand \label{sec:dyn-object-info}
3844 \begin_inset LatexCommand \label{sec:dyn-object-info}
3833
3845
3834 \end_inset
3846 \end_inset
3835
3847
3836 Dynamic object information
3848 Dynamic object information
3837 \layout Standard
3849 \layout Standard
3838
3850
3839 Typing
3851 Typing
3840 \family typewriter
3852 \family typewriter
3841 ?word
3853 ?word
3842 \family default
3854 \family default
3843 or
3855 or
3844 \family typewriter
3856 \family typewriter
3845 word?
3857 word?
3846 \family default
3858 \family default
3847 prints detailed information about an object.
3859 prints detailed information about an object.
3848 If certain strings in the object are too long (docstrings, code, etc.) they
3860 If certain strings in the object are too long (docstrings, code, etc.) they
3849 get snipped in the center for brevity.
3861 get snipped in the center for brevity.
3850 This system gives access variable types and values, full source code for
3862 This system gives access variable types and values, full source code for
3851 any object (if available), function prototypes and other useful information.
3863 any object (if available), function prototypes and other useful information.
3852 \layout Standard
3864 \layout Standard
3853
3865
3854 Typing
3866 Typing
3855 \family typewriter
3867 \family typewriter
3856 ??word
3868 ??word
3857 \family default
3869 \family default
3858 or
3870 or
3859 \family typewriter
3871 \family typewriter
3860 word??
3872 word??
3861 \family default
3873 \family default
3862 gives access to the full information without snipping long strings.
3874 gives access to the full information without snipping long strings.
3863 Long strings are sent to the screen through the
3875 Long strings are sent to the screen through the
3864 \family typewriter
3876 \family typewriter
3865 less
3877 less
3866 \family default
3878 \family default
3867 pager if longer than the screen and printed otherwise.
3879 pager if longer than the screen and printed otherwise.
3868 On systems lacking the
3880 On systems lacking the
3869 \family typewriter
3881 \family typewriter
3870 less
3882 less
3871 \family default
3883 \family default
3872 command, IPython uses a very basic internal pager.
3884 command, IPython uses a very basic internal pager.
3873 \layout Standard
3885 \layout Standard
3874
3886
3875 The following magic functions are particularly useful for gathering information
3887 The following magic functions are particularly useful for gathering information
3876 about your working environment.
3888 about your working environment.
3877 You can get more details by typing
3889 You can get more details by typing
3878 \family typewriter
3890 \family typewriter
3879 %magic
3891 %magic
3880 \family default
3892 \family default
3881 or querying them individually (use
3893 or querying them individually (use
3882 \family typewriter
3894 \family typewriter
3883 %function_name?
3895 %function_name?
3884 \family default
3896 \family default
3885 with or without the
3897 with or without the
3886 \family typewriter
3898 \family typewriter
3887 %
3899 %
3888 \family default
3900 \family default
3889 ), this is just a summary:
3901 ), this is just a summary:
3890 \layout List
3902 \layout List
3891 \labelwidthstring 00.00.0000
3903 \labelwidthstring 00.00.0000
3892
3904
3893
3905
3894 \family typewriter
3906 \family typewriter
3895 \series bold
3907 \series bold
3896 %pdoc\SpecialChar ~
3908 %pdoc\SpecialChar ~
3897 <object>
3909 <object>
3898 \family default
3910 \family default
3899 \series default
3911 \series default
3900 : Print (or run through a pager if too long) the docstring for an object.
3912 : Print (or run through a pager if too long) the docstring for an object.
3901 If the given object is a class, it will print both the class and the constructo
3913 If the given object is a class, it will print both the class and the constructo
3902 r docstrings.
3914 r docstrings.
3903 \layout List
3915 \layout List
3904 \labelwidthstring 00.00.0000
3916 \labelwidthstring 00.00.0000
3905
3917
3906
3918
3907 \family typewriter
3919 \family typewriter
3908 \series bold
3920 \series bold
3909 %pdef\SpecialChar ~
3921 %pdef\SpecialChar ~
3910 <object>
3922 <object>
3911 \family default
3923 \family default
3912 \series default
3924 \series default
3913 : Print the definition header for any callable object.
3925 : Print the definition header for any callable object.
3914 If the object is a class, print the constructor information.
3926 If the object is a class, print the constructor information.
3915 \layout List
3927 \layout List
3916 \labelwidthstring 00.00.0000
3928 \labelwidthstring 00.00.0000
3917
3929
3918
3930
3919 \family typewriter
3931 \family typewriter
3920 \series bold
3932 \series bold
3921 %psource\SpecialChar ~
3933 %psource\SpecialChar ~
3922 <object>
3934 <object>
3923 \family default
3935 \family default
3924 \series default
3936 \series default
3925 : Print (or run through a pager if too long) the source code for an object.
3937 : Print (or run through a pager if too long) the source code for an object.
3926 \layout List
3938 \layout List
3927 \labelwidthstring 00.00.0000
3939 \labelwidthstring 00.00.0000
3928
3940
3929
3941
3930 \family typewriter
3942 \family typewriter
3931 \series bold
3943 \series bold
3932 %pfile\SpecialChar ~
3944 %pfile\SpecialChar ~
3933 <object>
3945 <object>
3934 \family default
3946 \family default
3935 \series default
3947 \series default
3936 : Show the entire source file where an object was defined via a pager, opening
3948 : Show the entire source file where an object was defined via a pager, opening
3937 it at the line where the object definition begins.
3949 it at the line where the object definition begins.
3938 \layout List
3950 \layout List
3939 \labelwidthstring 00.00.0000
3951 \labelwidthstring 00.00.0000
3940
3952
3941
3953
3942 \family typewriter
3954 \family typewriter
3943 \series bold
3955 \series bold
3944 %who/%whos
3956 %who/%whos
3945 \family default
3957 \family default
3946 \series default
3958 \series default
3947 : These functions give information about identifiers you have defined interactiv
3959 : These functions give information about identifiers you have defined interactiv
3948 ely (not things you loaded or defined in your configuration files).
3960 ely (not things you loaded or defined in your configuration files).
3949
3961
3950 \family typewriter
3962 \family typewriter
3951 %who
3963 %who
3952 \family default
3964 \family default
3953 just prints a list of identifiers and
3965 just prints a list of identifiers and
3954 \family typewriter
3966 \family typewriter
3955 %whos
3967 %whos
3956 \family default
3968 \family default
3957 prints a table with some basic details about each identifier.
3969 prints a table with some basic details about each identifier.
3958 \layout Standard
3970 \layout Standard
3959
3971
3960 Note that the dynamic object information functions (
3972 Note that the dynamic object information functions (
3961 \family typewriter
3973 \family typewriter
3962 ?/??, %pdoc, %pfile, %pdef, %psource
3974 ?/??, %pdoc, %pfile, %pdef, %psource
3963 \family default
3975 \family default
3964 ) give you access to documentation even on things which are not really defined
3976 ) give you access to documentation even on things which are not really defined
3965 as separate identifiers.
3977 as separate identifiers.
3966 Try for example typing
3978 Try for example typing
3967 \family typewriter
3979 \family typewriter
3968 {}.get?
3980 {}.get?
3969 \family default
3981 \family default
3970 or after doing
3982 or after doing
3971 \family typewriter
3983 \family typewriter
3972 import os
3984 import os
3973 \family default
3985 \family default
3974 , type
3986 , type
3975 \family typewriter
3987 \family typewriter
3976 os.path.abspath??
3988 os.path.abspath??
3977 \family default
3989 \family default
3978 .
3990 .
3979 \layout Subsection
3991 \layout Subsection
3980
3992
3981
3993
3982 \begin_inset LatexCommand \label{sec:readline}
3994 \begin_inset LatexCommand \label{sec:readline}
3983
3995
3984 \end_inset
3996 \end_inset
3985
3997
3986 Readline-based features
3998 Readline-based features
3987 \layout Standard
3999 \layout Standard
3988
4000
3989 These features require the GNU readline library, so they won't work if your
4001 These features require the GNU readline library, so they won't work if your
3990 Python installation lacks readline support.
4002 Python installation lacks readline support.
3991 We will first describe the default behavior IPython uses, and then how
4003 We will first describe the default behavior IPython uses, and then how
3992 to change it to suit your preferences.
4004 to change it to suit your preferences.
3993 \layout Subsubsection
4005 \layout Subsubsection
3994
4006
3995 Command line completion
4007 Command line completion
3996 \layout Standard
4008 \layout Standard
3997
4009
3998 At any time, hitting TAB will complete any available python commands or
4010 At any time, hitting TAB will complete any available python commands or
3999 variable names, and show you a list of the possible completions if there's
4011 variable names, and show you a list of the possible completions if there's
4000 no unambiguous one.
4012 no unambiguous one.
4001 It will also complete filenames in the current directory if no python names
4013 It will also complete filenames in the current directory if no python names
4002 match what you've typed so far.
4014 match what you've typed so far.
4003 \layout Subsubsection
4015 \layout Subsubsection
4004
4016
4005 Search command history
4017 Search command history
4006 \layout Standard
4018 \layout Standard
4007
4019
4008 IPython provides two ways for searching through previous input and thus
4020 IPython provides two ways for searching through previous input and thus
4009 reduce the need for repetitive typing:
4021 reduce the need for repetitive typing:
4010 \layout Enumerate
4022 \layout Enumerate
4011
4023
4012 Start typing, and then use
4024 Start typing, and then use
4013 \family typewriter
4025 \family typewriter
4014 Ctrl-p
4026 Ctrl-p
4015 \family default
4027 \family default
4016 (previous,up) and
4028 (previous,up) and
4017 \family typewriter
4029 \family typewriter
4018 Ctrl-n
4030 Ctrl-n
4019 \family default
4031 \family default
4020 (next,down) to search through only the history items that match what you've
4032 (next,down) to search through only the history items that match what you've
4021 typed so far.
4033 typed so far.
4022 If you use
4034 If you use
4023 \family typewriter
4035 \family typewriter
4024 Ctrl-p/Ctrl-n
4036 Ctrl-p/Ctrl-n
4025 \family default
4037 \family default
4026 at a blank prompt, they just behave like normal arrow keys.
4038 at a blank prompt, they just behave like normal arrow keys.
4027 \layout Enumerate
4039 \layout Enumerate
4028
4040
4029 Hit
4041 Hit
4030 \family typewriter
4042 \family typewriter
4031 Ctrl-r
4043 Ctrl-r
4032 \family default
4044 \family default
4033 : opens a search prompt.
4045 : opens a search prompt.
4034 Begin typing and the system searches your history for lines that contain
4046 Begin typing and the system searches your history for lines that contain
4035 what you've typed so far, completing as much as it can.
4047 what you've typed so far, completing as much as it can.
4036 \layout Subsubsection
4048 \layout Subsubsection
4037
4049
4038 Persistent command history across sessions
4050 Persistent command history across sessions
4039 \layout Standard
4051 \layout Standard
4040
4052
4041 IPython will save your input history when it leaves and reload it next time
4053 IPython will save your input history when it leaves and reload it next time
4042 you restart it.
4054 you restart it.
4043 By default, the history file is named
4055 By default, the history file is named
4044 \family typewriter
4056 \family typewriter
4045 $IPYTHONDIR/history
4057 $IPYTHONDIR/history
4046 \family default
4058 \family default
4047 , but if you've loaded a named profile, '
4059 , but if you've loaded a named profile, '
4048 \family typewriter
4060 \family typewriter
4049 -PROFILE_NAME
4061 -PROFILE_NAME
4050 \family default
4062 \family default
4051 ' is appended to the name.
4063 ' is appended to the name.
4052 This allows you to keep separate histories related to various tasks: commands
4064 This allows you to keep separate histories related to various tasks: commands
4053 related to numerical work will not be clobbered by a system shell history,
4065 related to numerical work will not be clobbered by a system shell history,
4054 for example.
4066 for example.
4055 \layout Subsubsection
4067 \layout Subsubsection
4056
4068
4057 Autoindent
4069 Autoindent
4058 \layout Standard
4070 \layout Standard
4059
4071
4060 IPython can recognize lines ending in ':' and indent the next line, while
4072 IPython can recognize lines ending in ':' and indent the next line, while
4061 also un-indenting automatically after 'raise' or 'return'.
4073 also un-indenting automatically after 'raise' or 'return'.
4062
4074
4063 \layout Standard
4075 \layout Standard
4064
4076
4065 This feature uses the readline library, so it will honor your
4077 This feature uses the readline library, so it will honor your
4066 \family typewriter
4078 \family typewriter
4067 ~/.inputrc
4079 ~/.inputrc
4068 \family default
4080 \family default
4069 configuration (or whatever file your
4081 configuration (or whatever file your
4070 \family typewriter
4082 \family typewriter
4071 INPUTRC
4083 INPUTRC
4072 \family default
4084 \family default
4073 variable points to).
4085 variable points to).
4074 Adding the following lines to your
4086 Adding the following lines to your
4075 \family typewriter
4087 \family typewriter
4076 .inputrc
4088 .inputrc
4077 \family default
4089 \family default
4078 file can make indenting/unindenting more convenient (
4090 file can make indenting/unindenting more convenient (
4079 \family typewriter
4091 \family typewriter
4080 M-i
4092 M-i
4081 \family default
4093 \family default
4082 indents,
4094 indents,
4083 \family typewriter
4095 \family typewriter
4084 M-u
4096 M-u
4085 \family default
4097 \family default
4086 unindents):
4098 unindents):
4087 \layout Standard
4099 \layout Standard
4088
4100
4089
4101
4090 \family typewriter
4102 \family typewriter
4091 $if Python
4103 $if Python
4092 \newline
4104 \newline
4093 "
4105 "
4094 \backslash
4106 \backslash
4095 M-i": "\SpecialChar ~
4107 M-i": "\SpecialChar ~
4096 \SpecialChar ~
4108 \SpecialChar ~
4097 \SpecialChar ~
4109 \SpecialChar ~
4098 \SpecialChar ~
4110 \SpecialChar ~
4099 "
4111 "
4100 \newline
4112 \newline
4101 "
4113 "
4102 \backslash
4114 \backslash
4103 M-u": "
4115 M-u": "
4104 \backslash
4116 \backslash
4105 d
4117 d
4106 \backslash
4118 \backslash
4107 d
4119 d
4108 \backslash
4120 \backslash
4109 d
4121 d
4110 \backslash
4122 \backslash
4111 d"
4123 d"
4112 \newline
4124 \newline
4113 $endif
4125 $endif
4114 \layout Standard
4126 \layout Standard
4115
4127
4116 Note that there are 4 spaces between the quote marks after
4128 Note that there are 4 spaces between the quote marks after
4117 \family typewriter
4129 \family typewriter
4118 "M-i"
4130 "M-i"
4119 \family default
4131 \family default
4120 above.
4132 above.
4121 \layout Standard
4133 \layout Standard
4122
4134
4123
4135
4124 \series bold
4136 \series bold
4125 Warning:
4137 Warning:
4126 \series default
4138 \series default
4127 this feature is ON by default, but it can cause problems with the pasting
4139 this feature is ON by default, but it can cause problems with the pasting
4128 of multi-line indented code (the pasted code gets re-indented on each line).
4140 of multi-line indented code (the pasted code gets re-indented on each line).
4129 A magic function
4141 A magic function
4130 \family typewriter
4142 \family typewriter
4131 %autoindent
4143 %autoindent
4132 \family default
4144 \family default
4133 allows you to toggle it on/off at runtime.
4145 allows you to toggle it on/off at runtime.
4134 You can also disable it permanently on in your
4146 You can also disable it permanently on in your
4135 \family typewriter
4147 \family typewriter
4136 ipythonrc
4148 ipythonrc
4137 \family default
4149 \family default
4138 file (set
4150 file (set
4139 \family typewriter
4151 \family typewriter
4140 autoindent 0
4152 autoindent 0
4141 \family default
4153 \family default
4142 ).
4154 ).
4143 \layout Subsubsection
4155 \layout Subsubsection
4144
4156
4145 Customizing readline behavior
4157 Customizing readline behavior
4146 \layout Standard
4158 \layout Standard
4147
4159
4148 All these features are based on the GNU readline library, which has an extremely
4160 All these features are based on the GNU readline library, which has an extremely
4149 customizable interface.
4161 customizable interface.
4150 Normally, readline is configured via a file which defines the behavior
4162 Normally, readline is configured via a file which defines the behavior
4151 of the library; the details of the syntax for this can be found in the
4163 of the library; the details of the syntax for this can be found in the
4152 readline documentation available with your system or on the Internet.
4164 readline documentation available with your system or on the Internet.
4153 IPython doesn't read this file (if it exists) directly, but it does support
4165 IPython doesn't read this file (if it exists) directly, but it does support
4154 passing to readline valid options via a simple interface.
4166 passing to readline valid options via a simple interface.
4155 In brief, you can customize readline by setting the following options in
4167 In brief, you can customize readline by setting the following options in
4156 your
4168 your
4157 \family typewriter
4169 \family typewriter
4158 ipythonrc
4170 ipythonrc
4159 \family default
4171 \family default
4160 configuration file (note that these options can
4172 configuration file (note that these options can
4161 \emph on
4173 \emph on
4162 not
4174 not
4163 \emph default
4175 \emph default
4164 be specified at the command line):
4176 be specified at the command line):
4165 \layout List
4177 \layout List
4166 \labelwidthstring 00.00.0000
4178 \labelwidthstring 00.00.0000
4167
4179
4168
4180
4169 \family typewriter
4181 \family typewriter
4170 \series bold
4182 \series bold
4171 readline_parse_and_bind:
4183 readline_parse_and_bind:
4172 \family default
4184 \family default
4173 \series default
4185 \series default
4174 this option can appear as many times as you want, each time defining a
4186 this option can appear as many times as you want, each time defining a
4175 string to be executed via a
4187 string to be executed via a
4176 \family typewriter
4188 \family typewriter
4177 readline.parse_and_bind()
4189 readline.parse_and_bind()
4178 \family default
4190 \family default
4179 command.
4191 command.
4180 The syntax for valid commands of this kind can be found by reading the
4192 The syntax for valid commands of this kind can be found by reading the
4181 documentation for the GNU readline library, as these commands are of the
4193 documentation for the GNU readline library, as these commands are of the
4182 kind which readline accepts in its configuration file.
4194 kind which readline accepts in its configuration file.
4183 \layout List
4195 \layout List
4184 \labelwidthstring 00.00.0000
4196 \labelwidthstring 00.00.0000
4185
4197
4186
4198
4187 \family typewriter
4199 \family typewriter
4188 \series bold
4200 \series bold
4189 readline_remove_delims:
4201 readline_remove_delims:
4190 \family default
4202 \family default
4191 \series default
4203 \series default
4192 a string of characters to be removed from the default word-delimiters list
4204 a string of characters to be removed from the default word-delimiters list
4193 used by readline, so that completions may be performed on strings which
4205 used by readline, so that completions may be performed on strings which
4194 contain them.
4206 contain them.
4195 Do not change the default value unless you know what you're doing.
4207 Do not change the default value unless you know what you're doing.
4196 \layout List
4208 \layout List
4197 \labelwidthstring 00.00.0000
4209 \labelwidthstring 00.00.0000
4198
4210
4199
4211
4200 \family typewriter
4212 \family typewriter
4201 \series bold
4213 \series bold
4202 readline_omit__names
4214 readline_omit__names
4203 \family default
4215 \family default
4204 \series default
4216 \series default
4205 : when tab-completion is enabled, hitting
4217 : when tab-completion is enabled, hitting
4206 \family typewriter
4218 \family typewriter
4207 <tab>
4219 <tab>
4208 \family default
4220 \family default
4209 after a '
4221 after a '
4210 \family typewriter
4222 \family typewriter
4211 .
4223 .
4212 \family default
4224 \family default
4213 ' in a name will complete all attributes of an object, including all the
4225 ' in a name will complete all attributes of an object, including all the
4214 special methods whose names include double underscores (like
4226 special methods whose names include double underscores (like
4215 \family typewriter
4227 \family typewriter
4216 __getitem__
4228 __getitem__
4217 \family default
4229 \family default
4218 or
4230 or
4219 \family typewriter
4231 \family typewriter
4220 __class__
4232 __class__
4221 \family default
4233 \family default
4222 ).
4234 ).
4223 If you'd rather not see these names by default, you can set this option
4235 If you'd rather not see these names by default, you can set this option
4224 to 1.
4236 to 1.
4225 Note that even when this option is set, you can still see those names by
4237 Note that even when this option is set, you can still see those names by
4226 explicitly typing a
4238 explicitly typing a
4227 \family typewriter
4239 \family typewriter
4228 _
4240 _
4229 \family default
4241 \family default
4230 after the period and hitting
4242 after the period and hitting
4231 \family typewriter
4243 \family typewriter
4232 <tab>
4244 <tab>
4233 \family default
4245 \family default
4234 : '
4246 : '
4235 \family typewriter
4247 \family typewriter
4236 name._<tab>
4248 name._<tab>
4237 \family default
4249 \family default
4238 ' will always complete attribute names starting with '
4250 ' will always complete attribute names starting with '
4239 \family typewriter
4251 \family typewriter
4240 _
4252 _
4241 \family default
4253 \family default
4242 '.
4254 '.
4243 \layout List
4255 \layout List
4244 \labelwidthstring 00.00.0000
4256 \labelwidthstring 00.00.0000
4245
4257
4246 \SpecialChar ~
4258 \SpecialChar ~
4247 This option is off by default so that new users see all attributes of any
4259 This option is off by default so that new users see all attributes of any
4248 objects they are dealing with.
4260 objects they are dealing with.
4249 \layout Standard
4261 \layout Standard
4250
4262
4251 You will find the default values along with a corresponding detailed explanation
4263 You will find the default values along with a corresponding detailed explanation
4252 in your
4264 in your
4253 \family typewriter
4265 \family typewriter
4254 ipythonrc
4266 ipythonrc
4255 \family default
4267 \family default
4256 file.
4268 file.
4257 \layout Subsection
4269 \layout Subsection
4258
4270
4259 Session logging and restoring
4271 Session logging and restoring
4260 \layout Standard
4272 \layout Standard
4261
4273
4262 You can log all input from a session either by starting IPython with the
4274 You can log all input from a session either by starting IPython with the
4263 command line switches
4275 command line switches
4264 \family typewriter
4276 \family typewriter
4265 -log
4277 -log
4266 \family default
4278 \family default
4267 or
4279 or
4268 \family typewriter
4280 \family typewriter
4269 -logfile
4281 -logfile
4270 \family default
4282 \family default
4271 (see sec.
4283 (see sec.
4272
4284
4273 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4285 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4274
4286
4275 \end_inset
4287 \end_inset
4276
4288
4277 )or by activating the logging at any moment with the magic function
4289 )or by activating the logging at any moment with the magic function
4278 \family typewriter
4290 \family typewriter
4279 %logstart
4291 %logstart
4280 \family default
4292 \family default
4281 .
4293 .
4282
4294
4283 \layout Standard
4295 \layout Standard
4284
4296
4285 Log files can later be reloaded with the
4297 Log files can later be reloaded with the
4286 \family typewriter
4298 \family typewriter
4287 -logplay
4299 -logplay
4288 \family default
4300 \family default
4289 option and IPython will attempt to 'replay' the log by executing all the
4301 option and IPython will attempt to 'replay' the log by executing all the
4290 lines in it, thus restoring the state of a previous session.
4302 lines in it, thus restoring the state of a previous session.
4291 This feature is not quite perfect, but can still be useful in many cases.
4303 This feature is not quite perfect, but can still be useful in many cases.
4292 \layout Standard
4304 \layout Standard
4293
4305
4294 The log files can also be used as a way to have a permanent record of any
4306 The log files can also be used as a way to have a permanent record of any
4295 code you wrote while experimenting.
4307 code you wrote while experimenting.
4296 Log files are regular text files which you can later open in your favorite
4308 Log files are regular text files which you can later open in your favorite
4297 text editor to extract code or to 'clean them up' before using them to
4309 text editor to extract code or to 'clean them up' before using them to
4298 replay a session.
4310 replay a session.
4299 \layout Standard
4311 \layout Standard
4300
4312
4301 The
4313 The
4302 \family typewriter
4314 \family typewriter
4303 %logstart
4315 %logstart
4304 \family default
4316 \family default
4305 function for activating logging in mid-session is used as follows:
4317 function for activating logging in mid-session is used as follows:
4306 \layout Standard
4318 \layout Standard
4307
4319
4308
4320
4309 \family typewriter
4321 \family typewriter
4310 %logstart [log_name [log_mode]]
4322 %logstart [log_name [log_mode]]
4311 \layout Standard
4323 \layout Standard
4312
4324
4313 If no name is given, it defaults to a file named
4325 If no name is given, it defaults to a file named
4314 \family typewriter
4326 \family typewriter
4315 'log'
4327 'log'
4316 \family default
4328 \family default
4317 in your IPYTHONDIR directory, in
4329 in your IPYTHONDIR directory, in
4318 \family typewriter
4330 \family typewriter
4319 'rotate'
4331 'rotate'
4320 \family default
4332 \family default
4321 mode (see below).
4333 mode (see below).
4322 \layout Standard
4334 \layout Standard
4323
4335
4324 '
4336 '
4325 \family typewriter
4337 \family typewriter
4326 %logstart name
4338 %logstart name
4327 \family default
4339 \family default
4328 ' saves to file
4340 ' saves to file
4329 \family typewriter
4341 \family typewriter
4330 'name'
4342 'name'
4331 \family default
4343 \family default
4332 in
4344 in
4333 \family typewriter
4345 \family typewriter
4334 'backup'
4346 'backup'
4335 \family default
4347 \family default
4336 mode.
4348 mode.
4337 It saves your history up to that point and then continues logging.
4349 It saves your history up to that point and then continues logging.
4338 \layout Standard
4350 \layout Standard
4339
4351
4340
4352
4341 \family typewriter
4353 \family typewriter
4342 %logstart
4354 %logstart
4343 \family default
4355 \family default
4344 takes a second optional parameter: logging mode.
4356 takes a second optional parameter: logging mode.
4345 This can be one of (note that the modes are given unquoted):
4357 This can be one of (note that the modes are given unquoted):
4346 \layout List
4358 \layout List
4347 \labelwidthstring 00.00.0000
4359 \labelwidthstring 00.00.0000
4348
4360
4349
4361
4350 \family typewriter
4362 \family typewriter
4351 over
4363 over
4352 \family default
4364 \family default
4353 : overwrite existing
4365 : overwrite existing
4354 \family typewriter
4366 \family typewriter
4355 log_name
4367 log_name
4356 \family default
4368 \family default
4357 .
4369 .
4358 \layout List
4370 \layout List
4359 \labelwidthstring 00.00.0000
4371 \labelwidthstring 00.00.0000
4360
4372
4361
4373
4362 \family typewriter
4374 \family typewriter
4363 backup
4375 backup
4364 \family default
4376 \family default
4365 : rename (if exists) to
4377 : rename (if exists) to
4366 \family typewriter
4378 \family typewriter
4367 log_name~
4379 log_name~
4368 \family default
4380 \family default
4369 and start
4381 and start
4370 \family typewriter
4382 \family typewriter
4371 log_name
4383 log_name
4372 \family default
4384 \family default
4373 .
4385 .
4374 \layout List
4386 \layout List
4375 \labelwidthstring 00.00.0000
4387 \labelwidthstring 00.00.0000
4376
4388
4377
4389
4378 \family typewriter
4390 \family typewriter
4379 append
4391 append
4380 \family default
4392 \family default
4381 : well, that says it.
4393 : well, that says it.
4382 \layout List
4394 \layout List
4383 \labelwidthstring 00.00.0000
4395 \labelwidthstring 00.00.0000
4384
4396
4385
4397
4386 \family typewriter
4398 \family typewriter
4387 rotate
4399 rotate
4388 \family default
4400 \family default
4389 : create rotating logs
4401 : create rotating logs
4390 \family typewriter
4402 \family typewriter
4391 log_name
4403 log_name
4392 \family default
4404 \family default
4393 .
4405 .
4394 \family typewriter
4406 \family typewriter
4395 1~
4407 1~
4396 \family default
4408 \family default
4397 ,
4409 ,
4398 \family typewriter
4410 \family typewriter
4399 log_name.2~
4411 log_name.2~
4400 \family default
4412 \family default
4401 , etc.
4413 , etc.
4402 \layout Standard
4414 \layout Standard
4403
4415
4404 The
4416 The
4405 \family typewriter
4417 \family typewriter
4406 %logoff
4418 %logoff
4407 \family default
4419 \family default
4408 and
4420 and
4409 \family typewriter
4421 \family typewriter
4410 %logon
4422 %logon
4411 \family default
4423 \family default
4412 functions allow you to temporarily stop and resume logging to a file which
4424 functions allow you to temporarily stop and resume logging to a file which
4413 had previously been started with
4425 had previously been started with
4414 \family typewriter
4426 \family typewriter
4415 %logstart
4427 %logstart
4416 \family default
4428 \family default
4417 .
4429 .
4418 They will fail (with an explanation) if you try to use them before logging
4430 They will fail (with an explanation) if you try to use them before logging
4419 has been started.
4431 has been started.
4420 \layout Subsection
4432 \layout Subsection
4421
4433
4422
4434
4423 \begin_inset LatexCommand \label{sub:System-shell-access}
4435 \begin_inset LatexCommand \label{sub:System-shell-access}
4424
4436
4425 \end_inset
4437 \end_inset
4426
4438
4427 System shell access
4439 System shell access
4428 \layout Standard
4440 \layout Standard
4429
4441
4430 Any input line beginning with a
4442 Any input line beginning with a
4431 \family typewriter
4443 \family typewriter
4432 !
4444 !
4433 \family default
4445 \family default
4434 character is passed verbatim (minus the
4446 character is passed verbatim (minus the
4435 \family typewriter
4447 \family typewriter
4436 !
4448 !
4437 \family default
4449 \family default
4438 , of course) to the underlying operating system.
4450 , of course) to the underlying operating system.
4439 For example, typing
4451 For example, typing
4440 \family typewriter
4452 \family typewriter
4441 !ls
4453 !ls
4442 \family default
4454 \family default
4443 will run
4455 will run
4444 \family typewriter
4456 \family typewriter
4445 'ls'
4457 'ls'
4446 \family default
4458 \family default
4447 in the current directory.
4459 in the current directory.
4448 \layout Subsubsection
4460 \layout Subsubsection
4449
4461
4450 Manual capture of command output
4462 Manual capture of command output
4451 \layout Standard
4463 \layout Standard
4452
4464
4453 If the input line begins with
4465 If the input line begins with
4454 \emph on
4466 \emph on
4455 two
4467 two
4456 \emph default
4468 \emph default
4457 exclamation marks,
4469 exclamation marks,
4458 \family typewriter
4470 \family typewriter
4459 !!
4471 !!
4460 \family default
4472 \family default
4461 , the command is executed but its output is captured and returned as a python
4473 , the command is executed but its output is captured and returned as a python
4462 list, split on newlines.
4474 list, split on newlines.
4463 Any output sent by the subprocess to standard error is printed separately,
4475 Any output sent by the subprocess to standard error is printed separately,
4464 so that the resulting list only captures standard output.
4476 so that the resulting list only captures standard output.
4465 The
4477 The
4466 \family typewriter
4478 \family typewriter
4467 !!
4479 !!
4468 \family default
4480 \family default
4469 syntax is a shorthand for the
4481 syntax is a shorthand for the
4470 \family typewriter
4482 \family typewriter
4471 %sx
4483 %sx
4472 \family default
4484 \family default
4473 magic command.
4485 magic command.
4474 \layout Standard
4486 \layout Standard
4475
4487
4476 Finally, the
4488 Finally, the
4477 \family typewriter
4489 \family typewriter
4478 %sc
4490 %sc
4479 \family default
4491 \family default
4480 magic (short for `shell capture') is similar to
4492 magic (short for `shell capture') is similar to
4481 \family typewriter
4493 \family typewriter
4482 %sx
4494 %sx
4483 \family default
4495 \family default
4484 , but allowing more fine-grained control of the capture details, and storing
4496 , but allowing more fine-grained control of the capture details, and storing
4485 the result directly into a named variable.
4497 the result directly into a named variable.
4486 \layout Standard
4498 \layout Standard
4487
4499
4488 See Sec.\SpecialChar ~
4500 See Sec.\SpecialChar ~
4489
4501
4490 \begin_inset LatexCommand \ref{sec:magic}
4502 \begin_inset LatexCommand \ref{sec:magic}
4491
4503
4492 \end_inset
4504 \end_inset
4493
4505
4494 for details on the magics
4506 for details on the magics
4495 \family typewriter
4507 \family typewriter
4496 %sc
4508 %sc
4497 \family default
4509 \family default
4498 and
4510 and
4499 \family typewriter
4511 \family typewriter
4500 %sx
4512 %sx
4501 \family default
4513 \family default
4502 , or use IPython's own help (
4514 , or use IPython's own help (
4503 \family typewriter
4515 \family typewriter
4504 sc?
4516 sc?
4505 \family default
4517 \family default
4506 and
4518 and
4507 \family typewriter
4519 \family typewriter
4508 sx?
4520 sx?
4509 \family default
4521 \family default
4510 ) for further details.
4522 ) for further details.
4511 \layout Standard
4523 \layout Standard
4512
4524
4513 IPython also allows you to expand the value of python variables when making
4525 IPython also allows you to expand the value of python variables when making
4514 system calls.
4526 system calls.
4515 Any python variable or expression which you prepend with
4527 Any python variable or expression which you prepend with
4516 \family typewriter
4528 \family typewriter
4517 $
4529 $
4518 \family default
4530 \family default
4519 will get expanded before the system call is made.
4531 will get expanded before the system call is made.
4520
4532
4521 \layout Standard
4533 \layout Standard
4522
4534
4523
4535
4524 \family typewriter
4536 \family typewriter
4525 In [1]: pyvar='Hello world'
4537 In [1]: pyvar='Hello world'
4526 \newline
4538 \newline
4527 In [2]: !echo "A python variable: $pyvar"
4539 In [2]: !echo "A python variable: $pyvar"
4528 \newline
4540 \newline
4529 A python variable: Hello world
4541 A python variable: Hello world
4530 \layout Standard
4542 \layout Standard
4531
4543
4532 If you want the shell to actually see a literal
4544 If you want the shell to actually see a literal
4533 \family typewriter
4545 \family typewriter
4534 $
4546 $
4535 \family default
4547 \family default
4536 , you need to type it twice:
4548 , you need to type it twice:
4537 \layout Standard
4549 \layout Standard
4538
4550
4539
4551
4540 \family typewriter
4552 \family typewriter
4541 In [3]: !echo "A system variable: $$HOME"
4553 In [3]: !echo "A system variable: $$HOME"
4542 \newline
4554 \newline
4543 A system variable: /home/fperez
4555 A system variable: /home/fperez
4544 \layout Standard
4556 \layout Standard
4545
4557
4546 You can pass arbitrary expressions, though you'll need to delimit them with
4558 You can pass arbitrary expressions, though you'll need to delimit them with
4547
4559
4548 \family typewriter
4560 \family typewriter
4549 {}
4561 {}
4550 \family default
4562 \family default
4551 if there is ambiguity as to the extent of the expression:
4563 if there is ambiguity as to the extent of the expression:
4552 \layout Standard
4564 \layout Standard
4553
4565
4554
4566
4555 \family typewriter
4567 \family typewriter
4556 In [5]: x=10
4568 In [5]: x=10
4557 \newline
4569 \newline
4558 In [6]: y=20
4570 In [6]: y=20
4559 \newline
4571 \newline
4560 In [13]: !echo $x+y
4572 In [13]: !echo $x+y
4561 \newline
4573 \newline
4562 10+y
4574 10+y
4563 \newline
4575 \newline
4564 In [7]: !echo ${x+y}
4576 In [7]: !echo ${x+y}
4565 \newline
4577 \newline
4566 30
4578 30
4567 \layout Standard
4579 \layout Standard
4568
4580
4569 Even object attributes can be expanded:
4581 Even object attributes can be expanded:
4570 \layout Standard
4582 \layout Standard
4571
4583
4572
4584
4573 \family typewriter
4585 \family typewriter
4574 In [12]: !echo $sys.argv
4586 In [12]: !echo $sys.argv
4575 \newline
4587 \newline
4576 [/home/fperez/usr/bin/ipython]
4588 [/home/fperez/usr/bin/ipython]
4577 \layout Subsection
4589 \layout Subsection
4578
4590
4579 System command aliases
4591 System command aliases
4580 \layout Standard
4592 \layout Standard
4581
4593
4582 The
4594 The
4583 \family typewriter
4595 \family typewriter
4584 %alias
4596 %alias
4585 \family default
4597 \family default
4586 magic function and the
4598 magic function and the
4587 \family typewriter
4599 \family typewriter
4588 alias
4600 alias
4589 \family default
4601 \family default
4590 option in the
4602 option in the
4591 \family typewriter
4603 \family typewriter
4592 ipythonrc
4604 ipythonrc
4593 \family default
4605 \family default
4594 configuration file allow you to define magic functions which are in fact
4606 configuration file allow you to define magic functions which are in fact
4595 system shell commands.
4607 system shell commands.
4596 These aliases can have parameters.
4608 These aliases can have parameters.
4597
4609
4598 \layout Standard
4610 \layout Standard
4599
4611
4600 '
4612 '
4601 \family typewriter
4613 \family typewriter
4602 %alias alias_name cmd
4614 %alias alias_name cmd
4603 \family default
4615 \family default
4604 ' defines '
4616 ' defines '
4605 \family typewriter
4617 \family typewriter
4606 alias_name
4618 alias_name
4607 \family default
4619 \family default
4608 ' as an alias for '
4620 ' as an alias for '
4609 \family typewriter
4621 \family typewriter
4610 cmd
4622 cmd
4611 \family default
4623 \family default
4612 '
4624 '
4613 \layout Standard
4625 \layout Standard
4614
4626
4615 Then, typing '
4627 Then, typing '
4616 \family typewriter
4628 \family typewriter
4617 %alias_name params
4629 %alias_name params
4618 \family default
4630 \family default
4619 ' will execute the system command '
4631 ' will execute the system command '
4620 \family typewriter
4632 \family typewriter
4621 cmd params
4633 cmd params
4622 \family default
4634 \family default
4623 ' (from your underlying operating system).
4635 ' (from your underlying operating system).
4624
4636
4625 \layout Standard
4637 \layout Standard
4626
4638
4627 You can also define aliases with parameters using
4639 You can also define aliases with parameters using
4628 \family typewriter
4640 \family typewriter
4629 %s
4641 %s
4630 \family default
4642 \family default
4631 specifiers (one per parameter).
4643 specifiers (one per parameter).
4632 The following example defines the
4644 The following example defines the
4633 \family typewriter
4645 \family typewriter
4634 %parts
4646 %parts
4635 \family default
4647 \family default
4636 function as an alias to the command '
4648 function as an alias to the command '
4637 \family typewriter
4649 \family typewriter
4638 echo first %s second %s
4650 echo first %s second %s
4639 \family default
4651 \family default
4640 ' where each
4652 ' where each
4641 \family typewriter
4653 \family typewriter
4642 %s
4654 %s
4643 \family default
4655 \family default
4644 will be replaced by a positional parameter to the call to
4656 will be replaced by a positional parameter to the call to
4645 \family typewriter
4657 \family typewriter
4646 %parts:
4658 %parts:
4647 \layout Standard
4659 \layout Standard
4648
4660
4649
4661
4650 \family typewriter
4662 \family typewriter
4651 In [1]: alias parts echo first %s second %s
4663 In [1]: alias parts echo first %s second %s
4652 \newline
4664 \newline
4653 In [2]: %parts A B
4665 In [2]: %parts A B
4654 \newline
4666 \newline
4655 first A second B
4667 first A second B
4656 \newline
4668 \newline
4657 In [3]: %parts A
4669 In [3]: %parts A
4658 \newline
4670 \newline
4659 Incorrect number of arguments: 2 expected.
4671 Incorrect number of arguments: 2 expected.
4660
4672
4661 \newline
4673 \newline
4662 parts is an alias to: 'echo first %s second %s'
4674 parts is an alias to: 'echo first %s second %s'
4663 \layout Standard
4675 \layout Standard
4664
4676
4665 If called with no parameters,
4677 If called with no parameters,
4666 \family typewriter
4678 \family typewriter
4667 %alias
4679 %alias
4668 \family default
4680 \family default
4669 prints the table of currently defined aliases.
4681 prints the table of currently defined aliases.
4670 \layout Standard
4682 \layout Standard
4671
4683
4672 The
4684 The
4673 \family typewriter
4685 \family typewriter
4674 %rehash/rehashx
4686 %rehash/rehashx
4675 \family default
4687 \family default
4676 magics allow you to load your entire
4688 magics allow you to load your entire
4677 \family typewriter
4689 \family typewriter
4678 $PATH
4690 $PATH
4679 \family default
4691 \family default
4680 as ipython aliases.
4692 as ipython aliases.
4681 See their respective docstrings (or sec.\SpecialChar ~
4693 See their respective docstrings (or sec.\SpecialChar ~
4682
4694
4683 \begin_inset LatexCommand \ref{sec:magic}
4695 \begin_inset LatexCommand \ref{sec:magic}
4684
4696
4685 \end_inset
4697 \end_inset
4686
4698
4687 for further details).
4699 for further details).
4688 \layout Subsection
4700 \layout Subsection
4689
4701
4690
4702
4691 \begin_inset LatexCommand \label{sec:dreload}
4703 \begin_inset LatexCommand \label{sec:dreload}
4692
4704
4693 \end_inset
4705 \end_inset
4694
4706
4695 Recursive reload
4707 Recursive reload
4696 \layout Standard
4708 \layout Standard
4697
4709
4698 The
4710 The
4699 \family typewriter
4711 \family typewriter
4700 %dreload
4712 %dreload
4701 \family default
4713 \family default
4702 command does a recursive reload of a module: changes made to the module
4714 command does a recursive reload of a module: changes made to the module
4703 since you imported will actually be available without having to exit.
4715 since you imported will actually be available without having to exit.
4704 \layout Subsection
4716 \layout Subsection
4705
4717
4706 Verbose and colored exception traceback printouts
4718 Verbose and colored exception traceback printouts
4707 \layout Standard
4719 \layout Standard
4708
4720
4709 IPython provides the option to see very detailed exception tracebacks, which
4721 IPython provides the option to see very detailed exception tracebacks, which
4710 can be especially useful when debugging large programs.
4722 can be especially useful when debugging large programs.
4711 You can run any Python file with the
4723 You can run any Python file with the
4712 \family typewriter
4724 \family typewriter
4713 %run
4725 %run
4714 \family default
4726 \family default
4715 function to benefit from these detailed tracebacks.
4727 function to benefit from these detailed tracebacks.
4716 Furthermore, both normal and verbose tracebacks can be colored (if your
4728 Furthermore, both normal and verbose tracebacks can be colored (if your
4717 terminal supports it) which makes them much easier to parse visually.
4729 terminal supports it) which makes them much easier to parse visually.
4718 \layout Standard
4730 \layout Standard
4719
4731
4720 See the magic
4732 See the magic
4721 \family typewriter
4733 \family typewriter
4722 xmode
4734 xmode
4723 \family default
4735 \family default
4724 and
4736 and
4725 \family typewriter
4737 \family typewriter
4726 colors
4738 colors
4727 \family default
4739 \family default
4728 functions for details (just type
4740 functions for details (just type
4729 \family typewriter
4741 \family typewriter
4730 %magic
4742 %magic
4731 \family default
4743 \family default
4732 ).
4744 ).
4733 \layout Standard
4745 \layout Standard
4734
4746
4735 These features are basically a terminal version of Ka-Ping Yee's
4747 These features are basically a terminal version of Ka-Ping Yee's
4736 \family typewriter
4748 \family typewriter
4737 cgitb
4749 cgitb
4738 \family default
4750 \family default
4739 module, now part of the standard Python library.
4751 module, now part of the standard Python library.
4740 \layout Subsection
4752 \layout Subsection
4741
4753
4742
4754
4743 \begin_inset LatexCommand \label{sec:cache_input}
4755 \begin_inset LatexCommand \label{sec:cache_input}
4744
4756
4745 \end_inset
4757 \end_inset
4746
4758
4747 Input caching system
4759 Input caching system
4748 \layout Standard
4760 \layout Standard
4749
4761
4750 IPython offers numbered prompts (In/Out) with input and output caching.
4762 IPython offers numbered prompts (In/Out) with input and output caching.
4751 All input is saved and can be retrieved as variables (besides the usual
4763 All input is saved and can be retrieved as variables (besides the usual
4752 arrow key recall).
4764 arrow key recall).
4753 \layout Standard
4765 \layout Standard
4754
4766
4755 The following GLOBAL variables always exist (so don't overwrite them!):
4767 The following GLOBAL variables always exist (so don't overwrite them!):
4756
4768
4757 \family typewriter
4769 \family typewriter
4758 _i
4770 _i
4759 \family default
4771 \family default
4760 : stores previous input.
4772 : stores previous input.
4761
4773
4762 \family typewriter
4774 \family typewriter
4763 _ii
4775 _ii
4764 \family default
4776 \family default
4765 : next previous.
4777 : next previous.
4766
4778
4767 \family typewriter
4779 \family typewriter
4768 _iii
4780 _iii
4769 \family default
4781 \family default
4770 : next-next previous.
4782 : next-next previous.
4771
4783
4772 \family typewriter
4784 \family typewriter
4773 _ih
4785 _ih
4774 \family default
4786 \family default
4775 : a list of all input
4787 : a list of all input
4776 \family typewriter
4788 \family typewriter
4777 _ih[n]
4789 _ih[n]
4778 \family default
4790 \family default
4779 is the input from line
4791 is the input from line
4780 \family typewriter
4792 \family typewriter
4781 n
4793 n
4782 \family default
4794 \family default
4783 and this list is aliased to the global variable
4795 and this list is aliased to the global variable
4784 \family typewriter
4796 \family typewriter
4785 In
4797 In
4786 \family default
4798 \family default
4787 .
4799 .
4788 If you overwrite
4800 If you overwrite
4789 \family typewriter
4801 \family typewriter
4790 In
4802 In
4791 \family default
4803 \family default
4792 with a variable of your own, you can remake the assignment to the internal
4804 with a variable of your own, you can remake the assignment to the internal
4793 list with a simple
4805 list with a simple
4794 \family typewriter
4806 \family typewriter
4795 'In=_ih'
4807 'In=_ih'
4796 \family default
4808 \family default
4797 .
4809 .
4798 \layout Standard
4810 \layout Standard
4799
4811
4800 Additionally, global variables named
4812 Additionally, global variables named
4801 \family typewriter
4813 \family typewriter
4802 _i<n>
4814 _i<n>
4803 \family default
4815 \family default
4804 are dynamically created (
4816 are dynamically created (
4805 \family typewriter
4817 \family typewriter
4806 <n>
4818 <n>
4807 \family default
4819 \family default
4808 being the prompt counter), such that
4820 being the prompt counter), such that
4809 \newline
4821 \newline
4810
4822
4811 \family typewriter
4823 \family typewriter
4812 _i<n> == _ih[<n>] == In[<n>].
4824 _i<n> == _ih[<n>] == In[<n>].
4813 \layout Standard
4825 \layout Standard
4814
4826
4815 For example, what you typed at prompt 14 is available as
4827 For example, what you typed at prompt 14 is available as
4816 \family typewriter
4828 \family typewriter
4817 _i14,
4829 _i14,
4818 \family default
4830 \family default
4819
4831
4820 \family typewriter
4832 \family typewriter
4821 _ih[14]
4833 _ih[14]
4822 \family default
4834 \family default
4823 and
4835 and
4824 \family typewriter
4836 \family typewriter
4825 In[14]
4837 In[14]
4826 \family default
4838 \family default
4827 .
4839 .
4828 \layout Standard
4840 \layout Standard
4829
4841
4830 This allows you to easily cut and paste multi line interactive prompts by
4842 This allows you to easily cut and paste multi line interactive prompts by
4831 printing them out: they print like a clean string, without prompt characters.
4843 printing them out: they print like a clean string, without prompt characters.
4832 You can also manipulate them like regular variables (they are strings),
4844 You can also manipulate them like regular variables (they are strings),
4833 modify or exec them (typing
4845 modify or exec them (typing
4834 \family typewriter
4846 \family typewriter
4835 'exec _i9'
4847 'exec _i9'
4836 \family default
4848 \family default
4837 will re-execute the contents of input prompt 9, '
4849 will re-execute the contents of input prompt 9, '
4838 \family typewriter
4850 \family typewriter
4839 exec In[9:14]+In[18]
4851 exec In[9:14]+In[18]
4840 \family default
4852 \family default
4841 ' will re-execute lines 9 through 13 and line 18).
4853 ' will re-execute lines 9 through 13 and line 18).
4842 \layout Standard
4854 \layout Standard
4843
4855
4844 You can also re-execute multiple lines of input easily by using the magic
4856 You can also re-execute multiple lines of input easily by using the magic
4845
4857
4846 \family typewriter
4858 \family typewriter
4847 %macro
4859 %macro
4848 \family default
4860 \family default
4849 function (which automates the process and allows re-execution without having
4861 function (which automates the process and allows re-execution without having
4850 to type '
4862 to type '
4851 \family typewriter
4863 \family typewriter
4852 exec
4864 exec
4853 \family default
4865 \family default
4854 ' every time).
4866 ' every time).
4855 The macro system also allows you to re-execute previous lines which include
4867 The macro system also allows you to re-execute previous lines which include
4856 magic function calls (which require special processing).
4868 magic function calls (which require special processing).
4857 Type
4869 Type
4858 \family typewriter
4870 \family typewriter
4859 %macro?
4871 %macro?
4860 \family default
4872 \family default
4861 or see sec.
4873 or see sec.
4862
4874
4863 \begin_inset LatexCommand \ref{sec:magic}
4875 \begin_inset LatexCommand \ref{sec:magic}
4864
4876
4865 \end_inset
4877 \end_inset
4866
4878
4867 for more details on the macro system.
4879 for more details on the macro system.
4868 \layout Standard
4880 \layout Standard
4869
4881
4870 A history function
4882 A history function
4871 \family typewriter
4883 \family typewriter
4872 %hist
4884 %hist
4873 \family default
4885 \family default
4874 allows you to see any part of your input history by printing a range of
4886 allows you to see any part of your input history by printing a range of
4875 the
4887 the
4876 \family typewriter
4888 \family typewriter
4877 _i
4889 _i
4878 \family default
4890 \family default
4879 variables.
4891 variables.
4880 \layout Subsection
4892 \layout Subsection
4881
4893
4882
4894
4883 \begin_inset LatexCommand \label{sec:cache_output}
4895 \begin_inset LatexCommand \label{sec:cache_output}
4884
4896
4885 \end_inset
4897 \end_inset
4886
4898
4887 Output caching system
4899 Output caching system
4888 \layout Standard
4900 \layout Standard
4889
4901
4890 For output that is returned from actions, a system similar to the input
4902 For output that is returned from actions, a system similar to the input
4891 cache exists but using
4903 cache exists but using
4892 \family typewriter
4904 \family typewriter
4893 _
4905 _
4894 \family default
4906 \family default
4895 instead of
4907 instead of
4896 \family typewriter
4908 \family typewriter
4897 _i
4909 _i
4898 \family default
4910 \family default
4899 .
4911 .
4900 Only actions that produce a result (NOT assignments, for example) are cached.
4912 Only actions that produce a result (NOT assignments, for example) are cached.
4901 If you are familiar with Mathematica, IPython's
4913 If you are familiar with Mathematica, IPython's
4902 \family typewriter
4914 \family typewriter
4903 _
4915 _
4904 \family default
4916 \family default
4905 variables behave exactly like Mathematica's
4917 variables behave exactly like Mathematica's
4906 \family typewriter
4918 \family typewriter
4907 %
4919 %
4908 \family default
4920 \family default
4909 variables.
4921 variables.
4910 \layout Standard
4922 \layout Standard
4911
4923
4912 The following GLOBAL variables always exist (so don't overwrite them!):
4924 The following GLOBAL variables always exist (so don't overwrite them!):
4913
4925
4914 \layout List
4926 \layout List
4915 \labelwidthstring 00.00.0000
4927 \labelwidthstring 00.00.0000
4916
4928
4917
4929
4918 \family typewriter
4930 \family typewriter
4919 \series bold
4931 \series bold
4920 _
4932 _
4921 \family default
4933 \family default
4922 \series default
4934 \series default
4923 (a
4935 (a
4924 \emph on
4936 \emph on
4925 single
4937 single
4926 \emph default
4938 \emph default
4927 underscore) : stores previous output, like Python's default interpreter.
4939 underscore) : stores previous output, like Python's default interpreter.
4928 \layout List
4940 \layout List
4929 \labelwidthstring 00.00.0000
4941 \labelwidthstring 00.00.0000
4930
4942
4931
4943
4932 \family typewriter
4944 \family typewriter
4933 \series bold
4945 \series bold
4934 __
4946 __
4935 \family default
4947 \family default
4936 \series default
4948 \series default
4937 (two underscores): next previous.
4949 (two underscores): next previous.
4938 \layout List
4950 \layout List
4939 \labelwidthstring 00.00.0000
4951 \labelwidthstring 00.00.0000
4940
4952
4941
4953
4942 \family typewriter
4954 \family typewriter
4943 \series bold
4955 \series bold
4944 ___
4956 ___
4945 \family default
4957 \family default
4946 \series default
4958 \series default
4947 (three underscores): next-next previous.
4959 (three underscores): next-next previous.
4948 \layout Standard
4960 \layout Standard
4949
4961
4950 Additionally, global variables named
4962 Additionally, global variables named
4951 \family typewriter
4963 \family typewriter
4952 _<n>
4964 _<n>
4953 \family default
4965 \family default
4954 are dynamically created (
4966 are dynamically created (
4955 \family typewriter
4967 \family typewriter
4956 <n>
4968 <n>
4957 \family default
4969 \family default
4958 being the prompt counter), such that the result of output
4970 being the prompt counter), such that the result of output
4959 \family typewriter
4971 \family typewriter
4960 <n>
4972 <n>
4961 \family default
4973 \family default
4962 is always available as
4974 is always available as
4963 \family typewriter
4975 \family typewriter
4964 _<n>
4976 _<n>
4965 \family default
4977 \family default
4966 (don't use the angle brackets, just the number, e.g.
4978 (don't use the angle brackets, just the number, e.g.
4967
4979
4968 \family typewriter
4980 \family typewriter
4969 _21
4981 _21
4970 \family default
4982 \family default
4971 ).
4983 ).
4972 \layout Standard
4984 \layout Standard
4973
4985
4974 These global variables are all stored in a global dictionary (not a list,
4986 These global variables are all stored in a global dictionary (not a list,
4975 since it only has entries for lines which returned a result) available
4987 since it only has entries for lines which returned a result) available
4976 under the names
4988 under the names
4977 \family typewriter
4989 \family typewriter
4978 _oh
4990 _oh
4979 \family default
4991 \family default
4980 and
4992 and
4981 \family typewriter
4993 \family typewriter
4982 Out
4994 Out
4983 \family default
4995 \family default
4984 (similar to
4996 (similar to
4985 \family typewriter
4997 \family typewriter
4986 _ih
4998 _ih
4987 \family default
4999 \family default
4988 and
5000 and
4989 \family typewriter
5001 \family typewriter
4990 In
5002 In
4991 \family default
5003 \family default
4992 ).
5004 ).
4993 So the output from line 12 can be obtained as
5005 So the output from line 12 can be obtained as
4994 \family typewriter
5006 \family typewriter
4995 _12
5007 _12
4996 \family default
5008 \family default
4997 ,
5009 ,
4998 \family typewriter
5010 \family typewriter
4999 Out[12]
5011 Out[12]
5000 \family default
5012 \family default
5001 or
5013 or
5002 \family typewriter
5014 \family typewriter
5003 _oh[12]
5015 _oh[12]
5004 \family default
5016 \family default
5005 .
5017 .
5006 If you accidentally overwrite the
5018 If you accidentally overwrite the
5007 \family typewriter
5019 \family typewriter
5008 Out
5020 Out
5009 \family default
5021 \family default
5010 variable you can recover it by typing
5022 variable you can recover it by typing
5011 \family typewriter
5023 \family typewriter
5012 'Out=_oh
5024 'Out=_oh
5013 \family default
5025 \family default
5014 ' at the prompt.
5026 ' at the prompt.
5015 \layout Standard
5027 \layout Standard
5016
5028
5017 This system obviously can potentially put heavy memory demands on your system,
5029 This system obviously can potentially put heavy memory demands on your system,
5018 since it prevents Python's garbage collector from removing any previously
5030 since it prevents Python's garbage collector from removing any previously
5019 computed results.
5031 computed results.
5020 You can control how many results are kept in memory with the option (at
5032 You can control how many results are kept in memory with the option (at
5021 the command line or in your
5033 the command line or in your
5022 \family typewriter
5034 \family typewriter
5023 ipythonrc
5035 ipythonrc
5024 \family default
5036 \family default
5025 file)
5037 file)
5026 \family typewriter
5038 \family typewriter
5027 cache_size
5039 cache_size
5028 \family default
5040 \family default
5029 .
5041 .
5030 If you set it to 0, the whole system is completely disabled and the prompts
5042 If you set it to 0, the whole system is completely disabled and the prompts
5031 revert to the classic
5043 revert to the classic
5032 \family typewriter
5044 \family typewriter
5033 '>>>'
5045 '>>>'
5034 \family default
5046 \family default
5035 of normal Python.
5047 of normal Python.
5036 \layout Subsection
5048 \layout Subsection
5037
5049
5038 Directory history
5050 Directory history
5039 \layout Standard
5051 \layout Standard
5040
5052
5041 Your history of visited directories is kept in the global list
5053 Your history of visited directories is kept in the global list
5042 \family typewriter
5054 \family typewriter
5043 _dh
5055 _dh
5044 \family default
5056 \family default
5045 , and the magic
5057 , and the magic
5046 \family typewriter
5058 \family typewriter
5047 %cd
5059 %cd
5048 \family default
5060 \family default
5049 command can be used to go to any entry in that list.
5061 command can be used to go to any entry in that list.
5050 The
5062 The
5051 \family typewriter
5063 \family typewriter
5052 %dhist
5064 %dhist
5053 \family default
5065 \family default
5054 command allows you to view this history.
5066 command allows you to view this history.
5055 \layout Subsection
5067 \layout Subsection
5056
5068
5057 Automatic parentheses and quotes
5069 Automatic parentheses and quotes
5058 \layout Standard
5070 \layout Standard
5059
5071
5060 These features were adapted from Nathan Gray's LazyPython.
5072 These features were adapted from Nathan Gray's LazyPython.
5061 They are meant to allow less typing for common situations.
5073 They are meant to allow less typing for common situations.
5062 \layout Subsubsection
5074 \layout Subsubsection
5063
5075
5064 Automatic parentheses
5076 Automatic parentheses
5065 \layout Standard
5077 \layout Standard
5066
5078
5067 Callable objects (i.e.
5079 Callable objects (i.e.
5068 functions, methods, etc) can be invoked like this (notice the commas between
5080 functions, methods, etc) can be invoked like this (notice the commas between
5069 the arguments):
5081 the arguments):
5070 \layout Standard
5082 \layout Standard
5071
5083
5072
5084
5073 \family typewriter
5085 \family typewriter
5074 >>> callable_ob arg1, arg2, arg3
5086 >>> callable_ob arg1, arg2, arg3
5075 \layout Standard
5087 \layout Standard
5076
5088
5077 and the input will be translated to this:
5089 and the input will be translated to this:
5078 \layout Standard
5090 \layout Standard
5079
5091
5080
5092
5081 \family typewriter
5093 \family typewriter
5082 --> callable_ob(arg1, arg2, arg3)
5094 --> callable_ob(arg1, arg2, arg3)
5083 \layout Standard
5095 \layout Standard
5084
5096
5085 You can force automatic parentheses by using '/' as the first character
5097 You can force automatic parentheses by using '/' as the first character
5086 of a line.
5098 of a line.
5087 For example:
5099 For example:
5088 \layout Standard
5100 \layout Standard
5089
5101
5090
5102
5091 \family typewriter
5103 \family typewriter
5092 >>> /globals # becomes 'globals()'
5104 >>> /globals # becomes 'globals()'
5093 \layout Standard
5105 \layout Standard
5094
5106
5095 Note that the '/' MUST be the first character on the line! This won't work:
5107 Note that the '/' MUST be the first character on the line! This won't work:
5096
5108
5097 \layout Standard
5109 \layout Standard
5098
5110
5099
5111
5100 \family typewriter
5112 \family typewriter
5101 >>> print /globals # syntax error
5113 >>> print /globals # syntax error
5102 \layout Standard
5114 \layout Standard
5103
5115
5104 In most cases the automatic algorithm should work, so you should rarely
5116 In most cases the automatic algorithm should work, so you should rarely
5105 need to explicitly invoke /.
5117 need to explicitly invoke /.
5106 One notable exception is if you are trying to call a function with a list
5118 One notable exception is if you are trying to call a function with a list
5107 of tuples as arguments (the parenthesis will confuse IPython):
5119 of tuples as arguments (the parenthesis will confuse IPython):
5108 \layout Standard
5120 \layout Standard
5109
5121
5110
5122
5111 \family typewriter
5123 \family typewriter
5112 In [1]: zip (1,2,3),(4,5,6) # won't work
5124 In [1]: zip (1,2,3),(4,5,6) # won't work
5113 \layout Standard
5125 \layout Standard
5114
5126
5115 but this will work:
5127 but this will work:
5116 \layout Standard
5128 \layout Standard
5117
5129
5118
5130
5119 \family typewriter
5131 \family typewriter
5120 In [2]: /zip (1,2,3),(4,5,6)
5132 In [2]: /zip (1,2,3),(4,5,6)
5121 \newline
5133 \newline
5122 ------> zip ((1,2,3),(4,5,6))
5134 ------> zip ((1,2,3),(4,5,6))
5123 \newline
5135 \newline
5124 Out[2]= [(1, 4), (2, 5), (3, 6)]
5136 Out[2]= [(1, 4), (2, 5), (3, 6)]
5125 \layout Standard
5137 \layout Standard
5126
5138
5127 IPython tells you that it has altered your command line by displaying the
5139 IPython tells you that it has altered your command line by displaying the
5128 new command line preceded by
5140 new command line preceded by
5129 \family typewriter
5141 \family typewriter
5130 -->
5142 -->
5131 \family default
5143 \family default
5132 .
5144 .
5133 e.g.:
5145 e.g.:
5134 \layout Standard
5146 \layout Standard
5135
5147
5136
5148
5137 \family typewriter
5149 \family typewriter
5138 In [18]: callable list
5150 In [18]: callable list
5139 \newline
5151 \newline
5140 -------> callable (list)
5152 -------> callable (list)
5141 \layout Subsubsection
5153 \layout Subsubsection
5142
5154
5143 Automatic quoting
5155 Automatic quoting
5144 \layout Standard
5156 \layout Standard
5145
5157
5146 You can force automatic quoting of a function's arguments by using
5158 You can force automatic quoting of a function's arguments by using
5147 \family typewriter
5159 \family typewriter
5148 `,'
5160 `,'
5149 \family default
5161 \family default
5150 or
5162 or
5151 \family typewriter
5163 \family typewriter
5152 `;'
5164 `;'
5153 \family default
5165 \family default
5154 as the first character of a line.
5166 as the first character of a line.
5155 For example:
5167 For example:
5156 \layout Standard
5168 \layout Standard
5157
5169
5158
5170
5159 \family typewriter
5171 \family typewriter
5160 >>> ,my_function /home/me # becomes my_function("/home/me")
5172 >>> ,my_function /home/me # becomes my_function("/home/me")
5161 \layout Standard
5173 \layout Standard
5162
5174
5163 If you use
5175 If you use
5164 \family typewriter
5176 \family typewriter
5165 `;'
5177 `;'
5166 \family default
5178 \family default
5167 instead, the whole argument is quoted as a single string (while
5179 instead, the whole argument is quoted as a single string (while
5168 \family typewriter
5180 \family typewriter
5169 `,'
5181 `,'
5170 \family default
5182 \family default
5171 splits on whitespace):
5183 splits on whitespace):
5172 \layout Standard
5184 \layout Standard
5173
5185
5174
5186
5175 \family typewriter
5187 \family typewriter
5176 >>> ,my_function a b c # becomes my_function("a","b","c")
5188 >>> ,my_function a b c # becomes my_function("a","b","c")
5177 \layout Standard
5189 \layout Standard
5178
5190
5179
5191
5180 \family typewriter
5192 \family typewriter
5181 >>> ;my_function a b c # becomes my_function("a b c")
5193 >>> ;my_function a b c # becomes my_function("a b c")
5182 \layout Standard
5194 \layout Standard
5183
5195
5184 Note that the `
5196 Note that the `
5185 \family typewriter
5197 \family typewriter
5186 ,
5198 ,
5187 \family default
5199 \family default
5188 ' or `
5200 ' or `
5189 \family typewriter
5201 \family typewriter
5190 ;
5202 ;
5191 \family default
5203 \family default
5192 ' MUST be the first character on the line! This won't work:
5204 ' MUST be the first character on the line! This won't work:
5193 \layout Standard
5205 \layout Standard
5194
5206
5195
5207
5196 \family typewriter
5208 \family typewriter
5197 >>> x = ,my_function /home/me # syntax error
5209 >>> x = ,my_function /home/me # syntax error
5198 \layout Section
5210 \layout Section
5199
5211
5200
5212
5201 \begin_inset LatexCommand \label{sec:customization}
5213 \begin_inset LatexCommand \label{sec:customization}
5202
5214
5203 \end_inset
5215 \end_inset
5204
5216
5205 Customization
5217 Customization
5206 \layout Standard
5218 \layout Standard
5207
5219
5208 As we've already mentioned, IPython reads a configuration file which can
5220 As we've already mentioned, IPython reads a configuration file which can
5209 be specified at the command line (
5221 be specified at the command line (
5210 \family typewriter
5222 \family typewriter
5211 -rcfile
5223 -rcfile
5212 \family default
5224 \family default
5213 ) or which by default is assumed to be called
5225 ) or which by default is assumed to be called
5214 \family typewriter
5226 \family typewriter
5215 ipythonrc
5227 ipythonrc
5216 \family default
5228 \family default
5217 .
5229 .
5218 Such a file is looked for in the current directory where IPython is started
5230 Such a file is looked for in the current directory where IPython is started
5219 and then in your
5231 and then in your
5220 \family typewriter
5232 \family typewriter
5221 IPYTHONDIR
5233 IPYTHONDIR
5222 \family default
5234 \family default
5223 , which allows you to have local configuration files for specific projects.
5235 , which allows you to have local configuration files for specific projects.
5224 In this section we will call these types of configuration files simply
5236 In this section we will call these types of configuration files simply
5225 rcfiles (short for resource configuration file).
5237 rcfiles (short for resource configuration file).
5226 \layout Standard
5238 \layout Standard
5227
5239
5228 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5240 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5229 one per line.
5241 one per line.
5230 Lines beginning with a
5242 Lines beginning with a
5231 \family typewriter
5243 \family typewriter
5232 #
5244 #
5233 \family default
5245 \family default
5234 are ignored as comments, but comments can
5246 are ignored as comments, but comments can
5235 \series bold
5247 \series bold
5236 not
5248 not
5237 \series default
5249 \series default
5238 be put on lines with data (the parser is fairly primitive).
5250 be put on lines with data (the parser is fairly primitive).
5239 Note that these are not python files, and this is deliberate, because it
5251 Note that these are not python files, and this is deliberate, because it
5240 allows us to do some things which would be quite tricky to implement if
5252 allows us to do some things which would be quite tricky to implement if
5241 they were normal python files.
5253 they were normal python files.
5242 \layout Standard
5254 \layout Standard
5243
5255
5244 First, an rcfile can contain permanent default values for almost all command
5256 First, an rcfile can contain permanent default values for almost all command
5245 line options (except things like
5257 line options (except things like
5246 \family typewriter
5258 \family typewriter
5247 -help
5259 -help
5248 \family default
5260 \family default
5249 or
5261 or
5250 \family typewriter
5262 \family typewriter
5251 -Version
5263 -Version
5252 \family default
5264 \family default
5253 ).
5265 ).
5254 Sec\SpecialChar ~
5266 Sec\SpecialChar ~
5255
5267
5256 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5268 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5257
5269
5258 \end_inset
5270 \end_inset
5259
5271
5260 contains a description of all command-line options.
5272 contains a description of all command-line options.
5261 However, values you explicitly specify at the command line override the
5273 However, values you explicitly specify at the command line override the
5262 values defined in the rcfile.
5274 values defined in the rcfile.
5263 \layout Standard
5275 \layout Standard
5264
5276
5265 Besides command line option values, the rcfile can specify values for certain
5277 Besides command line option values, the rcfile can specify values for certain
5266 extra special options which are not available at the command line.
5278 extra special options which are not available at the command line.
5267 These options are briefly described below.
5279 These options are briefly described below.
5268
5280
5269 \layout Standard
5281 \layout Standard
5270
5282
5271 Each of these options may appear as many times as you need it in the file.
5283 Each of these options may appear as many times as you need it in the file.
5272 \layout List
5284 \layout List
5273 \labelwidthstring 00.00.0000
5285 \labelwidthstring 00.00.0000
5274
5286
5275
5287
5276 \family typewriter
5288 \family typewriter
5277 \series bold
5289 \series bold
5278 include\SpecialChar ~
5290 include\SpecialChar ~
5279 <file1>\SpecialChar ~
5291 <file1>\SpecialChar ~
5280 <file2>\SpecialChar ~
5292 <file2>\SpecialChar ~
5281 ...
5293 ...
5282 \family default
5294 \family default
5283 \series default
5295 \series default
5284 : you can name
5296 : you can name
5285 \emph on
5297 \emph on
5286 other
5298 other
5287 \emph default
5299 \emph default
5288 rcfiles you want to recursively load up to 15 levels (don't use the
5300 rcfiles you want to recursively load up to 15 levels (don't use the
5289 \family typewriter
5301 \family typewriter
5290 <>
5302 <>
5291 \family default
5303 \family default
5292 brackets in your names!).
5304 brackets in your names!).
5293 This feature allows you to define a 'base' rcfile with general options
5305 This feature allows you to define a 'base' rcfile with general options
5294 and special-purpose files which can be loaded only when needed with particular
5306 and special-purpose files which can be loaded only when needed with particular
5295 configuration options.
5307 configuration options.
5296 To make this more convenient, IPython accepts the
5308 To make this more convenient, IPython accepts the
5297 \family typewriter
5309 \family typewriter
5298 -profile <name>
5310 -profile <name>
5299 \family default
5311 \family default
5300 option (abbreviates to
5312 option (abbreviates to
5301 \family typewriter
5313 \family typewriter
5302 -p <name
5314 -p <name
5303 \family default
5315 \family default
5304 >)
5316 >)
5305 \family typewriter
5317 \family typewriter
5306 which
5318 which
5307 \family default
5319 \family default
5308 tells it to look for an rcfile named
5320 tells it to look for an rcfile named
5309 \family typewriter
5321 \family typewriter
5310 ipythonrc-<name>
5322 ipythonrc-<name>
5311 \family default
5323 \family default
5312 .
5324 .
5313
5325
5314 \layout List
5326 \layout List
5315 \labelwidthstring 00.00.0000
5327 \labelwidthstring 00.00.0000
5316
5328
5317
5329
5318 \family typewriter
5330 \family typewriter
5319 \series bold
5331 \series bold
5320 import_mod\SpecialChar ~
5332 import_mod\SpecialChar ~
5321 <mod1>\SpecialChar ~
5333 <mod1>\SpecialChar ~
5322 <mod2>\SpecialChar ~
5334 <mod2>\SpecialChar ~
5323 ...
5335 ...
5324 \family default
5336 \family default
5325 \series default
5337 \series default
5326 : import modules with '
5338 : import modules with '
5327 \family typewriter
5339 \family typewriter
5328 import
5340 import
5329 \family default
5341 \family default
5330
5342
5331 \family typewriter
5343 \family typewriter
5332 <mod1>,<mod2>,...
5344 <mod1>,<mod2>,...
5333 \family default
5345 \family default
5334 '
5346 '
5335 \layout List
5347 \layout List
5336 \labelwidthstring 00.00.0000
5348 \labelwidthstring 00.00.0000
5337
5349
5338
5350
5339 \family typewriter
5351 \family typewriter
5340 \series bold
5352 \series bold
5341 import_some\SpecialChar ~
5353 import_some\SpecialChar ~
5342 <mod>\SpecialChar ~
5354 <mod>\SpecialChar ~
5343 <f1>\SpecialChar ~
5355 <f1>\SpecialChar ~
5344 <f2>\SpecialChar ~
5356 <f2>\SpecialChar ~
5345 ...
5357 ...
5346 \family default
5358 \family default
5347 \series default
5359 \series default
5348 : import functions with '
5360 : import functions with '
5349 \family typewriter
5361 \family typewriter
5350 from <mod> import
5362 from <mod> import
5351 \family default
5363 \family default
5352
5364
5353 \family typewriter
5365 \family typewriter
5354 <f1>,<f2>,...
5366 <f1>,<f2>,...
5355 \family default
5367 \family default
5356 '
5368 '
5357 \layout List
5369 \layout List
5358 \labelwidthstring 00.00.0000
5370 \labelwidthstring 00.00.0000
5359
5371
5360
5372
5361 \family typewriter
5373 \family typewriter
5362 \series bold
5374 \series bold
5363 import_all\SpecialChar ~
5375 import_all\SpecialChar ~
5364 <mod1>\SpecialChar ~
5376 <mod1>\SpecialChar ~
5365 <mod2>\SpecialChar ~
5377 <mod2>\SpecialChar ~
5366 ...
5378 ...
5367 \family default
5379 \family default
5368 \series default
5380 \series default
5369 : for each module listed import functions with '
5381 : for each module listed import functions with '
5370 \family typewriter
5382 \family typewriter
5371 from <mod> import *
5383 from <mod> import *
5372 \family default
5384 \family default
5373 '
5385 '
5374 \layout List
5386 \layout List
5375 \labelwidthstring 00.00.0000
5387 \labelwidthstring 00.00.0000
5376
5388
5377
5389
5378 \family typewriter
5390 \family typewriter
5379 \series bold
5391 \series bold
5380 execute\SpecialChar ~
5392 execute\SpecialChar ~
5381 <python\SpecialChar ~
5393 <python\SpecialChar ~
5382 code>
5394 code>
5383 \family default
5395 \family default
5384 \series default
5396 \series default
5385 : give any single-line python code to be executed.
5397 : give any single-line python code to be executed.
5386 \layout List
5398 \layout List
5387 \labelwidthstring 00.00.0000
5399 \labelwidthstring 00.00.0000
5388
5400
5389
5401
5390 \family typewriter
5402 \family typewriter
5391 \series bold
5403 \series bold
5392 execfile\SpecialChar ~
5404 execfile\SpecialChar ~
5393 <filename>
5405 <filename>
5394 \family default
5406 \family default
5395 \series default
5407 \series default
5396 : execute the python file given with an '
5408 : execute the python file given with an '
5397 \family typewriter
5409 \family typewriter
5398 execfile(filename)
5410 execfile(filename)
5399 \family default
5411 \family default
5400 ' command.
5412 ' command.
5401 Username expansion is performed on the given names.
5413 Username expansion is performed on the given names.
5402 So if you need any amount of extra fancy customization that won't fit in
5414 So if you need any amount of extra fancy customization that won't fit in
5403 any of the above 'canned' options, you can just put it in a separate python
5415 any of the above 'canned' options, you can just put it in a separate python
5404 file and execute it.
5416 file and execute it.
5405 \layout List
5417 \layout List
5406 \labelwidthstring 00.00.0000
5418 \labelwidthstring 00.00.0000
5407
5419
5408
5420
5409 \family typewriter
5421 \family typewriter
5410 \series bold
5422 \series bold
5411 alias\SpecialChar ~
5423 alias\SpecialChar ~
5412 <alias_def>
5424 <alias_def>
5413 \family default
5425 \family default
5414 \series default
5426 \series default
5415 : this is equivalent to calling '
5427 : this is equivalent to calling '
5416 \family typewriter
5428 \family typewriter
5417 %alias\SpecialChar ~
5429 %alias\SpecialChar ~
5418 <alias_def>
5430 <alias_def>
5419 \family default
5431 \family default
5420 ' at the IPython command line.
5432 ' at the IPython command line.
5421 This way, from within IPython you can do common system tasks without having
5433 This way, from within IPython you can do common system tasks without having
5422 to exit it or use the
5434 to exit it or use the
5423 \family typewriter
5435 \family typewriter
5424 !
5436 !
5425 \family default
5437 \family default
5426 escape.
5438 escape.
5427 IPython isn't meant to be a shell replacement, but it is often very useful
5439 IPython isn't meant to be a shell replacement, but it is often very useful
5428 to be able to do things with files while testing code.
5440 to be able to do things with files while testing code.
5429 This gives you the flexibility to have within IPython any aliases you may
5441 This gives you the flexibility to have within IPython any aliases you may
5430 be used to under your normal system shell.
5442 be used to under your normal system shell.
5431 \layout Subsection
5443 \layout Subsection
5432
5444
5433
5445
5434 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5446 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5435
5447
5436 \end_inset
5448 \end_inset
5437
5449
5438 Sample
5450 Sample
5439 \family typewriter
5451 \family typewriter
5440 ipythonrc
5452 ipythonrc
5441 \family default
5453 \family default
5442 file
5454 file
5443 \layout Standard
5455 \layout Standard
5444
5456
5445 The default rcfile, called
5457 The default rcfile, called
5446 \family typewriter
5458 \family typewriter
5447 ipythonrc
5459 ipythonrc
5448 \family default
5460 \family default
5449 and supplied in your
5461 and supplied in your
5450 \family typewriter
5462 \family typewriter
5451 IPYTHONDIR
5463 IPYTHONDIR
5452 \family default
5464 \family default
5453 directory contains lots of comments on all of these options.
5465 directory contains lots of comments on all of these options.
5454 We reproduce it here for reference:
5466 We reproduce it here for reference:
5455 \layout Standard
5467 \layout Standard
5456
5468
5457
5469
5458 \begin_inset ERT
5470 \begin_inset ERT
5459 status Open
5471 status Open
5460
5472
5461 \layout Standard
5473 \layout Standard
5462
5474
5463 \backslash
5475 \backslash
5464 codelist{../IPython/UserConfig/ipythonrc}
5476 codelist{../IPython/UserConfig/ipythonrc}
5465 \end_inset
5477 \end_inset
5466
5478
5467
5479
5468 \layout Subsection
5480 \layout Subsection
5469
5481
5470
5482
5471 \begin_inset LatexCommand \label{sec:prompts}
5483 \begin_inset LatexCommand \label{sec:prompts}
5472
5484
5473 \end_inset
5485 \end_inset
5474
5486
5475 Fine-tuning your prompt
5487 Fine-tuning your prompt
5476 \layout Standard
5488 \layout Standard
5477
5489
5478 IPython's prompts can be customized using a syntax similar to that of the
5490 IPython's prompts can be customized using a syntax similar to that of the
5479
5491
5480 \family typewriter
5492 \family typewriter
5481 bash
5493 bash
5482 \family default
5494 \family default
5483 shell.
5495 shell.
5484 Many of
5496 Many of
5485 \family typewriter
5497 \family typewriter
5486 bash
5498 bash
5487 \family default
5499 \family default
5488 's escapes are supported, as well as a few additional ones.
5500 's escapes are supported, as well as a few additional ones.
5489 We list them below:
5501 We list them below:
5490 \layout Description
5502 \layout Description
5491
5503
5492
5504
5493 \backslash
5505 \backslash
5494 # the prompt/history count number
5506 # the prompt/history count number
5495 \layout Description
5507 \layout Description
5496
5508
5497
5509
5498 \backslash
5510 \backslash
5499 D the prompt/history count, with the actual digits replaced by dots.
5511 D the prompt/history count, with the actual digits replaced by dots.
5500 Used mainly in continuation prompts (prompt_in2)
5512 Used mainly in continuation prompts (prompt_in2)
5501 \layout Description
5513 \layout Description
5502
5514
5503
5515
5504 \backslash
5516 \backslash
5505 w the current working directory
5517 w the current working directory
5506 \layout Description
5518 \layout Description
5507
5519
5508
5520
5509 \backslash
5521 \backslash
5510 W the basename of current working directory
5522 W the basename of current working directory
5511 \layout Description
5523 \layout Description
5512
5524
5513
5525
5514 \backslash
5526 \backslash
5515 X
5527 X
5516 \emph on
5528 \emph on
5517 n
5529 n
5518 \emph default
5530 \emph default
5519 where
5531 where
5520 \begin_inset Formula $n=0\ldots5.$
5532 \begin_inset Formula $n=0\ldots5.$
5521 \end_inset
5533 \end_inset
5522
5534
5523 The current working directory, with
5535 The current working directory, with
5524 \family typewriter
5536 \family typewriter
5525 $HOME
5537 $HOME
5526 \family default
5538 \family default
5527 replaced by
5539 replaced by
5528 \family typewriter
5540 \family typewriter
5529 ~
5541 ~
5530 \family default
5542 \family default
5531 , and filtered out to contain only
5543 , and filtered out to contain only
5532 \begin_inset Formula $n$
5544 \begin_inset Formula $n$
5533 \end_inset
5545 \end_inset
5534
5546
5535 path elements
5547 path elements
5536 \layout Description
5548 \layout Description
5537
5549
5538
5550
5539 \backslash
5551 \backslash
5540 Y
5552 Y
5541 \emph on
5553 \emph on
5542 n
5554 n
5543 \emph default
5555 \emph default
5544 Similar to
5556 Similar to
5545 \backslash
5557 \backslash
5546 X
5558 X
5547 \emph on
5559 \emph on
5548 n
5560 n
5549 \emph default
5561 \emph default
5550 , but with the
5562 , but with the
5551 \begin_inset Formula $n+1$
5563 \begin_inset Formula $n+1$
5552 \end_inset
5564 \end_inset
5553
5565
5554 element included if it is
5566 element included if it is
5555 \family typewriter
5567 \family typewriter
5556 ~
5568 ~
5557 \family default
5569 \family default
5558 (this is similar to the behavior of the %c
5570 (this is similar to the behavior of the %c
5559 \emph on
5571 \emph on
5560 n
5572 n
5561 \emph default
5573 \emph default
5562 escapes in
5574 escapes in
5563 \family typewriter
5575 \family typewriter
5564 tcsh
5576 tcsh
5565 \family default
5577 \family default
5566 )
5578 )
5567 \layout Description
5579 \layout Description
5568
5580
5569
5581
5570 \backslash
5582 \backslash
5571 u the username of the current user
5583 u the username of the current user
5572 \layout Description
5584 \layout Description
5573
5585
5574
5586
5575 \backslash
5587 \backslash
5576 $ if the effective UID is 0, a #, otherwise a $
5588 $ if the effective UID is 0, a #, otherwise a $
5577 \layout Description
5589 \layout Description
5578
5590
5579
5591
5580 \backslash
5592 \backslash
5581 h the hostname up to the first `.'
5593 h the hostname up to the first `.'
5582 \layout Description
5594 \layout Description
5583
5595
5584
5596
5585 \backslash
5597 \backslash
5586 H the hostname
5598 H the hostname
5587 \layout Description
5599 \layout Description
5588
5600
5589
5601
5590 \backslash
5602 \backslash
5591 n a newline
5603 n a newline
5592 \layout Description
5604 \layout Description
5593
5605
5594
5606
5595 \backslash
5607 \backslash
5596 r a carriage return
5608 r a carriage return
5597 \layout Description
5609 \layout Description
5598
5610
5599
5611
5600 \backslash
5612 \backslash
5601 v IPython version string
5613 v IPython version string
5602 \layout Standard
5614 \layout Standard
5603
5615
5604 In addition to these, ANSI color escapes can be insterted into the prompts,
5616 In addition to these, ANSI color escapes can be insterted into the prompts,
5605 as
5617 as
5606 \family typewriter
5618 \family typewriter
5607
5619
5608 \backslash
5620 \backslash
5609 C_
5621 C_
5610 \emph on
5622 \emph on
5611 ColorName
5623 ColorName
5612 \family default
5624 \family default
5613 \emph default
5625 \emph default
5614 .
5626 .
5615 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5627 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5616 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5628 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5617 Normal, Purple, Red, White, Yellow.
5629 Normal, Purple, Red, White, Yellow.
5618 \layout Standard
5630 \layout Standard
5619
5631
5620 Finally, IPython supports the evaluation of arbitrary expressions in your
5632 Finally, IPython supports the evaluation of arbitrary expressions in your
5621 prompt string.
5633 prompt string.
5622 The prompt strings are evaluated through the syntax of PEP 215, but basically
5634 The prompt strings are evaluated through the syntax of PEP 215, but basically
5623 you can use
5635 you can use
5624 \family typewriter
5636 \family typewriter
5625 $x.y
5637 $x.y
5626 \family default
5638 \family default
5627 to expand the value of
5639 to expand the value of
5628 \family typewriter
5640 \family typewriter
5629 x.y
5641 x.y
5630 \family default
5642 \family default
5631 , and for more complicated expressions you can use braces:
5643 , and for more complicated expressions you can use braces:
5632 \family typewriter
5644 \family typewriter
5633 ${foo()+x}
5645 ${foo()+x}
5634 \family default
5646 \family default
5635 will call function
5647 will call function
5636 \family typewriter
5648 \family typewriter
5637 foo
5649 foo
5638 \family default
5650 \family default
5639 and add to it the value of
5651 and add to it the value of
5640 \family typewriter
5652 \family typewriter
5641 x
5653 x
5642 \family default
5654 \family default
5643 , before putting the result into your prompt.
5655 , before putting the result into your prompt.
5644 For example, using
5656 For example, using
5645 \newline
5657 \newline
5646
5658
5647 \family typewriter
5659 \family typewriter
5648 prompt_in1 '${commands.getoutput("uptime")}
5660 prompt_in1 '${commands.getoutput("uptime")}
5649 \backslash
5661 \backslash
5650 nIn [
5662 nIn [
5651 \backslash
5663 \backslash
5652 #]: '
5664 #]: '
5653 \newline
5665 \newline
5654
5666
5655 \family default
5667 \family default
5656 will print the result of the uptime command on each prompt (assuming the
5668 will print the result of the uptime command on each prompt (assuming the
5657
5669
5658 \family typewriter
5670 \family typewriter
5659 commands
5671 commands
5660 \family default
5672 \family default
5661 module has been imported in your
5673 module has been imported in your
5662 \family typewriter
5674 \family typewriter
5663 ipythonrc
5675 ipythonrc
5664 \family default
5676 \family default
5665 file).
5677 file).
5666 \layout Subsubsection
5678 \layout Subsubsection
5667
5679
5668 Prompt examples
5680 Prompt examples
5669 \layout Standard
5681 \layout Standard
5670
5682
5671 The following options in an ipythonrc file will give you IPython's default
5683 The following options in an ipythonrc file will give you IPython's default
5672 prompts:
5684 prompts:
5673 \layout Standard
5685 \layout Standard
5674
5686
5675
5687
5676 \family typewriter
5688 \family typewriter
5677 prompt_in1 'In [
5689 prompt_in1 'In [
5678 \backslash
5690 \backslash
5679 #]:'
5691 #]:'
5680 \newline
5692 \newline
5681 prompt_in2 '\SpecialChar ~
5693 prompt_in2 '\SpecialChar ~
5682 \SpecialChar ~
5694 \SpecialChar ~
5683 \SpecialChar ~
5695 \SpecialChar ~
5684 .
5696 .
5685 \backslash
5697 \backslash
5686 D.:'
5698 D.:'
5687 \newline
5699 \newline
5688 prompt_out 'Out[
5700 prompt_out 'Out[
5689 \backslash
5701 \backslash
5690 #]:'
5702 #]:'
5691 \layout Standard
5703 \layout Standard
5692
5704
5693 which look like this:
5705 which look like this:
5694 \layout Standard
5706 \layout Standard
5695
5707
5696
5708
5697 \family typewriter
5709 \family typewriter
5698 In [1]: 1+2
5710 In [1]: 1+2
5699 \newline
5711 \newline
5700 Out[1]: 3
5712 Out[1]: 3
5701 \layout Standard
5713 \layout Standard
5702
5714
5703
5715
5704 \family typewriter
5716 \family typewriter
5705 In [2]: for i in (1,2,3):
5717 In [2]: for i in (1,2,3):
5706 \newline
5718 \newline
5707
5719
5708 \begin_inset ERT
5720 \begin_inset ERT
5709 status Collapsed
5721 status Collapsed
5710
5722
5711 \layout Standard
5723 \layout Standard
5712
5724
5713 \backslash
5725 \backslash
5714 hspace*{0mm}
5726 hspace*{0mm}
5715 \end_inset
5727 \end_inset
5716
5728
5717 \SpecialChar ~
5729 \SpecialChar ~
5718 \SpecialChar ~
5730 \SpecialChar ~
5719 \SpecialChar ~
5731 \SpecialChar ~
5720 ...: \SpecialChar ~
5732 ...: \SpecialChar ~
5721 \SpecialChar ~
5733 \SpecialChar ~
5722 \SpecialChar ~
5734 \SpecialChar ~
5723 \SpecialChar ~
5735 \SpecialChar ~
5724 print i,
5736 print i,
5725 \newline
5737 \newline
5726
5738
5727 \begin_inset ERT
5739 \begin_inset ERT
5728 status Collapsed
5740 status Collapsed
5729
5741
5730 \layout Standard
5742 \layout Standard
5731
5743
5732 \backslash
5744 \backslash
5733 hspace*{0mm}
5745 hspace*{0mm}
5734 \end_inset
5746 \end_inset
5735
5747
5736 \SpecialChar ~
5748 \SpecialChar ~
5737 \SpecialChar ~
5749 \SpecialChar ~
5738 \SpecialChar ~
5750 \SpecialChar ~
5739 ...:
5751 ...:
5740 \newline
5752 \newline
5741 1 2 3
5753 1 2 3
5742 \layout Standard
5754 \layout Standard
5743
5755
5744 These will give you a very colorful prompt with path information:
5756 These will give you a very colorful prompt with path information:
5745 \layout Standard
5757 \layout Standard
5746
5758
5747
5759
5748 \family typewriter
5760 \family typewriter
5749 #prompt_in1 '
5761 #prompt_in1 '
5750 \backslash
5762 \backslash
5751 C_Red
5763 C_Red
5752 \backslash
5764 \backslash
5753 u
5765 u
5754 \backslash
5766 \backslash
5755 C_Blue[
5767 C_Blue[
5756 \backslash
5768 \backslash
5757 C_Cyan
5769 C_Cyan
5758 \backslash
5770 \backslash
5759 Y1
5771 Y1
5760 \backslash
5772 \backslash
5761 C_Blue]
5773 C_Blue]
5762 \backslash
5774 \backslash
5763 C_LightGreen
5775 C_LightGreen
5764 \backslash
5776 \backslash
5765 #>'
5777 #>'
5766 \newline
5778 \newline
5767 prompt_in2 ' ..
5779 prompt_in2 ' ..
5768 \backslash
5780 \backslash
5769 D>'
5781 D>'
5770 \newline
5782 \newline
5771 prompt_out '<
5783 prompt_out '<
5772 \backslash
5784 \backslash
5773 #>'
5785 #>'
5774 \layout Standard
5786 \layout Standard
5775
5787
5776 which look like this:
5788 which look like this:
5777 \layout Standard
5789 \layout Standard
5778
5790
5779
5791
5780 \family typewriter
5792 \family typewriter
5781 \color red
5793 \color red
5782 fperez
5794 fperez
5783 \color blue
5795 \color blue
5784 [
5796 [
5785 \color cyan
5797 \color cyan
5786 ~/ipython
5798 ~/ipython
5787 \color blue
5799 \color blue
5788 ]
5800 ]
5789 \color green
5801 \color green
5790 1>
5802 1>
5791 \color default
5803 \color default
5792 1+2
5804 1+2
5793 \newline
5805 \newline
5794
5806
5795 \begin_inset ERT
5807 \begin_inset ERT
5796 status Collapsed
5808 status Collapsed
5797
5809
5798 \layout Standard
5810 \layout Standard
5799
5811
5800 \backslash
5812 \backslash
5801 hspace*{0mm}
5813 hspace*{0mm}
5802 \end_inset
5814 \end_inset
5803
5815
5804 \SpecialChar ~
5816 \SpecialChar ~
5805 \SpecialChar ~
5817 \SpecialChar ~
5806 \SpecialChar ~
5818 \SpecialChar ~
5807 \SpecialChar ~
5819 \SpecialChar ~
5808 \SpecialChar ~
5820 \SpecialChar ~
5809 \SpecialChar ~
5821 \SpecialChar ~
5810 \SpecialChar ~
5822 \SpecialChar ~
5811 \SpecialChar ~
5823 \SpecialChar ~
5812 \SpecialChar ~
5824 \SpecialChar ~
5813 \SpecialChar ~
5825 \SpecialChar ~
5814 \SpecialChar ~
5826 \SpecialChar ~
5815 \SpecialChar ~
5827 \SpecialChar ~
5816 \SpecialChar ~
5828 \SpecialChar ~
5817 \SpecialChar ~
5829 \SpecialChar ~
5818 \SpecialChar ~
5830 \SpecialChar ~
5819 \SpecialChar ~
5831 \SpecialChar ~
5820
5832
5821 \color red
5833 \color red
5822 <1>
5834 <1>
5823 \color default
5835 \color default
5824 3
5836 3
5825 \newline
5837 \newline
5826
5838
5827 \color red
5839 \color red
5828 fperez
5840 fperez
5829 \color blue
5841 \color blue
5830 [
5842 [
5831 \color cyan
5843 \color cyan
5832 ~/ipython
5844 ~/ipython
5833 \color blue
5845 \color blue
5834 ]
5846 ]
5835 \color green
5847 \color green
5836 2>
5848 2>
5837 \color default
5849 \color default
5838 for i in (1,2,3):
5850 for i in (1,2,3):
5839 \newline
5851 \newline
5840
5852
5841 \begin_inset ERT
5853 \begin_inset ERT
5842 status Collapsed
5854 status Collapsed
5843
5855
5844 \layout Standard
5856 \layout Standard
5845
5857
5846 \backslash
5858 \backslash
5847 hspace*{0mm}
5859 hspace*{0mm}
5848 \end_inset
5860 \end_inset
5849
5861
5850 \SpecialChar ~
5862 \SpecialChar ~
5851 \SpecialChar ~
5863 \SpecialChar ~
5852 \SpecialChar ~
5864 \SpecialChar ~
5853 \SpecialChar ~
5865 \SpecialChar ~
5854 \SpecialChar ~
5866 \SpecialChar ~
5855 \SpecialChar ~
5867 \SpecialChar ~
5856 \SpecialChar ~
5868 \SpecialChar ~
5857 \SpecialChar ~
5869 \SpecialChar ~
5858 \SpecialChar ~
5870 \SpecialChar ~
5859 \SpecialChar ~
5871 \SpecialChar ~
5860 \SpecialChar ~
5872 \SpecialChar ~
5861 \SpecialChar ~
5873 \SpecialChar ~
5862 \SpecialChar ~
5874 \SpecialChar ~
5863 \SpecialChar ~
5875 \SpecialChar ~
5864 \SpecialChar ~
5876 \SpecialChar ~
5865
5877
5866 \color green
5878 \color green
5867 ...>
5879 ...>
5868 \color default
5880 \color default
5869 \SpecialChar ~
5881 \SpecialChar ~
5870 \SpecialChar ~
5882 \SpecialChar ~
5871 \SpecialChar ~
5883 \SpecialChar ~
5872 \SpecialChar ~
5884 \SpecialChar ~
5873 print i,
5885 print i,
5874 \newline
5886 \newline
5875
5887
5876 \begin_inset ERT
5888 \begin_inset ERT
5877 status Collapsed
5889 status Collapsed
5878
5890
5879 \layout Standard
5891 \layout Standard
5880
5892
5881 \backslash
5893 \backslash
5882 hspace*{0mm}
5894 hspace*{0mm}
5883 \end_inset
5895 \end_inset
5884
5896
5885 \SpecialChar ~
5897 \SpecialChar ~
5886 \SpecialChar ~
5898 \SpecialChar ~
5887 \SpecialChar ~
5899 \SpecialChar ~
5888 \SpecialChar ~
5900 \SpecialChar ~
5889 \SpecialChar ~
5901 \SpecialChar ~
5890 \SpecialChar ~
5902 \SpecialChar ~
5891 \SpecialChar ~
5903 \SpecialChar ~
5892 \SpecialChar ~
5904 \SpecialChar ~
5893 \SpecialChar ~
5905 \SpecialChar ~
5894 \SpecialChar ~
5906 \SpecialChar ~
5895 \SpecialChar ~
5907 \SpecialChar ~
5896 \SpecialChar ~
5908 \SpecialChar ~
5897 \SpecialChar ~
5909 \SpecialChar ~
5898 \SpecialChar ~
5910 \SpecialChar ~
5899 \SpecialChar ~
5911 \SpecialChar ~
5900
5912
5901 \color green
5913 \color green
5902 ...>
5914 ...>
5903 \color default
5915 \color default
5904
5916
5905 \newline
5917 \newline
5906 1 2 3
5918 1 2 3
5907 \layout Standard
5919 \layout Standard
5908
5920
5909 The following shows the usage of dynamic expression evaluation:
5921 The following shows the usage of dynamic expression evaluation:
5910 \layout Subsection
5922 \layout Subsection
5911
5923
5912
5924
5913 \begin_inset LatexCommand \label{sec:profiles}
5925 \begin_inset LatexCommand \label{sec:profiles}
5914
5926
5915 \end_inset
5927 \end_inset
5916
5928
5917 IPython profiles
5929 IPython profiles
5918 \layout Standard
5930 \layout Standard
5919
5931
5920 As we already mentioned, IPython supports the
5932 As we already mentioned, IPython supports the
5921 \family typewriter
5933 \family typewriter
5922 -profile
5934 -profile
5923 \family default
5935 \family default
5924 command-line option (see sec.
5936 command-line option (see sec.
5925
5937
5926 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5938 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5927
5939
5928 \end_inset
5940 \end_inset
5929
5941
5930 ).
5942 ).
5931 A profile is nothing more than a particular configuration file like your
5943 A profile is nothing more than a particular configuration file like your
5932 basic
5944 basic
5933 \family typewriter
5945 \family typewriter
5934 ipythonrc
5946 ipythonrc
5935 \family default
5947 \family default
5936 one, but with particular customizations for a specific purpose.
5948 one, but with particular customizations for a specific purpose.
5937 When you start IPython with '
5949 When you start IPython with '
5938 \family typewriter
5950 \family typewriter
5939 ipython -profile <name>
5951 ipython -profile <name>
5940 \family default
5952 \family default
5941 ', it assumes that in your
5953 ', it assumes that in your
5942 \family typewriter
5954 \family typewriter
5943 IPYTHONDIR
5955 IPYTHONDIR
5944 \family default
5956 \family default
5945 there is a file called
5957 there is a file called
5946 \family typewriter
5958 \family typewriter
5947 ipythonrc-<name>
5959 ipythonrc-<name>
5948 \family default
5960 \family default
5949 , and loads it instead of the normal
5961 , and loads it instead of the normal
5950 \family typewriter
5962 \family typewriter
5951 ipythonrc
5963 ipythonrc
5952 \family default
5964 \family default
5953 .
5965 .
5954 \layout Standard
5966 \layout Standard
5955
5967
5956 This system allows you to maintain multiple configurations which load modules,
5968 This system allows you to maintain multiple configurations which load modules,
5957 set options, define functions, etc.
5969 set options, define functions, etc.
5958 suitable for different tasks and activate them in a very simple manner.
5970 suitable for different tasks and activate them in a very simple manner.
5959 In order to avoid having to repeat all of your basic options (common things
5971 In order to avoid having to repeat all of your basic options (common things
5960 that don't change such as your color preferences, for example), any profile
5972 that don't change such as your color preferences, for example), any profile
5961 can include another configuration file.
5973 can include another configuration file.
5962 The most common way to use profiles is then to have each one include your
5974 The most common way to use profiles is then to have each one include your
5963 basic
5975 basic
5964 \family typewriter
5976 \family typewriter
5965 ipythonrc
5977 ipythonrc
5966 \family default
5978 \family default
5967 file as a starting point, and then add further customizations.
5979 file as a starting point, and then add further customizations.
5968 \layout Standard
5980 \layout Standard
5969
5981
5970 In sections
5982 In sections
5971 \begin_inset LatexCommand \ref{sec:syntax-extensions}
5983 \begin_inset LatexCommand \ref{sec:syntax-extensions}
5972
5984
5973 \end_inset
5985 \end_inset
5974
5986
5975 and
5987 and
5976 \begin_inset LatexCommand \ref{sec:Gnuplot}
5988 \begin_inset LatexCommand \ref{sec:Gnuplot}
5977
5989
5978 \end_inset
5990 \end_inset
5979
5991
5980 we discuss some particular profiles which come as part of the standard
5992 we discuss some particular profiles which come as part of the standard
5981 IPython distribution.
5993 IPython distribution.
5982 You may also look in your
5994 You may also look in your
5983 \family typewriter
5995 \family typewriter
5984 IPYTHONDIR
5996 IPYTHONDIR
5985 \family default
5997 \family default
5986 directory, any file whose name begins with
5998 directory, any file whose name begins with
5987 \family typewriter
5999 \family typewriter
5988 ipythonrc-
6000 ipythonrc-
5989 \family default
6001 \family default
5990 is a profile.
6002 is a profile.
5991 You can use those as examples for further customizations to suit your own
6003 You can use those as examples for further customizations to suit your own
5992 needs.
6004 needs.
5993 \layout Section
6005 \layout Section
5994
6006
5995
6007
5996 \begin_inset OptArg
6008 \begin_inset OptArg
5997 collapsed false
6009 collapsed false
5998
6010
5999 \layout Standard
6011 \layout Standard
6000
6012
6001 IPython as default...
6013 IPython as default...
6002 \end_inset
6014 \end_inset
6003
6015
6004 IPython as your default Python environment
6016 IPython as your default Python environment
6005 \layout Standard
6017 \layout Standard
6006
6018
6007 Python honors the environment variable
6019 Python honors the environment variable
6008 \family typewriter
6020 \family typewriter
6009 PYTHONSTARTUP
6021 PYTHONSTARTUP
6010 \family default
6022 \family default
6011 and will execute at startup the file referenced by this variable.
6023 and will execute at startup the file referenced by this variable.
6012 If you put at the end of this file the following two lines of code:
6024 If you put at the end of this file the following two lines of code:
6013 \layout Standard
6025 \layout Standard
6014
6026
6015
6027
6016 \family typewriter
6028 \family typewriter
6017 import IPython
6029 import IPython
6018 \newline
6030 \newline
6019 IPython.Shell.IPShell().mainloop(sys_exit=1)
6031 IPython.Shell.IPShell().mainloop(sys_exit=1)
6020 \layout Standard
6032 \layout Standard
6021
6033
6022 then IPython will be your working environment anytime you start Python.
6034 then IPython will be your working environment anytime you start Python.
6023 The
6035 The
6024 \family typewriter
6036 \family typewriter
6025 sys_exit=1
6037 sys_exit=1
6026 \family default
6038 \family default
6027 is needed to have IPython issue a call to
6039 is needed to have IPython issue a call to
6028 \family typewriter
6040 \family typewriter
6029 sys.exit()
6041 sys.exit()
6030 \family default
6042 \family default
6031 when it finishes, otherwise you'll be back at the normal Python '
6043 when it finishes, otherwise you'll be back at the normal Python '
6032 \family typewriter
6044 \family typewriter
6033 >>>
6045 >>>
6034 \family default
6046 \family default
6035 ' prompt
6047 ' prompt
6036 \begin_inset Foot
6048 \begin_inset Foot
6037 collapsed true
6049 collapsed true
6038
6050
6039 \layout Standard
6051 \layout Standard
6040
6052
6041 Based on an idea by Holger Krekel.
6053 Based on an idea by Holger Krekel.
6042 \end_inset
6054 \end_inset
6043
6055
6044 .
6056 .
6045 \layout Standard
6057 \layout Standard
6046
6058
6047 This is probably useful to developers who manage multiple Python versions
6059 This is probably useful to developers who manage multiple Python versions
6048 and don't want to have correspondingly multiple IPython versions.
6060 and don't want to have correspondingly multiple IPython versions.
6049 Note that in this mode, there is no way to pass IPython any command-line
6061 Note that in this mode, there is no way to pass IPython any command-line
6050 options, as those are trapped first by Python itself.
6062 options, as those are trapped first by Python itself.
6051 \layout Section
6063 \layout Section
6052
6064
6053
6065
6054 \begin_inset LatexCommand \label{sec:embed}
6066 \begin_inset LatexCommand \label{sec:embed}
6055
6067
6056 \end_inset
6068 \end_inset
6057
6069
6058 Embedding IPython
6070 Embedding IPython
6059 \layout Standard
6071 \layout Standard
6060
6072
6061 It is possible to start an IPython instance
6073 It is possible to start an IPython instance
6062 \emph on
6074 \emph on
6063 inside
6075 inside
6064 \emph default
6076 \emph default
6065 your own Python programs.
6077 your own Python programs.
6066 This allows you to evaluate dynamically the state of your code, operate
6078 This allows you to evaluate dynamically the state of your code, operate
6067 with your variables, analyze them, etc.
6079 with your variables, analyze them, etc.
6068 Note however that any changes you make to values while in the shell do
6080 Note however that any changes you make to values while in the shell do
6069
6081
6070 \emph on
6082 \emph on
6071 not
6083 not
6072 \emph default
6084 \emph default
6073 propagate back to the running code, so it is safe to modify your values
6085 propagate back to the running code, so it is safe to modify your values
6074 because you won't break your code in bizarre ways by doing so.
6086 because you won't break your code in bizarre ways by doing so.
6075 \layout Standard
6087 \layout Standard
6076
6088
6077 This feature allows you to easily have a fully functional python environment
6089 This feature allows you to easily have a fully functional python environment
6078 for doing object introspection anywhere in your code with a simple function
6090 for doing object introspection anywhere in your code with a simple function
6079 call.
6091 call.
6080 In some cases a simple print statement is enough, but if you need to do
6092 In some cases a simple print statement is enough, but if you need to do
6081 more detailed analysis of a code fragment this feature can be very valuable.
6093 more detailed analysis of a code fragment this feature can be very valuable.
6082 \layout Standard
6094 \layout Standard
6083
6095
6084 It can also be useful in scientific computing situations where it is common
6096 It can also be useful in scientific computing situations where it is common
6085 to need to do some automatic, computationally intensive part and then stop
6097 to need to do some automatic, computationally intensive part and then stop
6086 to look at data, plots, etc
6098 to look at data, plots, etc
6087 \begin_inset Foot
6099 \begin_inset Foot
6088 collapsed true
6100 collapsed true
6089
6101
6090 \layout Standard
6102 \layout Standard
6091
6103
6092 This functionality was inspired by IDL's combination of the
6104 This functionality was inspired by IDL's combination of the
6093 \family typewriter
6105 \family typewriter
6094 stop
6106 stop
6095 \family default
6107 \family default
6096 keyword and the
6108 keyword and the
6097 \family typewriter
6109 \family typewriter
6098 .continue
6110 .continue
6099 \family default
6111 \family default
6100 executive command, which I have found very useful in the past, and by a
6112 executive command, which I have found very useful in the past, and by a
6101 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6113 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6102 06/01 concerning similar uses of pyrepl.
6114 06/01 concerning similar uses of pyrepl.
6103 \end_inset
6115 \end_inset
6104
6116
6105 .
6117 .
6106 Opening an IPython instance will give you full access to your data and
6118 Opening an IPython instance will give you full access to your data and
6107 functions, and you can resume program execution once you are done with
6119 functions, and you can resume program execution once you are done with
6108 the interactive part (perhaps to stop again later, as many times as needed).
6120 the interactive part (perhaps to stop again later, as many times as needed).
6109 \layout Standard
6121 \layout Standard
6110
6122
6111 The following code snippet is the bare minimum you need to include in your
6123 The following code snippet is the bare minimum you need to include in your
6112 Python programs for this to work (detailed examples follow later):
6124 Python programs for this to work (detailed examples follow later):
6113 \layout LyX-Code
6125 \layout LyX-Code
6114
6126
6115 from IPython.Shell import IPShellEmbed
6127 from IPython.Shell import IPShellEmbed
6116 \layout LyX-Code
6128 \layout LyX-Code
6117
6129
6118 ipshell = IPShellEmbed()
6130 ipshell = IPShellEmbed()
6119 \layout LyX-Code
6131 \layout LyX-Code
6120
6132
6121 ipshell() # this call anywhere in your program will start IPython
6133 ipshell() # this call anywhere in your program will start IPython
6122 \layout Standard
6134 \layout Standard
6123
6135
6124 You can run embedded instances even in code which is itself being run at
6136 You can run embedded instances even in code which is itself being run at
6125 the IPython interactive prompt with '
6137 the IPython interactive prompt with '
6126 \family typewriter
6138 \family typewriter
6127 %run\SpecialChar ~
6139 %run\SpecialChar ~
6128 <filename>
6140 <filename>
6129 \family default
6141 \family default
6130 '.
6142 '.
6131 Since it's easy to get lost as to where you are (in your top-level IPython
6143 Since it's easy to get lost as to where you are (in your top-level IPython
6132 or in your embedded one), it's a good idea in such cases to set the in/out
6144 or in your embedded one), it's a good idea in such cases to set the in/out
6133 prompts to something different for the embedded instances.
6145 prompts to something different for the embedded instances.
6134 The code examples below illustrate this.
6146 The code examples below illustrate this.
6135 \layout Standard
6147 \layout Standard
6136
6148
6137 You can also have multiple IPython instances in your program and open them
6149 You can also have multiple IPython instances in your program and open them
6138 separately, for example with different options for data presentation.
6150 separately, for example with different options for data presentation.
6139 If you close and open the same instance multiple times, its prompt counters
6151 If you close and open the same instance multiple times, its prompt counters
6140 simply continue from each execution to the next.
6152 simply continue from each execution to the next.
6141 \layout Standard
6153 \layout Standard
6142
6154
6143 Please look at the docstrings in the
6155 Please look at the docstrings in the
6144 \family typewriter
6156 \family typewriter
6145 Shell.py
6157 Shell.py
6146 \family default
6158 \family default
6147 module for more details on the use of this system.
6159 module for more details on the use of this system.
6148 \layout Standard
6160 \layout Standard
6149
6161
6150 The following sample file illustrating how to use the embedding functionality
6162 The following sample file illustrating how to use the embedding functionality
6151 is provided in the examples directory as
6163 is provided in the examples directory as
6152 \family typewriter
6164 \family typewriter
6153 example-embed.py
6165 example-embed.py
6154 \family default
6166 \family default
6155 .
6167 .
6156 It should be fairly self-explanatory:
6168 It should be fairly self-explanatory:
6157 \layout Standard
6169 \layout Standard
6158
6170
6159
6171
6160 \begin_inset ERT
6172 \begin_inset ERT
6161 status Open
6173 status Open
6162
6174
6163 \layout Standard
6175 \layout Standard
6164
6176
6165 \backslash
6177 \backslash
6166 codelist{examples/example-embed.py}
6178 codelist{examples/example-embed.py}
6167 \end_inset
6179 \end_inset
6168
6180
6169
6181
6170 \layout Standard
6182 \layout Standard
6171
6183
6172 Once you understand how the system functions, you can use the following
6184 Once you understand how the system functions, you can use the following
6173 code fragments in your programs which are ready for cut and paste:
6185 code fragments in your programs which are ready for cut and paste:
6174 \layout Standard
6186 \layout Standard
6175
6187
6176
6188
6177 \begin_inset ERT
6189 \begin_inset ERT
6178 status Open
6190 status Open
6179
6191
6180 \layout Standard
6192 \layout Standard
6181
6193
6182 \backslash
6194 \backslash
6183 codelist{examples/example-embed-short.py}
6195 codelist{examples/example-embed-short.py}
6184 \end_inset
6196 \end_inset
6185
6197
6186
6198
6187 \layout Section
6199 \layout Section
6188
6200
6189
6201
6190 \begin_inset LatexCommand \label{sec:using-pdb}
6202 \begin_inset LatexCommand \label{sec:using-pdb}
6191
6203
6192 \end_inset
6204 \end_inset
6193
6205
6194 Using the Python debugger (
6206 Using the Python debugger (
6195 \family typewriter
6207 \family typewriter
6196 pdb
6208 pdb
6197 \family default
6209 \family default
6198 )
6210 )
6199 \layout Subsection
6211 \layout Subsection
6200
6212
6201 Running entire programs via
6213 Running entire programs via
6202 \family typewriter
6214 \family typewriter
6203 pdb
6215 pdb
6204 \layout Standard
6216 \layout Standard
6205
6217
6206
6218
6207 \family typewriter
6219 \family typewriter
6208 pdb
6220 pdb
6209 \family default
6221 \family default
6210 , the Python debugger, is a powerful interactive debugger which allows you
6222 , the Python debugger, is a powerful interactive debugger which allows you
6211 to step through code, set breakpoints, watch variables, etc.
6223 to step through code, set breakpoints, watch variables, etc.
6212 IPython makes it very easy to start any script under the control of
6224 IPython makes it very easy to start any script under the control of
6213 \family typewriter
6225 \family typewriter
6214 pdb
6226 pdb
6215 \family default
6227 \family default
6216 , regardless of whether you have wrapped it into a
6228 , regardless of whether you have wrapped it into a
6217 \family typewriter
6229 \family typewriter
6218 `main()'
6230 `main()'
6219 \family default
6231 \family default
6220 function or not.
6232 function or not.
6221 For this, simply type
6233 For this, simply type
6222 \family typewriter
6234 \family typewriter
6223 `%run -d myscript'
6235 `%run -d myscript'
6224 \family default
6236 \family default
6225 at an IPython prompt.
6237 at an IPython prompt.
6226 See the
6238 See the
6227 \family typewriter
6239 \family typewriter
6228 %run
6240 %run
6229 \family default
6241 \family default
6230 command's documentation (via
6242 command's documentation (via
6231 \family typewriter
6243 \family typewriter
6232 `%run?'
6244 `%run?'
6233 \family default
6245 \family default
6234 or in Sec.\SpecialChar ~
6246 or in Sec.\SpecialChar ~
6235
6247
6236 \begin_inset LatexCommand \ref{sec:magic}
6248 \begin_inset LatexCommand \ref{sec:magic}
6237
6249
6238 \end_inset
6250 \end_inset
6239
6251
6240 ) for more details, including how to control where
6252 ) for more details, including how to control where
6241 \family typewriter
6253 \family typewriter
6242 pdb
6254 pdb
6243 \family default
6255 \family default
6244 will stop execution first.
6256 will stop execution first.
6245 \layout Standard
6257 \layout Standard
6246
6258
6247 For more information on the use of the
6259 For more information on the use of the
6248 \family typewriter
6260 \family typewriter
6249 pdb
6261 pdb
6250 \family default
6262 \family default
6251 debugger, read the included
6263 debugger, read the included
6252 \family typewriter
6264 \family typewriter
6253 pdb.doc
6265 pdb.doc
6254 \family default
6266 \family default
6255 file (part of the standard Python distribution).
6267 file (part of the standard Python distribution).
6256 On a stock Linux system it is located at
6268 On a stock Linux system it is located at
6257 \family typewriter
6269 \family typewriter
6258 /usr/lib/python2.3/pdb.doc
6270 /usr/lib/python2.3/pdb.doc
6259 \family default
6271 \family default
6260 , but the easiest way to read it is by using the
6272 , but the easiest way to read it is by using the
6261 \family typewriter
6273 \family typewriter
6262 help()
6274 help()
6263 \family default
6275 \family default
6264 function of the
6276 function of the
6265 \family typewriter
6277 \family typewriter
6266 pdb
6278 pdb
6267 \family default
6279 \family default
6268 module as follows (in an IPython prompt):
6280 module as follows (in an IPython prompt):
6269 \layout Standard
6281 \layout Standard
6270
6282
6271
6283
6272 \family typewriter
6284 \family typewriter
6273 In [1]: import pdb
6285 In [1]: import pdb
6274 \newline
6286 \newline
6275 In [2]: pdb.help()
6287 In [2]: pdb.help()
6276 \layout Standard
6288 \layout Standard
6277
6289
6278 This will load the
6290 This will load the
6279 \family typewriter
6291 \family typewriter
6280 pdb.doc
6292 pdb.doc
6281 \family default
6293 \family default
6282 document in a file viewer for you automatically.
6294 document in a file viewer for you automatically.
6283 \layout Subsection
6295 \layout Subsection
6284
6296
6285 Automatic invocation of
6297 Automatic invocation of
6286 \family typewriter
6298 \family typewriter
6287 pdb
6299 pdb
6288 \family default
6300 \family default
6289 on exceptions
6301 on exceptions
6290 \layout Standard
6302 \layout Standard
6291
6303
6292 IPython, if started with the
6304 IPython, if started with the
6293 \family typewriter
6305 \family typewriter
6294 -pdb
6306 -pdb
6295 \family default
6307 \family default
6296 option (or if the option is set in your rc file) can call the Python
6308 option (or if the option is set in your rc file) can call the Python
6297 \family typewriter
6309 \family typewriter
6298 pdb
6310 pdb
6299 \family default
6311 \family default
6300 debugger every time your code triggers an uncaught exception
6312 debugger every time your code triggers an uncaught exception
6301 \begin_inset Foot
6313 \begin_inset Foot
6302 collapsed true
6314 collapsed true
6303
6315
6304 \layout Standard
6316 \layout Standard
6305
6317
6306 Many thanks to Christopher Hart for the request which prompted adding this
6318 Many thanks to Christopher Hart for the request which prompted adding this
6307 feature to IPython.
6319 feature to IPython.
6308 \end_inset
6320 \end_inset
6309
6321
6310 .
6322 .
6311 This feature can also be toggled at any time with the
6323 This feature can also be toggled at any time with the
6312 \family typewriter
6324 \family typewriter
6313 %pdb
6325 %pdb
6314 \family default
6326 \family default
6315 magic command.
6327 magic command.
6316 This can be extremely useful in order to find the origin of subtle bugs,
6328 This can be extremely useful in order to find the origin of subtle bugs,
6317 because
6329 because
6318 \family typewriter
6330 \family typewriter
6319 pdb
6331 pdb
6320 \family default
6332 \family default
6321 opens up at the point in your code which triggered the exception, and while
6333 opens up at the point in your code which triggered the exception, and while
6322 your program is at this point `dead', all the data is still available and
6334 your program is at this point `dead', all the data is still available and
6323 you can walk up and down the stack frame and understand the origin of the
6335 you can walk up and down the stack frame and understand the origin of the
6324 problem.
6336 problem.
6325 \layout Standard
6337 \layout Standard
6326
6338
6327 Furthermore, you can use these debugging facilities both with the embedded
6339 Furthermore, you can use these debugging facilities both with the embedded
6328 IPython mode and without IPython at all.
6340 IPython mode and without IPython at all.
6329 For an embedded shell (see sec.
6341 For an embedded shell (see sec.
6330
6342
6331 \begin_inset LatexCommand \ref{sec:embed}
6343 \begin_inset LatexCommand \ref{sec:embed}
6332
6344
6333 \end_inset
6345 \end_inset
6334
6346
6335 ), simply call the constructor with
6347 ), simply call the constructor with
6336 \family typewriter
6348 \family typewriter
6337 `-pdb'
6349 `-pdb'
6338 \family default
6350 \family default
6339 in the argument string and automatically
6351 in the argument string and automatically
6340 \family typewriter
6352 \family typewriter
6341 pdb
6353 pdb
6342 \family default
6354 \family default
6343 will be called if an uncaught exception is triggered by your code.
6355 will be called if an uncaught exception is triggered by your code.
6344
6356
6345 \layout Standard
6357 \layout Standard
6346
6358
6347 For stand-alone use of the feature in your programs which do not use IPython
6359 For stand-alone use of the feature in your programs which do not use IPython
6348 at all, put the following lines toward the top of your `main' routine:
6360 at all, put the following lines toward the top of your `main' routine:
6349 \layout Standard
6361 \layout Standard
6350 \align left
6362 \align left
6351
6363
6352 \family typewriter
6364 \family typewriter
6353 import sys,IPython.ultraTB
6365 import sys,IPython.ultraTB
6354 \newline
6366 \newline
6355 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6367 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6356 call_pdb=1)
6368 call_pdb=1)
6357 \layout Standard
6369 \layout Standard
6358
6370
6359 The
6371 The
6360 \family typewriter
6372 \family typewriter
6361 mode
6373 mode
6362 \family default
6374 \family default
6363 keyword can be either
6375 keyword can be either
6364 \family typewriter
6376 \family typewriter
6365 `Verbose'
6377 `Verbose'
6366 \family default
6378 \family default
6367 or
6379 or
6368 \family typewriter
6380 \family typewriter
6369 `Plain'
6381 `Plain'
6370 \family default
6382 \family default
6371 , giving either very detailed or normal tracebacks respectively.
6383 , giving either very detailed or normal tracebacks respectively.
6372 The
6384 The
6373 \family typewriter
6385 \family typewriter
6374 color_scheme
6386 color_scheme
6375 \family default
6387 \family default
6376 keyword can be one of
6388 keyword can be one of
6377 \family typewriter
6389 \family typewriter
6378 `NoColor'
6390 `NoColor'
6379 \family default
6391 \family default
6380 ,
6392 ,
6381 \family typewriter
6393 \family typewriter
6382 `Linux'
6394 `Linux'
6383 \family default
6395 \family default
6384 (default) or
6396 (default) or
6385 \family typewriter
6397 \family typewriter
6386 `LightBG'
6398 `LightBG'
6387 \family default
6399 \family default
6388 .
6400 .
6389 These are the same options which can be set in IPython with
6401 These are the same options which can be set in IPython with
6390 \family typewriter
6402 \family typewriter
6391 -colors
6403 -colors
6392 \family default
6404 \family default
6393 and
6405 and
6394 \family typewriter
6406 \family typewriter
6395 -xmode
6407 -xmode
6396 \family default
6408 \family default
6397 .
6409 .
6398 \layout Standard
6410 \layout Standard
6399
6411
6400 This will give any of your programs detailed, colored tracebacks with automatic
6412 This will give any of your programs detailed, colored tracebacks with automatic
6401 invocation of
6413 invocation of
6402 \family typewriter
6414 \family typewriter
6403 pdb
6415 pdb
6404 \family default
6416 \family default
6405 .
6417 .
6406 \layout Section
6418 \layout Section
6407
6419
6408
6420
6409 \begin_inset LatexCommand \label{sec:syntax-extensions}
6421 \begin_inset LatexCommand \label{sec:syntax-extensions}
6410
6422
6411 \end_inset
6423 \end_inset
6412
6424
6413 Extensions for syntax processing
6425 Extensions for syntax processing
6414 \layout Standard
6426 \layout Standard
6415
6427
6416 This isn't for the faint of heart, because the potential for breaking things
6428 This isn't for the faint of heart, because the potential for breaking things
6417 is quite high.
6429 is quite high.
6418 But it can be a very powerful and useful feature.
6430 But it can be a very powerful and useful feature.
6419 In a nutshell, you can redefine the way IPython processes the user input
6431 In a nutshell, you can redefine the way IPython processes the user input
6420 line to accept new, special extensions to the syntax without needing to
6432 line to accept new, special extensions to the syntax without needing to
6421 change any of IPython's own code.
6433 change any of IPython's own code.
6422 \layout Standard
6434 \layout Standard
6423
6435
6424 In the
6436 In the
6425 \family typewriter
6437 \family typewriter
6426 IPython/Extensions
6438 IPython/Extensions
6427 \family default
6439 \family default
6428 directory you will find some examples supplied, which we will briefly describe
6440 directory you will find some examples supplied, which we will briefly describe
6429 now.
6441 now.
6430 These can be used `as is' (and both provide very useful functionality),
6442 These can be used `as is' (and both provide very useful functionality),
6431 or you can use them as a starting point for writing your own extensions.
6443 or you can use them as a starting point for writing your own extensions.
6432 \layout Subsection
6444 \layout Subsection
6433
6445
6434 Pasting of code starting with
6446 Pasting of code starting with
6435 \family typewriter
6447 \family typewriter
6436 `>>>
6448 `>>>
6437 \family default
6449 \family default
6438 ' or
6450 ' or
6439 \family typewriter
6451 \family typewriter
6440 `...
6452 `...
6441
6453
6442 \family default
6454 \family default
6443 '
6455 '
6444 \layout Standard
6456 \layout Standard
6445
6457
6446 In the python tutorial it is common to find code examples which have been
6458 In the python tutorial it is common to find code examples which have been
6447 taken from real python sessions.
6459 taken from real python sessions.
6448 The problem with those is that all the lines begin with either
6460 The problem with those is that all the lines begin with either
6449 \family typewriter
6461 \family typewriter
6450 `>>>
6462 `>>>
6451 \family default
6463 \family default
6452 ' or
6464 ' or
6453 \family typewriter
6465 \family typewriter
6454 `...
6466 `...
6455
6467
6456 \family default
6468 \family default
6457 ', which makes it impossible to paste them all at once.
6469 ', which makes it impossible to paste them all at once.
6458 One must instead do a line by line manual copying, carefully removing the
6470 One must instead do a line by line manual copying, carefully removing the
6459 leading extraneous characters.
6471 leading extraneous characters.
6460 \layout Standard
6472 \layout Standard
6461
6473
6462 This extension identifies those starting characters and removes them from
6474 This extension identifies those starting characters and removes them from
6463 the input automatically, so that one can paste multi-line examples directly
6475 the input automatically, so that one can paste multi-line examples directly
6464 into IPython, saving a lot of time.
6476 into IPython, saving a lot of time.
6465 Please look at the file
6477 Please look at the file
6466 \family typewriter
6478 \family typewriter
6467 InterpreterPasteInput.py
6479 InterpreterPasteInput.py
6468 \family default
6480 \family default
6469 in the
6481 in the
6470 \family typewriter
6482 \family typewriter
6471 IPython/Extensions
6483 IPython/Extensions
6472 \family default
6484 \family default
6473 directory for details on how this is done.
6485 directory for details on how this is done.
6474 \layout Standard
6486 \layout Standard
6475
6487
6476 IPython comes with a special profile enabling this feature, called
6488 IPython comes with a special profile enabling this feature, called
6477 \family typewriter
6489 \family typewriter
6478 tutorial
6490 tutorial
6479 \family default
6491 \family default
6480 \emph on
6492 \emph on
6481 .
6493 .
6482
6494
6483 \emph default
6495 \emph default
6484 Simply start IPython via
6496 Simply start IPython via
6485 \family typewriter
6497 \family typewriter
6486 `ipython\SpecialChar ~
6498 `ipython\SpecialChar ~
6487 -p\SpecialChar ~
6499 -p\SpecialChar ~
6488 tutorial'
6500 tutorial'
6489 \family default
6501 \family default
6490 and the feature will be available.
6502 and the feature will be available.
6491 In a normal IPython session you can activate the feature by importing the
6503 In a normal IPython session you can activate the feature by importing the
6492 corresponding module with:
6504 corresponding module with:
6493 \newline
6505 \newline
6494
6506
6495 \family typewriter
6507 \family typewriter
6496 In [1]: import IPython.Extensions.InterpreterPasteInput
6508 In [1]: import IPython.Extensions.InterpreterPasteInput
6497 \layout Standard
6509 \layout Standard
6498
6510
6499 The following is a 'screenshot' of how things work when this extension is
6511 The following is a 'screenshot' of how things work when this extension is
6500 on, copying an example from the standard tutorial:
6512 on, copying an example from the standard tutorial:
6501 \layout Standard
6513 \layout Standard
6502
6514
6503
6515
6504 \family typewriter
6516 \family typewriter
6505 IPython profile: tutorial
6517 IPython profile: tutorial
6506 \newline
6518 \newline
6507 \SpecialChar ~
6519 \SpecialChar ~
6508
6520
6509 \newline
6521 \newline
6510 *** Pasting of code with ">>>" or "..." has been enabled.
6522 *** Pasting of code with ">>>" or "..." has been enabled.
6511 \newline
6523 \newline
6512 \SpecialChar ~
6524 \SpecialChar ~
6513
6525
6514 \newline
6526 \newline
6515 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6527 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6516 \newline
6528 \newline
6517
6529
6518 \begin_inset ERT
6530 \begin_inset ERT
6519 status Collapsed
6531 status Collapsed
6520
6532
6521 \layout Standard
6533 \layout Standard
6522
6534
6523 \backslash
6535 \backslash
6524 hspace*{0mm}
6536 hspace*{0mm}
6525 \end_inset
6537 \end_inset
6526
6538
6527 \SpecialChar ~
6539 \SpecialChar ~
6528 \SpecialChar ~
6540 \SpecialChar ~
6529 ...: ...\SpecialChar ~
6541 ...: ...\SpecialChar ~
6530 \SpecialChar ~
6542 \SpecialChar ~
6531 \SpecialChar ~
6543 \SpecialChar ~
6532 \SpecialChar ~
6544 \SpecialChar ~
6533 """Return a list containing the Fibonacci series up to n."""
6545 """Return a list containing the Fibonacci series up to n."""
6534 \newline
6546 \newline
6535
6547
6536 \begin_inset ERT
6548 \begin_inset ERT
6537 status Collapsed
6549 status Collapsed
6538
6550
6539 \layout Standard
6551 \layout Standard
6540
6552
6541 \backslash
6553 \backslash
6542 hspace*{0mm}
6554 hspace*{0mm}
6543 \end_inset
6555 \end_inset
6544
6556
6545 \SpecialChar ~
6557 \SpecialChar ~
6546 \SpecialChar ~
6558 \SpecialChar ~
6547 ...: ...\SpecialChar ~
6559 ...: ...\SpecialChar ~
6548 \SpecialChar ~
6560 \SpecialChar ~
6549 \SpecialChar ~
6561 \SpecialChar ~
6550 \SpecialChar ~
6562 \SpecialChar ~
6551 result = []
6563 result = []
6552 \newline
6564 \newline
6553
6565
6554 \begin_inset ERT
6566 \begin_inset ERT
6555 status Collapsed
6567 status Collapsed
6556
6568
6557 \layout Standard
6569 \layout Standard
6558
6570
6559 \backslash
6571 \backslash
6560 hspace*{0mm}
6572 hspace*{0mm}
6561 \end_inset
6573 \end_inset
6562
6574
6563 \SpecialChar ~
6575 \SpecialChar ~
6564 \SpecialChar ~
6576 \SpecialChar ~
6565 ...: ...\SpecialChar ~
6577 ...: ...\SpecialChar ~
6566 \SpecialChar ~
6578 \SpecialChar ~
6567 \SpecialChar ~
6579 \SpecialChar ~
6568 \SpecialChar ~
6580 \SpecialChar ~
6569 a, b = 0, 1
6581 a, b = 0, 1
6570 \newline
6582 \newline
6571
6583
6572 \begin_inset ERT
6584 \begin_inset ERT
6573 status Collapsed
6585 status Collapsed
6574
6586
6575 \layout Standard
6587 \layout Standard
6576
6588
6577 \backslash
6589 \backslash
6578 hspace*{0mm}
6590 hspace*{0mm}
6579 \end_inset
6591 \end_inset
6580
6592
6581 \SpecialChar ~
6593 \SpecialChar ~
6582 \SpecialChar ~
6594 \SpecialChar ~
6583 ...: ...\SpecialChar ~
6595 ...: ...\SpecialChar ~
6584 \SpecialChar ~
6596 \SpecialChar ~
6585 \SpecialChar ~
6597 \SpecialChar ~
6586 \SpecialChar ~
6598 \SpecialChar ~
6587 while b < n:
6599 while b < n:
6588 \newline
6600 \newline
6589
6601
6590 \begin_inset ERT
6602 \begin_inset ERT
6591 status Collapsed
6603 status Collapsed
6592
6604
6593 \layout Standard
6605 \layout Standard
6594
6606
6595 \backslash
6607 \backslash
6596 hspace*{0mm}
6608 hspace*{0mm}
6597 \end_inset
6609 \end_inset
6598
6610
6599 \SpecialChar ~
6611 \SpecialChar ~
6600 \SpecialChar ~
6612 \SpecialChar ~
6601 ...: ...\SpecialChar ~
6613 ...: ...\SpecialChar ~
6602 \SpecialChar ~
6614 \SpecialChar ~
6603 \SpecialChar ~
6615 \SpecialChar ~
6604 \SpecialChar ~
6616 \SpecialChar ~
6605 \SpecialChar ~
6617 \SpecialChar ~
6606 \SpecialChar ~
6618 \SpecialChar ~
6607 \SpecialChar ~
6619 \SpecialChar ~
6608 \SpecialChar ~
6620 \SpecialChar ~
6609 result.append(b)\SpecialChar ~
6621 result.append(b)\SpecialChar ~
6610 \SpecialChar ~
6622 \SpecialChar ~
6611 \SpecialChar ~
6623 \SpecialChar ~
6612 # see below
6624 # see below
6613 \newline
6625 \newline
6614
6626
6615 \begin_inset ERT
6627 \begin_inset ERT
6616 status Collapsed
6628 status Collapsed
6617
6629
6618 \layout Standard
6630 \layout Standard
6619
6631
6620 \backslash
6632 \backslash
6621 hspace*{0mm}
6633 hspace*{0mm}
6622 \end_inset
6634 \end_inset
6623
6635
6624 \SpecialChar ~
6636 \SpecialChar ~
6625 \SpecialChar ~
6637 \SpecialChar ~
6626 ...: ...\SpecialChar ~
6638 ...: ...\SpecialChar ~
6627 \SpecialChar ~
6639 \SpecialChar ~
6628 \SpecialChar ~
6640 \SpecialChar ~
6629 \SpecialChar ~
6641 \SpecialChar ~
6630 \SpecialChar ~
6642 \SpecialChar ~
6631 \SpecialChar ~
6643 \SpecialChar ~
6632 \SpecialChar ~
6644 \SpecialChar ~
6633 \SpecialChar ~
6645 \SpecialChar ~
6634 a, b = b, a+b
6646 a, b = b, a+b
6635 \newline
6647 \newline
6636
6648
6637 \begin_inset ERT
6649 \begin_inset ERT
6638 status Collapsed
6650 status Collapsed
6639
6651
6640 \layout Standard
6652 \layout Standard
6641
6653
6642 \backslash
6654 \backslash
6643 hspace*{0mm}
6655 hspace*{0mm}
6644 \end_inset
6656 \end_inset
6645
6657
6646 \SpecialChar ~
6658 \SpecialChar ~
6647 \SpecialChar ~
6659 \SpecialChar ~
6648 ...: ...\SpecialChar ~
6660 ...: ...\SpecialChar ~
6649 \SpecialChar ~
6661 \SpecialChar ~
6650 \SpecialChar ~
6662 \SpecialChar ~
6651 \SpecialChar ~
6663 \SpecialChar ~
6652 return result
6664 return result
6653 \newline
6665 \newline
6654
6666
6655 \begin_inset ERT
6667 \begin_inset ERT
6656 status Collapsed
6668 status Collapsed
6657
6669
6658 \layout Standard
6670 \layout Standard
6659
6671
6660 \backslash
6672 \backslash
6661 hspace*{0mm}
6673 hspace*{0mm}
6662 \end_inset
6674 \end_inset
6663
6675
6664 \SpecialChar ~
6676 \SpecialChar ~
6665 \SpecialChar ~
6677 \SpecialChar ~
6666 ...:
6678 ...:
6667 \newline
6679 \newline
6668 \SpecialChar ~
6680 \SpecialChar ~
6669
6681
6670 \newline
6682 \newline
6671 In [2]: fib2(10)
6683 In [2]: fib2(10)
6672 \newline
6684 \newline
6673 Out[2]: [1, 1, 2, 3, 5, 8]
6685 Out[2]: [1, 1, 2, 3, 5, 8]
6674 \layout Standard
6686 \layout Standard
6675
6687
6676 Note that as currently written, this extension does
6688 Note that as currently written, this extension does
6677 \emph on
6689 \emph on
6678 not
6690 not
6679 \emph default
6691 \emph default
6680 recognize IPython's prompts for pasting.
6692 recognize IPython's prompts for pasting.
6681 Those are more complicated, since the user can change them very easily,
6693 Those are more complicated, since the user can change them very easily,
6682 they involve numbers and can vary in length.
6694 they involve numbers and can vary in length.
6683 One could however extract all the relevant information from the IPython
6695 One could however extract all the relevant information from the IPython
6684 instance and build an appropriate regular expression.
6696 instance and build an appropriate regular expression.
6685 This is left as an exercise for the reader.
6697 This is left as an exercise for the reader.
6686 \layout Subsection
6698 \layout Subsection
6687
6699
6688 Input of physical quantities with units
6700 Input of physical quantities with units
6689 \layout Standard
6701 \layout Standard
6690
6702
6691 The module
6703 The module
6692 \family typewriter
6704 \family typewriter
6693 PhysicalQInput
6705 PhysicalQInput
6694 \family default
6706 \family default
6695 allows a simplified form of input for physical quantities with units.
6707 allows a simplified form of input for physical quantities with units.
6696 This file is meant to be used in conjunction with the
6708 This file is meant to be used in conjunction with the
6697 \family typewriter
6709 \family typewriter
6698 PhysicalQInteractive
6710 PhysicalQInteractive
6699 \family default
6711 \family default
6700 module (in the same directory) and
6712 module (in the same directory) and
6701 \family typewriter
6713 \family typewriter
6702 Physics.PhysicalQuantities
6714 Physics.PhysicalQuantities
6703 \family default
6715 \family default
6704 from Konrad Hinsen's ScientificPython (
6716 from Konrad Hinsen's ScientificPython (
6705 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
6717 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
6706
6718
6707 \end_inset
6719 \end_inset
6708
6720
6709 ).
6721 ).
6710 \layout Standard
6722 \layout Standard
6711
6723
6712 The
6724 The
6713 \family typewriter
6725 \family typewriter
6714 Physics.PhysicalQuantities
6726 Physics.PhysicalQuantities
6715 \family default
6727 \family default
6716 module defines
6728 module defines
6717 \family typewriter
6729 \family typewriter
6718 PhysicalQuantity
6730 PhysicalQuantity
6719 \family default
6731 \family default
6720 objects, but these must be declared as instances of a class.
6732 objects, but these must be declared as instances of a class.
6721 For example, to define
6733 For example, to define
6722 \family typewriter
6734 \family typewriter
6723 v
6735 v
6724 \family default
6736 \family default
6725 as a velocity of 3\SpecialChar ~
6737 as a velocity of 3\SpecialChar ~
6726 m/s, normally you would write:
6738 m/s, normally you would write:
6727 \family typewriter
6739 \family typewriter
6728
6740
6729 \newline
6741 \newline
6730 In [1]: v = PhysicalQuantity(3,'m/s')
6742 In [1]: v = PhysicalQuantity(3,'m/s')
6731 \layout Standard
6743 \layout Standard
6732
6744
6733 Using the
6745 Using the
6734 \family typewriter
6746 \family typewriter
6735 PhysicalQ_Input
6747 PhysicalQ_Input
6736 \family default
6748 \family default
6737 extension this can be input instead as:
6749 extension this can be input instead as:
6738 \family typewriter
6750 \family typewriter
6739
6751
6740 \newline
6752 \newline
6741 In [1]: v = 3 m/s
6753 In [1]: v = 3 m/s
6742 \family default
6754 \family default
6743
6755
6744 \newline
6756 \newline
6745 which is much more convenient for interactive use (even though it is blatantly
6757 which is much more convenient for interactive use (even though it is blatantly
6746 invalid Python syntax).
6758 invalid Python syntax).
6747 \layout Standard
6759 \layout Standard
6748
6760
6749 The
6761 The
6750 \family typewriter
6762 \family typewriter
6751 physics
6763 physics
6752 \family default
6764 \family default
6753 profile supplied with IPython (enabled via
6765 profile supplied with IPython (enabled via
6754 \family typewriter
6766 \family typewriter
6755 'ipython -p physics'
6767 'ipython -p physics'
6756 \family default
6768 \family default
6757 ) uses these extensions, which you can also activate with:
6769 ) uses these extensions, which you can also activate with:
6758 \layout Standard
6770 \layout Standard
6759
6771
6760
6772
6761 \family typewriter
6773 \family typewriter
6762 from math import * # math MUST be imported BEFORE PhysicalQInteractive
6774 from math import * # math MUST be imported BEFORE PhysicalQInteractive
6763 \newline
6775 \newline
6764 from IPython.Extensions.PhysicalQInteractive import *
6776 from IPython.Extensions.PhysicalQInteractive import *
6765 \newline
6777 \newline
6766 import IPython.Extensions.PhysicalQInput
6778 import IPython.Extensions.PhysicalQInput
6767 \layout Section
6779 \layout Section
6768
6780
6769 IPython as a system shell
6781 IPython as a system shell
6770 \layout Standard
6782 \layout Standard
6771
6783
6772 IPython ships with a special profile called
6784 IPython ships with a special profile called
6773 \family typewriter
6785 \family typewriter
6774 pysh
6786 pysh
6775 \family default
6787 \family default
6776 , which you can activate at the command line as
6788 , which you can activate at the command line as
6777 \family typewriter
6789 \family typewriter
6778 `ipython -p pysh'
6790 `ipython -p pysh'
6779 \family default
6791 \family default
6780 .
6792 .
6781 This loads
6793 This loads
6782 \family typewriter
6794 \family typewriter
6783 InterpreterExec
6795 InterpreterExec
6784 \family default
6796 \family default
6785 , along with some additional facilities and a prompt customized for filesystem
6797 , along with some additional facilities and a prompt customized for filesystem
6786 navigation.
6798 navigation.
6787 \layout Standard
6799 \layout Standard
6788
6800
6789 Note that this does
6801 Note that this does
6790 \emph on
6802 \emph on
6791 not
6803 not
6792 \emph default
6804 \emph default
6793 make IPython a full-fledged system shell.
6805 make IPython a full-fledged system shell.
6794 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
6806 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
6795 you'll suspend pysh itself, not the process you just started.
6807 you'll suspend pysh itself, not the process you just started.
6796
6808
6797 \layout Standard
6809 \layout Standard
6798
6810
6799 What the shell profile allows you to do is to use the convenient and powerful
6811 What the shell profile allows you to do is to use the convenient and powerful
6800 syntax of Python to do quick scripting at the command line.
6812 syntax of Python to do quick scripting at the command line.
6801 Below we describe some of its features.
6813 Below we describe some of its features.
6802 \layout Subsection
6814 \layout Subsection
6803
6815
6804 Aliases
6816 Aliases
6805 \layout Standard
6817 \layout Standard
6806
6818
6807 All of your
6819 All of your
6808 \family typewriter
6820 \family typewriter
6809 $PATH
6821 $PATH
6810 \family default
6822 \family default
6811 has been loaded as IPython aliases, so you should be able to type any normal
6823 has been loaded as IPython aliases, so you should be able to type any normal
6812 system command and have it executed.
6824 system command and have it executed.
6813 See
6825 See
6814 \family typewriter
6826 \family typewriter
6815 %alias?
6827 %alias?
6816 \family default
6828 \family default
6817 and
6829 and
6818 \family typewriter
6830 \family typewriter
6819 %unalias?
6831 %unalias?
6820 \family default
6832 \family default
6821 for details on the alias facilities.
6833 for details on the alias facilities.
6822 See also
6834 See also
6823 \family typewriter
6835 \family typewriter
6824 %rehash?
6836 %rehash?
6825 \family default
6837 \family default
6826 and
6838 and
6827 \family typewriter
6839 \family typewriter
6828 %rehashx?
6840 %rehashx?
6829 \family default
6841 \family default
6830 for details on the mechanism used to load
6842 for details on the mechanism used to load
6831 \family typewriter
6843 \family typewriter
6832 $PATH
6844 $PATH
6833 \family default
6845 \family default
6834 .
6846 .
6835 \layout Subsection
6847 \layout Subsection
6836
6848
6837 Special syntax
6849 Special syntax
6838 \layout Standard
6850 \layout Standard
6839
6851
6840 Any lines which begin with
6852 Any lines which begin with
6841 \family typewriter
6853 \family typewriter
6842 `~'
6854 `~'
6843 \family default
6855 \family default
6844 ,
6856 ,
6845 \family typewriter
6857 \family typewriter
6846 `/'
6858 `/'
6847 \family default
6859 \family default
6848 and
6860 and
6849 \family typewriter
6861 \family typewriter
6850 `.'
6862 `.'
6851 \family default
6863 \family default
6852 will be executed as shell commands instead of as Python code.
6864 will be executed as shell commands instead of as Python code.
6853 The special escapes below are also recognized.
6865 The special escapes below are also recognized.
6854
6866
6855 \family typewriter
6867 \family typewriter
6856 !cmd
6868 !cmd
6857 \family default
6869 \family default
6858 is valid in single or multi-line input, all others are only valid in single-lin
6870 is valid in single or multi-line input, all others are only valid in single-lin
6859 e input:
6871 e input:
6860 \layout Description
6872 \layout Description
6861
6873
6862
6874
6863 \family typewriter
6875 \family typewriter
6864 !cmd
6876 !cmd
6865 \family default
6877 \family default
6866 pass `cmd' directly to the shell
6878 pass `cmd' directly to the shell
6867 \layout Description
6879 \layout Description
6868
6880
6869
6881
6870 \family typewriter
6882 \family typewriter
6871 !!cmd
6883 !!cmd
6872 \family default
6884 \family default
6873 execute `cmd' and return output as a list (split on `
6885 execute `cmd' and return output as a list (split on `
6874 \backslash
6886 \backslash
6875 n')
6887 n')
6876 \layout Description
6888 \layout Description
6877
6889
6878
6890
6879 \family typewriter
6891 \family typewriter
6880 $var=cmd
6892 $var=cmd
6881 \family default
6893 \family default
6882 capture output of cmd into var, as a string
6894 capture output of cmd into var, as a string
6883 \layout Description
6895 \layout Description
6884
6896
6885
6897
6886 \family typewriter
6898 \family typewriter
6887 $$var=cmd
6899 $$var=cmd
6888 \family default
6900 \family default
6889 capture output of cmd into var, as a list (split on `
6901 capture output of cmd into var, as a list (split on `
6890 \backslash
6902 \backslash
6891 n')
6903 n')
6892 \layout Standard
6904 \layout Standard
6893
6905
6894 The
6906 The
6895 \family typewriter
6907 \family typewriter
6896 $
6908 $
6897 \family default
6909 \family default
6898 /
6910 /
6899 \family typewriter
6911 \family typewriter
6900 $$
6912 $$
6901 \family default
6913 \family default
6902 syntaxes make Python variables from system output, which you can later
6914 syntaxes make Python variables from system output, which you can later
6903 use for further scripting.
6915 use for further scripting.
6904 The converse is also possible: when executing an alias or calling to the
6916 The converse is also possible: when executing an alias or calling to the
6905 system via
6917 system via
6906 \family typewriter
6918 \family typewriter
6907 !
6919 !
6908 \family default
6920 \family default
6909 /
6921 /
6910 \family typewriter
6922 \family typewriter
6911 !!
6923 !!
6912 \family default
6924 \family default
6913 , you can expand any python variable or expression by prepending it with
6925 , you can expand any python variable or expression by prepending it with
6914
6926
6915 \family typewriter
6927 \family typewriter
6916 $
6928 $
6917 \family default
6929 \family default
6918 .
6930 .
6919 Full details of the allowed syntax can be found in Python's PEP 215.
6931 Full details of the allowed syntax can be found in Python's PEP 215.
6920 \layout Standard
6932 \layout Standard
6921
6933
6922 A few brief examples will illustrate these (note that the indentation below
6934 A few brief examples will illustrate these (note that the indentation below
6923 may be incorrectly displayed):
6935 may be incorrectly displayed):
6924 \layout Standard
6936 \layout Standard
6925
6937
6926
6938
6927 \family typewriter
6939 \family typewriter
6928 fperez[~/test]|3> !ls *s.py
6940 fperez[~/test]|3> !ls *s.py
6929 \newline
6941 \newline
6930 scopes.py strings.py
6942 scopes.py strings.py
6931 \layout Standard
6943 \layout Standard
6932
6944
6933 ls is an internal alias, so there's no need to use
6945 ls is an internal alias, so there's no need to use
6934 \family typewriter
6946 \family typewriter
6935 !
6947 !
6936 \family default
6948 \family default
6937 :
6949 :
6938 \layout Standard
6950 \layout Standard
6939
6951
6940
6952
6941 \family typewriter
6953 \family typewriter
6942 fperez[~/test]|4> ls *s.py
6954 fperez[~/test]|4> ls *s.py
6943 \newline
6955 \newline
6944 scopes.py* strings.py
6956 scopes.py* strings.py
6945 \layout Standard
6957 \layout Standard
6946
6958
6947 !!ls will return the output into a Python variable:
6959 !!ls will return the output into a Python variable:
6948 \layout Standard
6960 \layout Standard
6949
6961
6950
6962
6951 \family typewriter
6963 \family typewriter
6952 fperez[~/test]|5> !!ls *s.py
6964 fperez[~/test]|5> !!ls *s.py
6953 \newline
6965 \newline
6954
6966
6955 \begin_inset ERT
6967 \begin_inset ERT
6956 status Collapsed
6968 status Collapsed
6957
6969
6958 \layout Standard
6970 \layout Standard
6959
6971
6960 \backslash
6972 \backslash
6961 hspace*{0mm}
6973 hspace*{0mm}
6962 \end_inset
6974 \end_inset
6963
6975
6964 \SpecialChar ~
6976 \SpecialChar ~
6965 \SpecialChar ~
6977 \SpecialChar ~
6966 \SpecialChar ~
6978 \SpecialChar ~
6967 \SpecialChar ~
6979 \SpecialChar ~
6968 \SpecialChar ~
6980 \SpecialChar ~
6969 \SpecialChar ~
6981 \SpecialChar ~
6970 \SpecialChar ~
6982 \SpecialChar ~
6971 \SpecialChar ~
6983 \SpecialChar ~
6972 \SpecialChar ~
6984 \SpecialChar ~
6973 \SpecialChar ~
6985 \SpecialChar ~
6974 \SpecialChar ~
6986 \SpecialChar ~
6975 \SpecialChar ~
6987 \SpecialChar ~
6976 \SpecialChar ~
6988 \SpecialChar ~
6977 \SpecialChar ~
6989 \SpecialChar ~
6978 <5> ['scopes.py', 'strings.py']
6990 <5> ['scopes.py', 'strings.py']
6979 \newline
6991 \newline
6980 fperez[~/test]|6> print _5
6992 fperez[~/test]|6> print _5
6981 \newline
6993 \newline
6982 ['scopes.py', 'strings.py']
6994 ['scopes.py', 'strings.py']
6983 \layout Standard
6995 \layout Standard
6984
6996
6985
6997
6986 \family typewriter
6998 \family typewriter
6987 $
6999 $
6988 \family default
7000 \family default
6989 and
7001 and
6990 \family typewriter
7002 \family typewriter
6991 $$
7003 $$
6992 \family default
7004 \family default
6993 allow direct capture to named variables:
7005 allow direct capture to named variables:
6994 \layout Standard
7006 \layout Standard
6995
7007
6996
7008
6997 \family typewriter
7009 \family typewriter
6998 fperez[~/test]|7> $astr = ls *s.py
7010 fperez[~/test]|7> $astr = ls *s.py
6999 \newline
7011 \newline
7000 fperez[~/test]|8> astr
7012 fperez[~/test]|8> astr
7001 \newline
7013 \newline
7002
7014
7003 \begin_inset ERT
7015 \begin_inset ERT
7004 status Collapsed
7016 status Collapsed
7005
7017
7006 \layout Standard
7018 \layout Standard
7007
7019
7008 \backslash
7020 \backslash
7009 hspace*{0mm}
7021 hspace*{0mm}
7010 \end_inset
7022 \end_inset
7011
7023
7012 \SpecialChar ~
7024 \SpecialChar ~
7013 \SpecialChar ~
7025 \SpecialChar ~
7014 \SpecialChar ~
7026 \SpecialChar ~
7015 \SpecialChar ~
7027 \SpecialChar ~
7016 \SpecialChar ~
7028 \SpecialChar ~
7017 \SpecialChar ~
7029 \SpecialChar ~
7018 \SpecialChar ~
7030 \SpecialChar ~
7019 \SpecialChar ~
7031 \SpecialChar ~
7020 \SpecialChar ~
7032 \SpecialChar ~
7021 \SpecialChar ~
7033 \SpecialChar ~
7022 \SpecialChar ~
7034 \SpecialChar ~
7023 \SpecialChar ~
7035 \SpecialChar ~
7024 \SpecialChar ~
7036 \SpecialChar ~
7025 \SpecialChar ~
7037 \SpecialChar ~
7026 <8> 'scopes.py
7038 <8> 'scopes.py
7027 \backslash
7039 \backslash
7028 nstrings.py'
7040 nstrings.py'
7029 \layout Standard
7041 \layout Standard
7030
7042
7031
7043
7032 \family typewriter
7044 \family typewriter
7033 fperez[~/test]|9> $$alist = ls *s.py
7045 fperez[~/test]|9> $$alist = ls *s.py
7034 \newline
7046 \newline
7035 fperez[~/test]|10> alist
7047 fperez[~/test]|10> alist
7036 \newline
7048 \newline
7037
7049
7038 \begin_inset ERT
7050 \begin_inset ERT
7039 status Collapsed
7051 status Collapsed
7040
7052
7041 \layout Standard
7053 \layout Standard
7042
7054
7043 \backslash
7055 \backslash
7044 hspace*{0mm}
7056 hspace*{0mm}
7045 \end_inset
7057 \end_inset
7046
7058
7047 \SpecialChar ~
7059 \SpecialChar ~
7048 \SpecialChar ~
7060 \SpecialChar ~
7049 \SpecialChar ~
7061 \SpecialChar ~
7050 \SpecialChar ~
7062 \SpecialChar ~
7051 \SpecialChar ~
7063 \SpecialChar ~
7052 \SpecialChar ~
7064 \SpecialChar ~
7053 \SpecialChar ~
7065 \SpecialChar ~
7054 \SpecialChar ~
7066 \SpecialChar ~
7055 \SpecialChar ~
7067 \SpecialChar ~
7056 \SpecialChar ~
7068 \SpecialChar ~
7057 \SpecialChar ~
7069 \SpecialChar ~
7058 \SpecialChar ~
7070 \SpecialChar ~
7059 \SpecialChar ~
7071 \SpecialChar ~
7060 \SpecialChar ~
7072 \SpecialChar ~
7061 <10> ['scopes.py', 'strings.py']
7073 <10> ['scopes.py', 'strings.py']
7062 \layout Standard
7074 \layout Standard
7063
7075
7064 alist is now a normal python list you can loop over.
7076 alist is now a normal python list you can loop over.
7065 Using
7077 Using
7066 \family typewriter
7078 \family typewriter
7067 $
7079 $
7068 \family default
7080 \family default
7069 will expand back the python values when alias calls are made:
7081 will expand back the python values when alias calls are made:
7070 \layout Standard
7082 \layout Standard
7071
7083
7072
7084
7073 \family typewriter
7085 \family typewriter
7074 fperez[~/test]|11> for f in alist:
7086 fperez[~/test]|11> for f in alist:
7075 \newline
7087 \newline
7076
7088
7077 \begin_inset ERT
7089 \begin_inset ERT
7078 status Collapsed
7090 status Collapsed
7079
7091
7080 \layout Standard
7092 \layout Standard
7081
7093
7082 \backslash
7094 \backslash
7083 hspace*{0mm}
7095 hspace*{0mm}
7084 \end_inset
7096 \end_inset
7085
7097
7086 \SpecialChar ~
7098 \SpecialChar ~
7087 \SpecialChar ~
7099 \SpecialChar ~
7088 \SpecialChar ~
7100 \SpecialChar ~
7089 \SpecialChar ~
7101 \SpecialChar ~
7090 \SpecialChar ~
7102 \SpecialChar ~
7091 \SpecialChar ~
7103 \SpecialChar ~
7092 \SpecialChar ~
7104 \SpecialChar ~
7093 \SpecialChar ~
7105 \SpecialChar ~
7094 \SpecialChar ~
7106 \SpecialChar ~
7095 \SpecialChar ~
7107 \SpecialChar ~
7096 \SpecialChar ~
7108 \SpecialChar ~
7097 \SpecialChar ~
7109 \SpecialChar ~
7098 \SpecialChar ~
7110 \SpecialChar ~
7099 \SpecialChar ~
7111 \SpecialChar ~
7100 |..> \SpecialChar ~
7112 |..> \SpecialChar ~
7101 \SpecialChar ~
7113 \SpecialChar ~
7102 \SpecialChar ~
7114 \SpecialChar ~
7103 \SpecialChar ~
7115 \SpecialChar ~
7104 print 'file',f,
7116 print 'file',f,
7105 \newline
7117 \newline
7106
7118
7107 \begin_inset ERT
7119 \begin_inset ERT
7108 status Collapsed
7120 status Collapsed
7109
7121
7110 \layout Standard
7122 \layout Standard
7111
7123
7112 \backslash
7124 \backslash
7113 hspace*{0mm}
7125 hspace*{0mm}
7114 \end_inset
7126 \end_inset
7115
7127
7116 \SpecialChar ~
7128 \SpecialChar ~
7117 \SpecialChar ~
7129 \SpecialChar ~
7118 \SpecialChar ~
7130 \SpecialChar ~
7119 \SpecialChar ~
7131 \SpecialChar ~
7120 \SpecialChar ~
7132 \SpecialChar ~
7121 \SpecialChar ~
7133 \SpecialChar ~
7122 \SpecialChar ~
7134 \SpecialChar ~
7123 \SpecialChar ~
7135 \SpecialChar ~
7124 \SpecialChar ~
7136 \SpecialChar ~
7125 \SpecialChar ~
7137 \SpecialChar ~
7126 \SpecialChar ~
7138 \SpecialChar ~
7127 \SpecialChar ~
7139 \SpecialChar ~
7128 \SpecialChar ~
7140 \SpecialChar ~
7129 \SpecialChar ~
7141 \SpecialChar ~
7130 |..> \SpecialChar ~
7142 |..> \SpecialChar ~
7131 \SpecialChar ~
7143 \SpecialChar ~
7132 \SpecialChar ~
7144 \SpecialChar ~
7133 \SpecialChar ~
7145 \SpecialChar ~
7134 wc -l $f
7146 wc -l $f
7135 \newline
7147 \newline
7136
7148
7137 \begin_inset ERT
7149 \begin_inset ERT
7138 status Collapsed
7150 status Collapsed
7139
7151
7140 \layout Standard
7152 \layout Standard
7141
7153
7142 \backslash
7154 \backslash
7143 hspace*{0mm}
7155 hspace*{0mm}
7144 \end_inset
7156 \end_inset
7145
7157
7146 \SpecialChar ~
7158 \SpecialChar ~
7147 \SpecialChar ~
7159 \SpecialChar ~
7148 \SpecialChar ~
7160 \SpecialChar ~
7149 \SpecialChar ~
7161 \SpecialChar ~
7150 \SpecialChar ~
7162 \SpecialChar ~
7151 \SpecialChar ~
7163 \SpecialChar ~
7152 \SpecialChar ~
7164 \SpecialChar ~
7153 \SpecialChar ~
7165 \SpecialChar ~
7154 \SpecialChar ~
7166 \SpecialChar ~
7155 \SpecialChar ~
7167 \SpecialChar ~
7156 \SpecialChar ~
7168 \SpecialChar ~
7157 \SpecialChar ~
7169 \SpecialChar ~
7158 \SpecialChar ~
7170 \SpecialChar ~
7159 \SpecialChar ~
7171 \SpecialChar ~
7160 |..>
7172 |..>
7161 \newline
7173 \newline
7162 file scopes.py 13 scopes.py
7174 file scopes.py 13 scopes.py
7163 \newline
7175 \newline
7164 file strings.py 4 strings.py
7176 file strings.py 4 strings.py
7165 \layout Standard
7177 \layout Standard
7166
7178
7167 Note that you may need to protect your variables with braces if you want
7179 Note that you may need to protect your variables with braces if you want
7168 to append strings to their names.
7180 to append strings to their names.
7169 To copy all files in alist to
7181 To copy all files in alist to
7170 \family typewriter
7182 \family typewriter
7171 .bak
7183 .bak
7172 \family default
7184 \family default
7173 extensions, you must use:
7185 extensions, you must use:
7174 \layout Standard
7186 \layout Standard
7175
7187
7176
7188
7177 \family typewriter
7189 \family typewriter
7178 fperez[~/test]|12> for f in alist:
7190 fperez[~/test]|12> for f in alist:
7179 \newline
7191 \newline
7180
7192
7181 \begin_inset ERT
7193 \begin_inset ERT
7182 status Collapsed
7194 status Collapsed
7183
7195
7184 \layout Standard
7196 \layout Standard
7185
7197
7186 \backslash
7198 \backslash
7187 hspace*{0mm}
7199 hspace*{0mm}
7188 \end_inset
7200 \end_inset
7189
7201
7190 \SpecialChar ~
7202 \SpecialChar ~
7191 \SpecialChar ~
7203 \SpecialChar ~
7192 \SpecialChar ~
7204 \SpecialChar ~
7193 \SpecialChar ~
7205 \SpecialChar ~
7194 \SpecialChar ~
7206 \SpecialChar ~
7195 \SpecialChar ~
7207 \SpecialChar ~
7196 \SpecialChar ~
7208 \SpecialChar ~
7197 \SpecialChar ~
7209 \SpecialChar ~
7198 \SpecialChar ~
7210 \SpecialChar ~
7199 \SpecialChar ~
7211 \SpecialChar ~
7200 \SpecialChar ~
7212 \SpecialChar ~
7201 \SpecialChar ~
7213 \SpecialChar ~
7202 \SpecialChar ~
7214 \SpecialChar ~
7203 \SpecialChar ~
7215 \SpecialChar ~
7204 |..> \SpecialChar ~
7216 |..> \SpecialChar ~
7205 \SpecialChar ~
7217 \SpecialChar ~
7206 \SpecialChar ~
7218 \SpecialChar ~
7207 \SpecialChar ~
7219 \SpecialChar ~
7208 cp $f ${f}.bak
7220 cp $f ${f}.bak
7209 \layout Standard
7221 \layout Standard
7210
7222
7211 If you try using
7223 If you try using
7212 \family typewriter
7224 \family typewriter
7213 $f.bak
7225 $f.bak
7214 \family default
7226 \family default
7215 , you'll get an AttributeError exception saying that your string object
7227 , you'll get an AttributeError exception saying that your string object
7216 doesn't have a
7228 doesn't have a
7217 \family typewriter
7229 \family typewriter
7218 .bak
7230 .bak
7219 \family default
7231 \family default
7220 attribute.
7232 attribute.
7221 This is because the
7233 This is because the
7222 \family typewriter
7234 \family typewriter
7223 $
7235 $
7224 \family default
7236 \family default
7225 expansion mechanism allows you to expand full Python expressions:
7237 expansion mechanism allows you to expand full Python expressions:
7226 \layout Standard
7238 \layout Standard
7227
7239
7228
7240
7229 \family typewriter
7241 \family typewriter
7230 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7242 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7231 \newline
7243 \newline
7232 sys.platform is: linux2
7244 sys.platform is: linux2
7233 \layout Standard
7245 \layout Standard
7234
7246
7235 IPython's input history handling is still active, which allows you to rerun
7247 IPython's input history handling is still active, which allows you to rerun
7236 a single block of multi-line input by simply using exec:
7248 a single block of multi-line input by simply using exec:
7237 \newline
7249 \newline
7238
7250
7239 \family typewriter
7251 \family typewriter
7240 fperez[~/test]|14> $$alist = ls *.eps
7252 fperez[~/test]|14> $$alist = ls *.eps
7241 \newline
7253 \newline
7242 fperez[~/test]|15> exec _i11
7254 fperez[~/test]|15> exec _i11
7243 \newline
7255 \newline
7244 file image2.eps 921 image2.eps
7256 file image2.eps 921 image2.eps
7245 \newline
7257 \newline
7246 file image.eps 921 image.eps
7258 file image.eps 921 image.eps
7247 \layout Standard
7259 \layout Standard
7248
7260
7249 While these are new special-case syntaxes, they are designed to allow very
7261 While these are new special-case syntaxes, they are designed to allow very
7250 efficient use of the shell with minimal typing.
7262 efficient use of the shell with minimal typing.
7251 At an interactive shell prompt, conciseness of expression wins over readability.
7263 At an interactive shell prompt, conciseness of expression wins over readability.
7252 \layout Subsection
7264 \layout Subsection
7253
7265
7254 Useful functions and modules
7266 Useful functions and modules
7255 \layout Standard
7267 \layout Standard
7256
7268
7257 The os, sys and shutil modules from the Python standard library are automaticall
7269 The os, sys and shutil modules from the Python standard library are automaticall
7258 y loaded.
7270 y loaded.
7259 Some additional functions, useful for shell usage, are listed below.
7271 Some additional functions, useful for shell usage, are listed below.
7260 You can request more help about them with `
7272 You can request more help about them with `
7261 \family typewriter
7273 \family typewriter
7262 ?
7274 ?
7263 \family default
7275 \family default
7264 '.
7276 '.
7265 \layout Description
7277 \layout Description
7266
7278
7267
7279
7268 \family typewriter
7280 \family typewriter
7269 shell
7281 shell
7270 \family default
7282 \family default
7271 - execute a command in the underlying system shell
7283 - execute a command in the underlying system shell
7272 \layout Description
7284 \layout Description
7273
7285
7274
7286
7275 \family typewriter
7287 \family typewriter
7276 system
7288 system
7277 \family default
7289 \family default
7278 - like
7290 - like
7279 \family typewriter
7291 \family typewriter
7280 shell()
7292 shell()
7281 \family default
7293 \family default
7282 , but return the exit status of the command
7294 , but return the exit status of the command
7283 \layout Description
7295 \layout Description
7284
7296
7285
7297
7286 \family typewriter
7298 \family typewriter
7287 sout
7299 sout
7288 \family default
7300 \family default
7289 - capture the output of a command as a string
7301 - capture the output of a command as a string
7290 \layout Description
7302 \layout Description
7291
7303
7292
7304
7293 \family typewriter
7305 \family typewriter
7294 lout
7306 lout
7295 \family default
7307 \family default
7296 - capture the output of a command as a list (split on `
7308 - capture the output of a command as a list (split on `
7297 \backslash
7309 \backslash
7298 n')
7310 n')
7299 \layout Description
7311 \layout Description
7300
7312
7301
7313
7302 \family typewriter
7314 \family typewriter
7303 getoutputerror
7315 getoutputerror
7304 \family default
7316 \family default
7305 - capture (output,error) of a shell commandss
7317 - capture (output,error) of a shell commandss
7306 \layout Standard
7318 \layout Standard
7307
7319
7308
7320
7309 \family typewriter
7321 \family typewriter
7310 sout
7322 sout
7311 \family default
7323 \family default
7312 /
7324 /
7313 \family typewriter
7325 \family typewriter
7314 lout
7326 lout
7315 \family default
7327 \family default
7316 are the functional equivalents of
7328 are the functional equivalents of
7317 \family typewriter
7329 \family typewriter
7318 $
7330 $
7319 \family default
7331 \family default
7320 /
7332 /
7321 \family typewriter
7333 \family typewriter
7322 $$
7334 $$
7323 \family default
7335 \family default
7324 .
7336 .
7325 They are provided to allow you to capture system output in the middle of
7337 They are provided to allow you to capture system output in the middle of
7326 true python code, function definitions, etc (where
7338 true python code, function definitions, etc (where
7327 \family typewriter
7339 \family typewriter
7328 $
7340 $
7329 \family default
7341 \family default
7330 and
7342 and
7331 \family typewriter
7343 \family typewriter
7332 $$
7344 $$
7333 \family default
7345 \family default
7334 are invalid).
7346 are invalid).
7335 \layout Subsection
7347 \layout Subsection
7336
7348
7337 Directory management
7349 Directory management
7338 \layout Standard
7350 \layout Standard
7339
7351
7340 Since each command passed by pysh to the underlying system is executed in
7352 Since each command passed by pysh to the underlying system is executed in
7341 a subshell which exits immediately, you can NOT use !cd to navigate the
7353 a subshell which exits immediately, you can NOT use !cd to navigate the
7342 filesystem.
7354 filesystem.
7343 \layout Standard
7355 \layout Standard
7344
7356
7345 Pysh provides its own builtin
7357 Pysh provides its own builtin
7346 \family typewriter
7358 \family typewriter
7347 `%cd
7359 `%cd
7348 \family default
7360 \family default
7349 ' magic command to move in the filesystem (the
7361 ' magic command to move in the filesystem (the
7350 \family typewriter
7362 \family typewriter
7351 %
7363 %
7352 \family default
7364 \family default
7353 is not required with automagic on).
7365 is not required with automagic on).
7354 It also maintains a list of visited directories (use
7366 It also maintains a list of visited directories (use
7355 \family typewriter
7367 \family typewriter
7356 %dhist
7368 %dhist
7357 \family default
7369 \family default
7358 to see it) and allows direct switching to any of them.
7370 to see it) and allows direct switching to any of them.
7359 Type
7371 Type
7360 \family typewriter
7372 \family typewriter
7361 `cd?
7373 `cd?
7362 \family default
7374 \family default
7363 ' for more details.
7375 ' for more details.
7364 \layout Standard
7376 \layout Standard
7365
7377
7366
7378
7367 \family typewriter
7379 \family typewriter
7368 %pushd
7380 %pushd
7369 \family default
7381 \family default
7370 ,
7382 ,
7371 \family typewriter
7383 \family typewriter
7372 %popd
7384 %popd
7373 \family default
7385 \family default
7374 and
7386 and
7375 \family typewriter
7387 \family typewriter
7376 %dirs
7388 %dirs
7377 \family default
7389 \family default
7378 are provided for directory stack handling.
7390 are provided for directory stack handling.
7379 \layout Subsection
7391 \layout Subsection
7380
7392
7381 Prompt customization
7393 Prompt customization
7382 \layout Standard
7394 \layout Standard
7383
7395
7384 The supplied
7396 The supplied
7385 \family typewriter
7397 \family typewriter
7386 ipythonrc-pysh
7398 ipythonrc-pysh
7387 \family default
7399 \family default
7388 profile comes with an example of a very colored and detailed prompt, mainly
7400 profile comes with an example of a very colored and detailed prompt, mainly
7389 to serve as an illustration.
7401 to serve as an illustration.
7390 The valid escape sequences, besides color names, are:
7402 The valid escape sequences, besides color names, are:
7391 \layout Description
7403 \layout Description
7392
7404
7393
7405
7394 \backslash
7406 \backslash
7395 # - Prompt number.
7407 # - Prompt number.
7396 \layout Description
7408 \layout Description
7397
7409
7398
7410
7399 \backslash
7411 \backslash
7400 D - Dots, as many as there are digits in
7412 D - Dots, as many as there are digits in
7401 \backslash
7413 \backslash
7402 # (so they align).
7414 # (so they align).
7403 \layout Description
7415 \layout Description
7404
7416
7405
7417
7406 \backslash
7418 \backslash
7407 w - Current working directory (cwd).
7419 w - Current working directory (cwd).
7408 \layout Description
7420 \layout Description
7409
7421
7410
7422
7411 \backslash
7423 \backslash
7412 W - Basename of current working directory.
7424 W - Basename of current working directory.
7413 \layout Description
7425 \layout Description
7414
7426
7415
7427
7416 \backslash
7428 \backslash
7417 X
7429 X
7418 \emph on
7430 \emph on
7419 N
7431 N
7420 \emph default
7432 \emph default
7421 - Where
7433 - Where
7422 \emph on
7434 \emph on
7423 N
7435 N
7424 \emph default
7436 \emph default
7425 =0..5.
7437 =0..5.
7426 N terms of the cwd, with $HOME written as ~.
7438 N terms of the cwd, with $HOME written as ~.
7427 \layout Description
7439 \layout Description
7428
7440
7429
7441
7430 \backslash
7442 \backslash
7431 Y
7443 Y
7432 \emph on
7444 \emph on
7433 N
7445 N
7434 \emph default
7446 \emph default
7435 - Where
7447 - Where
7436 \emph on
7448 \emph on
7437 N
7449 N
7438 \emph default
7450 \emph default
7439 =0..5.
7451 =0..5.
7440 Like X
7452 Like X
7441 \emph on
7453 \emph on
7442 N
7454 N
7443 \emph default
7455 \emph default
7444 , but if ~ is term
7456 , but if ~ is term
7445 \emph on
7457 \emph on
7446 N
7458 N
7447 \emph default
7459 \emph default
7448 +1 it's also shown.
7460 +1 it's also shown.
7449 \layout Description
7461 \layout Description
7450
7462
7451
7463
7452 \backslash
7464 \backslash
7453 u - Username.
7465 u - Username.
7454 \layout Description
7466 \layout Description
7455
7467
7456
7468
7457 \backslash
7469 \backslash
7458 H - Full hostname.
7470 H - Full hostname.
7459 \layout Description
7471 \layout Description
7460
7472
7461
7473
7462 \backslash
7474 \backslash
7463 h - Hostname up to first '.'
7475 h - Hostname up to first '.'
7464 \layout Description
7476 \layout Description
7465
7477
7466
7478
7467 \backslash
7479 \backslash
7468 $ - Root symbol ($ or #).
7480 $ - Root symbol ($ or #).
7469
7481
7470 \layout Description
7482 \layout Description
7471
7483
7472
7484
7473 \backslash
7485 \backslash
7474 t - Current time, in H:M:S format.
7486 t - Current time, in H:M:S format.
7475 \layout Description
7487 \layout Description
7476
7488
7477
7489
7478 \backslash
7490 \backslash
7479 v - IPython release version.
7491 v - IPython release version.
7480
7492
7481 \layout Description
7493 \layout Description
7482
7494
7483
7495
7484 \backslash
7496 \backslash
7485 n - Newline.
7497 n - Newline.
7486
7498
7487 \layout Description
7499 \layout Description
7488
7500
7489
7501
7490 \backslash
7502 \backslash
7491 r - Carriage return.
7503 r - Carriage return.
7492
7504
7493 \layout Description
7505 \layout Description
7494
7506
7495
7507
7496 \backslash
7508 \backslash
7497
7509
7498 \backslash
7510 \backslash
7499 - An explicitly escaped '
7511 - An explicitly escaped '
7500 \backslash
7512 \backslash
7501 '.
7513 '.
7502 \layout Standard
7514 \layout Standard
7503
7515
7504 You can configure your prompt colors using any ANSI color escape.
7516 You can configure your prompt colors using any ANSI color escape.
7505 Each color escape sets the color for any subsequent text, until another
7517 Each color escape sets the color for any subsequent text, until another
7506 escape comes in and changes things.
7518 escape comes in and changes things.
7507 The valid color escapes are:
7519 The valid color escapes are:
7508 \layout Description
7520 \layout Description
7509
7521
7510
7522
7511 \backslash
7523 \backslash
7512 C_Black
7524 C_Black
7513 \layout Description
7525 \layout Description
7514
7526
7515
7527
7516 \backslash
7528 \backslash
7517 C_Blue
7529 C_Blue
7518 \layout Description
7530 \layout Description
7519
7531
7520
7532
7521 \backslash
7533 \backslash
7522 C_Brown
7534 C_Brown
7523 \layout Description
7535 \layout Description
7524
7536
7525
7537
7526 \backslash
7538 \backslash
7527 C_Cyan
7539 C_Cyan
7528 \layout Description
7540 \layout Description
7529
7541
7530
7542
7531 \backslash
7543 \backslash
7532 C_DarkGray
7544 C_DarkGray
7533 \layout Description
7545 \layout Description
7534
7546
7535
7547
7536 \backslash
7548 \backslash
7537 C_Green
7549 C_Green
7538 \layout Description
7550 \layout Description
7539
7551
7540
7552
7541 \backslash
7553 \backslash
7542 C_LightBlue
7554 C_LightBlue
7543 \layout Description
7555 \layout Description
7544
7556
7545
7557
7546 \backslash
7558 \backslash
7547 C_LightCyan
7559 C_LightCyan
7548 \layout Description
7560 \layout Description
7549
7561
7550
7562
7551 \backslash
7563 \backslash
7552 C_LightGray
7564 C_LightGray
7553 \layout Description
7565 \layout Description
7554
7566
7555
7567
7556 \backslash
7568 \backslash
7557 C_LightGreen
7569 C_LightGreen
7558 \layout Description
7570 \layout Description
7559
7571
7560
7572
7561 \backslash
7573 \backslash
7562 C_LightPurple
7574 C_LightPurple
7563 \layout Description
7575 \layout Description
7564
7576
7565
7577
7566 \backslash
7578 \backslash
7567 C_LightRed
7579 C_LightRed
7568 \layout Description
7580 \layout Description
7569
7581
7570
7582
7571 \backslash
7583 \backslash
7572 C_Purple
7584 C_Purple
7573 \layout Description
7585 \layout Description
7574
7586
7575
7587
7576 \backslash
7588 \backslash
7577 C_Red
7589 C_Red
7578 \layout Description
7590 \layout Description
7579
7591
7580
7592
7581 \backslash
7593 \backslash
7582 C_White
7594 C_White
7583 \layout Description
7595 \layout Description
7584
7596
7585
7597
7586 \backslash
7598 \backslash
7587 C_Yellow
7599 C_Yellow
7588 \layout Description
7600 \layout Description
7589
7601
7590
7602
7591 \backslash
7603 \backslash
7592 C_Normal Stop coloring, defaults to your terminal settings.
7604 C_Normal Stop coloring, defaults to your terminal settings.
7593 \layout Section
7605 \layout Section
7594
7606
7595
7607
7596 \begin_inset LatexCommand \label{sec:Threading-support}
7608 \begin_inset LatexCommand \label{sec:Threading-support}
7597
7609
7598 \end_inset
7610 \end_inset
7599
7611
7600 Threading support
7612 Threading support
7601 \layout Standard
7613 \layout Standard
7602
7614
7603
7615
7604 \series bold
7616 \series bold
7605 WARNING:
7617 WARNING:
7606 \series default
7618 \series default
7607 The threading support is still somewhat experimental, and it has only seen
7619 The threading support is still somewhat experimental, and it has only seen
7608 reasonable testing under Linux.
7620 reasonable testing under Linux.
7609 Threaded code is particularly tricky to debug, and it tends to show extremely
7621 Threaded code is particularly tricky to debug, and it tends to show extremely
7610 platform-dependent behavior.
7622 platform-dependent behavior.
7611 Since I only have access to Linux machines, I will have to rely on user's
7623 Since I only have access to Linux machines, I will have to rely on user's
7612 experiences and assistance for this area of IPython to improve under other
7624 experiences and assistance for this area of IPython to improve under other
7613 platforms.
7625 platforms.
7614 \layout Standard
7626 \layout Standard
7615
7627
7616 IPython, via the
7628 IPython, via the
7617 \family typewriter
7629 \family typewriter
7618 -gthread
7630 -gthread
7619 \family default
7631 \family default
7620 ,
7632 ,
7621 \family typewriter
7633 \family typewriter
7622 -qthread
7634 -qthread
7623 \family default
7635 \family default
7624 and
7636 and
7625 \family typewriter
7637 \family typewriter
7626 -wthread
7638 -wthread
7627 \family default
7639 \family default
7628 options (described in Sec.\SpecialChar ~
7640 options (described in Sec.\SpecialChar ~
7629
7641
7630 \begin_inset LatexCommand \ref{sec:threading-opts}
7642 \begin_inset LatexCommand \ref{sec:threading-opts}
7631
7643
7632 \end_inset
7644 \end_inset
7633
7645
7634 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7646 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7635 respectively.
7647 respectively.
7636 These GUI toolkits need to control the python main loop of execution, so
7648 These GUI toolkits need to control the python main loop of execution, so
7637 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7649 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7638 will immediately freeze the shell.
7650 will immediately freeze the shell.
7639
7651
7640 \layout Standard
7652 \layout Standard
7641
7653
7642 IPython, with one of these options (you can only use one at a time), separates
7654 IPython, with one of these options (you can only use one at a time), separates
7643 the graphical loop and IPython's code execution run into different threads.
7655 the graphical loop and IPython's code execution run into different threads.
7644 This allows you to test interactively (with
7656 This allows you to test interactively (with
7645 \family typewriter
7657 \family typewriter
7646 %run
7658 %run
7647 \family default
7659 \family default
7648 , for example) your GUI code without blocking.
7660 , for example) your GUI code without blocking.
7649 \layout Standard
7661 \layout Standard
7650
7662
7651 A nice mini-tutorial on using IPython along with the Qt Designer application
7663 A nice mini-tutorial on using IPython along with the Qt Designer application
7652 is available at the SciPy wiki:
7664 is available at the SciPy wiki:
7653 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7665 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7654
7666
7655 \end_inset
7667 \end_inset
7656
7668
7657 .
7669 .
7658 \layout Subsection
7670 \layout Subsection
7659
7671
7660 Tk issues
7672 Tk issues
7661 \layout Standard
7673 \layout Standard
7662
7674
7663 As indicated in Sec.\SpecialChar ~
7675 As indicated in Sec.\SpecialChar ~
7664
7676
7665 \begin_inset LatexCommand \ref{sec:threading-opts}
7677 \begin_inset LatexCommand \ref{sec:threading-opts}
7666
7678
7667 \end_inset
7679 \end_inset
7668
7680
7669 , a special
7681 , a special
7670 \family typewriter
7682 \family typewriter
7671 -tk
7683 -tk
7672 \family default
7684 \family default
7673 option is provided to try and allow Tk graphical applications to coexist
7685 option is provided to try and allow Tk graphical applications to coexist
7674 interactively with WX, Qt or GTK ones.
7686 interactively with WX, Qt or GTK ones.
7675 Whether this works at all, however, is very platform and configuration
7687 Whether this works at all, however, is very platform and configuration
7676 dependent.
7688 dependent.
7677 Please experiment with simple test cases before committing to using this
7689 Please experiment with simple test cases before committing to using this
7678 combination of Tk and GTK/Qt/WX threading in a production environment.
7690 combination of Tk and GTK/Qt/WX threading in a production environment.
7679 \layout Subsection
7691 \layout Subsection
7680
7692
7681 Signals and Threads
7693 Signals and Threads
7682 \layout Standard
7694 \layout Standard
7683
7695
7684 When any of the thread systems (GTK, Qt or WX) are active, either directly
7696 When any of the thread systems (GTK, Qt or WX) are active, either directly
7685 or via
7697 or via
7686 \family typewriter
7698 \family typewriter
7687 -pylab
7699 -pylab
7688 \family default
7700 \family default
7689 with a threaded backend, it is impossible to interrupt long-running Python
7701 with a threaded backend, it is impossible to interrupt long-running Python
7690 code via
7702 code via
7691 \family typewriter
7703 \family typewriter
7692 Ctrl-C
7704 Ctrl-C
7693 \family default
7705 \family default
7694 .
7706 .
7695 IPython can not pass the KeyboardInterrupt exception (or the underlying
7707 IPython can not pass the KeyboardInterrupt exception (or the underlying
7696
7708
7697 \family typewriter
7709 \family typewriter
7698 SIGINT
7710 SIGINT
7699 \family default
7711 \family default
7700 ) across threads, so any long-running process started from IPython will
7712 ) across threads, so any long-running process started from IPython will
7701 run to completion, or will have to be killed via an external (OS-based)
7713 run to completion, or will have to be killed via an external (OS-based)
7702 mechanism.
7714 mechanism.
7703 \layout Standard
7715 \layout Standard
7704
7716
7705 To the best of my knowledge, this limitation is imposed by the Python interprete
7717 To the best of my knowledge, this limitation is imposed by the Python interprete
7706 r itself, and it comes from the difficulty of writing portable signal/threaded
7718 r itself, and it comes from the difficulty of writing portable signal/threaded
7707 code.
7719 code.
7708 If any user is an expert on this topic and can suggest a better solution,
7720 If any user is an expert on this topic and can suggest a better solution,
7709 I would love to hear about it.
7721 I would love to hear about it.
7710 In the IPython sources, look at the
7722 In the IPython sources, look at the
7711 \family typewriter
7723 \family typewriter
7712 Shell.py
7724 Shell.py
7713 \family default
7725 \family default
7714 module, and in particular at the
7726 module, and in particular at the
7715 \family typewriter
7727 \family typewriter
7716 runcode()
7728 runcode()
7717 \family default
7729 \family default
7718 method.
7730 method.
7719
7731
7720 \layout Subsection
7732 \layout Subsection
7721
7733
7722 I/O pitfalls
7734 I/O pitfalls
7723 \layout Standard
7735 \layout Standard
7724
7736
7725 Be mindful that the Python interpreter switches between threads every
7737 Be mindful that the Python interpreter switches between threads every
7726 \begin_inset Formula $N$
7738 \begin_inset Formula $N$
7727 \end_inset
7739 \end_inset
7728
7740
7729 bytecodes, where the default value as of Python\SpecialChar ~
7741 bytecodes, where the default value as of Python\SpecialChar ~
7730 2.3 is
7742 2.3 is
7731 \begin_inset Formula $N=100.$
7743 \begin_inset Formula $N=100.$
7732 \end_inset
7744 \end_inset
7733
7745
7734 This value can be read by using the
7746 This value can be read by using the
7735 \family typewriter
7747 \family typewriter
7736 sys.getcheckinterval()
7748 sys.getcheckinterval()
7737 \family default
7749 \family default
7738 function, and it can be reset via
7750 function, and it can be reset via
7739 \family typewriter
7751 \family typewriter
7740 sys.setcheckinterval(
7752 sys.setcheckinterval(
7741 \emph on
7753 \emph on
7742 N
7754 N
7743 \emph default
7755 \emph default
7744 )
7756 )
7745 \family default
7757 \family default
7746 .
7758 .
7747 This switching of threads can cause subtly confusing effects if one of
7759 This switching of threads can cause subtly confusing effects if one of
7748 your threads is doing file I/O.
7760 your threads is doing file I/O.
7749 In text mode, most systems only flush file buffers when they encounter
7761 In text mode, most systems only flush file buffers when they encounter
7750 a
7762 a
7751 \family typewriter
7763 \family typewriter
7752 `
7764 `
7753 \backslash
7765 \backslash
7754 n'
7766 n'
7755 \family default
7767 \family default
7756 .
7768 .
7757 An instruction as simple as
7769 An instruction as simple as
7758 \family typewriter
7770 \family typewriter
7759
7771
7760 \newline
7772 \newline
7761 \SpecialChar ~
7773 \SpecialChar ~
7762 \SpecialChar ~
7774 \SpecialChar ~
7763 print >> filehandle,
7775 print >> filehandle,
7764 \begin_inset Quotes eld
7776 \begin_inset Quotes eld
7765 \end_inset
7777 \end_inset
7766
7778
7767 hello world
7779 hello world
7768 \begin_inset Quotes erd
7780 \begin_inset Quotes erd
7769 \end_inset
7781 \end_inset
7770
7782
7771
7783
7772 \family default
7784 \family default
7773
7785
7774 \newline
7786 \newline
7775 actually consists of several bytecodes, so it is possible that the newline
7787 actually consists of several bytecodes, so it is possible that the newline
7776 does not reach your file before the next thread switch.
7788 does not reach your file before the next thread switch.
7777 Similarly, if you are writing to a file in binary mode, the file won't
7789 Similarly, if you are writing to a file in binary mode, the file won't
7778 be flushed until the buffer fills, and your other thread may see apparently
7790 be flushed until the buffer fills, and your other thread may see apparently
7779 truncated files.
7791 truncated files.
7780
7792
7781 \layout Standard
7793 \layout Standard
7782
7794
7783 For this reason, if you are using IPython's thread support and have (for
7795 For this reason, if you are using IPython's thread support and have (for
7784 example) a GUI application which will read data generated by files written
7796 example) a GUI application which will read data generated by files written
7785 to from the IPython thread, the safest approach is to open all of your
7797 to from the IPython thread, the safest approach is to open all of your
7786 files in unbuffered mode (the third argument to the
7798 files in unbuffered mode (the third argument to the
7787 \family typewriter
7799 \family typewriter
7788 file/open
7800 file/open
7789 \family default
7801 \family default
7790 function is the buffering value):
7802 function is the buffering value):
7791 \newline
7803 \newline
7792
7804
7793 \family typewriter
7805 \family typewriter
7794 \SpecialChar ~
7806 \SpecialChar ~
7795 \SpecialChar ~
7807 \SpecialChar ~
7796 filehandle = open(filename,mode,0)
7808 filehandle = open(filename,mode,0)
7797 \layout Standard
7809 \layout Standard
7798
7810
7799 This is obviously a brute force way of avoiding race conditions with the
7811 This is obviously a brute force way of avoiding race conditions with the
7800 file buffering.
7812 file buffering.
7801 If you want to do it cleanly, and you have a resource which is being shared
7813 If you want to do it cleanly, and you have a resource which is being shared
7802 by the interactive IPython loop and your GUI thread, you should really
7814 by the interactive IPython loop and your GUI thread, you should really
7803 handle it with thread locking and syncrhonization properties.
7815 handle it with thread locking and syncrhonization properties.
7804 The Python documentation discusses these.
7816 The Python documentation discusses these.
7805 \layout Section
7817 \layout Section
7806
7818
7807
7819
7808 \begin_inset LatexCommand \label{sec:interactive-demos}
7820 \begin_inset LatexCommand \label{sec:interactive-demos}
7809
7821
7810 \end_inset
7822 \end_inset
7811
7823
7812 Interactive demos with IPython
7824 Interactive demos with IPython
7813 \layout Standard
7825 \layout Standard
7814
7826
7815 IPython ships with a basic system for running scripts interactively in sections,
7827 IPython ships with a basic system for running scripts interactively in sections,
7816 useful when presenting code to audiences.
7828 useful when presenting code to audiences.
7817 A few tags embedded in comments (so that the script remains valid Python
7829 A few tags embedded in comments (so that the script remains valid Python
7818 code) divide a file into separate blocks, and the demo can be run one block
7830 code) divide a file into separate blocks, and the demo can be run one block
7819 at a time, with IPython printing (with syntax highlighting) the block before
7831 at a time, with IPython printing (with syntax highlighting) the block before
7820 executing it, and returning to the interactive prompt after each block.
7832 executing it, and returning to the interactive prompt after each block.
7821 The interactive namespace is updated after each block is run with the contents
7833 The interactive namespace is updated after each block is run with the contents
7822 of the demo's namespace.
7834 of the demo's namespace.
7823 \layout Standard
7835 \layout Standard
7824
7836
7825 This allows you to show a piece of code, run it and then execute interactively
7837 This allows you to show a piece of code, run it and then execute interactively
7826 commands based on the variables just created.
7838 commands based on the variables just created.
7827 Once you want to continue, you simply execute the next block of the demo.
7839 Once you want to continue, you simply execute the next block of the demo.
7828 The following listing shows the markup necessary for dividing a script
7840 The following listing shows the markup necessary for dividing a script
7829 into sections for execution as a demo.
7841 into sections for execution as a demo.
7830 \layout Standard
7842 \layout Standard
7831
7843
7832
7844
7833 \begin_inset ERT
7845 \begin_inset ERT
7834 status Open
7846 status Open
7835
7847
7836 \layout Standard
7848 \layout Standard
7837
7849
7838 \backslash
7850 \backslash
7839 codelist{examples/example-demo.py}
7851 codelist{examples/example-demo.py}
7840 \end_inset
7852 \end_inset
7841
7853
7842
7854
7843 \layout Standard
7855 \layout Standard
7844
7856
7845 In order to run a file as a demo, you must first make a
7857 In order to run a file as a demo, you must first make a
7846 \family typewriter
7858 \family typewriter
7847 Demo
7859 Demo
7848 \family default
7860 \family default
7849 object out of it.
7861 object out of it.
7850 If the file is named
7862 If the file is named
7851 \family typewriter
7863 \family typewriter
7852 myscript.py
7864 myscript.py
7853 \family default
7865 \family default
7854 , the following code will make a demo:
7866 , the following code will make a demo:
7855 \layout LyX-Code
7867 \layout LyX-Code
7856
7868
7857 from IPython.demo import Demo
7869 from IPython.demo import Demo
7858 \layout LyX-Code
7870 \layout LyX-Code
7859
7871
7860 mydemo = Demo('myscript.py')
7872 mydemo = Demo('myscript.py')
7861 \layout Standard
7873 \layout Standard
7862
7874
7863 This creates the
7875 This creates the
7864 \family typewriter
7876 \family typewriter
7865 mydemo
7877 mydemo
7866 \family default
7878 \family default
7867 object, whose blocks you run one at a time by simply calling the object
7879 object, whose blocks you run one at a time by simply calling the object
7868 with no arguments.
7880 with no arguments.
7869 If you have autocall active in IPython (the default), all you need to do
7881 If you have autocall active in IPython (the default), all you need to do
7870 is type
7882 is type
7871 \layout LyX-Code
7883 \layout LyX-Code
7872
7884
7873 mydemo
7885 mydemo
7874 \layout Standard
7886 \layout Standard
7875
7887
7876 and IPython will call it, executing each block.
7888 and IPython will call it, executing each block.
7877 Demo objects can be restarted, you can move forward or back skipping blocks,
7889 Demo objects can be restarted, you can move forward or back skipping blocks,
7878 re-execute the last block, etc.
7890 re-execute the last block, etc.
7879 Simply use the Tab key on a demo object to see its methods, and call
7891 Simply use the Tab key on a demo object to see its methods, and call
7880 \family typewriter
7892 \family typewriter
7881 `?'
7893 `?'
7882 \family default
7894 \family default
7883 on them to see their docstrings for more usage details.
7895 on them to see their docstrings for more usage details.
7884 In addition, the
7896 In addition, the
7885 \family typewriter
7897 \family typewriter
7886 demo
7898 demo
7887 \family default
7899 \family default
7888 module itself contains a comprehensive docstring, which you can access
7900 module itself contains a comprehensive docstring, which you can access
7889 via
7901 via
7890 \layout LyX-Code
7902 \layout LyX-Code
7891
7903
7892 from IPython import demo
7904 from IPython import demo
7893 \layout LyX-Code
7905 \layout LyX-Code
7894
7906
7895 demo?
7907 demo?
7896 \layout Standard
7908 \layout Standard
7897
7909
7898
7910
7899 \series bold
7911 \series bold
7900 Limitations:
7912 Limitations:
7901 \series default
7913 \series default
7902 It is important to note that these demos are limited to fairly simple uses.
7914 It is important to note that these demos are limited to fairly simple uses.
7903 In particular, you can
7915 In particular, you can
7904 \emph on
7916 \emph on
7905 not
7917 not
7906 \emph default
7918 \emph default
7907 put division marks in indented code (loops, if statements, function definitions
7919 put division marks in indented code (loops, if statements, function definitions
7908 , etc.) Supporting something like this would basically require tracking the
7920 , etc.) Supporting something like this would basically require tracking the
7909 internal execution state of the Python interpreter, so only top-level divisions
7921 internal execution state of the Python interpreter, so only top-level divisions
7910 are allowed.
7922 are allowed.
7911 If you want to be able to open an IPython instance at an arbitrary point
7923 If you want to be able to open an IPython instance at an arbitrary point
7912 in a program, you can use IPython's embedding facilities, described in
7924 in a program, you can use IPython's embedding facilities, described in
7913 detail in Sec\SpecialChar \@.
7925 detail in Sec\SpecialChar \@.
7914 \SpecialChar ~
7926 \SpecialChar ~
7915
7927
7916 \begin_inset LatexCommand \ref{sec:embed}
7928 \begin_inset LatexCommand \ref{sec:embed}
7917
7929
7918 \end_inset
7930 \end_inset
7919
7931
7920 .
7932 .
7921 \layout Section
7933 \layout Section
7922
7934
7923
7935
7924 \begin_inset LatexCommand \label{sec:matplotlib-support}
7936 \begin_inset LatexCommand \label{sec:matplotlib-support}
7925
7937
7926 \end_inset
7938 \end_inset
7927
7939
7928 Plotting with
7940 Plotting with
7929 \family typewriter
7941 \family typewriter
7930 matplotlib
7942 matplotlib
7931 \family default
7943 \family default
7932
7944
7933 \layout Standard
7945 \layout Standard
7934
7946
7935 The matplotlib library (
7947 The matplotlib library (
7936 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
7948 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
7937
7949
7938 \end_inset
7950 \end_inset
7939
7951
7940 ) provides high quality 2D plotting for Python.
7952 ) provides high quality 2D plotting for Python.
7941 Matplotlib can produce plots on screen using a variety of GUI toolkits,
7953 Matplotlib can produce plots on screen using a variety of GUI toolkits,
7942 including Tk, GTK and WXPython.
7954 including Tk, GTK and WXPython.
7943 It also provides a number of commands useful for scientific computing,
7955 It also provides a number of commands useful for scientific computing,
7944 all with a syntax compatible with that of the popular Matlab program.
7956 all with a syntax compatible with that of the popular Matlab program.
7945 \layout Standard
7957 \layout Standard
7946
7958
7947 IPython accepts the special option
7959 IPython accepts the special option
7948 \family typewriter
7960 \family typewriter
7949 -pylab
7961 -pylab
7950 \family default
7962 \family default
7951 (Sec.\SpecialChar ~
7963 (Sec.\SpecialChar ~
7952
7964
7953 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
7965 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
7954
7966
7955 \end_inset
7967 \end_inset
7956
7968
7957 ).
7969 ).
7958 This configures it to support matplotlib, honoring the settings in the
7970 This configures it to support matplotlib, honoring the settings in the
7959
7971
7960 \family typewriter
7972 \family typewriter
7961 .matplotlibrc
7973 .matplotlibrc
7962 \family default
7974 \family default
7963 file.
7975 file.
7964 IPython will detect the user's choice of matplotlib GUI backend, and automatica
7976 IPython will detect the user's choice of matplotlib GUI backend, and automatica
7965 lly select the proper threading model to prevent blocking.
7977 lly select the proper threading model to prevent blocking.
7966 It also sets matplotlib in interactive mode and modifies
7978 It also sets matplotlib in interactive mode and modifies
7967 \family typewriter
7979 \family typewriter
7968 %run
7980 %run
7969 \family default
7981 \family default
7970 slightly, so that any matplotlib-based script can be executed using
7982 slightly, so that any matplotlib-based script can be executed using
7971 \family typewriter
7983 \family typewriter
7972 %run
7984 %run
7973 \family default
7985 \family default
7974 and the final
7986 and the final
7975 \family typewriter
7987 \family typewriter
7976 show()
7988 show()
7977 \family default
7989 \family default
7978 command does not block the interactive shell.
7990 command does not block the interactive shell.
7979 \layout Standard
7991 \layout Standard
7980
7992
7981 The
7993 The
7982 \family typewriter
7994 \family typewriter
7983 -pylab
7995 -pylab
7984 \family default
7996 \family default
7985 option must be given first in order for IPython to configure its threading
7997 option must be given first in order for IPython to configure its threading
7986 mode.
7998 mode.
7987 However, you can still issue other options afterwards.
7999 However, you can still issue other options afterwards.
7988 This allows you to have a matplotlib-based environment customized with
8000 This allows you to have a matplotlib-based environment customized with
7989 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
8001 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
7990
8002
7991 \begin_inset LatexCommand \ref{sec:profiles}
8003 \begin_inset LatexCommand \ref{sec:profiles}
7992
8004
7993 \end_inset
8005 \end_inset
7994
8006
7995 ): ``
8007 ): ``
7996 \family typewriter
8008 \family typewriter
7997 ipython -pylab -p myprofile
8009 ipython -pylab -p myprofile
7998 \family default
8010 \family default
7999 '' will load the profile defined in
8011 '' will load the profile defined in
8000 \family typewriter
8012 \family typewriter
8001 ipythonrc-myprofile
8013 ipythonrc-myprofile
8002 \family default
8014 \family default
8003 after configuring matplotlib.
8015 after configuring matplotlib.
8004 \layout Section
8016 \layout Section
8005
8017
8006
8018
8007 \begin_inset LatexCommand \label{sec:Gnuplot}
8019 \begin_inset LatexCommand \label{sec:Gnuplot}
8008
8020
8009 \end_inset
8021 \end_inset
8010
8022
8011 Plotting with
8023 Plotting with
8012 \family typewriter
8024 \family typewriter
8013 Gnuplot
8025 Gnuplot
8014 \layout Standard
8026 \layout Standard
8015
8027
8016 Through the magic extension system described in sec.
8028 Through the magic extension system described in sec.
8017
8029
8018 \begin_inset LatexCommand \ref{sec:magic}
8030 \begin_inset LatexCommand \ref{sec:magic}
8019
8031
8020 \end_inset
8032 \end_inset
8021
8033
8022 , IPython incorporates a mechanism for conveniently interfacing with the
8034 , IPython incorporates a mechanism for conveniently interfacing with the
8023 Gnuplot system (
8035 Gnuplot system (
8024 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8036 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8025
8037
8026 \end_inset
8038 \end_inset
8027
8039
8028 ).
8040 ).
8029 Gnuplot is a very complete 2D and 3D plotting package available for many
8041 Gnuplot is a very complete 2D and 3D plotting package available for many
8030 operating systems and commonly included in modern Linux distributions.
8042 operating systems and commonly included in modern Linux distributions.
8031
8043
8032 \layout Standard
8044 \layout Standard
8033
8045
8034 Besides having Gnuplot installed, this functionality requires the
8046 Besides having Gnuplot installed, this functionality requires the
8035 \family typewriter
8047 \family typewriter
8036 Gnuplot.py
8048 Gnuplot.py
8037 \family default
8049 \family default
8038 module for interfacing python with Gnuplot.
8050 module for interfacing python with Gnuplot.
8039 It can be downloaded from:
8051 It can be downloaded from:
8040 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8052 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8041
8053
8042 \end_inset
8054 \end_inset
8043
8055
8044 .
8056 .
8045 \layout Subsection
8057 \layout Subsection
8046
8058
8047 Proper Gnuplot configuration
8059 Proper Gnuplot configuration
8048 \layout Standard
8060 \layout Standard
8049
8061
8050 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8062 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8051 However, as of
8063 However, as of
8052 \family typewriter
8064 \family typewriter
8053 Gnuplot.py
8065 Gnuplot.py
8054 \family default
8066 \family default
8055 version 1.7, a new option was added to communicate between Python and Gnuplot
8067 version 1.7, a new option was added to communicate between Python and Gnuplot
8056 via FIFOs (pipes).
8068 via FIFOs (pipes).
8057 This mechanism, while fast, also breaks the mouse system.
8069 This mechanism, while fast, also breaks the mouse system.
8058 You must therefore set the variable
8070 You must therefore set the variable
8059 \family typewriter
8071 \family typewriter
8060 prefer_fifo_data
8072 prefer_fifo_data
8061 \family default
8073 \family default
8062 to
8074 to
8063 \family typewriter
8075 \family typewriter
8064 0
8076 0
8065 \family default
8077 \family default
8066 in file
8078 in file
8067 \family typewriter
8079 \family typewriter
8068 gp_unix.py
8080 gp_unix.py
8069 \family default
8081 \family default
8070 if you wish to keep the interactive mouse and keyboard features working
8082 if you wish to keep the interactive mouse and keyboard features working
8071 properly (
8083 properly (
8072 \family typewriter
8084 \family typewriter
8073 prefer_inline_data
8085 prefer_inline_data
8074 \family default
8086 \family default
8075 also must be
8087 also must be
8076 \family typewriter
8088 \family typewriter
8077 0
8089 0
8078 \family default
8090 \family default
8079 , but this is the default so unless you've changed it manually you should
8091 , but this is the default so unless you've changed it manually you should
8080 be fine).
8092 be fine).
8081 \layout Standard
8093 \layout Standard
8082
8094
8083 'Out of the box', Gnuplot is configured with a rather poor set of size,
8095 'Out of the box', Gnuplot is configured with a rather poor set of size,
8084 color and linewidth choices which make the graphs fairly hard to read on
8096 color and linewidth choices which make the graphs fairly hard to read on
8085 modern high-resolution displays (although they work fine on old 640x480
8097 modern high-resolution displays (although they work fine on old 640x480
8086 ones).
8098 ones).
8087 Below is a section of my
8099 Below is a section of my
8088 \family typewriter
8100 \family typewriter
8089 .Xdefaults
8101 .Xdefaults
8090 \family default
8102 \family default
8091 file which I use for having a more convenient Gnuplot setup.
8103 file which I use for having a more convenient Gnuplot setup.
8092 Remember to load it by running
8104 Remember to load it by running
8093 \family typewriter
8105 \family typewriter
8094 `xrdb .Xdefaults`
8106 `xrdb .Xdefaults`
8095 \family default
8107 \family default
8096 :
8108 :
8097 \layout Standard
8109 \layout Standard
8098
8110
8099
8111
8100 \family typewriter
8112 \family typewriter
8101 !******************************************************************
8113 !******************************************************************
8102 \newline
8114 \newline
8103 ! gnuplot options
8115 ! gnuplot options
8104 \newline
8116 \newline
8105 ! modify this for a convenient window size
8117 ! modify this for a convenient window size
8106 \newline
8118 \newline
8107 gnuplot*geometry: 780x580
8119 gnuplot*geometry: 780x580
8108 \layout Standard
8120 \layout Standard
8109
8121
8110
8122
8111 \family typewriter
8123 \family typewriter
8112 ! on-screen font (not for PostScript)
8124 ! on-screen font (not for PostScript)
8113 \newline
8125 \newline
8114 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8126 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8115 \layout Standard
8127 \layout Standard
8116
8128
8117
8129
8118 \family typewriter
8130 \family typewriter
8119 ! color options
8131 ! color options
8120 \newline
8132 \newline
8121 gnuplot*background: black
8133 gnuplot*background: black
8122 \newline
8134 \newline
8123 gnuplot*textColor: white
8135 gnuplot*textColor: white
8124 \newline
8136 \newline
8125 gnuplot*borderColor: white
8137 gnuplot*borderColor: white
8126 \newline
8138 \newline
8127 gnuplot*axisColor: white
8139 gnuplot*axisColor: white
8128 \newline
8140 \newline
8129 gnuplot*line1Color: red
8141 gnuplot*line1Color: red
8130 \newline
8142 \newline
8131 gnuplot*line2Color: green
8143 gnuplot*line2Color: green
8132 \newline
8144 \newline
8133 gnuplot*line3Color: blue
8145 gnuplot*line3Color: blue
8134 \newline
8146 \newline
8135 gnuplot*line4Color: magenta
8147 gnuplot*line4Color: magenta
8136 \newline
8148 \newline
8137 gnuplot*line5Color: cyan
8149 gnuplot*line5Color: cyan
8138 \newline
8150 \newline
8139 gnuplot*line6Color: sienna
8151 gnuplot*line6Color: sienna
8140 \newline
8152 \newline
8141 gnuplot*line7Color: orange
8153 gnuplot*line7Color: orange
8142 \newline
8154 \newline
8143 gnuplot*line8Color: coral
8155 gnuplot*line8Color: coral
8144 \layout Standard
8156 \layout Standard
8145
8157
8146
8158
8147 \family typewriter
8159 \family typewriter
8148 ! multiplicative factor for point styles
8160 ! multiplicative factor for point styles
8149 \newline
8161 \newline
8150 gnuplot*pointsize: 2
8162 gnuplot*pointsize: 2
8151 \layout Standard
8163 \layout Standard
8152
8164
8153
8165
8154 \family typewriter
8166 \family typewriter
8155 ! line width options (in pixels)
8167 ! line width options (in pixels)
8156 \newline
8168 \newline
8157 gnuplot*borderWidth: 2
8169 gnuplot*borderWidth: 2
8158 \newline
8170 \newline
8159 gnuplot*axisWidth: 2
8171 gnuplot*axisWidth: 2
8160 \newline
8172 \newline
8161 gnuplot*line1Width: 2
8173 gnuplot*line1Width: 2
8162 \newline
8174 \newline
8163 gnuplot*line2Width: 2
8175 gnuplot*line2Width: 2
8164 \newline
8176 \newline
8165 gnuplot*line3Width: 2
8177 gnuplot*line3Width: 2
8166 \newline
8178 \newline
8167 gnuplot*line4Width: 2
8179 gnuplot*line4Width: 2
8168 \newline
8180 \newline
8169 gnuplot*line5Width: 2
8181 gnuplot*line5Width: 2
8170 \newline
8182 \newline
8171 gnuplot*line6Width: 2
8183 gnuplot*line6Width: 2
8172 \newline
8184 \newline
8173 gnuplot*line7Width: 2
8185 gnuplot*line7Width: 2
8174 \newline
8186 \newline
8175 gnuplot*line8Width: 2
8187 gnuplot*line8Width: 2
8176 \layout Subsection
8188 \layout Subsection
8177
8189
8178 The
8190 The
8179 \family typewriter
8191 \family typewriter
8180 IPython.GnuplotRuntime
8192 IPython.GnuplotRuntime
8181 \family default
8193 \family default
8182 module
8194 module
8183 \layout Standard
8195 \layout Standard
8184
8196
8185 IPython includes a module called
8197 IPython includes a module called
8186 \family typewriter
8198 \family typewriter
8187 Gnuplot2.py
8199 Gnuplot2.py
8188 \family default
8200 \family default
8189 which extends and improves the default
8201 which extends and improves the default
8190 \family typewriter
8202 \family typewriter
8191 Gnuplot
8203 Gnuplot
8192 \family default
8204 \family default
8193 .
8205 .
8194 \family typewriter
8206 \family typewriter
8195 py
8207 py
8196 \family default
8208 \family default
8197 (which it still relies upon).
8209 (which it still relies upon).
8198 For example, the new
8210 For example, the new
8199 \family typewriter
8211 \family typewriter
8200 plot
8212 plot
8201 \family default
8213 \family default
8202 function adds several improvements to the original making it more convenient
8214 function adds several improvements to the original making it more convenient
8203 for interactive use, and
8215 for interactive use, and
8204 \family typewriter
8216 \family typewriter
8205 hardcopy
8217 hardcopy
8206 \family default
8218 \family default
8207 fixes a bug in the original which under some circumstances blocks the creation
8219 fixes a bug in the original which under some circumstances blocks the creation
8208 of PostScript output.
8220 of PostScript output.
8209 \layout Standard
8221 \layout Standard
8210
8222
8211 For scripting use,
8223 For scripting use,
8212 \family typewriter
8224 \family typewriter
8213 GnuplotRuntime.py
8225 GnuplotRuntime.py
8214 \family default
8226 \family default
8215 is provided, which wraps
8227 is provided, which wraps
8216 \family typewriter
8228 \family typewriter
8217 Gnuplot2.py
8229 Gnuplot2.py
8218 \family default
8230 \family default
8219 and creates a series of global aliases.
8231 and creates a series of global aliases.
8220 These make it easy to control Gnuplot plotting jobs through the Python
8232 These make it easy to control Gnuplot plotting jobs through the Python
8221 language.
8233 language.
8222 \layout Standard
8234 \layout Standard
8223
8235
8224 Below is some example code which illustrates how to configure Gnuplot inside
8236 Below is some example code which illustrates how to configure Gnuplot inside
8225 your own programs but have it available for further interactive use through
8237 your own programs but have it available for further interactive use through
8226 an embedded IPython instance.
8238 an embedded IPython instance.
8227 Simply run this file at a system prompt.
8239 Simply run this file at a system prompt.
8228 This file is provided as
8240 This file is provided as
8229 \family typewriter
8241 \family typewriter
8230 example-gnuplot.py
8242 example-gnuplot.py
8231 \family default
8243 \family default
8232 in the examples directory:
8244 in the examples directory:
8233 \layout Standard
8245 \layout Standard
8234
8246
8235
8247
8236 \begin_inset ERT
8248 \begin_inset ERT
8237 status Open
8249 status Open
8238
8250
8239 \layout Standard
8251 \layout Standard
8240
8252
8241 \backslash
8253 \backslash
8242 codelist{examples/example-gnuplot.py}
8254 codelist{examples/example-gnuplot.py}
8243 \end_inset
8255 \end_inset
8244
8256
8245
8257
8246 \layout Subsection
8258 \layout Subsection
8247
8259
8248 The
8260 The
8249 \family typewriter
8261 \family typewriter
8250 numeric
8262 numeric
8251 \family default
8263 \family default
8252 profile: a scientific computing environment
8264 profile: a scientific computing environment
8253 \layout Standard
8265 \layout Standard
8254
8266
8255 The
8267 The
8256 \family typewriter
8268 \family typewriter
8257 numeric
8269 numeric
8258 \family default
8270 \family default
8259 IPython profile, which you can activate with
8271 IPython profile, which you can activate with
8260 \family typewriter
8272 \family typewriter
8261 `ipython -p numeric
8273 `ipython -p numeric
8262 \family default
8274 \family default
8263 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8275 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8264 other useful things for numerical computing), contained in the
8276 other useful things for numerical computing), contained in the
8265 \family typewriter
8277 \family typewriter
8266 IPython.GnuplotInteractive
8278 IPython.GnuplotInteractive
8267 \family default
8279 \family default
8268 module.
8280 module.
8269 This will create the globals
8281 This will create the globals
8270 \family typewriter
8282 \family typewriter
8271 Gnuplot
8283 Gnuplot
8272 \family default
8284 \family default
8273 (an alias to the improved Gnuplot2 module),
8285 (an alias to the improved Gnuplot2 module),
8274 \family typewriter
8286 \family typewriter
8275 gp
8287 gp
8276 \family default
8288 \family default
8277 (a Gnuplot active instance), the new magic commands
8289 (a Gnuplot active instance), the new magic commands
8278 \family typewriter
8290 \family typewriter
8279 %gpc
8291 %gpc
8280 \family default
8292 \family default
8281 and
8293 and
8282 \family typewriter
8294 \family typewriter
8283 %gp_set_instance
8295 %gp_set_instance
8284 \family default
8296 \family default
8285 and several other convenient globals.
8297 and several other convenient globals.
8286 Type
8298 Type
8287 \family typewriter
8299 \family typewriter
8288 gphelp()
8300 gphelp()
8289 \family default
8301 \family default
8290 for further details.
8302 for further details.
8291 \layout Standard
8303 \layout Standard
8292
8304
8293 This should turn IPython into a convenient environment for numerical computing,
8305 This should turn IPython into a convenient environment for numerical computing,
8294 with all the functions in the NumPy library and the Gnuplot facilities
8306 with all the functions in the NumPy library and the Gnuplot facilities
8295 for plotting.
8307 for plotting.
8296 Further improvements can be obtained by loading the SciPy libraries for
8308 Further improvements can be obtained by loading the SciPy libraries for
8297 scientific computing, available at
8309 scientific computing, available at
8298 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8310 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8299
8311
8300 \end_inset
8312 \end_inset
8301
8313
8302 .
8314 .
8303 \layout Standard
8315 \layout Standard
8304
8316
8305 If you are in the middle of a working session with numerical objects and
8317 If you are in the middle of a working session with numerical objects and
8306 need to plot them but you didn't start the
8318 need to plot them but you didn't start the
8307 \family typewriter
8319 \family typewriter
8308 numeric
8320 numeric
8309 \family default
8321 \family default
8310 profile, you can load these extensions at any time by typing
8322 profile, you can load these extensions at any time by typing
8311 \newline
8323 \newline
8312
8324
8313 \family typewriter
8325 \family typewriter
8314 from IPython.GnuplotInteractive import *
8326 from IPython.GnuplotInteractive import *
8315 \newline
8327 \newline
8316
8328
8317 \family default
8329 \family default
8318 at the IPython prompt.
8330 at the IPython prompt.
8319 This will allow you to keep your objects intact and start using Gnuplot
8331 This will allow you to keep your objects intact and start using Gnuplot
8320 to view them.
8332 to view them.
8321 \layout Section
8333 \layout Section
8322
8334
8323 Reporting bugs
8335 Reporting bugs
8324 \layout Subsection*
8336 \layout Subsection*
8325
8337
8326 Automatic crash reports
8338 Automatic crash reports
8327 \layout Standard
8339 \layout Standard
8328
8340
8329 Ideally, IPython itself shouldn't crash.
8341 Ideally, IPython itself shouldn't crash.
8330 It will catch exceptions produced by you, but bugs in its internals will
8342 It will catch exceptions produced by you, but bugs in its internals will
8331 still crash it.
8343 still crash it.
8332 \layout Standard
8344 \layout Standard
8333
8345
8334 In such a situation, IPython will leave a file named
8346 In such a situation, IPython will leave a file named
8335 \family typewriter
8347 \family typewriter
8336 IPython_crash_report.txt
8348 IPython_crash_report.txt
8337 \family default
8349 \family default
8338 in your IPYTHONDIR directory (that way if crashes happen several times
8350 in your IPYTHONDIR directory (that way if crashes happen several times
8339 it won't litter many directories, the post-mortem file is always located
8351 it won't litter many directories, the post-mortem file is always located
8340 in the same place and new occurrences just overwrite the previous one).
8352 in the same place and new occurrences just overwrite the previous one).
8341 If you can mail this file to the developers (see sec.
8353 If you can mail this file to the developers (see sec.
8342
8354
8343 \begin_inset LatexCommand \ref{sec:credits}
8355 \begin_inset LatexCommand \ref{sec:credits}
8344
8356
8345 \end_inset
8357 \end_inset
8346
8358
8347 for names and addresses), it will help us
8359 for names and addresses), it will help us
8348 \emph on
8360 \emph on
8349 a lot
8361 a lot
8350 \emph default
8362 \emph default
8351 in understanding the cause of the problem and fixing it sooner.
8363 in understanding the cause of the problem and fixing it sooner.
8352 \layout Subsection*
8364 \layout Subsection*
8353
8365
8354 The bug tracker
8366 The bug tracker
8355 \layout Standard
8367 \layout Standard
8356
8368
8357 IPython also has an online bug-tracker, located at
8369 IPython also has an online bug-tracker, located at
8358 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8370 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8359
8371
8360 \end_inset
8372 \end_inset
8361
8373
8362 .
8374 .
8363 In addition to mailing the developers, it would be a good idea to file
8375 In addition to mailing the developers, it would be a good idea to file
8364 a bug report here.
8376 a bug report here.
8365 This will ensure that the issue is properly followed to conclusion.
8377 This will ensure that the issue is properly followed to conclusion.
8366 \layout Standard
8378 \layout Standard
8367
8379
8368 You can also use this bug tracker to file feature requests.
8380 You can also use this bug tracker to file feature requests.
8369 \layout Section
8381 \layout Section
8370
8382
8371 Brief history
8383 Brief history
8372 \layout Subsection
8384 \layout Subsection
8373
8385
8374 Origins
8386 Origins
8375 \layout Standard
8387 \layout Standard
8376
8388
8377 The current IPython system grew out of the following three projects:
8389 The current IPython system grew out of the following three projects:
8378 \layout List
8390 \layout List
8379 \labelwidthstring 00.00.0000
8391 \labelwidthstring 00.00.0000
8380
8392
8381 ipython by Fernando Pérez.
8393 ipython by Fernando Pérez.
8382 I was working on adding Mathematica-type prompts and a flexible configuration
8394 I was working on adding Mathematica-type prompts and a flexible configuration
8383 system (something better than
8395 system (something better than
8384 \family typewriter
8396 \family typewriter
8385 $PYTHONSTARTUP
8397 $PYTHONSTARTUP
8386 \family default
8398 \family default
8387 ) to the standard Python interactive interpreter.
8399 ) to the standard Python interactive interpreter.
8388 \layout List
8400 \layout List
8389 \labelwidthstring 00.00.0000
8401 \labelwidthstring 00.00.0000
8390
8402
8391 IPP by Janko Hauser.
8403 IPP by Janko Hauser.
8392 Very well organized, great usability.
8404 Very well organized, great usability.
8393 Had an old help system.
8405 Had an old help system.
8394 IPP was used as the `container' code into which I added the functionality
8406 IPP was used as the `container' code into which I added the functionality
8395 from ipython and LazyPython.
8407 from ipython and LazyPython.
8396 \layout List
8408 \layout List
8397 \labelwidthstring 00.00.0000
8409 \labelwidthstring 00.00.0000
8398
8410
8399 LazyPython by Nathan Gray.
8411 LazyPython by Nathan Gray.
8400 Simple but
8412 Simple but
8401 \emph on
8413 \emph on
8402 very
8414 very
8403 \emph default
8415 \emph default
8404 powerful.
8416 powerful.
8405 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8417 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8406 were all taken from here.
8418 were all taken from here.
8407 \layout Standard
8419 \layout Standard
8408
8420
8409 When I found out (see sec.
8421 When I found out (see sec.
8410
8422
8411 \begin_inset LatexCommand \ref{figgins}
8423 \begin_inset LatexCommand \ref{figgins}
8412
8424
8413 \end_inset
8425 \end_inset
8414
8426
8415 ) about IPP and LazyPython I tried to join all three into a unified system.
8427 ) about IPP and LazyPython I tried to join all three into a unified system.
8416 I thought this could provide a very nice working environment, both for
8428 I thought this could provide a very nice working environment, both for
8417 regular programming and scientific computing: shell-like features, IDL/Matlab
8429 regular programming and scientific computing: shell-like features, IDL/Matlab
8418 numerics, Mathematica-type prompt history and great object introspection
8430 numerics, Mathematica-type prompt history and great object introspection
8419 and help facilities.
8431 and help facilities.
8420 I think it worked reasonably well, though it was a lot more work than I
8432 I think it worked reasonably well, though it was a lot more work than I
8421 had initially planned.
8433 had initially planned.
8422 \layout Subsection
8434 \layout Subsection
8423
8435
8424 Current status
8436 Current status
8425 \layout Standard
8437 \layout Standard
8426
8438
8427 The above listed features work, and quite well for the most part.
8439 The above listed features work, and quite well for the most part.
8428 But until a major internal restructuring is done (see below), only bug
8440 But until a major internal restructuring is done (see below), only bug
8429 fixing will be done, no other features will be added (unless very minor
8441 fixing will be done, no other features will be added (unless very minor
8430 and well localized in the cleaner parts of the code).
8442 and well localized in the cleaner parts of the code).
8431 \layout Standard
8443 \layout Standard
8432
8444
8433 IPython consists of some 12000 lines of pure python code, of which roughly
8445 IPython consists of some 12000 lines of pure python code, of which roughly
8434 50% are fairly clean.
8446 50% are fairly clean.
8435 The other 50% are fragile, messy code which needs a massive restructuring
8447 The other 50% are fragile, messy code which needs a massive restructuring
8436 before any further major work is done.
8448 before any further major work is done.
8437 Even the messy code is fairly well documented though, and most of the problems
8449 Even the messy code is fairly well documented though, and most of the problems
8438 in the (non-existent) class design are well pointed to by a PyChecker run.
8450 in the (non-existent) class design are well pointed to by a PyChecker run.
8439 So the rewriting work isn't that bad, it will just be time-consuming.
8451 So the rewriting work isn't that bad, it will just be time-consuming.
8440 \layout Subsection
8452 \layout Subsection
8441
8453
8442 Future
8454 Future
8443 \layout Standard
8455 \layout Standard
8444
8456
8445 See the separate
8457 See the separate
8446 \family typewriter
8458 \family typewriter
8447 new_design
8459 new_design
8448 \family default
8460 \family default
8449 document for details.
8461 document for details.
8450 Ultimately, I would like to see IPython become part of the standard Python
8462 Ultimately, I would like to see IPython become part of the standard Python
8451 distribution as a `big brother with batteries' to the standard Python interacti
8463 distribution as a `big brother with batteries' to the standard Python interacti
8452 ve interpreter.
8464 ve interpreter.
8453 But that will never happen with the current state of the code, so all contribut
8465 But that will never happen with the current state of the code, so all contribut
8454 ions are welcome.
8466 ions are welcome.
8455 \layout Section
8467 \layout Section
8456
8468
8457 License
8469 License
8458 \layout Standard
8470 \layout Standard
8459
8471
8460 IPython is released under the terms of the BSD license, whose general form
8472 IPython is released under the terms of the BSD license, whose general form
8461 can be found at:
8473 can be found at:
8462 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8474 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8463
8475
8464 \end_inset
8476 \end_inset
8465
8477
8466 .
8478 .
8467 The full text of the IPython license is reproduced below:
8479 The full text of the IPython license is reproduced below:
8468 \layout Quote
8480 \layout Quote
8469
8481
8470
8482
8471 \family typewriter
8483 \family typewriter
8472 \size small
8484 \size small
8473 IPython is released under a BSD-type license.
8485 IPython is released under a BSD-type license.
8474 \layout Quote
8486 \layout Quote
8475
8487
8476
8488
8477 \family typewriter
8489 \family typewriter
8478 \size small
8490 \size small
8479 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8491 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8480 \layout Quote
8492 \layout Quote
8481
8493
8482
8494
8483 \family typewriter
8495 \family typewriter
8484 \size small
8496 \size small
8485 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8497 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8486 \newline
8498 \newline
8487 Nathaniel Gray <n8gray@caltech.edu>.
8499 Nathaniel Gray <n8gray@caltech.edu>.
8488 \layout Quote
8500 \layout Quote
8489
8501
8490
8502
8491 \family typewriter
8503 \family typewriter
8492 \size small
8504 \size small
8493 All rights reserved.
8505 All rights reserved.
8494 \layout Quote
8506 \layout Quote
8495
8507
8496
8508
8497 \family typewriter
8509 \family typewriter
8498 \size small
8510 \size small
8499 Redistribution and use in source and binary forms, with or without modification,
8511 Redistribution and use in source and binary forms, with or without modification,
8500 are permitted provided that the following conditions are met:
8512 are permitted provided that the following conditions are met:
8501 \layout Quote
8513 \layout Quote
8502
8514
8503
8515
8504 \family typewriter
8516 \family typewriter
8505 \size small
8517 \size small
8506 a.
8518 a.
8507 Redistributions of source code must retain the above copyright notice,
8519 Redistributions of source code must retain the above copyright notice,
8508 this list of conditions and the following disclaimer.
8520 this list of conditions and the following disclaimer.
8509 \layout Quote
8521 \layout Quote
8510
8522
8511
8523
8512 \family typewriter
8524 \family typewriter
8513 \size small
8525 \size small
8514 b.
8526 b.
8515 Redistributions in binary form must reproduce the above copyright notice,
8527 Redistributions in binary form must reproduce the above copyright notice,
8516 this list of conditions and the following disclaimer in the documentation
8528 this list of conditions and the following disclaimer in the documentation
8517 and/or other materials provided with the distribution.
8529 and/or other materials provided with the distribution.
8518 \layout Quote
8530 \layout Quote
8519
8531
8520
8532
8521 \family typewriter
8533 \family typewriter
8522 \size small
8534 \size small
8523 c.
8535 c.
8524 Neither the name of the copyright holders nor the names of any contributors
8536 Neither the name of the copyright holders nor the names of any contributors
8525 to this software may be used to endorse or promote products derived from
8537 to this software may be used to endorse or promote products derived from
8526 this software without specific prior written permission.
8538 this software without specific prior written permission.
8527 \layout Quote
8539 \layout Quote
8528
8540
8529
8541
8530 \family typewriter
8542 \family typewriter
8531 \size small
8543 \size small
8532 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8544 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8533 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8545 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8534 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8546 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8535 PURPOSE ARE DISCLAIMED.
8547 PURPOSE ARE DISCLAIMED.
8536 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8548 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8537 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8549 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8538 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8550 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8539 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8551 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8540 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8552 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8541 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8553 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8542 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8554 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8543
8555
8544 \layout Standard
8556 \layout Standard
8545
8557
8546 Individual authors are the holders of the copyright for their code and are
8558 Individual authors are the holders of the copyright for their code and are
8547 listed in each file.
8559 listed in each file.
8548 \layout Standard
8560 \layout Standard
8549
8561
8550 Some files (
8562 Some files (
8551 \family typewriter
8563 \family typewriter
8552 DPyGetOpt.py
8564 DPyGetOpt.py
8553 \family default
8565 \family default
8554 , for example) may be licensed under different conditions.
8566 , for example) may be licensed under different conditions.
8555 Ultimately each file indicates clearly the conditions under which its author/au
8567 Ultimately each file indicates clearly the conditions under which its author/au
8556 thors have decided to publish the code.
8568 thors have decided to publish the code.
8557 \layout Standard
8569 \layout Standard
8558
8570
8559 Versions of IPython up to and including 0.6.3 were released under the GNU
8571 Versions of IPython up to and including 0.6.3 were released under the GNU
8560 Lesser General Public License (LGPL), available at
8572 Lesser General Public License (LGPL), available at
8561 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8573 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8562
8574
8563 \end_inset
8575 \end_inset
8564
8576
8565 .
8577 .
8566 \layout Section
8578 \layout Section
8567
8579
8568
8580
8569 \begin_inset LatexCommand \label{sec:credits}
8581 \begin_inset LatexCommand \label{sec:credits}
8570
8582
8571 \end_inset
8583 \end_inset
8572
8584
8573 Credits
8585 Credits
8574 \layout Standard
8586 \layout Standard
8575
8587
8576 IPython is mainly developed by Fernando Pérez
8588 IPython is mainly developed by Fernando Pérez
8577 \family typewriter
8589 \family typewriter
8578 <fperez@colorado.edu>
8590 <fperez@colorado.edu>
8579 \family default
8591 \family default
8580 , but the project was born from mixing in Fernando's code with the IPP project
8592 , but the project was born from mixing in Fernando's code with the IPP project
8581 by Janko Hauser
8593 by Janko Hauser
8582 \family typewriter
8594 \family typewriter
8583 <jhauser-AT-zscout.de>
8595 <jhauser-AT-zscout.de>
8584 \family default
8596 \family default
8585 and LazyPython by Nathan Gray
8597 and LazyPython by Nathan Gray
8586 \family typewriter
8598 \family typewriter
8587 <n8gray-AT-caltech.edu>
8599 <n8gray-AT-caltech.edu>
8588 \family default
8600 \family default
8589 .
8601 .
8590 For all IPython-related requests, please contact Fernando.
8602 For all IPython-related requests, please contact Fernando.
8591
8603
8592 \layout Standard
8604 \layout Standard
8593
8605
8594 As of late 2005, the following developers have joined the core team:
8606 As of late 2005, the following developers have joined the core team:
8595 \layout List
8607 \layout List
8596 \labelwidthstring 00.00.0000
8608 \labelwidthstring 00.00.0000
8597
8609
8598 Robert\SpecialChar ~
8610 Robert\SpecialChar ~
8599 Kern
8611 Kern
8600 \family typewriter
8612 \family typewriter
8601 <rkern-AT-enthought.com>
8613 <rkern-AT-enthought.com>
8602 \family default
8614 \family default
8603 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8615 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8604 ve notebooks (XML documents) and graphical interface.
8616 ve notebooks (XML documents) and graphical interface.
8605 This project was awarded to the students Tzanko Matev
8617 This project was awarded to the students Tzanko Matev
8606 \family typewriter
8618 \family typewriter
8607 <tsanko-AT-gmail.com>
8619 <tsanko-AT-gmail.com>
8608 \family default
8620 \family default
8609 and Toni Alatalo
8621 and Toni Alatalo
8610 \family typewriter
8622 \family typewriter
8611 <antont-AT-an.org>
8623 <antont-AT-an.org>
8612 \layout List
8624 \layout List
8613 \labelwidthstring 00.00.0000
8625 \labelwidthstring 00.00.0000
8614
8626
8615 Brian\SpecialChar ~
8627 Brian\SpecialChar ~
8616 Granger
8628 Granger
8617 \family typewriter
8629 \family typewriter
8618 <bgranger-AT-scu.edu>
8630 <bgranger-AT-scu.edu>
8619 \family default
8631 \family default
8620 : extending IPython to allow support for interactive parallel computing.
8632 : extending IPython to allow support for interactive parallel computing.
8621 \layout Standard
8633 \layout Standard
8622
8634
8623 User or development help should be requested via the IPython mailing lists:
8635 User or development help should be requested via the IPython mailing lists:
8624 \layout Description
8636 \layout Description
8625
8637
8626 User\SpecialChar ~
8638 User\SpecialChar ~
8627 list:
8639 list:
8628 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8640 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8629
8641
8630 \end_inset
8642 \end_inset
8631
8643
8632
8644
8633 \layout Description
8645 \layout Description
8634
8646
8635 Developer's\SpecialChar ~
8647 Developer's\SpecialChar ~
8636 list:
8648 list:
8637 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8649 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8638
8650
8639 \end_inset
8651 \end_inset
8640
8652
8641
8653
8642 \layout Standard
8654 \layout Standard
8643
8655
8644 The IPython project is also very grateful to
8656 The IPython project is also very grateful to
8645 \begin_inset Foot
8657 \begin_inset Foot
8646 collapsed true
8658 collapsed true
8647
8659
8648 \layout Standard
8660 \layout Standard
8649
8661
8650 I've mangled email addresses to reduce spam, since the IPython manuals can
8662 I've mangled email addresses to reduce spam, since the IPython manuals can
8651 be accessed online.
8663 be accessed online.
8652 \end_inset
8664 \end_inset
8653
8665
8654 :
8666 :
8655 \layout Standard
8667 \layout Standard
8656
8668
8657 Bill Bumgarner
8669 Bill Bumgarner
8658 \family typewriter
8670 \family typewriter
8659 <bbum-AT-friday.com>
8671 <bbum-AT-friday.com>
8660 \family default
8672 \family default
8661 : for providing the DPyGetOpt module which gives very powerful and convenient
8673 : for providing the DPyGetOpt module which gives very powerful and convenient
8662 handling of command-line options (light years ahead of what Python 2.1.1's
8674 handling of command-line options (light years ahead of what Python 2.1.1's
8663 getopt module does).
8675 getopt module does).
8664 \layout Standard
8676 \layout Standard
8665
8677
8666 Ka-Ping Yee
8678 Ka-Ping Yee
8667 \family typewriter
8679 \family typewriter
8668 <ping-AT-lfw.org>
8680 <ping-AT-lfw.org>
8669 \family default
8681 \family default
8670 : for providing the Itpl module for convenient and powerful string interpolation
8682 : for providing the Itpl module for convenient and powerful string interpolation
8671 with a much nicer syntax than formatting through the '%' operator.
8683 with a much nicer syntax than formatting through the '%' operator.
8672 \layout Standard
8684 \layout Standard
8673
8685
8674 Arnd Bäcker
8686 Arnd Bäcker
8675 \family typewriter
8687 \family typewriter
8676 <baecker-AT-physik.tu-dresden.de>
8688 <baecker-AT-physik.tu-dresden.de>
8677 \family default
8689 \family default
8678 : for his many very useful suggestions and comments, and lots of help with
8690 : for his many very useful suggestions and comments, and lots of help with
8679 testing and documentation checking.
8691 testing and documentation checking.
8680 Many of IPython's newer features are a result of discussions with him (bugs
8692 Many of IPython's newer features are a result of discussions with him (bugs
8681 are still my fault, not his).
8693 are still my fault, not his).
8682 \layout Standard
8694 \layout Standard
8683
8695
8684 Obviously Guido van\SpecialChar ~
8696 Obviously Guido van\SpecialChar ~
8685 Rossum and the whole Python development team, that goes
8697 Rossum and the whole Python development team, that goes
8686 without saying.
8698 without saying.
8687 \layout Standard
8699 \layout Standard
8688
8700
8689 IPython's website is generously hosted at
8701 IPython's website is generously hosted at
8690 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
8702 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
8691
8703
8692 \end_inset
8704 \end_inset
8693
8705
8694 by Enthought (
8706 by Enthought (
8695 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
8707 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
8696
8708
8697 \end_inset
8709 \end_inset
8698
8710
8699 ).
8711 ).
8700 I am very grateful to them and all of the SciPy team for their contribution.
8712 I am very grateful to them and all of the SciPy team for their contribution.
8701 \layout Standard
8713 \layout Standard
8702
8714
8703
8715
8704 \begin_inset LatexCommand \label{figgins}
8716 \begin_inset LatexCommand \label{figgins}
8705
8717
8706 \end_inset
8718 \end_inset
8707
8719
8708 Fernando would also like to thank Stephen Figgins
8720 Fernando would also like to thank Stephen Figgins
8709 \family typewriter
8721 \family typewriter
8710 <fig-AT-monitor.net>
8722 <fig-AT-monitor.net>
8711 \family default
8723 \family default
8712 , an O'Reilly Python editor.
8724 , an O'Reilly Python editor.
8713 His Oct/11/2001 article about IPP and LazyPython, was what got this project
8725 His Oct/11/2001 article about IPP and LazyPython, was what got this project
8714 started.
8726 started.
8715 You can read it at:
8727 You can read it at:
8716 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
8728 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
8717
8729
8718 \end_inset
8730 \end_inset
8719
8731
8720 .
8732 .
8721 \layout Standard
8733 \layout Standard
8722
8734
8723 And last but not least, all the kind IPython users who have emailed new
8735 And last but not least, all the kind IPython users who have emailed new
8724 code, bug reports, fixes, comments and ideas.
8736 code, bug reports, fixes, comments and ideas.
8725 A brief list follows, please let me know if I have ommitted your name by
8737 A brief list follows, please let me know if I have ommitted your name by
8726 accident:
8738 accident:
8727 \layout List
8739 \layout List
8728 \labelwidthstring 00.00.0000
8740 \labelwidthstring 00.00.0000
8729
8741
8730 Jack\SpecialChar ~
8742 Jack\SpecialChar ~
8731 Moffit
8743 Moffit
8732 \family typewriter
8744 \family typewriter
8733 <jack-AT-xiph.org>
8745 <jack-AT-xiph.org>
8734 \family default
8746 \family default
8735 Bug fixes, including the infamous color problem.
8747 Bug fixes, including the infamous color problem.
8736 This bug alone caused many lost hours and frustration, many thanks to him
8748 This bug alone caused many lost hours and frustration, many thanks to him
8737 for the fix.
8749 for the fix.
8738 I've always been a fan of Ogg & friends, now I have one more reason to
8750 I've always been a fan of Ogg & friends, now I have one more reason to
8739 like these folks.
8751 like these folks.
8740 \newline
8752 \newline
8741 Jack is also contributing with Debian packaging and many other things.
8753 Jack is also contributing with Debian packaging and many other things.
8742 \layout List
8754 \layout List
8743 \labelwidthstring 00.00.0000
8755 \labelwidthstring 00.00.0000
8744
8756
8745 Alexander\SpecialChar ~
8757 Alexander\SpecialChar ~
8746 Schmolck
8758 Schmolck
8747 \family typewriter
8759 \family typewriter
8748 <a.schmolck-AT-gmx.net>
8760 <a.schmolck-AT-gmx.net>
8749 \family default
8761 \family default
8750 Emacs work, bug reports, bug fixes, ideas, lots more.
8762 Emacs work, bug reports, bug fixes, ideas, lots more.
8751 The ipython.el mode for (X)Emacs is Alex's code, providing full support
8763 The ipython.el mode for (X)Emacs is Alex's code, providing full support
8752 for IPython under (X)Emacs.
8764 for IPython under (X)Emacs.
8753 \layout List
8765 \layout List
8754 \labelwidthstring 00.00.0000
8766 \labelwidthstring 00.00.0000
8755
8767
8756 Andrea\SpecialChar ~
8768 Andrea\SpecialChar ~
8757 Riciputi
8769 Riciputi
8758 \family typewriter
8770 \family typewriter
8759 <andrea.riciputi-AT-libero.it>
8771 <andrea.riciputi-AT-libero.it>
8760 \family default
8772 \family default
8761 Mac OSX information, Fink package management.
8773 Mac OSX information, Fink package management.
8762 \layout List
8774 \layout List
8763 \labelwidthstring 00.00.0000
8775 \labelwidthstring 00.00.0000
8764
8776
8765 Gary\SpecialChar ~
8777 Gary\SpecialChar ~
8766 Bishop
8778 Bishop
8767 \family typewriter
8779 \family typewriter
8768 <gb-AT-cs.unc.edu>
8780 <gb-AT-cs.unc.edu>
8769 \family default
8781 \family default
8770 Bug reports, and patches to work around the exception handling idiosyncracies
8782 Bug reports, and patches to work around the exception handling idiosyncracies
8771 of WxPython.
8783 of WxPython.
8772 Readline and color support for Windows.
8784 Readline and color support for Windows.
8773 \layout List
8785 \layout List
8774 \labelwidthstring 00.00.0000
8786 \labelwidthstring 00.00.0000
8775
8787
8776 Jeffrey\SpecialChar ~
8788 Jeffrey\SpecialChar ~
8777 Collins
8789 Collins
8778 \family typewriter
8790 \family typewriter
8779 <Jeff.Collins-AT-vexcel.com>
8791 <Jeff.Collins-AT-vexcel.com>
8780 \family default
8792 \family default
8781 Bug reports.
8793 Bug reports.
8782 Much improved readline support, including fixes for Python 2.3.
8794 Much improved readline support, including fixes for Python 2.3.
8783 \layout List
8795 \layout List
8784 \labelwidthstring 00.00.0000
8796 \labelwidthstring 00.00.0000
8785
8797
8786 Dryice\SpecialChar ~
8798 Dryice\SpecialChar ~
8787 Liu
8799 Liu
8788 \family typewriter
8800 \family typewriter
8789 <dryice-AT-liu.com.cn>
8801 <dryice-AT-liu.com.cn>
8790 \family default
8802 \family default
8791 FreeBSD port.
8803 FreeBSD port.
8792 \layout List
8804 \layout List
8793 \labelwidthstring 00.00.0000
8805 \labelwidthstring 00.00.0000
8794
8806
8795 Mike\SpecialChar ~
8807 Mike\SpecialChar ~
8796 Heeter
8808 Heeter
8797 \family typewriter
8809 \family typewriter
8798 <korora-AT-SDF.LONESTAR.ORG>
8810 <korora-AT-SDF.LONESTAR.ORG>
8799 \layout List
8811 \layout List
8800 \labelwidthstring 00.00.0000
8812 \labelwidthstring 00.00.0000
8801
8813
8802 Christopher\SpecialChar ~
8814 Christopher\SpecialChar ~
8803 Hart
8815 Hart
8804 \family typewriter
8816 \family typewriter
8805 <hart-AT-caltech.edu>
8817 <hart-AT-caltech.edu>
8806 \family default
8818 \family default
8807 PDB integration.
8819 PDB integration.
8808 \layout List
8820 \layout List
8809 \labelwidthstring 00.00.0000
8821 \labelwidthstring 00.00.0000
8810
8822
8811 Milan\SpecialChar ~
8823 Milan\SpecialChar ~
8812 Zamazal
8824 Zamazal
8813 \family typewriter
8825 \family typewriter
8814 <pdm-AT-zamazal.org>
8826 <pdm-AT-zamazal.org>
8815 \family default
8827 \family default
8816 Emacs info.
8828 Emacs info.
8817 \layout List
8829 \layout List
8818 \labelwidthstring 00.00.0000
8830 \labelwidthstring 00.00.0000
8819
8831
8820 Philip\SpecialChar ~
8832 Philip\SpecialChar ~
8821 Hisley
8833 Hisley
8822 \family typewriter
8834 \family typewriter
8823 <compsys-AT-starpower.net>
8835 <compsys-AT-starpower.net>
8824 \layout List
8836 \layout List
8825 \labelwidthstring 00.00.0000
8837 \labelwidthstring 00.00.0000
8826
8838
8827 Holger\SpecialChar ~
8839 Holger\SpecialChar ~
8828 Krekel
8840 Krekel
8829 \family typewriter
8841 \family typewriter
8830 <pyth-AT-devel.trillke.net>
8842 <pyth-AT-devel.trillke.net>
8831 \family default
8843 \family default
8832 Tab completion, lots more.
8844 Tab completion, lots more.
8833 \layout List
8845 \layout List
8834 \labelwidthstring 00.00.0000
8846 \labelwidthstring 00.00.0000
8835
8847
8836 Robin\SpecialChar ~
8848 Robin\SpecialChar ~
8837 Siebler
8849 Siebler
8838 \family typewriter
8850 \family typewriter
8839 <robinsiebler-AT-starband.net>
8851 <robinsiebler-AT-starband.net>
8840 \layout List
8852 \layout List
8841 \labelwidthstring 00.00.0000
8853 \labelwidthstring 00.00.0000
8842
8854
8843 Ralf\SpecialChar ~
8855 Ralf\SpecialChar ~
8844 Ahlbrink
8856 Ahlbrink
8845 \family typewriter
8857 \family typewriter
8846 <ralf_ahlbrink-AT-web.de>
8858 <ralf_ahlbrink-AT-web.de>
8847 \layout List
8859 \layout List
8848 \labelwidthstring 00.00.0000
8860 \labelwidthstring 00.00.0000
8849
8861
8850 Thorsten\SpecialChar ~
8862 Thorsten\SpecialChar ~
8851 Kampe
8863 Kampe
8852 \family typewriter
8864 \family typewriter
8853 <thorsten-AT-thorstenkampe.de>
8865 <thorsten-AT-thorstenkampe.de>
8854 \layout List
8866 \layout List
8855 \labelwidthstring 00.00.0000
8867 \labelwidthstring 00.00.0000
8856
8868
8857 Fredrik\SpecialChar ~
8869 Fredrik\SpecialChar ~
8858 Kant
8870 Kant
8859 \family typewriter
8871 \family typewriter
8860 <fredrik.kant-AT-front.com>
8872 <fredrik.kant-AT-front.com>
8861 \family default
8873 \family default
8862 Windows setup.
8874 Windows setup.
8863 \layout List
8875 \layout List
8864 \labelwidthstring 00.00.0000
8876 \labelwidthstring 00.00.0000
8865
8877
8866 Syver\SpecialChar ~
8878 Syver\SpecialChar ~
8867 Enstad
8879 Enstad
8868 \family typewriter
8880 \family typewriter
8869 <syver-en-AT-online.no>
8881 <syver-en-AT-online.no>
8870 \family default
8882 \family default
8871 Windows setup.
8883 Windows setup.
8872 \layout List
8884 \layout List
8873 \labelwidthstring 00.00.0000
8885 \labelwidthstring 00.00.0000
8874
8886
8875 Richard
8887 Richard
8876 \family typewriter
8888 \family typewriter
8877 <rxe-AT-renre-europe.com>
8889 <rxe-AT-renre-europe.com>
8878 \family default
8890 \family default
8879 Global embedding.
8891 Global embedding.
8880 \layout List
8892 \layout List
8881 \labelwidthstring 00.00.0000
8893 \labelwidthstring 00.00.0000
8882
8894
8883 Hayden\SpecialChar ~
8895 Hayden\SpecialChar ~
8884 Callow
8896 Callow
8885 \family typewriter
8897 \family typewriter
8886 <h.callow-AT-elec.canterbury.ac.nz>
8898 <h.callow-AT-elec.canterbury.ac.nz>
8887 \family default
8899 \family default
8888 Gnuplot.py 1.6 compatibility.
8900 Gnuplot.py 1.6 compatibility.
8889 \layout List
8901 \layout List
8890 \labelwidthstring 00.00.0000
8902 \labelwidthstring 00.00.0000
8891
8903
8892 Leonardo\SpecialChar ~
8904 Leonardo\SpecialChar ~
8893 Santagada
8905 Santagada
8894 \family typewriter
8906 \family typewriter
8895 <retype-AT-terra.com.br>
8907 <retype-AT-terra.com.br>
8896 \family default
8908 \family default
8897 Fixes for Windows installation.
8909 Fixes for Windows installation.
8898 \layout List
8910 \layout List
8899 \labelwidthstring 00.00.0000
8911 \labelwidthstring 00.00.0000
8900
8912
8901 Christopher\SpecialChar ~
8913 Christopher\SpecialChar ~
8902 Armstrong
8914 Armstrong
8903 \family typewriter
8915 \family typewriter
8904 <radix-AT-twistedmatrix.com>
8916 <radix-AT-twistedmatrix.com>
8905 \family default
8917 \family default
8906 Bugfixes.
8918 Bugfixes.
8907 \layout List
8919 \layout List
8908 \labelwidthstring 00.00.0000
8920 \labelwidthstring 00.00.0000
8909
8921
8910 Francois\SpecialChar ~
8922 Francois\SpecialChar ~
8911 Pinard
8923 Pinard
8912 \family typewriter
8924 \family typewriter
8913 <pinard-AT-iro.umontreal.ca>
8925 <pinard-AT-iro.umontreal.ca>
8914 \family default
8926 \family default
8915 Code and documentation fixes.
8927 Code and documentation fixes.
8916 \layout List
8928 \layout List
8917 \labelwidthstring 00.00.0000
8929 \labelwidthstring 00.00.0000
8918
8930
8919 Cory\SpecialChar ~
8931 Cory\SpecialChar ~
8920 Dodt
8932 Dodt
8921 \family typewriter
8933 \family typewriter
8922 <cdodt-AT-fcoe.k12.ca.us>
8934 <cdodt-AT-fcoe.k12.ca.us>
8923 \family default
8935 \family default
8924 Bug reports and Windows ideas.
8936 Bug reports and Windows ideas.
8925 Patches for Windows installer.
8937 Patches for Windows installer.
8926 \layout List
8938 \layout List
8927 \labelwidthstring 00.00.0000
8939 \labelwidthstring 00.00.0000
8928
8940
8929 Olivier\SpecialChar ~
8941 Olivier\SpecialChar ~
8930 Aubert
8942 Aubert
8931 \family typewriter
8943 \family typewriter
8932 <oaubert-AT-bat710.univ-lyon1.fr>
8944 <oaubert-AT-bat710.univ-lyon1.fr>
8933 \family default
8945 \family default
8934 New magics.
8946 New magics.
8935 \layout List
8947 \layout List
8936 \labelwidthstring 00.00.0000
8948 \labelwidthstring 00.00.0000
8937
8949
8938 King\SpecialChar ~
8950 King\SpecialChar ~
8939 C.\SpecialChar ~
8951 C.\SpecialChar ~
8940 Shu
8952 Shu
8941 \family typewriter
8953 \family typewriter
8942 <kingshu-AT-myrealbox.com>
8954 <kingshu-AT-myrealbox.com>
8943 \family default
8955 \family default
8944 Autoindent patch.
8956 Autoindent patch.
8945 \layout List
8957 \layout List
8946 \labelwidthstring 00.00.0000
8958 \labelwidthstring 00.00.0000
8947
8959
8948 Chris\SpecialChar ~
8960 Chris\SpecialChar ~
8949 Drexler
8961 Drexler
8950 \family typewriter
8962 \family typewriter
8951 <chris-AT-ac-drexler.de>
8963 <chris-AT-ac-drexler.de>
8952 \family default
8964 \family default
8953 Readline packages for Win32/CygWin.
8965 Readline packages for Win32/CygWin.
8954 \layout List
8966 \layout List
8955 \labelwidthstring 00.00.0000
8967 \labelwidthstring 00.00.0000
8956
8968
8957 Gustavo\SpecialChar ~
8969 Gustavo\SpecialChar ~
8958 Córdova\SpecialChar ~
8970 Córdova\SpecialChar ~
8959 Avila
8971 Avila
8960 \family typewriter
8972 \family typewriter
8961 <gcordova-AT-sismex.com>
8973 <gcordova-AT-sismex.com>
8962 \family default
8974 \family default
8963 EvalDict code for nice, lightweight string interpolation.
8975 EvalDict code for nice, lightweight string interpolation.
8964 \layout List
8976 \layout List
8965 \labelwidthstring 00.00.0000
8977 \labelwidthstring 00.00.0000
8966
8978
8967 Kasper\SpecialChar ~
8979 Kasper\SpecialChar ~
8968 Souren
8980 Souren
8969 \family typewriter
8981 \family typewriter
8970 <Kasper.Souren-AT-ircam.fr>
8982 <Kasper.Souren-AT-ircam.fr>
8971 \family default
8983 \family default
8972 Bug reports, ideas.
8984 Bug reports, ideas.
8973 \layout List
8985 \layout List
8974 \labelwidthstring 00.00.0000
8986 \labelwidthstring 00.00.0000
8975
8987
8976 Gever\SpecialChar ~
8988 Gever\SpecialChar ~
8977 Tulley
8989 Tulley
8978 \family typewriter
8990 \family typewriter
8979 <gever-AT-helium.com>
8991 <gever-AT-helium.com>
8980 \family default
8992 \family default
8981 Code contributions.
8993 Code contributions.
8982 \layout List
8994 \layout List
8983 \labelwidthstring 00.00.0000
8995 \labelwidthstring 00.00.0000
8984
8996
8985 Ralf\SpecialChar ~
8997 Ralf\SpecialChar ~
8986 Schmitt
8998 Schmitt
8987 \family typewriter
8999 \family typewriter
8988 <ralf-AT-brainbot.com>
9000 <ralf-AT-brainbot.com>
8989 \family default
9001 \family default
8990 Bug reports & fixes.
9002 Bug reports & fixes.
8991 \layout List
9003 \layout List
8992 \labelwidthstring 00.00.0000
9004 \labelwidthstring 00.00.0000
8993
9005
8994 Oliver\SpecialChar ~
9006 Oliver\SpecialChar ~
8995 Sander
9007 Sander
8996 \family typewriter
9008 \family typewriter
8997 <osander-AT-gmx.de>
9009 <osander-AT-gmx.de>
8998 \family default
9010 \family default
8999 Bug reports.
9011 Bug reports.
9000 \layout List
9012 \layout List
9001 \labelwidthstring 00.00.0000
9013 \labelwidthstring 00.00.0000
9002
9014
9003 Rod\SpecialChar ~
9015 Rod\SpecialChar ~
9004 Holland
9016 Holland
9005 \family typewriter
9017 \family typewriter
9006 <rhh-AT-structurelabs.com>
9018 <rhh-AT-structurelabs.com>
9007 \family default
9019 \family default
9008 Bug reports and fixes to logging module.
9020 Bug reports and fixes to logging module.
9009 \layout List
9021 \layout List
9010 \labelwidthstring 00.00.0000
9022 \labelwidthstring 00.00.0000
9011
9023
9012 Daniel\SpecialChar ~
9024 Daniel\SpecialChar ~
9013 'Dang'\SpecialChar ~
9025 'Dang'\SpecialChar ~
9014 Griffith
9026 Griffith
9015 \family typewriter
9027 \family typewriter
9016 <pythondev-dang-AT-lazytwinacres.net>
9028 <pythondev-dang-AT-lazytwinacres.net>
9017 \family default
9029 \family default
9018 Fixes, enhancement suggestions for system shell use.
9030 Fixes, enhancement suggestions for system shell use.
9019 \layout List
9031 \layout List
9020 \labelwidthstring 00.00.0000
9032 \labelwidthstring 00.00.0000
9021
9033
9022 Viktor\SpecialChar ~
9034 Viktor\SpecialChar ~
9023 Ransmayr
9035 Ransmayr
9024 \family typewriter
9036 \family typewriter
9025 <viktor.ransmayr-AT-t-online.de>
9037 <viktor.ransmayr-AT-t-online.de>
9026 \family default
9038 \family default
9027 Tests and reports on Windows installation issues.
9039 Tests and reports on Windows installation issues.
9028 Contributed a true Windows binary installer.
9040 Contributed a true Windows binary installer.
9029 \layout List
9041 \layout List
9030 \labelwidthstring 00.00.0000
9042 \labelwidthstring 00.00.0000
9031
9043
9032 Mike\SpecialChar ~
9044 Mike\SpecialChar ~
9033 Salib
9045 Salib
9034 \family typewriter
9046 \family typewriter
9035 <msalib-AT-mit.edu>
9047 <msalib-AT-mit.edu>
9036 \family default
9048 \family default
9037 Help fixing a subtle bug related to traceback printing.
9049 Help fixing a subtle bug related to traceback printing.
9038 \layout List
9050 \layout List
9039 \labelwidthstring 00.00.0000
9051 \labelwidthstring 00.00.0000
9040
9052
9041 W.J.\SpecialChar ~
9053 W.J.\SpecialChar ~
9042 van\SpecialChar ~
9054 van\SpecialChar ~
9043 der\SpecialChar ~
9055 der\SpecialChar ~
9044 Laan
9056 Laan
9045 \family typewriter
9057 \family typewriter
9046 <gnufnork-AT-hetdigitalegat.nl>
9058 <gnufnork-AT-hetdigitalegat.nl>
9047 \family default
9059 \family default
9048 Bash-like prompt specials.
9060 Bash-like prompt specials.
9049 \layout List
9061 \layout List
9050 \labelwidthstring 00.00.0000
9062 \labelwidthstring 00.00.0000
9051
9063
9052 Ville\SpecialChar ~
9064 Ville\SpecialChar ~
9053 Vainio
9065 Vainio
9054 \family typewriter
9066 \family typewriter
9055 <vivainio-AT-kolumbus.fi>
9067 <vivainio-AT-kolumbus.fi>
9056 \family default
9068 \family default
9057 Bugfixes and suggestions.
9069 Bugfixes and suggestions.
9058 Excellent patches for many new features.
9070 Excellent patches for many new features.
9059 \layout List
9071 \layout List
9060 \labelwidthstring 00.00.0000
9072 \labelwidthstring 00.00.0000
9061
9073
9062 Antoon\SpecialChar ~
9074 Antoon\SpecialChar ~
9063 Pardon
9075 Pardon
9064 \family typewriter
9076 \family typewriter
9065 <Antoon.Pardon-AT-rece.vub.ac.be>
9077 <Antoon.Pardon-AT-rece.vub.ac.be>
9066 \family default
9078 \family default
9067 Critical fix for the multithreaded IPython.
9079 Critical fix for the multithreaded IPython.
9068 \layout List
9080 \layout List
9069 \labelwidthstring 00.00.0000
9081 \labelwidthstring 00.00.0000
9070
9082
9071 John\SpecialChar ~
9083 John\SpecialChar ~
9072 Hunter
9084 Hunter
9073 \family typewriter
9085 \family typewriter
9074 <jdhunter-AT-nitace.bsd.uchicago.edu>
9086 <jdhunter-AT-nitace.bsd.uchicago.edu>
9075 \family default
9087 \family default
9076 Matplotlib author, helped with all the development of support for matplotlib
9088 Matplotlib author, helped with all the development of support for matplotlib
9077 in IPyhton, including making necessary changes to matplotlib itself.
9089 in IPyhton, including making necessary changes to matplotlib itself.
9078 \layout List
9090 \layout List
9079 \labelwidthstring 00.00.0000
9091 \labelwidthstring 00.00.0000
9080
9092
9081 Matthew\SpecialChar ~
9093 Matthew\SpecialChar ~
9082 Arnison
9094 Arnison
9083 \family typewriter
9095 \family typewriter
9084 <maffew-AT-cat.org.au>
9096 <maffew-AT-cat.org.au>
9085 \family default
9097 \family default
9086 Bug reports, `
9098 Bug reports, `
9087 \family typewriter
9099 \family typewriter
9088 %run -d
9100 %run -d
9089 \family default
9101 \family default
9090 ' idea.
9102 ' idea.
9091 \layout List
9103 \layout List
9092 \labelwidthstring 00.00.0000
9104 \labelwidthstring 00.00.0000
9093
9105
9094 Prabhu\SpecialChar ~
9106 Prabhu\SpecialChar ~
9095 Ramachandran
9107 Ramachandran
9096 \family typewriter
9108 \family typewriter
9097 <prabhu_r-AT-users.sourceforge.net>
9109 <prabhu_r-AT-users.sourceforge.net>
9098 \family default
9110 \family default
9099 Help with (X)Emacs support, threading patches, ideas...
9111 Help with (X)Emacs support, threading patches, ideas...
9100 \layout List
9112 \layout List
9101 \labelwidthstring 00.00.0000
9113 \labelwidthstring 00.00.0000
9102
9114
9103 Norbert\SpecialChar ~
9115 Norbert\SpecialChar ~
9104 Tretkowski
9116 Tretkowski
9105 \family typewriter
9117 \family typewriter
9106 <tretkowski-AT-inittab.de>
9118 <tretkowski-AT-inittab.de>
9107 \family default
9119 \family default
9108 help with Debian packaging and distribution.
9120 help with Debian packaging and distribution.
9109 \layout List
9121 \layout List
9110 \labelwidthstring 00.00.0000
9122 \labelwidthstring 00.00.0000
9111
9123
9112 George\SpecialChar ~
9124 George\SpecialChar ~
9113 Sakkis <
9125 Sakkis <
9114 \family typewriter
9126 \family typewriter
9115 gsakkis-AT-eden.rutgers.edu>
9127 gsakkis-AT-eden.rutgers.edu>
9116 \family default
9128 \family default
9117 New matcher for tab-completing named arguments of user-defined functions.
9129 New matcher for tab-completing named arguments of user-defined functions.
9118 \layout List
9130 \layout List
9119 \labelwidthstring 00.00.0000
9131 \labelwidthstring 00.00.0000
9120
9132
9121 J�rgen\SpecialChar ~
9133 J�rgen\SpecialChar ~
9122 Stenarson
9134 Stenarson
9123 \family typewriter
9135 \family typewriter
9124 <jorgen.stenarson-AT-bostream.nu>
9136 <jorgen.stenarson-AT-bostream.nu>
9125 \family default
9137 \family default
9126 Wildcard support implementation for searching namespaces.
9138 Wildcard support implementation for searching namespaces.
9127 \layout List
9139 \layout List
9128 \labelwidthstring 00.00.0000
9140 \labelwidthstring 00.00.0000
9129
9141
9130 Vivian\SpecialChar ~
9142 Vivian\SpecialChar ~
9131 De\SpecialChar ~
9143 De\SpecialChar ~
9132 Smedt
9144 Smedt
9133 \family typewriter
9145 \family typewriter
9134 <vivian-AT-vdesmedt.com>
9146 <vivian-AT-vdesmedt.com>
9135 \family default
9147 \family default
9136 Debugger enhancements, so that when pdb is activated from within IPython,
9148 Debugger enhancements, so that when pdb is activated from within IPython,
9137 coloring, tab completion and other features continue to work seamlessly.
9149 coloring, tab completion and other features continue to work seamlessly.
9138 \layout List
9150 \layout List
9139 \labelwidthstring 00.00.0000
9151 \labelwidthstring 00.00.0000
9140
9152
9141 Scott\SpecialChar ~
9153 Scott\SpecialChar ~
9142 Tsai
9154 Tsai
9143 \family typewriter
9155 \family typewriter
9144 <scottt958-AT-yahoo.com.tw>
9156 <scottt958-AT-yahoo.com.tw>
9145 \family default
9157 \family default
9146 Support for automatic editor invocation on syntax errors (see
9158 Support for automatic editor invocation on syntax errors (see
9147 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
9159 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
9148
9160
9149 \end_inset
9161 \end_inset
9150
9162
9151 ).
9163 ).
9152 \layout List
9164 \layout List
9153 \labelwidthstring 00.00.0000
9165 \labelwidthstring 00.00.0000
9154
9166
9155 Alexander\SpecialChar ~
9167 Alexander\SpecialChar ~
9156 Belchenko
9168 Belchenko
9157 \family typewriter
9169 \family typewriter
9158 <bialix-AT-ukr.net>
9170 <bialix-AT-ukr.net>
9159 \family default
9171 \family default
9160 Improvements for win32 paging system.
9172 Improvements for win32 paging system.
9161 \the_end
9173 \the_end
General Comments 0
You need to be logged in to leave comments. Login now