##// END OF EJS Templates
Added support for automatically reopening the editor if the file had a...
fperez -
Show More
@@ -1,2579 +1,2579 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 958 2005-12-27 23:17:51Z fperez $"""
4 $Id: Magic.py 960 2005-12-28 06:51:01Z 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 from cStringIO import StringIO
33 from cStringIO import StringIO
34 from getopt import getopt
34 from getopt import getopt
35 from pprint import pprint, pformat
35 from pprint import pprint, pformat
36
36
37 # profile isn't bundled by default in Debian for license reasons
37 # profile isn't bundled by default in Debian for license reasons
38 try:
38 try:
39 import profile,pstats
39 import profile,pstats
40 except ImportError:
40 except ImportError:
41 profile = pstats = None
41 profile = pstats = None
42
42
43 # Homebrewed
43 # Homebrewed
44 from IPython import Debugger, OInspect, wildcard
44 from IPython import Debugger, OInspect, wildcard
45 from IPython.FakeModule import FakeModule
45 from IPython.FakeModule import FakeModule
46 from IPython.Itpl import Itpl, itpl, printpl,itplns
46 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 from IPython.PyColorize import Parser
47 from IPython.PyColorize import Parser
48 from IPython.Struct import Struct
48 from IPython.Struct import Struct
49 from IPython.genutils import *
49 from IPython.genutils import *
50
50
51 # Globals to be set later by Magic constructor
51 # Globals to be set later by Magic constructor
52 MAGIC_PREFIX = ''
52 MAGIC_PREFIX = ''
53 MAGIC_ESCAPE = ''
53 MAGIC_ESCAPE = ''
54
54
55 #***************************************************************************
55 #***************************************************************************
56 # Utility functions
56 # Utility functions
57 def magic2python(cmd):
57 def magic2python(cmd):
58 """Convert a command string of magic syntax to valid Python code."""
58 """Convert a command string of magic syntax to valid Python code."""
59
59
60 if cmd.startswith('#'+MAGIC_ESCAPE) or \
60 if cmd.startswith('#'+MAGIC_ESCAPE) or \
61 cmd.startswith(MAGIC_ESCAPE):
61 cmd.startswith(MAGIC_ESCAPE):
62 if cmd[0]=='#':
62 if cmd[0]=='#':
63 cmd = cmd[1:]
63 cmd = cmd[1:]
64 # we need to return the proper line end later
64 # we need to return the proper line end later
65 if cmd[-1] == '\n':
65 if cmd[-1] == '\n':
66 endl = '\n'
66 endl = '\n'
67 else:
67 else:
68 endl = ''
68 endl = ''
69 try:
69 try:
70 func,args = cmd[1:].split(' ',1)
70 func,args = cmd[1:].split(' ',1)
71 except:
71 except:
72 func,args = cmd[1:].rstrip(),''
72 func,args = cmd[1:].rstrip(),''
73 args = args.replace('"','\\"').replace("'","\\'").rstrip()
73 args = args.replace('"','\\"').replace("'","\\'").rstrip()
74 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
74 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
75 else:
75 else:
76 return cmd
76 return cmd
77
77
78 def on_off(tag):
78 def on_off(tag):
79 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
79 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
80 return ['OFF','ON'][tag]
80 return ['OFF','ON'][tag]
81
81
82
82
83 #****************************************************************************
83 #****************************************************************************
84 # Utility classes
84 # Utility classes
85 class Macro:
85 class Macro:
86 """Simple class to store the value of macros as strings.
86 """Simple class to store the value of macros as strings.
87
87
88 This allows us to later exec them by checking when something is an
88 This allows us to later exec them by checking when something is an
89 instance of this class."""
89 instance of this class."""
90
90
91 def __init__(self,cmds):
91 def __init__(self,cmds):
92 """Build a macro from a list of commands."""
92 """Build a macro from a list of commands."""
93
93
94 # Since the list may include multi-line entries, first make sure that
94 # Since the list may include multi-line entries, first make sure that
95 # they've been all broken up before passing it to magic2python
95 # they've been all broken up before passing it to magic2python
96 cmdlist = map(magic2python,''.join(cmds).split('\n'))
96 cmdlist = map(magic2python,''.join(cmds).split('\n'))
97 self.value = '\n'.join(cmdlist)
97 self.value = '\n'.join(cmdlist)
98
98
99 def __str__(self):
99 def __str__(self):
100 return self.value
100 return self.value
101
101
102 #***************************************************************************
102 #***************************************************************************
103 # Main class implementing Magic functionality
103 # Main class implementing Magic functionality
104 class Magic:
104 class Magic:
105 """Magic functions for InteractiveShell.
105 """Magic functions for InteractiveShell.
106
106
107 Shell functions which can be reached as %function_name. All magic
107 Shell functions which can be reached as %function_name. All magic
108 functions should accept a string, which they can parse for their own
108 functions should accept a string, which they can parse for their own
109 needs. This can make some functions easier to type, eg `%cd ../`
109 needs. This can make some functions easier to type, eg `%cd ../`
110 vs. `%cd("../")`
110 vs. `%cd("../")`
111
111
112 ALL definitions MUST begin with the prefix magic_. The user won't need it
112 ALL definitions MUST begin with the prefix magic_. The user won't need it
113 at the command line, but it is is needed in the definition. """
113 at the command line, but it is is needed in the definition. """
114
114
115 # class globals
115 # class globals
116 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
116 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
117 'Automagic is ON, % prefix NOT needed for magic functions.']
117 'Automagic is ON, % prefix NOT needed for magic functions.']
118
118
119 #......................................................................
119 #......................................................................
120 # some utility functions
120 # some utility functions
121
121
122 def __init__(self,shell):
122 def __init__(self,shell):
123 # XXX This is hackish, clean up later to avoid these messy globals
123 # XXX This is hackish, clean up later to avoid these messy globals
124 global MAGIC_PREFIX, MAGIC_ESCAPE
124 global MAGIC_PREFIX, MAGIC_ESCAPE
125
125
126 self.options_table = {}
126 self.options_table = {}
127 MAGIC_PREFIX = shell.name+'.magic_'
127 MAGIC_PREFIX = shell.name+'.magic_'
128 MAGIC_ESCAPE = shell.ESC_MAGIC
128 MAGIC_ESCAPE = shell.ESC_MAGIC
129 if profile is None:
129 if profile is None:
130 self.magic_prun = self.profile_missing_notice
130 self.magic_prun = self.profile_missing_notice
131
131
132 def profile_missing_notice(self, *args, **kwargs):
132 def profile_missing_notice(self, *args, **kwargs):
133 error("""\
133 error("""\
134 The profile module could not be found. If you are a Debian user,
134 The profile module could not be found. If you are a Debian user,
135 it has been removed from the standard Debian package because of its non-free
135 it has been removed from the standard Debian package because of its non-free
136 license. To use profiling, please install"python2.3-profiler" from non-free.""")
136 license. To use profiling, please install"python2.3-profiler" from non-free.""")
137
137
138 def default_option(self,fn,optstr):
138 def default_option(self,fn,optstr):
139 """Make an entry in the options_table for fn, with value optstr"""
139 """Make an entry in the options_table for fn, with value optstr"""
140
140
141 if fn not in self.lsmagic():
141 if fn not in self.lsmagic():
142 error("%s is not a magic function" % fn)
142 error("%s is not a magic function" % fn)
143 self.options_table[fn] = optstr
143 self.options_table[fn] = optstr
144
144
145 def lsmagic(self):
145 def lsmagic(self):
146 """Return a list of currently available magic functions.
146 """Return a list of currently available magic functions.
147
147
148 Gives a list of the bare names after mangling (['ls','cd', ...], not
148 Gives a list of the bare names after mangling (['ls','cd', ...], not
149 ['magic_ls','magic_cd',...]"""
149 ['magic_ls','magic_cd',...]"""
150
150
151 # FIXME. This needs a cleanup, in the way the magics list is built.
151 # FIXME. This needs a cleanup, in the way the magics list is built.
152
152
153 # magics in class definition
153 # magics in class definition
154 class_magic = lambda fn: fn.startswith('magic_') and \
154 class_magic = lambda fn: fn.startswith('magic_') and \
155 callable(Magic.__dict__[fn])
155 callable(Magic.__dict__[fn])
156 # in instance namespace (run-time user additions)
156 # in instance namespace (run-time user additions)
157 inst_magic = lambda fn: fn.startswith('magic_') and \
157 inst_magic = lambda fn: fn.startswith('magic_') and \
158 callable(self.__dict__[fn])
158 callable(self.__dict__[fn])
159 # and bound magics by user (so they can access self):
159 # and bound magics by user (so they can access self):
160 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
160 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
161 callable(self.__class__.__dict__[fn])
161 callable(self.__class__.__dict__[fn])
162 magics = filter(class_magic,Magic.__dict__.keys()) + \
162 magics = filter(class_magic,Magic.__dict__.keys()) + \
163 filter(inst_magic,self.__dict__.keys()) + \
163 filter(inst_magic,self.__dict__.keys()) + \
164 filter(inst_bound_magic,self.__class__.__dict__.keys())
164 filter(inst_bound_magic,self.__class__.__dict__.keys())
165 out = []
165 out = []
166 for fn in magics:
166 for fn in magics:
167 out.append(fn.replace('magic_','',1))
167 out.append(fn.replace('magic_','',1))
168 out.sort()
168 out.sort()
169 return out
169 return out
170
170
171 def set_shell(self,shell):
171 def set_shell(self,shell):
172 self.shell = shell
172 self.shell = shell
173 self.alias_table = shell.alias_table
173 self.alias_table = shell.alias_table
174
174
175 def extract_input_slices(self,slices):
175 def extract_input_slices(self,slices):
176 """Return as a string a set of input history slices.
176 """Return as a string a set of input history slices.
177
177
178 The set of slices is given as a list of strings (like ['1','4:8','9'],
178 The set of slices is given as a list of strings (like ['1','4:8','9'],
179 since this function is for use by magic functions which get their
179 since this function is for use by magic functions which get their
180 arguments as strings."""
180 arguments as strings."""
181
181
182 cmds = []
182 cmds = []
183 for chunk in slices:
183 for chunk in slices:
184 if ':' in chunk:
184 if ':' in chunk:
185 ini,fin = map(int,chunk.split(':'))
185 ini,fin = map(int,chunk.split(':'))
186 else:
186 else:
187 ini = int(chunk)
187 ini = int(chunk)
188 fin = ini+1
188 fin = ini+1
189 cmds.append(self.shell.input_hist[ini:fin])
189 cmds.append(self.shell.input_hist[ini:fin])
190 return cmds
190 return cmds
191
191
192 def _ofind(self,oname):
192 def _ofind(self,oname):
193 """Find an object in the available namespaces.
193 """Find an object in the available namespaces.
194
194
195 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
195 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
196
196
197 Has special code to detect magic functions.
197 Has special code to detect magic functions.
198 """
198 """
199
199
200 oname = oname.strip()
200 oname = oname.strip()
201
201
202 # Namespaces to search in:
202 # Namespaces to search in:
203 user_ns = self.shell.user_ns
203 user_ns = self.shell.user_ns
204 internal_ns = self.shell.internal_ns
204 internal_ns = self.shell.internal_ns
205 builtin_ns = __builtin__.__dict__
205 builtin_ns = __builtin__.__dict__
206 alias_ns = self.shell.alias_table
206 alias_ns = self.shell.alias_table
207
207
208 # Put them in a list. The order is important so that we find things in
208 # Put them in a list. The order is important so that we find things in
209 # the same order that Python finds them.
209 # the same order that Python finds them.
210 namespaces = [ ('Interactive',user_ns),
210 namespaces = [ ('Interactive',user_ns),
211 ('IPython internal',internal_ns),
211 ('IPython internal',internal_ns),
212 ('Python builtin',builtin_ns),
212 ('Python builtin',builtin_ns),
213 ('Alias',alias_ns),
213 ('Alias',alias_ns),
214 ]
214 ]
215
215
216 # initialize results to 'null'
216 # initialize results to 'null'
217 found = 0; obj = None; ospace = None; ds = None;
217 found = 0; obj = None; ospace = None; ds = None;
218 ismagic = 0; isalias = 0
218 ismagic = 0; isalias = 0
219
219
220 # Look for the given name by splitting it in parts. If the head is
220 # Look for the given name by splitting it in parts. If the head is
221 # found, then we look for all the remaining parts as members, and only
221 # found, then we look for all the remaining parts as members, and only
222 # declare success if we can find them all.
222 # declare success if we can find them all.
223 oname_parts = oname.split('.')
223 oname_parts = oname.split('.')
224 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
224 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
225 for nsname,ns in namespaces:
225 for nsname,ns in namespaces:
226 try:
226 try:
227 obj = ns[oname_head]
227 obj = ns[oname_head]
228 except KeyError:
228 except KeyError:
229 continue
229 continue
230 else:
230 else:
231 for part in oname_rest:
231 for part in oname_rest:
232 try:
232 try:
233 obj = getattr(obj,part)
233 obj = getattr(obj,part)
234 except:
234 except:
235 # Blanket except b/c some badly implemented objects
235 # Blanket except b/c some badly implemented objects
236 # allow __getattr__ to raise exceptions other than
236 # allow __getattr__ to raise exceptions other than
237 # AttributeError, which then crashes IPython.
237 # AttributeError, which then crashes IPython.
238 break
238 break
239 else:
239 else:
240 # If we finish the for loop (no break), we got all members
240 # If we finish the for loop (no break), we got all members
241 found = 1
241 found = 1
242 ospace = nsname
242 ospace = nsname
243 if ns == alias_ns:
243 if ns == alias_ns:
244 isalias = 1
244 isalias = 1
245 break # namespace loop
245 break # namespace loop
246
246
247 # Try to see if it's magic
247 # Try to see if it's magic
248 if not found:
248 if not found:
249 if oname.startswith(self.shell.ESC_MAGIC):
249 if oname.startswith(self.shell.ESC_MAGIC):
250 oname = oname[1:]
250 oname = oname[1:]
251 obj = getattr(self,'magic_'+oname,None)
251 obj = getattr(self,'magic_'+oname,None)
252 if obj is not None:
252 if obj is not None:
253 found = 1
253 found = 1
254 ospace = 'IPython internal'
254 ospace = 'IPython internal'
255 ismagic = 1
255 ismagic = 1
256
256
257 # Last try: special-case some literals like '', [], {}, etc:
257 # Last try: special-case some literals like '', [], {}, etc:
258 if not found and oname_head in ["''",'""','[]','{}','()']:
258 if not found and oname_head in ["''",'""','[]','{}','()']:
259 obj = eval(oname_head)
259 obj = eval(oname_head)
260 found = 1
260 found = 1
261 ospace = 'Interactive'
261 ospace = 'Interactive'
262
262
263 return {'found':found, 'obj':obj, 'namespace':ospace,
263 return {'found':found, 'obj':obj, 'namespace':ospace,
264 'ismagic':ismagic, 'isalias':isalias}
264 'ismagic':ismagic, 'isalias':isalias}
265
265
266 def arg_err(self,func):
266 def arg_err(self,func):
267 """Print docstring if incorrect arguments were passed"""
267 """Print docstring if incorrect arguments were passed"""
268 print 'Error in arguments:'
268 print 'Error in arguments:'
269 print OInspect.getdoc(func)
269 print OInspect.getdoc(func)
270
270
271
271
272 def format_latex(self,str):
272 def format_latex(self,str):
273 """Format a string for latex inclusion."""
273 """Format a string for latex inclusion."""
274
274
275 # Characters that need to be escaped for latex:
275 # Characters that need to be escaped for latex:
276 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
276 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
277 # Magic command names as headers:
277 # Magic command names as headers:
278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
279 re.MULTILINE)
279 re.MULTILINE)
280 # Magic commands
280 # Magic commands
281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
282 re.MULTILINE)
282 re.MULTILINE)
283 # Paragraph continue
283 # Paragraph continue
284 par_re = re.compile(r'\\$',re.MULTILINE)
284 par_re = re.compile(r'\\$',re.MULTILINE)
285
285
286 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
286 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
287 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
287 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
288 str = par_re.sub(r'\\\\',str)
288 str = par_re.sub(r'\\\\',str)
289 str = escape_re.sub(r'\\\1',str)
289 str = escape_re.sub(r'\\\1',str)
290 return str
290 return str
291
291
292 def format_screen(self,str):
292 def format_screen(self,str):
293 """Format a string for screen printing.
293 """Format a string for screen printing.
294
294
295 This removes some latex-type format codes."""
295 This removes some latex-type format codes."""
296 # Paragraph continue
296 # Paragraph continue
297 par_re = re.compile(r'\\$',re.MULTILINE)
297 par_re = re.compile(r'\\$',re.MULTILINE)
298 str = par_re.sub('',str)
298 str = par_re.sub('',str)
299 return str
299 return str
300
300
301 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
301 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
302 """Parse options passed to an argument string.
302 """Parse options passed to an argument string.
303
303
304 The interface is similar to that of getopt(), but it returns back a
304 The interface is similar to that of getopt(), but it returns back a
305 Struct with the options as keys and the stripped argument string still
305 Struct with the options as keys and the stripped argument string still
306 as a string.
306 as a string.
307
307
308 arg_str is quoted as a true sys.argv vector by using shlex.split.
308 arg_str is quoted as a true sys.argv vector by using shlex.split.
309 This allows us to easily expand variables, glob files, quote
309 This allows us to easily expand variables, glob files, quote
310 arguments, etc.
310 arguments, etc.
311
311
312 Options:
312 Options:
313 -mode: default 'string'. If given as 'list', the argument string is
313 -mode: default 'string'. If given as 'list', the argument string is
314 returned as a list (split on whitespace) instead of a string.
314 returned as a list (split on whitespace) instead of a string.
315
315
316 -list_all: put all option values in lists. Normally only options
316 -list_all: put all option values in lists. Normally only options
317 appearing more than once are put in a list."""
317 appearing more than once are put in a list."""
318
318
319 # inject default options at the beginning of the input line
319 # inject default options at the beginning of the input line
320 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
320 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
321 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
321 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
322
322
323 mode = kw.get('mode','string')
323 mode = kw.get('mode','string')
324 if mode not in ['string','list']:
324 if mode not in ['string','list']:
325 raise ValueError,'incorrect mode given: %s' % mode
325 raise ValueError,'incorrect mode given: %s' % mode
326 # Get options
326 # Get options
327 list_all = kw.get('list_all',0)
327 list_all = kw.get('list_all',0)
328
328
329 # Check if we have more than one argument to warrant extra processing:
329 # Check if we have more than one argument to warrant extra processing:
330 odict = {} # Dictionary with options
330 odict = {} # Dictionary with options
331 args = arg_str.split()
331 args = arg_str.split()
332 if len(args) >= 1:
332 if len(args) >= 1:
333 # If the list of inputs only has 0 or 1 thing in it, there's no
333 # If the list of inputs only has 0 or 1 thing in it, there's no
334 # need to look for options
334 # need to look for options
335 argv = shlex_split(arg_str)
335 argv = shlex_split(arg_str)
336 # Do regular option processing
336 # Do regular option processing
337 opts,args = getopt(argv,opt_str,*long_opts)
337 opts,args = getopt(argv,opt_str,*long_opts)
338 for o,a in opts:
338 for o,a in opts:
339 if o.startswith('--'):
339 if o.startswith('--'):
340 o = o[2:]
340 o = o[2:]
341 else:
341 else:
342 o = o[1:]
342 o = o[1:]
343 try:
343 try:
344 odict[o].append(a)
344 odict[o].append(a)
345 except AttributeError:
345 except AttributeError:
346 odict[o] = [odict[o],a]
346 odict[o] = [odict[o],a]
347 except KeyError:
347 except KeyError:
348 if list_all:
348 if list_all:
349 odict[o] = [a]
349 odict[o] = [a]
350 else:
350 else:
351 odict[o] = a
351 odict[o] = a
352
352
353 # Prepare opts,args for return
353 # Prepare opts,args for return
354 opts = Struct(odict)
354 opts = Struct(odict)
355 if mode == 'string':
355 if mode == 'string':
356 args = ' '.join(args)
356 args = ' '.join(args)
357
357
358 return opts,args
358 return opts,args
359
359
360 #......................................................................
360 #......................................................................
361 # And now the actual magic functions
361 # And now the actual magic functions
362
362
363 # Functions for IPython shell work (vars,funcs, config, etc)
363 # Functions for IPython shell work (vars,funcs, config, etc)
364 def magic_lsmagic(self, parameter_s = ''):
364 def magic_lsmagic(self, parameter_s = ''):
365 """List currently available magic functions."""
365 """List currently available magic functions."""
366 mesc = self.shell.ESC_MAGIC
366 mesc = self.shell.ESC_MAGIC
367 print 'Available magic functions:\n'+mesc+\
367 print 'Available magic functions:\n'+mesc+\
368 (' '+mesc).join(self.lsmagic())
368 (' '+mesc).join(self.lsmagic())
369 print '\n' + Magic.auto_status[self.shell.rc.automagic]
369 print '\n' + Magic.auto_status[self.shell.rc.automagic]
370 return None
370 return None
371
371
372 def magic_magic(self, parameter_s = ''):
372 def magic_magic(self, parameter_s = ''):
373 """Print information about the magic function system."""
373 """Print information about the magic function system."""
374
374
375 mode = ''
375 mode = ''
376 try:
376 try:
377 if parameter_s.split()[0] == '-latex':
377 if parameter_s.split()[0] == '-latex':
378 mode = 'latex'
378 mode = 'latex'
379 except:
379 except:
380 pass
380 pass
381
381
382 magic_docs = []
382 magic_docs = []
383 for fname in self.lsmagic():
383 for fname in self.lsmagic():
384 mname = 'magic_' + fname
384 mname = 'magic_' + fname
385 for space in (Magic,self,self.__class__):
385 for space in (Magic,self,self.__class__):
386 try:
386 try:
387 fn = space.__dict__[mname]
387 fn = space.__dict__[mname]
388 except KeyError:
388 except KeyError:
389 pass
389 pass
390 else:
390 else:
391 break
391 break
392 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
392 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
393 fname,fn.__doc__))
393 fname,fn.__doc__))
394 magic_docs = ''.join(magic_docs)
394 magic_docs = ''.join(magic_docs)
395
395
396 if mode == 'latex':
396 if mode == 'latex':
397 print self.format_latex(magic_docs)
397 print self.format_latex(magic_docs)
398 return
398 return
399 else:
399 else:
400 magic_docs = self.format_screen(magic_docs)
400 magic_docs = self.format_screen(magic_docs)
401
401
402 outmsg = """
402 outmsg = """
403 IPython's 'magic' functions
403 IPython's 'magic' functions
404 ===========================
404 ===========================
405
405
406 The magic function system provides a series of functions which allow you to
406 The magic function system provides a series of functions which allow you to
407 control the behavior of IPython itself, plus a lot of system-type
407 control the behavior of IPython itself, plus a lot of system-type
408 features. All these functions are prefixed with a % character, but parameters
408 features. All these functions are prefixed with a % character, but parameters
409 are given without parentheses or quotes.
409 are given without parentheses or quotes.
410
410
411 NOTE: If you have 'automagic' enabled (via the command line option or with the
411 NOTE: If you have 'automagic' enabled (via the command line option or with the
412 %automagic function), you don't need to type in the % explicitly. By default,
412 %automagic function), you don't need to type in the % explicitly. By default,
413 IPython ships with automagic on, so you should only rarely need the % escape.
413 IPython ships with automagic on, so you should only rarely need the % escape.
414
414
415 Example: typing '%cd mydir' (without the quotes) changes you working directory
415 Example: typing '%cd mydir' (without the quotes) changes you working directory
416 to 'mydir', if it exists.
416 to 'mydir', if it exists.
417
417
418 You can define your own magic functions to extend the system. See the supplied
418 You can define your own magic functions to extend the system. See the supplied
419 ipythonrc and example-magic.py files for details (in your ipython
419 ipythonrc and example-magic.py files for details (in your ipython
420 configuration directory, typically $HOME/.ipython/).
420 configuration directory, typically $HOME/.ipython/).
421
421
422 You can also define your own aliased names for magic functions. In your
422 You can also define your own aliased names for magic functions. In your
423 ipythonrc file, placing a line like:
423 ipythonrc file, placing a line like:
424
424
425 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
425 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
426
426
427 will define %pf as a new name for %profile.
427 will define %pf as a new name for %profile.
428
428
429 You can also call magics in code using the ipmagic() function, which IPython
429 You can also call magics in code using the ipmagic() function, which IPython
430 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
430 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
431
431
432 For a list of the available magic functions, use %lsmagic. For a description
432 For a list of the available magic functions, use %lsmagic. For a description
433 of any of them, type %magic_name?, e.g. '%cd?'.
433 of any of them, type %magic_name?, e.g. '%cd?'.
434
434
435 Currently the magic system has the following functions:\n"""
435 Currently the magic system has the following functions:\n"""
436
436
437 mesc = self.shell.ESC_MAGIC
437 mesc = self.shell.ESC_MAGIC
438 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
438 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
439 "\n\n%s%s\n\n%s" % (outmsg,
439 "\n\n%s%s\n\n%s" % (outmsg,
440 magic_docs,mesc,mesc,
440 magic_docs,mesc,mesc,
441 (' '+mesc).join(self.lsmagic()),
441 (' '+mesc).join(self.lsmagic()),
442 Magic.auto_status[self.shell.rc.automagic] ) )
442 Magic.auto_status[self.shell.rc.automagic] ) )
443
443
444 page(outmsg,screen_lines=self.shell.rc.screen_length)
444 page(outmsg,screen_lines=self.shell.rc.screen_length)
445
445
446 def magic_automagic(self, parameter_s = ''):
446 def magic_automagic(self, parameter_s = ''):
447 """Make magic functions callable without having to type the initial %.
447 """Make magic functions callable without having to type the initial %.
448
448
449 Toggles on/off (when off, you must call it as %automagic, of
449 Toggles on/off (when off, you must call it as %automagic, of
450 course). Note that magic functions have lowest priority, so if there's
450 course). Note that magic functions have lowest priority, so if there's
451 a variable whose name collides with that of a magic fn, automagic
451 a variable whose name collides with that of a magic fn, automagic
452 won't work for that function (you get the variable instead). However,
452 won't work for that function (you get the variable instead). However,
453 if you delete the variable (del var), the previously shadowed magic
453 if you delete the variable (del var), the previously shadowed magic
454 function becomes visible to automagic again."""
454 function becomes visible to automagic again."""
455
455
456 rc = self.shell.rc
456 rc = self.shell.rc
457 rc.automagic = not rc.automagic
457 rc.automagic = not rc.automagic
458 print '\n' + Magic.auto_status[rc.automagic]
458 print '\n' + Magic.auto_status[rc.automagic]
459
459
460 def magic_autocall(self, parameter_s = ''):
460 def magic_autocall(self, parameter_s = ''):
461 """Make functions callable without having to type parentheses.
461 """Make functions callable without having to type parentheses.
462
462
463 This toggles the autocall command line option on and off."""
463 This toggles the autocall command line option on and off."""
464
464
465 rc = self.shell.rc
465 rc = self.shell.rc
466 rc.autocall = not rc.autocall
466 rc.autocall = not rc.autocall
467 print "Automatic calling is:",['OFF','ON'][rc.autocall]
467 print "Automatic calling is:",['OFF','ON'][rc.autocall]
468
468
469 def magic_autoindent(self, parameter_s = ''):
469 def magic_autoindent(self, parameter_s = ''):
470 """Toggle autoindent on/off (if available)."""
470 """Toggle autoindent on/off (if available)."""
471
471
472 self.shell.set_autoindent()
472 self.shell.set_autoindent()
473 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
473 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
474
474
475 def magic_system_verbose(self, parameter_s = ''):
475 def magic_system_verbose(self, parameter_s = ''):
476 """Toggle verbose printing of system calls on/off."""
476 """Toggle verbose printing of system calls on/off."""
477
477
478 self.shell.rc_set_toggle('system_verbose')
478 self.shell.rc_set_toggle('system_verbose')
479 print "System verbose printing is:",\
479 print "System verbose printing is:",\
480 ['OFF','ON'][self.shell.rc.system_verbose]
480 ['OFF','ON'][self.shell.rc.system_verbose]
481
481
482 def magic_history(self, parameter_s = ''):
482 def magic_history(self, parameter_s = ''):
483 """Print input history (_i<n> variables), with most recent last.
483 """Print input history (_i<n> variables), with most recent last.
484
484
485 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
485 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
486 %history [-n] n -> print at most n inputs\\
486 %history [-n] n -> print at most n inputs\\
487 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
487 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
488
488
489 Each input's number <n> is shown, and is accessible as the
489 Each input's number <n> is shown, and is accessible as the
490 automatically generated variable _i<n>. Multi-line statements are
490 automatically generated variable _i<n>. Multi-line statements are
491 printed starting at a new line for easy copy/paste.
491 printed starting at a new line for easy copy/paste.
492
492
493 If option -n is used, input numbers are not printed. This is useful if
493 If option -n is used, input numbers are not printed. This is useful if
494 you want to get a printout of many lines which can be directly pasted
494 you want to get a printout of many lines which can be directly pasted
495 into a text editor.
495 into a text editor.
496
496
497 This feature is only available if numbered prompts are in use."""
497 This feature is only available if numbered prompts are in use."""
498
498
499 if not self.do_full_cache:
499 if not self.do_full_cache:
500 print 'This feature is only available if numbered prompts are in use.'
500 print 'This feature is only available if numbered prompts are in use.'
501 return
501 return
502 opts,args = self.parse_options(parameter_s,'n',mode='list')
502 opts,args = self.parse_options(parameter_s,'n',mode='list')
503
503
504 default_length = 40
504 default_length = 40
505 if len(args) == 0:
505 if len(args) == 0:
506 final = self.outputcache.prompt_count
506 final = self.outputcache.prompt_count
507 init = max(1,final-default_length)
507 init = max(1,final-default_length)
508 elif len(args) == 1:
508 elif len(args) == 1:
509 final = self.outputcache.prompt_count
509 final = self.outputcache.prompt_count
510 init = max(1,final-int(args[0]))
510 init = max(1,final-int(args[0]))
511 elif len(args) == 2:
511 elif len(args) == 2:
512 init,final = map(int,args)
512 init,final = map(int,args)
513 else:
513 else:
514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
515 print self.magic_hist.__doc__
515 print self.magic_hist.__doc__
516 return
516 return
517 width = len(str(final))
517 width = len(str(final))
518 line_sep = ['','\n']
518 line_sep = ['','\n']
519 input_hist = self.shell.input_hist
519 input_hist = self.shell.input_hist
520 print_nums = not opts.has_key('n')
520 print_nums = not opts.has_key('n')
521 for in_num in range(init,final):
521 for in_num in range(init,final):
522 inline = input_hist[in_num]
522 inline = input_hist[in_num]
523 multiline = inline.count('\n') > 1
523 multiline = inline.count('\n') > 1
524 if print_nums:
524 if print_nums:
525 print str(in_num).ljust(width)+':'+ line_sep[multiline],
525 print str(in_num).ljust(width)+':'+ line_sep[multiline],
526 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
526 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
527 inline.startswith('#!'):
527 inline.startswith('#!'):
528 print inline[1:],
528 print inline[1:],
529 else:
529 else:
530 print inline,
530 print inline,
531
531
532 def magic_hist(self, parameter_s=''):
532 def magic_hist(self, parameter_s=''):
533 """Alternate name for %history."""
533 """Alternate name for %history."""
534 return self.magic_history(parameter_s)
534 return self.magic_history(parameter_s)
535
535
536 def magic_p(self, parameter_s=''):
536 def magic_p(self, parameter_s=''):
537 """Just a short alias for Python's 'print'."""
537 """Just a short alias for Python's 'print'."""
538 exec 'print ' + parameter_s in self.shell.user_ns
538 exec 'print ' + parameter_s in self.shell.user_ns
539
539
540 def magic_r(self, parameter_s=''):
540 def magic_r(self, parameter_s=''):
541 """Repeat previous input.
541 """Repeat previous input.
542
542
543 If given an argument, repeats the previous command which starts with
543 If given an argument, repeats the previous command which starts with
544 the same string, otherwise it just repeats the previous input.
544 the same string, otherwise it just repeats the previous input.
545
545
546 Shell escaped commands (with ! as first character) are not recognized
546 Shell escaped commands (with ! as first character) are not recognized
547 by this system, only pure python code and magic commands.
547 by this system, only pure python code and magic commands.
548 """
548 """
549
549
550 start = parameter_s.strip()
550 start = parameter_s.strip()
551 esc_magic = self.shell.ESC_MAGIC
551 esc_magic = self.shell.ESC_MAGIC
552 # Identify magic commands even if automagic is on (which means
552 # Identify magic commands even if automagic is on (which means
553 # the in-memory version is different from that typed by the user).
553 # the in-memory version is different from that typed by the user).
554 if self.shell.rc.automagic:
554 if self.shell.rc.automagic:
555 start_magic = esc_magic+start
555 start_magic = esc_magic+start
556 else:
556 else:
557 start_magic = start
557 start_magic = start
558 # Look through the input history in reverse
558 # Look through the input history in reverse
559 for n in range(len(self.shell.input_hist)-2,0,-1):
559 for n in range(len(self.shell.input_hist)-2,0,-1):
560 input = self.shell.input_hist[n]
560 input = self.shell.input_hist[n]
561 # skip plain 'r' lines so we don't recurse to infinity
561 # skip plain 'r' lines so we don't recurse to infinity
562 if input != 'ipmagic("r")\n' and \
562 if input != 'ipmagic("r")\n' and \
563 (input.startswith(start) or input.startswith(start_magic)):
563 (input.startswith(start) or input.startswith(start_magic)):
564 #print 'match',`input` # dbg
564 #print 'match',`input` # dbg
565 if input.startswith(esc_magic):
565 if input.startswith(esc_magic):
566 input = magic2python(input)
566 input = magic2python(input)
567 #print 'modified',`input` # dbg
567 #print 'modified',`input` # dbg
568 print 'Executing:',input,
568 print 'Executing:',input,
569 exec input in self.shell.user_ns
569 exec input in self.shell.user_ns
570 return
570 return
571 print 'No previous input matching `%s` found.' % start
571 print 'No previous input matching `%s` found.' % start
572
572
573 def magic_page(self, parameter_s=''):
573 def magic_page(self, parameter_s=''):
574 """Pretty print the object and display it through a pager.
574 """Pretty print the object and display it through a pager.
575
575
576 If no parameter is given, use _ (last output)."""
576 If no parameter is given, use _ (last output)."""
577 # After a function contributed by Olivier Aubert, slightly modified.
577 # After a function contributed by Olivier Aubert, slightly modified.
578
578
579 oname = parameter_s and parameter_s or '_'
579 oname = parameter_s and parameter_s or '_'
580 info = self._ofind(oname)
580 info = self._ofind(oname)
581 if info['found']:
581 if info['found']:
582 page(pformat(info['obj']))
582 page(pformat(info['obj']))
583 else:
583 else:
584 print 'Object `%s` not found' % oname
584 print 'Object `%s` not found' % oname
585
585
586 def magic_profile(self, parameter_s=''):
586 def magic_profile(self, parameter_s=''):
587 """Print your currently active IPyhton profile."""
587 """Print your currently active IPyhton profile."""
588 if self.shell.rc.profile:
588 if self.shell.rc.profile:
589 printpl('Current IPython profile: $self.shell.rc.profile.')
589 printpl('Current IPython profile: $self.shell.rc.profile.')
590 else:
590 else:
591 print 'No profile active.'
591 print 'No profile active.'
592
592
593 def _inspect(self,meth,oname,**kw):
593 def _inspect(self,meth,oname,**kw):
594 """Generic interface to the inspector system.
594 """Generic interface to the inspector system.
595
595
596 This function is meant to be called by pdef, pdoc & friends."""
596 This function is meant to be called by pdef, pdoc & friends."""
597
597
598 oname = oname.strip()
598 oname = oname.strip()
599 info = Struct(self._ofind(oname))
599 info = Struct(self._ofind(oname))
600 if info.found:
600 if info.found:
601 pmethod = getattr(self.shell.inspector,meth)
601 pmethod = getattr(self.shell.inspector,meth)
602 formatter = info.ismagic and self.format_screen or None
602 formatter = info.ismagic and self.format_screen or None
603 if meth == 'pdoc':
603 if meth == 'pdoc':
604 pmethod(info.obj,oname,formatter)
604 pmethod(info.obj,oname,formatter)
605 elif meth == 'pinfo':
605 elif meth == 'pinfo':
606 pmethod(info.obj,oname,formatter,info,**kw)
606 pmethod(info.obj,oname,formatter,info,**kw)
607 else:
607 else:
608 pmethod(info.obj,oname)
608 pmethod(info.obj,oname)
609 else:
609 else:
610 print 'Object `%s` not found.' % oname
610 print 'Object `%s` not found.' % oname
611 return 'not found' # so callers can take other action
611 return 'not found' # so callers can take other action
612
612
613 def magic_pdef(self, parameter_s=''):
613 def magic_pdef(self, parameter_s=''):
614 """Print the definition header for any callable object.
614 """Print the definition header for any callable object.
615
615
616 If the object is a class, print the constructor information."""
616 If the object is a class, print the constructor information."""
617 self._inspect('pdef',parameter_s)
617 self._inspect('pdef',parameter_s)
618
618
619 def magic_pdoc(self, parameter_s=''):
619 def magic_pdoc(self, parameter_s=''):
620 """Print the docstring for an object.
620 """Print the docstring for an object.
621
621
622 If the given object is a class, it will print both the class and the
622 If the given object is a class, it will print both the class and the
623 constructor docstrings."""
623 constructor docstrings."""
624 self._inspect('pdoc',parameter_s)
624 self._inspect('pdoc',parameter_s)
625
625
626 def magic_psource(self, parameter_s=''):
626 def magic_psource(self, parameter_s=''):
627 """Print (or run through pager) the source code for an object."""
627 """Print (or run through pager) the source code for an object."""
628 self._inspect('psource',parameter_s)
628 self._inspect('psource',parameter_s)
629
629
630 def magic_pfile(self, parameter_s=''):
630 def magic_pfile(self, parameter_s=''):
631 """Print (or run through pager) the file where an object is defined.
631 """Print (or run through pager) the file where an object is defined.
632
632
633 The file opens at the line where the object definition begins. IPython
633 The file opens at the line where the object definition begins. IPython
634 will honor the environment variable PAGER if set, and otherwise will
634 will honor the environment variable PAGER if set, and otherwise will
635 do its best to print the file in a convenient form.
635 do its best to print the file in a convenient form.
636
636
637 If the given argument is not an object currently defined, IPython will
637 If the given argument is not an object currently defined, IPython will
638 try to interpret it as a filename (automatically adding a .py extension
638 try to interpret it as a filename (automatically adding a .py extension
639 if needed). You can thus use %pfile as a syntax highlighting code
639 if needed). You can thus use %pfile as a syntax highlighting code
640 viewer."""
640 viewer."""
641
641
642 # first interpret argument as an object name
642 # first interpret argument as an object name
643 out = self._inspect('pfile',parameter_s)
643 out = self._inspect('pfile',parameter_s)
644 # if not, try the input as a filename
644 # if not, try the input as a filename
645 if out == 'not found':
645 if out == 'not found':
646 try:
646 try:
647 filename = get_py_filename(parameter_s)
647 filename = get_py_filename(parameter_s)
648 except IOError,msg:
648 except IOError,msg:
649 print msg
649 print msg
650 return
650 return
651 page(self.shell.inspector.format(file(filename).read()))
651 page(self.shell.inspector.format(file(filename).read()))
652
652
653 def magic_pinfo(self, parameter_s=''):
653 def magic_pinfo(self, parameter_s=''):
654 """Provide detailed information about an object.
654 """Provide detailed information about an object.
655
655
656 '%pinfo object' is just a synonym for object? or ?object."""
656 '%pinfo object' is just a synonym for object? or ?object."""
657
657
658 #print 'pinfo par: <%s>' % parameter_s # dbg
658 #print 'pinfo par: <%s>' % parameter_s # dbg
659
659
660 # detail_level: 0 -> obj? , 1 -> obj??
660 # detail_level: 0 -> obj? , 1 -> obj??
661 detail_level = 0
661 detail_level = 0
662 # We need to detect if we got called as 'pinfo pinfo foo', which can
662 # We need to detect if we got called as 'pinfo pinfo foo', which can
663 # happen if the user types 'pinfo foo?' at the cmd line.
663 # happen if the user types 'pinfo foo?' at the cmd line.
664 pinfo,qmark1,oname,qmark2 = \
664 pinfo,qmark1,oname,qmark2 = \
665 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
665 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
666 if pinfo or qmark1 or qmark2:
666 if pinfo or qmark1 or qmark2:
667 detail_level = 1
667 detail_level = 1
668 if "*" in oname:
668 if "*" in oname:
669 self.magic_psearch(oname)
669 self.magic_psearch(oname)
670 else:
670 else:
671 self._inspect('pinfo',oname,detail_level=detail_level)
671 self._inspect('pinfo',oname,detail_level=detail_level)
672
672
673 def magic_psearch(self, parameter_s=''):
673 def magic_psearch(self, parameter_s=''):
674 """Search for object in namespaces by wildcard.
674 """Search for object in namespaces by wildcard.
675
675
676 %psearch [options] PATTERN [OBJECT TYPE]
676 %psearch [options] PATTERN [OBJECT TYPE]
677
677
678 Note: ? can be used as a synonym for %psearch, at the beginning or at
678 Note: ? can be used as a synonym for %psearch, at the beginning or at
679 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
679 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
680 rest of the command line must be unchanged (options come first), so
680 rest of the command line must be unchanged (options come first), so
681 for example the following forms are equivalent
681 for example the following forms are equivalent
682
682
683 %psearch -i a* function
683 %psearch -i a* function
684 -i a* function?
684 -i a* function?
685 ?-i a* function
685 ?-i a* function
686
686
687 Arguments:
687 Arguments:
688
688
689 PATTERN
689 PATTERN
690
690
691 where PATTERN is a string containing * as a wildcard similar to its
691 where PATTERN is a string containing * as a wildcard similar to its
692 use in a shell. The pattern is matched in all namespaces on the
692 use in a shell. The pattern is matched in all namespaces on the
693 search path. By default objects starting with a single _ are not
693 search path. By default objects starting with a single _ are not
694 matched, many IPython generated objects have a single
694 matched, many IPython generated objects have a single
695 underscore. The default is case insensitive matching. Matching is
695 underscore. The default is case insensitive matching. Matching is
696 also done on the attributes of objects and not only on the objects
696 also done on the attributes of objects and not only on the objects
697 in a module.
697 in a module.
698
698
699 [OBJECT TYPE]
699 [OBJECT TYPE]
700
700
701 Is the name of a python type from the types module. The name is
701 Is the name of a python type from the types module. The name is
702 given in lowercase without the ending type, ex. StringType is
702 given in lowercase without the ending type, ex. StringType is
703 written string. By adding a type here only objects matching the
703 written string. By adding a type here only objects matching the
704 given type are matched. Using all here makes the pattern match all
704 given type are matched. Using all here makes the pattern match all
705 types (this is the default).
705 types (this is the default).
706
706
707 Options:
707 Options:
708
708
709 -a: makes the pattern match even objects whose names start with a
709 -a: makes the pattern match even objects whose names start with a
710 single underscore. These names are normally ommitted from the
710 single underscore. These names are normally ommitted from the
711 search.
711 search.
712
712
713 -i/-c: make the pattern case insensitive/sensitive. If neither of
713 -i/-c: make the pattern case insensitive/sensitive. If neither of
714 these options is given, the default is read from your ipythonrc
714 these options is given, the default is read from your ipythonrc
715 file. The option name which sets this value is
715 file. The option name which sets this value is
716 'wildcards_case_sensitive'. If this option is not specified in your
716 'wildcards_case_sensitive'. If this option is not specified in your
717 ipythonrc file, IPython's internal default is to do a case sensitive
717 ipythonrc file, IPython's internal default is to do a case sensitive
718 search.
718 search.
719
719
720 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
720 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
721 specifiy can be searched in any of the following namespaces:
721 specifiy can be searched in any of the following namespaces:
722 'builtin', 'user', 'user_global','internal', 'alias', where
722 'builtin', 'user', 'user_global','internal', 'alias', where
723 'builtin' and 'user' are the search defaults. Note that you should
723 'builtin' and 'user' are the search defaults. Note that you should
724 not use quotes when specifying namespaces.
724 not use quotes when specifying namespaces.
725
725
726 'Builtin' contains the python module builtin, 'user' contains all
726 'Builtin' contains the python module builtin, 'user' contains all
727 user data, 'alias' only contain the shell aliases and no python
727 user data, 'alias' only contain the shell aliases and no python
728 objects, 'internal' contains objects used by IPython. The
728 objects, 'internal' contains objects used by IPython. The
729 'user_global' namespace is only used by embedded IPython instances,
729 'user_global' namespace is only used by embedded IPython instances,
730 and it contains module-level globals. You can add namespaces to the
730 and it contains module-level globals. You can add namespaces to the
731 search with -s or exclude them with -e (these options can be given
731 search with -s or exclude them with -e (these options can be given
732 more than once).
732 more than once).
733
733
734 Examples:
734 Examples:
735
735
736 %psearch a* -> objects beginning with an a
736 %psearch a* -> objects beginning with an a
737 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
737 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
738 %psearch a* function -> all functions beginning with an a
738 %psearch a* function -> all functions beginning with an a
739 %psearch re.e* -> objects beginning with an e in module re
739 %psearch re.e* -> objects beginning with an e in module re
740 %psearch r*.e* -> objects that start with e in modules starting in r
740 %psearch r*.e* -> objects that start with e in modules starting in r
741 %psearch r*.* string -> all strings in modules beginning with r
741 %psearch r*.* string -> all strings in modules beginning with r
742
742
743 Case sensitve search:
743 Case sensitve search:
744
744
745 %psearch -c a* list all object beginning with lower case a
745 %psearch -c a* list all object beginning with lower case a
746
746
747 Show objects beginning with a single _:
747 Show objects beginning with a single _:
748
748
749 %psearch -a _* list objects beginning with a single underscore"""
749 %psearch -a _* list objects beginning with a single underscore"""
750
750
751 # default namespaces to be searched
751 # default namespaces to be searched
752 def_search = ['user','builtin']
752 def_search = ['user','builtin']
753
753
754 # Process options/args
754 # Process options/args
755 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
755 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
756 opt = opts.get
756 opt = opts.get
757 shell = self.shell
757 shell = self.shell
758 psearch = shell.inspector.psearch
758 psearch = shell.inspector.psearch
759
759
760 # select case options
760 # select case options
761 if opts.has_key('i'):
761 if opts.has_key('i'):
762 ignore_case = True
762 ignore_case = True
763 elif opts.has_key('c'):
763 elif opts.has_key('c'):
764 ignore_case = False
764 ignore_case = False
765 else:
765 else:
766 ignore_case = not shell.rc.wildcards_case_sensitive
766 ignore_case = not shell.rc.wildcards_case_sensitive
767
767
768 # Build list of namespaces to search from user options
768 # Build list of namespaces to search from user options
769 def_search.extend(opt('s',[]))
769 def_search.extend(opt('s',[]))
770 ns_exclude = ns_exclude=opt('e',[])
770 ns_exclude = ns_exclude=opt('e',[])
771 ns_search = [nm for nm in def_search if nm not in ns_exclude]
771 ns_search = [nm for nm in def_search if nm not in ns_exclude]
772
772
773 # Call the actual search
773 # Call the actual search
774 try:
774 try:
775 psearch(args,shell.ns_table,ns_search,
775 psearch(args,shell.ns_table,ns_search,
776 show_all=opt('a'),ignore_case=ignore_case)
776 show_all=opt('a'),ignore_case=ignore_case)
777 except:
777 except:
778 shell.showtraceback()
778 shell.showtraceback()
779
779
780 def magic_who_ls(self, parameter_s=''):
780 def magic_who_ls(self, parameter_s=''):
781 """Return a sorted list of all interactive variables.
781 """Return a sorted list of all interactive variables.
782
782
783 If arguments are given, only variables of types matching these
783 If arguments are given, only variables of types matching these
784 arguments are returned."""
784 arguments are returned."""
785
785
786 user_ns = self.shell.user_ns
786 user_ns = self.shell.user_ns
787 out = []
787 out = []
788 typelist = parameter_s.split()
788 typelist = parameter_s.split()
789 for i in self.shell.user_ns.keys():
789 for i in self.shell.user_ns.keys():
790 if not (i.startswith('_') or i.startswith('_i')) \
790 if not (i.startswith('_') or i.startswith('_i')) \
791 and not (self.internal_ns.has_key(i) or
791 and not (self.internal_ns.has_key(i) or
792 self.user_config_ns.has_key(i)):
792 self.user_config_ns.has_key(i)):
793 if typelist:
793 if typelist:
794 if type(user_ns[i]).__name__ in typelist:
794 if type(user_ns[i]).__name__ in typelist:
795 out.append(i)
795 out.append(i)
796 else:
796 else:
797 out.append(i)
797 out.append(i)
798 out.sort()
798 out.sort()
799 return out
799 return out
800
800
801 def magic_who(self, parameter_s=''):
801 def magic_who(self, parameter_s=''):
802 """Print all interactive variables, with some minimal formatting.
802 """Print all interactive variables, with some minimal formatting.
803
803
804 If any arguments are given, only variables whose type matches one of
804 If any arguments are given, only variables whose type matches one of
805 these are printed. For example:
805 these are printed. For example:
806
806
807 %who function str
807 %who function str
808
808
809 will only list functions and strings, excluding all other types of
809 will only list functions and strings, excluding all other types of
810 variables. To find the proper type names, simply use type(var) at a
810 variables. To find the proper type names, simply use type(var) at a
811 command line to see how python prints type names. For example:
811 command line to see how python prints type names. For example:
812
812
813 In [1]: type('hello')\\
813 In [1]: type('hello')\\
814 Out[1]: <type 'str'>
814 Out[1]: <type 'str'>
815
815
816 indicates that the type name for strings is 'str'.
816 indicates that the type name for strings is 'str'.
817
817
818 %who always excludes executed names loaded through your configuration
818 %who always excludes executed names loaded through your configuration
819 file and things which are internal to IPython.
819 file and things which are internal to IPython.
820
820
821 This is deliberate, as typically you may load many modules and the
821 This is deliberate, as typically you may load many modules and the
822 purpose of %who is to show you only what you've manually defined."""
822 purpose of %who is to show you only what you've manually defined."""
823
823
824 varlist = self.magic_who_ls(parameter_s)
824 varlist = self.magic_who_ls(parameter_s)
825 if not varlist:
825 if not varlist:
826 print 'Interactive namespace is empty.'
826 print 'Interactive namespace is empty.'
827 return
827 return
828
828
829 # if we have variables, move on...
829 # if we have variables, move on...
830
830
831 # stupid flushing problem: when prompts have no separators, stdout is
831 # stupid flushing problem: when prompts have no separators, stdout is
832 # getting lost. I'm starting to think this is a python bug. I'm having
832 # getting lost. I'm starting to think this is a python bug. I'm having
833 # to force a flush with a print because even a sys.stdout.flush
833 # to force a flush with a print because even a sys.stdout.flush
834 # doesn't seem to do anything!
834 # doesn't seem to do anything!
835
835
836 count = 0
836 count = 0
837 for i in varlist:
837 for i in varlist:
838 print i+'\t',
838 print i+'\t',
839 count += 1
839 count += 1
840 if count > 8:
840 if count > 8:
841 count = 0
841 count = 0
842 print
842 print
843 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
843 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
844
844
845 print # well, this does force a flush at the expense of an extra \n
845 print # well, this does force a flush at the expense of an extra \n
846
846
847 def magic_whos(self, parameter_s=''):
847 def magic_whos(self, parameter_s=''):
848 """Like %who, but gives some extra information about each variable.
848 """Like %who, but gives some extra information about each variable.
849
849
850 The same type filtering of %who can be applied here.
850 The same type filtering of %who can be applied here.
851
851
852 For all variables, the type is printed. Additionally it prints:
852 For all variables, the type is printed. Additionally it prints:
853
853
854 - For {},[],(): their length.
854 - For {},[],(): their length.
855
855
856 - For Numeric arrays, a summary with shape, number of elements,
856 - For Numeric arrays, a summary with shape, number of elements,
857 typecode and size in memory.
857 typecode and size in memory.
858
858
859 - Everything else: a string representation, snipping their middle if
859 - Everything else: a string representation, snipping their middle if
860 too long."""
860 too long."""
861
861
862 varnames = self.magic_who_ls(parameter_s)
862 varnames = self.magic_who_ls(parameter_s)
863 if not varnames:
863 if not varnames:
864 print 'Interactive namespace is empty.'
864 print 'Interactive namespace is empty.'
865 return
865 return
866
866
867 # if we have variables, move on...
867 # if we have variables, move on...
868
868
869 # for these types, show len() instead of data:
869 # for these types, show len() instead of data:
870 seq_types = [types.DictType,types.ListType,types.TupleType]
870 seq_types = [types.DictType,types.ListType,types.TupleType]
871
871
872 # for Numeric arrays, display summary info
872 # for Numeric arrays, display summary info
873 try:
873 try:
874 import Numeric
874 import Numeric
875 except ImportError:
875 except ImportError:
876 array_type = None
876 array_type = None
877 else:
877 else:
878 array_type = Numeric.ArrayType.__name__
878 array_type = Numeric.ArrayType.__name__
879
879
880 # Find all variable names and types so we can figure out column sizes
880 # Find all variable names and types so we can figure out column sizes
881 get_vars = lambda i: self.shell.user_ns[i]
881 get_vars = lambda i: self.shell.user_ns[i]
882 type_name = lambda v: type(v).__name__
882 type_name = lambda v: type(v).__name__
883 varlist = map(get_vars,varnames)
883 varlist = map(get_vars,varnames)
884 typelist = map(type_name,varlist)
884 typelist = map(type_name,varlist)
885 # column labels and # of spaces as separator
885 # column labels and # of spaces as separator
886 varlabel = 'Variable'
886 varlabel = 'Variable'
887 typelabel = 'Type'
887 typelabel = 'Type'
888 datalabel = 'Data/Info'
888 datalabel = 'Data/Info'
889 colsep = 3
889 colsep = 3
890 # variable format strings
890 # variable format strings
891 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
891 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
892 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
892 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
893 aformat = "%s: %s elems, type `%s`, %s bytes"
893 aformat = "%s: %s elems, type `%s`, %s bytes"
894 # find the size of the columns to format the output nicely
894 # find the size of the columns to format the output nicely
895 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
895 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
896 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
896 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
897 # table header
897 # table header
898 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
898 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
899 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
899 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
900 # and the table itself
900 # and the table itself
901 kb = 1024
901 kb = 1024
902 Mb = 1048576 # kb**2
902 Mb = 1048576 # kb**2
903 for vname,var,vtype in zip(varnames,varlist,typelist):
903 for vname,var,vtype in zip(varnames,varlist,typelist):
904 print itpl(vformat),
904 print itpl(vformat),
905 if vtype in seq_types:
905 if vtype in seq_types:
906 print len(var)
906 print len(var)
907 elif vtype==array_type:
907 elif vtype==array_type:
908 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
908 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
909 vsize = Numeric.size(var)
909 vsize = Numeric.size(var)
910 vbytes = vsize*var.itemsize()
910 vbytes = vsize*var.itemsize()
911 if vbytes < 100000:
911 if vbytes < 100000:
912 print aformat % (vshape,vsize,var.typecode(),vbytes)
912 print aformat % (vshape,vsize,var.typecode(),vbytes)
913 else:
913 else:
914 print aformat % (vshape,vsize,var.typecode(),vbytes),
914 print aformat % (vshape,vsize,var.typecode(),vbytes),
915 if vbytes < Mb:
915 if vbytes < Mb:
916 print '(%s kb)' % (vbytes/kb,)
916 print '(%s kb)' % (vbytes/kb,)
917 else:
917 else:
918 print '(%s Mb)' % (vbytes/Mb,)
918 print '(%s Mb)' % (vbytes/Mb,)
919 else:
919 else:
920 vstr = str(var)
920 vstr = str(var)
921 if len(vstr) < 50:
921 if len(vstr) < 50:
922 print vstr
922 print vstr
923 else:
923 else:
924 printpl(vfmt_short)
924 printpl(vfmt_short)
925
925
926 def magic_reset(self, parameter_s=''):
926 def magic_reset(self, parameter_s=''):
927 """Resets the namespace by removing all names defined by the user.
927 """Resets the namespace by removing all names defined by the user.
928
928
929 Input/Output history are left around in case you need them."""
929 Input/Output history are left around in case you need them."""
930
930
931 ans = raw_input(
931 ans = raw_input(
932 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
932 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
933 if not ans.lower() == 'y':
933 if not ans.lower() == 'y':
934 print 'Nothing done.'
934 print 'Nothing done.'
935 return
935 return
936 user_ns = self.shell.user_ns
936 user_ns = self.shell.user_ns
937 for i in self.magic_who_ls():
937 for i in self.magic_who_ls():
938 del(user_ns[i])
938 del(user_ns[i])
939
939
940 def magic_config(self,parameter_s=''):
940 def magic_config(self,parameter_s=''):
941 """Show IPython's internal configuration."""
941 """Show IPython's internal configuration."""
942
942
943 page('Current configuration structure:\n'+
943 page('Current configuration structure:\n'+
944 pformat(self.shell.rc.dict()))
944 pformat(self.shell.rc.dict()))
945
945
946 def magic_logstart(self,parameter_s=''):
946 def magic_logstart(self,parameter_s=''):
947 """Start logging anywhere in a session.
947 """Start logging anywhere in a session.
948
948
949 %logstart [log_name [log_mode]]
949 %logstart [log_name [log_mode]]
950
950
951 If no name is given, it defaults to a file named 'ipython.log' in your
951 If no name is given, it defaults to a file named 'ipython.log' in your
952 current directory, in 'rotate' mode (see below).
952 current directory, in 'rotate' mode (see below).
953
953
954 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
954 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
955 history up to that point and then continues logging.
955 history up to that point and then continues logging.
956
956
957 %logstart takes a second optional parameter: logging mode. This can be one
957 %logstart takes a second optional parameter: logging mode. This can be one
958 of (note that the modes are given unquoted):\\
958 of (note that the modes are given unquoted):\\
959 over: overwrite existing log.\\
959 over: overwrite existing log.\\
960 backup: rename (if exists) to name~ and start name.\\
960 backup: rename (if exists) to name~ and start name.\\
961 append: well, that says it.\\
961 append: well, that says it.\\
962 rotate: create rotating logs name.1~, name.2~, etc.
962 rotate: create rotating logs name.1~, name.2~, etc.
963 """
963 """
964
964
965 #FIXME. This function should all be moved to the Logger class.
965 #FIXME. This function should all be moved to the Logger class.
966
966
967 valid_modes = qw('over backup append rotate')
967 valid_modes = qw('over backup append rotate')
968 if self.LOG:
968 if self.LOG:
969 print 'Logging is already in place. Logfile:',self.LOG
969 print 'Logging is already in place. Logfile:',self.LOG
970 return
970 return
971
971
972 par = parameter_s.strip()
972 par = parameter_s.strip()
973 if not par:
973 if not par:
974 logname = self.LOGDEF
974 logname = self.LOGDEF
975 logmode = 'rotate' # use rotate for the auto-generated logs
975 logmode = 'rotate' # use rotate for the auto-generated logs
976 else:
976 else:
977 try:
977 try:
978 logname,logmode = par.split()
978 logname,logmode = par.split()
979 except:
979 except:
980 try:
980 try:
981 logname = par
981 logname = par
982 logmode = 'backup'
982 logmode = 'backup'
983 except:
983 except:
984 warn('Usage: %log [log_name [log_mode]]')
984 warn('Usage: %log [log_name [log_mode]]')
985 return
985 return
986 if not logmode in valid_modes:
986 if not logmode in valid_modes:
987 warn('Logging NOT activated.\n'
987 warn('Logging NOT activated.\n'
988 'Usage: %log [log_name [log_mode]]\n'
988 'Usage: %log [log_name [log_mode]]\n'
989 'Valid modes: '+str(valid_modes))
989 'Valid modes: '+str(valid_modes))
990 return
990 return
991
991
992 # If we made it this far, I think we're ok:
992 # If we made it this far, I think we're ok:
993 print 'Activating auto-logging.'
993 print 'Activating auto-logging.'
994 print 'Current session state plus future input saved to:',logname
994 print 'Current session state plus future input saved to:',logname
995 print 'Logging mode: ',logmode
995 print 'Logging mode: ',logmode
996 # put logname into rc struct as if it had been called on the command line,
996 # put logname into rc struct as if it had been called on the command line,
997 # so it ends up saved in the log header
997 # so it ends up saved in the log header
998 # Save it in case we need to restore it...
998 # Save it in case we need to restore it...
999 old_logfile = self.shell.rc.opts.get('logfile','')
999 old_logfile = self.shell.rc.opts.get('logfile','')
1000 logname = os.path.expanduser(logname)
1000 logname = os.path.expanduser(logname)
1001 self.shell.rc.opts.logfile = logname
1001 self.shell.rc.opts.logfile = logname
1002 self.LOGMODE = logmode # FIXME: this should be set through a function.
1002 self.LOGMODE = logmode # FIXME: this should be set through a function.
1003 try:
1003 try:
1004 header = str(self.LOGHEAD)
1004 header = str(self.LOGHEAD)
1005 self.create_log(header,logname)
1005 self.create_log(header,logname)
1006 self.logstart(header,logname)
1006 self.logstart(header,logname)
1007 except:
1007 except:
1008 self.LOG = '' # we are NOT logging, something went wrong
1008 self.LOG = '' # we are NOT logging, something went wrong
1009 self.shell.rc.opts.logfile = old_logfile
1009 self.shell.rc.opts.logfile = old_logfile
1010 warn("Couldn't start log: "+str(sys.exc_info()[1]))
1010 warn("Couldn't start log: "+str(sys.exc_info()[1]))
1011 else: # log input history up to this point
1011 else: # log input history up to this point
1012 self.logfile.write(self.shell.user_ns['_ih'][1:])
1012 self.logfile.write(self.shell.user_ns['_ih'][1:])
1013 self.logfile.flush()
1013 self.logfile.flush()
1014
1014
1015 def magic_logoff(self,parameter_s=''):
1015 def magic_logoff(self,parameter_s=''):
1016 """Temporarily stop logging.
1016 """Temporarily stop logging.
1017
1017
1018 You must have previously started logging."""
1018 You must have previously started logging."""
1019 self.switch_log(0)
1019 self.switch_log(0)
1020
1020
1021 def magic_logon(self,parameter_s=''):
1021 def magic_logon(self,parameter_s=''):
1022 """Restart logging.
1022 """Restart logging.
1023
1023
1024 This function is for restarting logging which you've temporarily
1024 This function is for restarting logging which you've temporarily
1025 stopped with %logoff. For starting logging for the first time, you
1025 stopped with %logoff. For starting logging for the first time, you
1026 must use the %logstart function, which allows you to specify an
1026 must use the %logstart function, which allows you to specify an
1027 optional log filename."""
1027 optional log filename."""
1028
1028
1029 self.switch_log(1)
1029 self.switch_log(1)
1030
1030
1031 def magic_logstate(self,parameter_s=''):
1031 def magic_logstate(self,parameter_s=''):
1032 """Print the status of the logging system."""
1032 """Print the status of the logging system."""
1033
1033
1034 self.logstate()
1034 self.logstate()
1035
1035
1036 def magic_pdb(self, parameter_s=''):
1036 def magic_pdb(self, parameter_s=''):
1037 """Control the calling of the pdb interactive debugger.
1037 """Control the calling of the pdb interactive debugger.
1038
1038
1039 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1039 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1040 argument it works as a toggle.
1040 argument it works as a toggle.
1041
1041
1042 When an exception is triggered, IPython can optionally call the
1042 When an exception is triggered, IPython can optionally call the
1043 interactive pdb debugger after the traceback printout. %pdb toggles
1043 interactive pdb debugger after the traceback printout. %pdb toggles
1044 this feature on and off."""
1044 this feature on and off."""
1045
1045
1046 par = parameter_s.strip().lower()
1046 par = parameter_s.strip().lower()
1047
1047
1048 if par:
1048 if par:
1049 try:
1049 try:
1050 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1050 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1051 except KeyError:
1051 except KeyError:
1052 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
1052 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
1053 return
1053 return
1054 else:
1054 else:
1055 self.shell.InteractiveTB.call_pdb = pdb
1055 self.shell.InteractiveTB.call_pdb = pdb
1056 else:
1056 else:
1057 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
1057 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
1058 print 'Automatic pdb calling has been turned',\
1058 print 'Automatic pdb calling has been turned',\
1059 on_off(self.shell.InteractiveTB.call_pdb)
1059 on_off(self.shell.InteractiveTB.call_pdb)
1060
1060
1061
1061
1062 def magic_prun(self, parameter_s ='',user_mode=1,
1062 def magic_prun(self, parameter_s ='',user_mode=1,
1063 opts=None,arg_lst=None,prog_ns=None):
1063 opts=None,arg_lst=None,prog_ns=None):
1064
1064
1065 """Run a statement through the python code profiler.
1065 """Run a statement through the python code profiler.
1066
1066
1067 Usage:\\
1067 Usage:\\
1068 %prun [options] statement
1068 %prun [options] statement
1069
1069
1070 The given statement (which doesn't require quote marks) is run via the
1070 The given statement (which doesn't require quote marks) is run via the
1071 python profiler in a manner similar to the profile.run() function.
1071 python profiler in a manner similar to the profile.run() function.
1072 Namespaces are internally managed to work correctly; profile.run
1072 Namespaces are internally managed to work correctly; profile.run
1073 cannot be used in IPython because it makes certain assumptions about
1073 cannot be used in IPython because it makes certain assumptions about
1074 namespaces which do not hold under IPython.
1074 namespaces which do not hold under IPython.
1075
1075
1076 Options:
1076 Options:
1077
1077
1078 -l <limit>: you can place restrictions on what or how much of the
1078 -l <limit>: you can place restrictions on what or how much of the
1079 profile gets printed. The limit value can be:
1079 profile gets printed. The limit value can be:
1080
1080
1081 * A string: only information for function names containing this string
1081 * A string: only information for function names containing this string
1082 is printed.
1082 is printed.
1083
1083
1084 * An integer: only these many lines are printed.
1084 * An integer: only these many lines are printed.
1085
1085
1086 * A float (between 0 and 1): this fraction of the report is printed
1086 * A float (between 0 and 1): this fraction of the report is printed
1087 (for example, use a limit of 0.4 to see the topmost 40% only).
1087 (for example, use a limit of 0.4 to see the topmost 40% only).
1088
1088
1089 You can combine several limits with repeated use of the option. For
1089 You can combine several limits with repeated use of the option. For
1090 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1090 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1091 information about class constructors.
1091 information about class constructors.
1092
1092
1093 -r: return the pstats.Stats object generated by the profiling. This
1093 -r: return the pstats.Stats object generated by the profiling. This
1094 object has all the information about the profile in it, and you can
1094 object has all the information about the profile in it, and you can
1095 later use it for further analysis or in other functions.
1095 later use it for further analysis or in other functions.
1096
1096
1097 Since magic functions have a particular form of calling which prevents
1097 Since magic functions have a particular form of calling which prevents
1098 you from writing something like:\\
1098 you from writing something like:\\
1099 In [1]: p = %prun -r print 4 # invalid!\\
1099 In [1]: p = %prun -r print 4 # invalid!\\
1100 you must instead use IPython's automatic variables to assign this:\\
1100 you must instead use IPython's automatic variables to assign this:\\
1101 In [1]: %prun -r print 4 \\
1101 In [1]: %prun -r print 4 \\
1102 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1102 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1103 In [2]: stats = _
1103 In [2]: stats = _
1104
1104
1105 If you really need to assign this value via an explicit function call,
1105 If you really need to assign this value via an explicit function call,
1106 you can always tap directly into the true name of the magic function
1106 you can always tap directly into the true name of the magic function
1107 by using the ipmagic function (which IPython automatically adds to the
1107 by using the ipmagic function (which IPython automatically adds to the
1108 builtins):\\
1108 builtins):\\
1109 In [3]: stats = ipmagic('prun','-r print 4')
1109 In [3]: stats = ipmagic('prun','-r print 4')
1110
1110
1111 You can type ipmagic? for more details on ipmagic.
1111 You can type ipmagic? for more details on ipmagic.
1112
1112
1113 -s <key>: sort profile by given key. You can provide more than one key
1113 -s <key>: sort profile by given key. You can provide more than one key
1114 by using the option several times: '-s key1 -s key2 -s key3...'. The
1114 by using the option several times: '-s key1 -s key2 -s key3...'. The
1115 default sorting key is 'time'.
1115 default sorting key is 'time'.
1116
1116
1117 The following is copied verbatim from the profile documentation
1117 The following is copied verbatim from the profile documentation
1118 referenced below:
1118 referenced below:
1119
1119
1120 When more than one key is provided, additional keys are used as
1120 When more than one key is provided, additional keys are used as
1121 secondary criteria when the there is equality in all keys selected
1121 secondary criteria when the there is equality in all keys selected
1122 before them.
1122 before them.
1123
1123
1124 Abbreviations can be used for any key names, as long as the
1124 Abbreviations can be used for any key names, as long as the
1125 abbreviation is unambiguous. The following are the keys currently
1125 abbreviation is unambiguous. The following are the keys currently
1126 defined:
1126 defined:
1127
1127
1128 Valid Arg Meaning\\
1128 Valid Arg Meaning\\
1129 "calls" call count\\
1129 "calls" call count\\
1130 "cumulative" cumulative time\\
1130 "cumulative" cumulative time\\
1131 "file" file name\\
1131 "file" file name\\
1132 "module" file name\\
1132 "module" file name\\
1133 "pcalls" primitive call count\\
1133 "pcalls" primitive call count\\
1134 "line" line number\\
1134 "line" line number\\
1135 "name" function name\\
1135 "name" function name\\
1136 "nfl" name/file/line\\
1136 "nfl" name/file/line\\
1137 "stdname" standard name\\
1137 "stdname" standard name\\
1138 "time" internal time
1138 "time" internal time
1139
1139
1140 Note that all sorts on statistics are in descending order (placing
1140 Note that all sorts on statistics are in descending order (placing
1141 most time consuming items first), where as name, file, and line number
1141 most time consuming items first), where as name, file, and line number
1142 searches are in ascending order (i.e., alphabetical). The subtle
1142 searches are in ascending order (i.e., alphabetical). The subtle
1143 distinction between "nfl" and "stdname" is that the standard name is a
1143 distinction between "nfl" and "stdname" is that the standard name is a
1144 sort of the name as printed, which means that the embedded line
1144 sort of the name as printed, which means that the embedded line
1145 numbers get compared in an odd way. For example, lines 3, 20, and 40
1145 numbers get compared in an odd way. For example, lines 3, 20, and 40
1146 would (if the file names were the same) appear in the string order
1146 would (if the file names were the same) appear in the string order
1147 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1147 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1148 line numbers. In fact, sort_stats("nfl") is the same as
1148 line numbers. In fact, sort_stats("nfl") is the same as
1149 sort_stats("name", "file", "line").
1149 sort_stats("name", "file", "line").
1150
1150
1151 -T <filename>: save profile results as shown on screen to a text
1151 -T <filename>: save profile results as shown on screen to a text
1152 file. The profile is still shown on screen.
1152 file. The profile is still shown on screen.
1153
1153
1154 -D <filename>: save (via dump_stats) profile statistics to given
1154 -D <filename>: save (via dump_stats) profile statistics to given
1155 filename. This data is in a format understod by the pstats module, and
1155 filename. This data is in a format understod by the pstats module, and
1156 is generated by a call to the dump_stats() method of profile
1156 is generated by a call to the dump_stats() method of profile
1157 objects. The profile is still shown on screen.
1157 objects. The profile is still shown on screen.
1158
1158
1159 If you want to run complete programs under the profiler's control, use
1159 If you want to run complete programs under the profiler's control, use
1160 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1160 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1161 contains profiler specific options as described here.
1161 contains profiler specific options as described here.
1162
1162
1163 You can read the complete documentation for the profile module with:\\
1163 You can read the complete documentation for the profile module with:\\
1164 In [1]: import profile; profile.help() """
1164 In [1]: import profile; profile.help() """
1165
1165
1166 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1166 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1167 # protect user quote marks
1167 # protect user quote marks
1168 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1168 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1169
1169
1170 if user_mode: # regular user call
1170 if user_mode: # regular user call
1171 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1171 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1172 list_all=1)
1172 list_all=1)
1173 namespace = self.shell.user_ns
1173 namespace = self.shell.user_ns
1174 else: # called to run a program by %run -p
1174 else: # called to run a program by %run -p
1175 try:
1175 try:
1176 filename = get_py_filename(arg_lst[0])
1176 filename = get_py_filename(arg_lst[0])
1177 except IOError,msg:
1177 except IOError,msg:
1178 error(msg)
1178 error(msg)
1179 return
1179 return
1180
1180
1181 arg_str = 'execfile(filename,prog_ns)'
1181 arg_str = 'execfile(filename,prog_ns)'
1182 namespace = locals()
1182 namespace = locals()
1183
1183
1184 opts.merge(opts_def)
1184 opts.merge(opts_def)
1185
1185
1186 prof = profile.Profile()
1186 prof = profile.Profile()
1187 try:
1187 try:
1188 prof = prof.runctx(arg_str,namespace,namespace)
1188 prof = prof.runctx(arg_str,namespace,namespace)
1189 sys_exit = ''
1189 sys_exit = ''
1190 except SystemExit:
1190 except SystemExit:
1191 sys_exit = """*** SystemExit exception caught in code being profiled."""
1191 sys_exit = """*** SystemExit exception caught in code being profiled."""
1192
1192
1193 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1193 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1194
1194
1195 lims = opts.l
1195 lims = opts.l
1196 if lims:
1196 if lims:
1197 lims = [] # rebuild lims with ints/floats/strings
1197 lims = [] # rebuild lims with ints/floats/strings
1198 for lim in opts.l:
1198 for lim in opts.l:
1199 try:
1199 try:
1200 lims.append(int(lim))
1200 lims.append(int(lim))
1201 except ValueError:
1201 except ValueError:
1202 try:
1202 try:
1203 lims.append(float(lim))
1203 lims.append(float(lim))
1204 except ValueError:
1204 except ValueError:
1205 lims.append(lim)
1205 lims.append(lim)
1206
1206
1207 # trap output
1207 # trap output
1208 sys_stdout = sys.stdout
1208 sys_stdout = sys.stdout
1209 stdout_trap = StringIO()
1209 stdout_trap = StringIO()
1210 try:
1210 try:
1211 sys.stdout = stdout_trap
1211 sys.stdout = stdout_trap
1212 stats.print_stats(*lims)
1212 stats.print_stats(*lims)
1213 finally:
1213 finally:
1214 sys.stdout = sys_stdout
1214 sys.stdout = sys_stdout
1215 output = stdout_trap.getvalue()
1215 output = stdout_trap.getvalue()
1216 output = output.rstrip()
1216 output = output.rstrip()
1217
1217
1218 page(output,screen_lines=self.shell.rc.screen_length)
1218 page(output,screen_lines=self.shell.rc.screen_length)
1219 print sys_exit,
1219 print sys_exit,
1220
1220
1221 dump_file = opts.D[0]
1221 dump_file = opts.D[0]
1222 text_file = opts.T[0]
1222 text_file = opts.T[0]
1223 if dump_file:
1223 if dump_file:
1224 prof.dump_stats(dump_file)
1224 prof.dump_stats(dump_file)
1225 print '\n*** Profile stats marshalled to file',\
1225 print '\n*** Profile stats marshalled to file',\
1226 `dump_file`+'.',sys_exit
1226 `dump_file`+'.',sys_exit
1227 if text_file:
1227 if text_file:
1228 file(text_file,'w').write(output)
1228 file(text_file,'w').write(output)
1229 print '\n*** Profile printout saved to text file',\
1229 print '\n*** Profile printout saved to text file',\
1230 `text_file`+'.',sys_exit
1230 `text_file`+'.',sys_exit
1231
1231
1232 if opts.has_key('r'):
1232 if opts.has_key('r'):
1233 return stats
1233 return stats
1234 else:
1234 else:
1235 return None
1235 return None
1236
1236
1237 def magic_run(self, parameter_s ='',runner=None):
1237 def magic_run(self, parameter_s ='',runner=None):
1238 """Run the named file inside IPython as a program.
1238 """Run the named file inside IPython as a program.
1239
1239
1240 Usage:\\
1240 Usage:\\
1241 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1241 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1242
1242
1243 Parameters after the filename are passed as command-line arguments to
1243 Parameters after the filename are passed as command-line arguments to
1244 the program (put in sys.argv). Then, control returns to IPython's
1244 the program (put in sys.argv). Then, control returns to IPython's
1245 prompt.
1245 prompt.
1246
1246
1247 This is similar to running at a system prompt:\\
1247 This is similar to running at a system prompt:\\
1248 $ python file args\\
1248 $ python file args\\
1249 but with the advantage of giving you IPython's tracebacks, and of
1249 but with the advantage of giving you IPython's tracebacks, and of
1250 loading all variables into your interactive namespace for further use
1250 loading all variables into your interactive namespace for further use
1251 (unless -p is used, see below).
1251 (unless -p is used, see below).
1252
1252
1253 The file is executed in a namespace initially consisting only of
1253 The file is executed in a namespace initially consisting only of
1254 __name__=='__main__' and sys.argv constructed as indicated. It thus
1254 __name__=='__main__' and sys.argv constructed as indicated. It thus
1255 sees its environment as if it were being run as a stand-alone
1255 sees its environment as if it were being run as a stand-alone
1256 program. But after execution, the IPython interactive namespace gets
1256 program. But after execution, the IPython interactive namespace gets
1257 updated with all variables defined in the program (except for __name__
1257 updated with all variables defined in the program (except for __name__
1258 and sys.argv). This allows for very convenient loading of code for
1258 and sys.argv). This allows for very convenient loading of code for
1259 interactive work, while giving each program a 'clean sheet' to run in.
1259 interactive work, while giving each program a 'clean sheet' to run in.
1260
1260
1261 Options:
1261 Options:
1262
1262
1263 -n: __name__ is NOT set to '__main__', but to the running file's name
1263 -n: __name__ is NOT set to '__main__', but to the running file's name
1264 without extension (as python does under import). This allows running
1264 without extension (as python does under import). This allows running
1265 scripts and reloading the definitions in them without calling code
1265 scripts and reloading the definitions in them without calling code
1266 protected by an ' if __name__ == "__main__" ' clause.
1266 protected by an ' if __name__ == "__main__" ' clause.
1267
1267
1268 -i: run the file in IPython's namespace instead of an empty one. This
1268 -i: run the file in IPython's namespace instead of an empty one. This
1269 is useful if you are experimenting with code written in a text editor
1269 is useful if you are experimenting with code written in a text editor
1270 which depends on variables defined interactively.
1270 which depends on variables defined interactively.
1271
1271
1272 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1272 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1273 being run. This is particularly useful if IPython is being used to
1273 being run. This is particularly useful if IPython is being used to
1274 run unittests, which always exit with a sys.exit() call. In such
1274 run unittests, which always exit with a sys.exit() call. In such
1275 cases you are interested in the output of the test results, not in
1275 cases you are interested in the output of the test results, not in
1276 seeing a traceback of the unittest module.
1276 seeing a traceback of the unittest module.
1277
1277
1278 -t: print timing information at the end of the run. IPython will give
1278 -t: print timing information at the end of the run. IPython will give
1279 you an estimated CPU time consumption for your script, which under
1279 you an estimated CPU time consumption for your script, which under
1280 Unix uses the resource module to avoid the wraparound problems of
1280 Unix uses the resource module to avoid the wraparound problems of
1281 time.clock(). Under Unix, an estimate of time spent on system tasks
1281 time.clock(). Under Unix, an estimate of time spent on system tasks
1282 is also given (for Windows platforms this is reported as 0.0).
1282 is also given (for Windows platforms this is reported as 0.0).
1283
1283
1284 If -t is given, an additional -N<N> option can be given, where <N>
1284 If -t is given, an additional -N<N> option can be given, where <N>
1285 must be an integer indicating how many times you want the script to
1285 must be an integer indicating how many times you want the script to
1286 run. The final timing report will include total and per run results.
1286 run. The final timing report will include total and per run results.
1287
1287
1288 For example (testing the script uniq_stable.py):
1288 For example (testing the script uniq_stable.py):
1289
1289
1290 In [1]: run -t uniq_stable
1290 In [1]: run -t uniq_stable
1291
1291
1292 IPython CPU timings (estimated):\\
1292 IPython CPU timings (estimated):\\
1293 User : 0.19597 s.\\
1293 User : 0.19597 s.\\
1294 System: 0.0 s.\\
1294 System: 0.0 s.\\
1295
1295
1296 In [2]: run -t -N5 uniq_stable
1296 In [2]: run -t -N5 uniq_stable
1297
1297
1298 IPython CPU timings (estimated):\\
1298 IPython CPU timings (estimated):\\
1299 Total runs performed: 5\\
1299 Total runs performed: 5\\
1300 Times : Total Per run\\
1300 Times : Total Per run\\
1301 User : 0.910862 s, 0.1821724 s.\\
1301 User : 0.910862 s, 0.1821724 s.\\
1302 System: 0.0 s, 0.0 s.
1302 System: 0.0 s, 0.0 s.
1303
1303
1304 -d: run your program under the control of pdb, the Python debugger.
1304 -d: run your program under the control of pdb, the Python debugger.
1305 This allows you to execute your program step by step, watch variables,
1305 This allows you to execute your program step by step, watch variables,
1306 etc. Internally, what IPython does is similar to calling:
1306 etc. Internally, what IPython does is similar to calling:
1307
1307
1308 pdb.run('execfile("YOURFILENAME")')
1308 pdb.run('execfile("YOURFILENAME")')
1309
1309
1310 with a breakpoint set on line 1 of your file. You can change the line
1310 with a breakpoint set on line 1 of your file. You can change the line
1311 number for this automatic breakpoint to be <N> by using the -bN option
1311 number for this automatic breakpoint to be <N> by using the -bN option
1312 (where N must be an integer). For example:
1312 (where N must be an integer). For example:
1313
1313
1314 %run -d -b40 myscript
1314 %run -d -b40 myscript
1315
1315
1316 will set the first breakpoint at line 40 in myscript.py. Note that
1316 will set the first breakpoint at line 40 in myscript.py. Note that
1317 the first breakpoint must be set on a line which actually does
1317 the first breakpoint must be set on a line which actually does
1318 something (not a comment or docstring) for it to stop execution.
1318 something (not a comment or docstring) for it to stop execution.
1319
1319
1320 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1320 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1321 first enter 'c' (without qoutes) to start execution up to the first
1321 first enter 'c' (without qoutes) to start execution up to the first
1322 breakpoint.
1322 breakpoint.
1323
1323
1324 Entering 'help' gives information about the use of the debugger. You
1324 Entering 'help' gives information about the use of the debugger. You
1325 can easily see pdb's full documentation with "import pdb;pdb.help()"
1325 can easily see pdb's full documentation with "import pdb;pdb.help()"
1326 at a prompt.
1326 at a prompt.
1327
1327
1328 -p: run program under the control of the Python profiler module (which
1328 -p: run program under the control of the Python profiler module (which
1329 prints a detailed report of execution times, function calls, etc).
1329 prints a detailed report of execution times, function calls, etc).
1330
1330
1331 You can pass other options after -p which affect the behavior of the
1331 You can pass other options after -p which affect the behavior of the
1332 profiler itself. See the docs for %prun for details.
1332 profiler itself. See the docs for %prun for details.
1333
1333
1334 In this mode, the program's variables do NOT propagate back to the
1334 In this mode, the program's variables do NOT propagate back to the
1335 IPython interactive namespace (because they remain in the namespace
1335 IPython interactive namespace (because they remain in the namespace
1336 where the profiler executes them).
1336 where the profiler executes them).
1337
1337
1338 Internally this triggers a call to %prun, see its documentation for
1338 Internally this triggers a call to %prun, see its documentation for
1339 details on the options available specifically for profiling."""
1339 details on the options available specifically for profiling."""
1340
1340
1341 # get arguments and set sys.argv for program to be run.
1341 # get arguments and set sys.argv for program to be run.
1342 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1342 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1343 mode='list',list_all=1)
1343 mode='list',list_all=1)
1344
1344
1345 try:
1345 try:
1346 filename = get_py_filename(arg_lst[0])
1346 filename = get_py_filename(arg_lst[0])
1347 except IndexError:
1347 except IndexError:
1348 warn('you must provide at least a filename.')
1348 warn('you must provide at least a filename.')
1349 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1349 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1350 return
1350 return
1351 except IOError,msg:
1351 except IOError,msg:
1352 error(msg)
1352 error(msg)
1353 return
1353 return
1354
1354
1355 # Control the response to exit() calls made by the script being run
1355 # Control the response to exit() calls made by the script being run
1356 exit_ignore = opts.has_key('e')
1356 exit_ignore = opts.has_key('e')
1357
1357
1358 # Make sure that the running script gets a proper sys.argv as if it
1358 # Make sure that the running script gets a proper sys.argv as if it
1359 # were run from a system shell.
1359 # were run from a system shell.
1360 save_argv = sys.argv # save it for later restoring
1360 save_argv = sys.argv # save it for later restoring
1361 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1361 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1362
1362
1363 if opts.has_key('i'):
1363 if opts.has_key('i'):
1364 prog_ns = self.shell.user_ns
1364 prog_ns = self.shell.user_ns
1365 __name__save = self.shell.user_ns['__name__']
1365 __name__save = self.shell.user_ns['__name__']
1366 prog_ns['__name__'] = '__main__'
1366 prog_ns['__name__'] = '__main__'
1367 else:
1367 else:
1368 if opts.has_key('n'):
1368 if opts.has_key('n'):
1369 name = os.path.splitext(os.path.basename(filename))[0]
1369 name = os.path.splitext(os.path.basename(filename))[0]
1370 else:
1370 else:
1371 name = '__main__'
1371 name = '__main__'
1372 prog_ns = {'__name__':name}
1372 prog_ns = {'__name__':name}
1373
1373
1374 # pickle fix. See iplib for an explanation
1374 # pickle fix. See iplib for an explanation
1375 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1375 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1376
1376
1377 stats = None
1377 stats = None
1378 try:
1378 try:
1379 if opts.has_key('p'):
1379 if opts.has_key('p'):
1380 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1380 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1381 else:
1381 else:
1382 if opts.has_key('d'):
1382 if opts.has_key('d'):
1383 deb = Debugger.Pdb(self.shell.rc.colors)
1383 deb = Debugger.Pdb(self.shell.rc.colors)
1384 # reset Breakpoint state, which is moronically kept
1384 # reset Breakpoint state, which is moronically kept
1385 # in a class
1385 # in a class
1386 bdb.Breakpoint.next = 1
1386 bdb.Breakpoint.next = 1
1387 bdb.Breakpoint.bplist = {}
1387 bdb.Breakpoint.bplist = {}
1388 bdb.Breakpoint.bpbynumber = [None]
1388 bdb.Breakpoint.bpbynumber = [None]
1389 # Set an initial breakpoint to stop execution
1389 # Set an initial breakpoint to stop execution
1390 maxtries = 10
1390 maxtries = 10
1391 bp = int(opts.get('b',[1])[0])
1391 bp = int(opts.get('b',[1])[0])
1392 checkline = deb.checkline(filename,bp)
1392 checkline = deb.checkline(filename,bp)
1393 if not checkline:
1393 if not checkline:
1394 for bp in range(bp+1,bp+maxtries+1):
1394 for bp in range(bp+1,bp+maxtries+1):
1395 if deb.checkline(filename,bp):
1395 if deb.checkline(filename,bp):
1396 break
1396 break
1397 else:
1397 else:
1398 msg = ("\nI failed to find a valid line to set "
1398 msg = ("\nI failed to find a valid line to set "
1399 "a breakpoint\n"
1399 "a breakpoint\n"
1400 "after trying up to line: %s.\n"
1400 "after trying up to line: %s.\n"
1401 "Please set a valid breakpoint manually "
1401 "Please set a valid breakpoint manually "
1402 "with the -b option." % bp)
1402 "with the -b option." % bp)
1403 error(msg)
1403 error(msg)
1404 return
1404 return
1405 # if we find a good linenumber, set the breakpoint
1405 # if we find a good linenumber, set the breakpoint
1406 deb.do_break('%s:%s' % (filename,bp))
1406 deb.do_break('%s:%s' % (filename,bp))
1407 # Start file run
1407 # Start file run
1408 print "NOTE: Enter 'c' at the",
1408 print "NOTE: Enter 'c' at the",
1409 print "ipdb> prompt to start your script."
1409 print "ipdb> prompt to start your script."
1410 try:
1410 try:
1411 deb.run('execfile("%s")' % filename,prog_ns)
1411 deb.run('execfile("%s")' % filename,prog_ns)
1412 except:
1412 except:
1413 etype, value, tb = sys.exc_info()
1413 etype, value, tb = sys.exc_info()
1414 # Skip three frames in the traceback: the %run one,
1414 # Skip three frames in the traceback: the %run one,
1415 # one inside bdb.py, and the command-line typed by the
1415 # one inside bdb.py, and the command-line typed by the
1416 # user (run by exec in pdb itself).
1416 # user (run by exec in pdb itself).
1417 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1417 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1418 else:
1418 else:
1419 if runner is None:
1419 if runner is None:
1420 runner = self.shell.safe_execfile
1420 runner = self.shell.safe_execfile
1421 if opts.has_key('t'):
1421 if opts.has_key('t'):
1422 try:
1422 try:
1423 nruns = int(opts['N'][0])
1423 nruns = int(opts['N'][0])
1424 if nruns < 1:
1424 if nruns < 1:
1425 error('Number of runs must be >=1')
1425 error('Number of runs must be >=1')
1426 return
1426 return
1427 except (KeyError):
1427 except (KeyError):
1428 nruns = 1
1428 nruns = 1
1429 if nruns == 1:
1429 if nruns == 1:
1430 t0 = clock2()
1430 t0 = clock2()
1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1432 t1 = clock2()
1432 t1 = clock2()
1433 t_usr = t1[0]-t0[0]
1433 t_usr = t1[0]-t0[0]
1434 t_sys = t1[1]-t1[1]
1434 t_sys = t1[1]-t1[1]
1435 print "\nIPython CPU timings (estimated):"
1435 print "\nIPython CPU timings (estimated):"
1436 print " User : %10s s." % t_usr
1436 print " User : %10s s." % t_usr
1437 print " System: %10s s." % t_sys
1437 print " System: %10s s." % t_sys
1438 else:
1438 else:
1439 runs = range(nruns)
1439 runs = range(nruns)
1440 t0 = clock2()
1440 t0 = clock2()
1441 for nr in runs:
1441 for nr in runs:
1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1443 t1 = clock2()
1443 t1 = clock2()
1444 t_usr = t1[0]-t0[0]
1444 t_usr = t1[0]-t0[0]
1445 t_sys = t1[1]-t1[1]
1445 t_sys = t1[1]-t1[1]
1446 print "\nIPython CPU timings (estimated):"
1446 print "\nIPython CPU timings (estimated):"
1447 print "Total runs performed:",nruns
1447 print "Total runs performed:",nruns
1448 print " Times : %10s %10s" % ('Total','Per run')
1448 print " Times : %10s %10s" % ('Total','Per run')
1449 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1449 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1450 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1450 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1451
1451
1452 else:
1452 else:
1453 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1453 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1454 if opts.has_key('i'):
1454 if opts.has_key('i'):
1455 self.shell.user_ns['__name__'] = __name__save
1455 self.shell.user_ns['__name__'] = __name__save
1456 else:
1456 else:
1457 # update IPython interactive namespace
1457 # update IPython interactive namespace
1458 del prog_ns['__name__']
1458 del prog_ns['__name__']
1459 self.shell.user_ns.update(prog_ns)
1459 self.shell.user_ns.update(prog_ns)
1460 finally:
1460 finally:
1461 sys.argv = save_argv
1461 sys.argv = save_argv
1462 return stats
1462 return stats
1463
1463
1464 def magic_runlog(self, parameter_s =''):
1464 def magic_runlog(self, parameter_s =''):
1465 """Run files as logs.
1465 """Run files as logs.
1466
1466
1467 Usage:\\
1467 Usage:\\
1468 %runlog file1 file2 ...
1468 %runlog file1 file2 ...
1469
1469
1470 Run the named files (treating them as log files) in sequence inside
1470 Run the named files (treating them as log files) in sequence inside
1471 the interpreter, and return to the prompt. This is much slower than
1471 the interpreter, and return to the prompt. This is much slower than
1472 %run because each line is executed in a try/except block, but it
1472 %run because each line is executed in a try/except block, but it
1473 allows running files with syntax errors in them.
1473 allows running files with syntax errors in them.
1474
1474
1475 Normally IPython will guess when a file is one of its own logfiles, so
1475 Normally IPython will guess when a file is one of its own logfiles, so
1476 you can typically use %run even for logs. This shorthand allows you to
1476 you can typically use %run even for logs. This shorthand allows you to
1477 force any file to be treated as a log file."""
1477 force any file to be treated as a log file."""
1478
1478
1479 for f in parameter_s.split():
1479 for f in parameter_s.split():
1480 self.shell.safe_execfile(f,self.shell.user_ns,
1480 self.shell.safe_execfile(f,self.shell.user_ns,
1481 self.shell.user_ns,islog=1)
1481 self.shell.user_ns,islog=1)
1482
1482
1483 def magic_time(self,parameter_s = ''):
1483 def magic_time(self,parameter_s = ''):
1484 """Time execution of a Python statement or expression.
1484 """Time execution of a Python statement or expression.
1485
1485
1486 The CPU and wall clock times are printed, and the value of the
1486 The CPU and wall clock times are printed, and the value of the
1487 expression (if any) is returned. Note that under Win32, system time
1487 expression (if any) is returned. Note that under Win32, system time
1488 is always reported as 0, since it can not be measured.
1488 is always reported as 0, since it can not be measured.
1489
1489
1490 This function provides very basic timing functionality. In Python
1490 This function provides very basic timing functionality. In Python
1491 2.3, the timeit module offers more control and sophistication, but for
1491 2.3, the timeit module offers more control and sophistication, but for
1492 now IPython supports Python 2.2, so we can not rely on timeit being
1492 now IPython supports Python 2.2, so we can not rely on timeit being
1493 present.
1493 present.
1494
1494
1495 Some examples:
1495 Some examples:
1496
1496
1497 In [1]: time 2**128
1497 In [1]: time 2**128
1498 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1498 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1499 Wall time: 0.00
1499 Wall time: 0.00
1500 Out[1]: 340282366920938463463374607431768211456L
1500 Out[1]: 340282366920938463463374607431768211456L
1501
1501
1502 In [2]: n = 1000000
1502 In [2]: n = 1000000
1503
1503
1504 In [3]: time sum(range(n))
1504 In [3]: time sum(range(n))
1505 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1505 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1506 Wall time: 1.37
1506 Wall time: 1.37
1507 Out[3]: 499999500000L
1507 Out[3]: 499999500000L
1508
1508
1509 In [4]: time print 'hello world'
1509 In [4]: time print 'hello world'
1510 hello world
1510 hello world
1511 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1511 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1512 Wall time: 0.00
1512 Wall time: 0.00
1513 """
1513 """
1514
1514
1515 # fail immediately if the given expression can't be compiled
1515 # fail immediately if the given expression can't be compiled
1516 try:
1516 try:
1517 mode = 'eval'
1517 mode = 'eval'
1518 code = compile(parameter_s,'<timed eval>',mode)
1518 code = compile(parameter_s,'<timed eval>',mode)
1519 except SyntaxError:
1519 except SyntaxError:
1520 mode = 'exec'
1520 mode = 'exec'
1521 code = compile(parameter_s,'<timed exec>',mode)
1521 code = compile(parameter_s,'<timed exec>',mode)
1522 # skew measurement as little as possible
1522 # skew measurement as little as possible
1523 glob = self.shell.user_ns
1523 glob = self.shell.user_ns
1524 clk = clock2
1524 clk = clock2
1525 wtime = time.time
1525 wtime = time.time
1526 # time execution
1526 # time execution
1527 wall_st = wtime()
1527 wall_st = wtime()
1528 if mode=='eval':
1528 if mode=='eval':
1529 st = clk()
1529 st = clk()
1530 out = eval(code,glob)
1530 out = eval(code,glob)
1531 end = clk()
1531 end = clk()
1532 else:
1532 else:
1533 st = clk()
1533 st = clk()
1534 exec code in glob
1534 exec code in glob
1535 end = clk()
1535 end = clk()
1536 out = None
1536 out = None
1537 wall_end = wtime()
1537 wall_end = wtime()
1538 # Compute actual times and report
1538 # Compute actual times and report
1539 wall_time = wall_end-wall_st
1539 wall_time = wall_end-wall_st
1540 cpu_user = end[0]-st[0]
1540 cpu_user = end[0]-st[0]
1541 cpu_sys = end[1]-st[1]
1541 cpu_sys = end[1]-st[1]
1542 cpu_tot = cpu_user+cpu_sys
1542 cpu_tot = cpu_user+cpu_sys
1543 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1543 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1544 (cpu_user,cpu_sys,cpu_tot)
1544 (cpu_user,cpu_sys,cpu_tot)
1545 print "Wall time: %.2f" % wall_time
1545 print "Wall time: %.2f" % wall_time
1546 return out
1546 return out
1547
1547
1548 def magic_macro(self,parameter_s = ''):
1548 def magic_macro(self,parameter_s = ''):
1549 """Define a set of input lines as a macro for future re-execution.
1549 """Define a set of input lines as a macro for future re-execution.
1550
1550
1551 Usage:\\
1551 Usage:\\
1552 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1552 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1553
1553
1554 This will define a global variable called `name` which is a string
1554 This will define a global variable called `name` which is a string
1555 made of joining the slices and lines you specify (n1,n2,... numbers
1555 made of joining the slices and lines you specify (n1,n2,... numbers
1556 above) from your input history into a single string. This variable
1556 above) from your input history into a single string. This variable
1557 acts like an automatic function which re-executes those lines as if
1557 acts like an automatic function which re-executes those lines as if
1558 you had typed them. You just type 'name' at the prompt and the code
1558 you had typed them. You just type 'name' at the prompt and the code
1559 executes.
1559 executes.
1560
1560
1561 Note that the slices use the standard Python slicing notation (5:8
1561 Note that the slices use the standard Python slicing notation (5:8
1562 means include lines numbered 5,6,7).
1562 means include lines numbered 5,6,7).
1563
1563
1564 For example, if your history contains (%hist prints it):
1564 For example, if your history contains (%hist prints it):
1565
1565
1566 44: x=1\\
1566 44: x=1\\
1567 45: y=3\\
1567 45: y=3\\
1568 46: z=x+y\\
1568 46: z=x+y\\
1569 47: print x\\
1569 47: print x\\
1570 48: a=5\\
1570 48: a=5\\
1571 49: print 'x',x,'y',y\\
1571 49: print 'x',x,'y',y\\
1572
1572
1573 you can create a macro with lines 44 through 47 (included) and line 49
1573 you can create a macro with lines 44 through 47 (included) and line 49
1574 called my_macro with:
1574 called my_macro with:
1575
1575
1576 In [51]: %macro my_macro 44:48 49
1576 In [51]: %macro my_macro 44:48 49
1577
1577
1578 Now, typing `my_macro` (without quotes) will re-execute all this code
1578 Now, typing `my_macro` (without quotes) will re-execute all this code
1579 in one pass.
1579 in one pass.
1580
1580
1581 You don't need to give the line-numbers in order, and any given line
1581 You don't need to give the line-numbers in order, and any given line
1582 number can appear multiple times. You can assemble macros with any
1582 number can appear multiple times. You can assemble macros with any
1583 lines from your input history in any order.
1583 lines from your input history in any order.
1584
1584
1585 The macro is a simple object which holds its value in an attribute,
1585 The macro is a simple object which holds its value in an attribute,
1586 but IPython's display system checks for macros and executes them as
1586 but IPython's display system checks for macros and executes them as
1587 code instead of printing them when you type their name.
1587 code instead of printing them when you type their name.
1588
1588
1589 You can view a macro's contents by explicitly printing it with:
1589 You can view a macro's contents by explicitly printing it with:
1590
1590
1591 'print macro_name'.
1591 'print macro_name'.
1592
1592
1593 For one-off cases which DON'T contain magic function calls in them you
1593 For one-off cases which DON'T contain magic function calls in them you
1594 can obtain similar results by explicitly executing slices from your
1594 can obtain similar results by explicitly executing slices from your
1595 input history with:
1595 input history with:
1596
1596
1597 In [60]: exec In[44:48]+In[49]"""
1597 In [60]: exec In[44:48]+In[49]"""
1598
1598
1599 args = parameter_s.split()
1599 args = parameter_s.split()
1600 name,ranges = args[0], args[1:]
1600 name,ranges = args[0], args[1:]
1601 #print 'rng',ranges # dbg
1601 #print 'rng',ranges # dbg
1602 cmds = self.extract_input_slices(ranges)
1602 cmds = self.extract_input_slices(ranges)
1603 macro = Macro(cmds)
1603 macro = Macro(cmds)
1604 self.shell.user_ns.update({name:macro})
1604 self.shell.user_ns.update({name:macro})
1605 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1605 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1606 print 'Macro contents:'
1606 print 'Macro contents:'
1607 print str(macro).rstrip(),
1607 print str(macro).rstrip(),
1608
1608
1609 def magic_save(self,parameter_s = ''):
1609 def magic_save(self,parameter_s = ''):
1610 """Save a set of lines to a given filename.
1610 """Save a set of lines to a given filename.
1611
1611
1612 Usage:\\
1612 Usage:\\
1613 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1613 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1614
1614
1615 This function uses the same syntax as %macro for line extraction, but
1615 This function uses the same syntax as %macro for line extraction, but
1616 instead of creating a macro it saves the resulting string to the
1616 instead of creating a macro it saves the resulting string to the
1617 filename you specify.
1617 filename you specify.
1618
1618
1619 It adds a '.py' extension to the file if you don't do so yourself, and
1619 It adds a '.py' extension to the file if you don't do so yourself, and
1620 it asks for confirmation before overwriting existing files."""
1620 it asks for confirmation before overwriting existing files."""
1621
1621
1622 args = parameter_s.split()
1622 args = parameter_s.split()
1623 fname,ranges = args[0], args[1:]
1623 fname,ranges = args[0], args[1:]
1624 if not fname.endswith('.py'):
1624 if not fname.endswith('.py'):
1625 fname += '.py'
1625 fname += '.py'
1626 if os.path.isfile(fname):
1626 if os.path.isfile(fname):
1627 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1627 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1628 if ans.lower() not in ['y','yes']:
1628 if ans.lower() not in ['y','yes']:
1629 print 'Operation cancelled.'
1629 print 'Operation cancelled.'
1630 return
1630 return
1631 cmds = ''.join(self.extract_input_slices(ranges))
1631 cmds = ''.join(self.extract_input_slices(ranges))
1632 f = file(fname,'w')
1632 f = file(fname,'w')
1633 f.write(cmds)
1633 f.write(cmds)
1634 f.close()
1634 f.close()
1635 print 'The following commands were written to file `%s`:' % fname
1635 print 'The following commands were written to file `%s`:' % fname
1636 print cmds
1636 print cmds
1637
1637
1638 def magic_ed(self,parameter_s = ''):
1638 def magic_ed(self,parameter_s = ''):
1639 """Alias to %edit."""
1639 """Alias to %edit."""
1640 return self.magic_edit(parameter_s)
1640 return self.magic_edit(parameter_s)
1641
1641
1642 def magic_edit(self,parameter_s = '',last_call=['','']):
1642 def magic_edit(self,parameter_s = '',last_call=['','']):
1643 """Bring up an editor and execute the resulting code.
1643 """Bring up an editor and execute the resulting code.
1644
1644
1645 Usage:
1645 Usage:
1646 %edit [options] [args]
1646 %edit [options] [args]
1647
1647
1648 %edit runs IPython's editor hook. The default version of this hook is
1648 %edit runs IPython's editor hook. The default version of this hook is
1649 set to call the __IPYTHON__.rc.editor command. This is read from your
1649 set to call the __IPYTHON__.rc.editor command. This is read from your
1650 environment variable $EDITOR. If this isn't found, it will default to
1650 environment variable $EDITOR. If this isn't found, it will default to
1651 vi under Linux/Unix and to notepad under Windows. See the end of this
1651 vi under Linux/Unix and to notepad under Windows. See the end of this
1652 docstring for how to change the editor hook.
1652 docstring for how to change the editor hook.
1653
1653
1654 You can also set the value of this editor via the command line option
1654 You can also set the value of this editor via the command line option
1655 '-editor' or in your ipythonrc file. This is useful if you wish to use
1655 '-editor' or in your ipythonrc file. This is useful if you wish to use
1656 specifically for IPython an editor different from your typical default
1656 specifically for IPython an editor different from your typical default
1657 (and for Windows users who typically don't set environment variables).
1657 (and for Windows users who typically don't set environment variables).
1658
1658
1659 This command allows you to conveniently edit multi-line code right in
1659 This command allows you to conveniently edit multi-line code right in
1660 your IPython session.
1660 your IPython session.
1661
1661
1662 If called without arguments, %edit opens up an empty editor with a
1662 If called without arguments, %edit opens up an empty editor with a
1663 temporary file and will execute the contents of this file when you
1663 temporary file and will execute the contents of this file when you
1664 close it (don't forget to save it!).
1664 close it (don't forget to save it!).
1665
1665
1666 Options:
1666 Options:
1667
1667
1668 -p: this will call the editor with the same data as the previous time
1668 -p: this will call the editor with the same data as the previous time
1669 it was used, regardless of how long ago (in your current session) it
1669 it was used, regardless of how long ago (in your current session) it
1670 was.
1670 was.
1671
1671
1672 -x: do not execute the edited code immediately upon exit. This is
1672 -x: do not execute the edited code immediately upon exit. This is
1673 mainly useful if you are editing programs which need to be called with
1673 mainly useful if you are editing programs which need to be called with
1674 command line arguments, which you can then do using %run.
1674 command line arguments, which you can then do using %run.
1675
1675
1676 Arguments:
1676 Arguments:
1677
1677
1678 If arguments are given, the following possibilites exist:
1678 If arguments are given, the following possibilites exist:
1679
1679
1680 - The arguments are numbers or pairs of colon-separated numbers (like
1680 - The arguments are numbers or pairs of colon-separated numbers (like
1681 1 4:8 9). These are interpreted as lines of previous input to be
1681 1 4:8 9). These are interpreted as lines of previous input to be
1682 loaded into the editor. The syntax is the same of the %macro command.
1682 loaded into the editor. The syntax is the same of the %macro command.
1683
1683
1684 - If the argument doesn't start with a number, it is evaluated as a
1684 - If the argument doesn't start with a number, it is evaluated as a
1685 variable and its contents loaded into the editor. You can thus edit
1685 variable and its contents loaded into the editor. You can thus edit
1686 any string which contains python code (including the result of
1686 any string which contains python code (including the result of
1687 previous edits).
1687 previous edits).
1688
1688
1689 - If the argument is the name of an object (other than a string),
1689 - If the argument is the name of an object (other than a string),
1690 IPython will try to locate the file where it was defined and open the
1690 IPython will try to locate the file where it was defined and open the
1691 editor at the point where it is defined. You can use `%edit function`
1691 editor at the point where it is defined. You can use `%edit function`
1692 to load an editor exactly at the point where 'function' is defined,
1692 to load an editor exactly at the point where 'function' is defined,
1693 edit it and have the file be executed automatically.
1693 edit it and have the file be executed automatically.
1694
1694
1695 Note: opening at an exact line is only supported under Unix, and some
1695 Note: opening at an exact line is only supported under Unix, and some
1696 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1696 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1697 '+NUMBER' parameter necessary for this feature. Good editors like
1697 '+NUMBER' parameter necessary for this feature. Good editors like
1698 (X)Emacs, vi, jed, pico and joe all do.
1698 (X)Emacs, vi, jed, pico and joe all do.
1699
1699
1700 - If the argument is not found as a variable, IPython will look for a
1700 - If the argument is not found as a variable, IPython will look for a
1701 file with that name (adding .py if necessary) and load it into the
1701 file with that name (adding .py if necessary) and load it into the
1702 editor. It will execute its contents with execfile() when you exit,
1702 editor. It will execute its contents with execfile() when you exit,
1703 loading any code in the file into your interactive namespace.
1703 loading any code in the file into your interactive namespace.
1704
1704
1705 After executing your code, %edit will return as output the code you
1705 After executing your code, %edit will return as output the code you
1706 typed in the editor (except when it was an existing file). This way
1706 typed in the editor (except when it was an existing file). This way
1707 you can reload the code in further invocations of %edit as a variable,
1707 you can reload the code in further invocations of %edit as a variable,
1708 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1708 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1709 the output.
1709 the output.
1710
1710
1711 Note that %edit is also available through the alias %ed.
1711 Note that %edit is also available through the alias %ed.
1712
1712
1713 This is an example of creating a simple function inside the editor and
1713 This is an example of creating a simple function inside the editor and
1714 then modifying it. First, start up the editor:
1714 then modifying it. First, start up the editor:
1715
1715
1716 In [1]: ed\\
1716 In [1]: ed\\
1717 Editing... done. Executing edited code...\\
1717 Editing... done. Executing edited code...\\
1718 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1718 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1719
1719
1720 We can then call the function foo():
1720 We can then call the function foo():
1721
1721
1722 In [2]: foo()\\
1722 In [2]: foo()\\
1723 foo() was defined in an editing session
1723 foo() was defined in an editing session
1724
1724
1725 Now we edit foo. IPython automatically loads the editor with the
1725 Now we edit foo. IPython automatically loads the editor with the
1726 (temporary) file where foo() was previously defined:
1726 (temporary) file where foo() was previously defined:
1727
1727
1728 In [3]: ed foo\\
1728 In [3]: ed foo\\
1729 Editing... done. Executing edited code...
1729 Editing... done. Executing edited code...
1730
1730
1731 And if we call foo() again we get the modified version:
1731 And if we call foo() again we get the modified version:
1732
1732
1733 In [4]: foo()\\
1733 In [4]: foo()\\
1734 foo() has now been changed!
1734 foo() has now been changed!
1735
1735
1736 Here is an example of how to edit a code snippet successive
1736 Here is an example of how to edit a code snippet successive
1737 times. First we call the editor:
1737 times. First we call the editor:
1738
1738
1739 In [8]: ed\\
1739 In [8]: ed\\
1740 Editing... done. Executing edited code...\\
1740 Editing... done. Executing edited code...\\
1741 hello\\
1741 hello\\
1742 Out[8]: "print 'hello'\\n"
1742 Out[8]: "print 'hello'\\n"
1743
1743
1744 Now we call it again with the previous output (stored in _):
1744 Now we call it again with the previous output (stored in _):
1745
1745
1746 In [9]: ed _\\
1746 In [9]: ed _\\
1747 Editing... done. Executing edited code...\\
1747 Editing... done. Executing edited code...\\
1748 hello world\\
1748 hello world\\
1749 Out[9]: "print 'hello world'\\n"
1749 Out[9]: "print 'hello world'\\n"
1750
1750
1751 Now we call it with the output #8 (stored in _8, also as Out[8]):
1751 Now we call it with the output #8 (stored in _8, also as Out[8]):
1752
1752
1753 In [10]: ed _8\\
1753 In [10]: ed _8\\
1754 Editing... done. Executing edited code...\\
1754 Editing... done. Executing edited code...\\
1755 hello again\\
1755 hello again\\
1756 Out[10]: "print 'hello again'\\n"
1756 Out[10]: "print 'hello again'\\n"
1757
1757
1758
1758
1759 Changing the default editor hook:
1759 Changing the default editor hook:
1760
1760
1761 If you wish to write your own editor hook, you can put it in a
1761 If you wish to write your own editor hook, you can put it in a
1762 configuration file which you load at startup time. The default hook
1762 configuration file which you load at startup time. The default hook
1763 is defined in the IPython.hooks module, and you can use that as a
1763 is defined in the IPython.hooks module, and you can use that as a
1764 starting example for further modifications. That file also has
1764 starting example for further modifications. That file also has
1765 general instructions on how to set a new hook for use once you've
1765 general instructions on how to set a new hook for use once you've
1766 defined it."""
1766 defined it."""
1767
1767
1768 # FIXME: This function has become a convoluted mess. It needs a
1768 # FIXME: This function has become a convoluted mess. It needs a
1769 # ground-up rewrite with clean, simple logic.
1769 # ground-up rewrite with clean, simple logic.
1770
1770
1771 def make_filename(arg):
1771 def make_filename(arg):
1772 "Make a filename from the given args"
1772 "Make a filename from the given args"
1773 try:
1773 try:
1774 filename = get_py_filename(arg)
1774 filename = get_py_filename(arg)
1775 except IOError:
1775 except IOError:
1776 if args.endswith('.py'):
1776 if args.endswith('.py'):
1777 filename = arg
1777 filename = arg
1778 else:
1778 else:
1779 filename = None
1779 filename = None
1780 return filename
1780 return filename
1781
1781
1782 # custom exceptions
1782 # custom exceptions
1783 class DataIsObject(Exception): pass
1783 class DataIsObject(Exception): pass
1784
1784
1785 opts,args = self.parse_options(parameter_s,'px')
1785 opts,args = self.parse_options(parameter_s,'px')
1786
1786
1787 # Default line number value
1787 # Default line number value
1788 lineno = None
1788 lineno = None
1789 if opts.has_key('p'):
1789 if opts.has_key('p'):
1790 args = '_%s' % last_call[0]
1790 args = '_%s' % last_call[0]
1791 if not self.shell.user_ns.has_key(args):
1791 if not self.shell.user_ns.has_key(args):
1792 args = last_call[1]
1792 args = last_call[1]
1793
1793
1794 # use last_call to remember the state of the previous call, but don't
1794 # use last_call to remember the state of the previous call, but don't
1795 # let it be clobbered by successive '-p' calls.
1795 # let it be clobbered by successive '-p' calls.
1796 try:
1796 try:
1797 last_call[0] = self.shell.outputcache.prompt_count
1797 last_call[0] = self.shell.outputcache.prompt_count
1798 if not opts.has_key('p'):
1798 if not opts.has_key('p'):
1799 last_call[1] = parameter_s
1799 last_call[1] = parameter_s
1800 except:
1800 except:
1801 pass
1801 pass
1802
1802
1803 # by default this is done with temp files, except when the given
1803 # by default this is done with temp files, except when the given
1804 # arg is a filename
1804 # arg is a filename
1805 use_temp = 1
1805 use_temp = 1
1806
1806
1807 if re.match(r'\d',args):
1807 if re.match(r'\d',args):
1808 # Mode where user specifies ranges of lines, like in %macro.
1808 # Mode where user specifies ranges of lines, like in %macro.
1809 # This means that you can't edit files whose names begin with
1809 # This means that you can't edit files whose names begin with
1810 # numbers this way. Tough.
1810 # numbers this way. Tough.
1811 ranges = args.split()
1811 ranges = args.split()
1812 data = ''.join(self.extract_input_slices(ranges))
1812 data = ''.join(self.extract_input_slices(ranges))
1813 elif args.endswith('.py'):
1813 elif args.endswith('.py'):
1814 filename = make_filename(args)
1814 filename = make_filename(args)
1815 data = ''
1815 data = ''
1816 use_temp = 0
1816 use_temp = 0
1817 elif args:
1817 elif args:
1818 try:
1818 try:
1819 # Load the parameter given as a variable. If not a string,
1819 # Load the parameter given as a variable. If not a string,
1820 # process it as an object instead (below)
1820 # process it as an object instead (below)
1821
1821
1822 #print '*** args',args,'type',type(args) # dbg
1822 #print '*** args',args,'type',type(args) # dbg
1823 data = eval(args,self.shell.user_ns)
1823 data = eval(args,self.shell.user_ns)
1824 if not type(data) in StringTypes:
1824 if not type(data) in StringTypes:
1825 raise DataIsObject
1825 raise DataIsObject
1826 except (NameError,SyntaxError):
1826 except (NameError,SyntaxError):
1827 # given argument is not a variable, try as a filename
1827 # given argument is not a variable, try as a filename
1828 filename = make_filename(args)
1828 filename = make_filename(args)
1829 if filename is None:
1829 if filename is None:
1830 warn("Argument given (%s) can't be found as a variable "
1830 warn("Argument given (%s) can't be found as a variable "
1831 "or as a filename." % args)
1831 "or as a filename." % args)
1832 return
1832 return
1833 data = ''
1833 data = ''
1834 use_temp = 0
1834 use_temp = 0
1835 except DataIsObject:
1835 except DataIsObject:
1836 # For objects, try to edit the file where they are defined
1836 # For objects, try to edit the file where they are defined
1837 try:
1837 try:
1838 filename = inspect.getabsfile(data)
1838 filename = inspect.getabsfile(data)
1839 datafile = 1
1839 datafile = 1
1840 except TypeError:
1840 except TypeError:
1841 filename = make_filename(args)
1841 filename = make_filename(args)
1842 datafile = 1
1842 datafile = 1
1843 warn('Could not find file where `%s` is defined.\n'
1843 warn('Could not find file where `%s` is defined.\n'
1844 'Opening a file named `%s`' % (args,filename))
1844 'Opening a file named `%s`' % (args,filename))
1845 # Now, make sure we can actually read the source (if it was in
1845 # Now, make sure we can actually read the source (if it was in
1846 # a temp file it's gone by now).
1846 # a temp file it's gone by now).
1847 if datafile:
1847 if datafile:
1848 try:
1848 try:
1849 lineno = inspect.getsourcelines(data)[1]
1849 lineno = inspect.getsourcelines(data)[1]
1850 except IOError:
1850 except IOError:
1851 filename = make_filename(args)
1851 filename = make_filename(args)
1852 if filename is None:
1852 if filename is None:
1853 warn('The file `%s` where `%s` was defined cannot '
1853 warn('The file `%s` where `%s` was defined cannot '
1854 'be read.' % (filename,data))
1854 'be read.' % (filename,data))
1855 return
1855 return
1856 use_temp = 0
1856 use_temp = 0
1857 else:
1857 else:
1858 data = ''
1858 data = ''
1859
1859
1860 if use_temp:
1860 if use_temp:
1861 filename = tempfile.mktemp('.py')
1861 filename = tempfile.mktemp('.py')
1862 self.shell.tempfiles.append(filename)
1862 self.shell.tempfiles.append(filename)
1863
1863
1864 if data and use_temp:
1864 if data and use_temp:
1865 tmp_file = open(filename,'w')
1865 tmp_file = open(filename,'w')
1866 tmp_file.write(data)
1866 tmp_file.write(data)
1867 tmp_file.close()
1867 tmp_file.close()
1868
1868
1869 # do actual editing here
1869 # do actual editing here
1870 print 'Editing...',
1870 print 'Editing...',
1871 sys.stdout.flush()
1871 sys.stdout.flush()
1872 self.shell.hooks.editor(filename,lineno)
1872 self.shell.hooks.editor(filename,lineno)
1873 if opts.has_key('x'): # -x prevents actual execution
1873 if opts.has_key('x'): # -x prevents actual execution
1874 print
1874 print
1875 else:
1875 else:
1876 print 'done. Executing edited code...'
1876 print 'done. Executing edited code...'
1877 try:
1877 try:
1878 execfile(filename,self.shell.user_ns)
1878 self.shell.safe_execfile(filename,self.shell.user_ns)
1879 except IOError,msg:
1879 except IOError,msg:
1880 if msg.filename == filename:
1880 if msg.filename == filename:
1881 warn('File not found. Did you forget to save?')
1881 warn('File not found. Did you forget to save?')
1882 return
1882 return
1883 else:
1883 else:
1884 self.shell.showtraceback()
1884 self.shell.showtraceback()
1885 except:
1885 except:
1886 self.shell.showtraceback()
1886 self.shell.showtraceback()
1887 if use_temp:
1887 if use_temp:
1888 contents = open(filename).read()
1888 contents = open(filename).read()
1889 return contents
1889 return contents
1890
1890
1891 def magic_xmode(self,parameter_s = ''):
1891 def magic_xmode(self,parameter_s = ''):
1892 """Switch modes for the exception handlers.
1892 """Switch modes for the exception handlers.
1893
1893
1894 Valid modes: Plain, Context and Verbose.
1894 Valid modes: Plain, Context and Verbose.
1895
1895
1896 If called without arguments, acts as a toggle."""
1896 If called without arguments, acts as a toggle."""
1897
1897
1898 new_mode = parameter_s.strip().capitalize()
1898 new_mode = parameter_s.strip().capitalize()
1899 try:
1899 try:
1900 self.InteractiveTB.set_mode(mode = new_mode)
1900 self.InteractiveTB.set_mode(mode = new_mode)
1901 print 'Exception reporting mode:',self.InteractiveTB.mode
1901 print 'Exception reporting mode:',self.InteractiveTB.mode
1902 except:
1902 except:
1903 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1903 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1904
1904
1905 def magic_colors(self,parameter_s = ''):
1905 def magic_colors(self,parameter_s = ''):
1906 """Switch color scheme for prompts, info system and exception handlers.
1906 """Switch color scheme for prompts, info system and exception handlers.
1907
1907
1908 Currently implemented schemes: NoColor, Linux, LightBG.
1908 Currently implemented schemes: NoColor, Linux, LightBG.
1909
1909
1910 Color scheme names are not case-sensitive."""
1910 Color scheme names are not case-sensitive."""
1911
1911
1912 new_scheme = parameter_s.strip()
1912 new_scheme = parameter_s.strip()
1913 if not new_scheme:
1913 if not new_scheme:
1914 print 'You must specify a color scheme.'
1914 print 'You must specify a color scheme.'
1915 return
1915 return
1916 # Under Windows, check for Gary Bishop's readline, which is necessary
1916 # Under Windows, check for Gary Bishop's readline, which is necessary
1917 # for ANSI coloring
1917 # for ANSI coloring
1918 if os.name in ['nt','dos']:
1918 if os.name in ['nt','dos']:
1919 try:
1919 try:
1920 import readline
1920 import readline
1921 except ImportError:
1921 except ImportError:
1922 has_readline = 0
1922 has_readline = 0
1923 else:
1923 else:
1924 try:
1924 try:
1925 readline.GetOutputFile()
1925 readline.GetOutputFile()
1926 except AttributeError:
1926 except AttributeError:
1927 has_readline = 0
1927 has_readline = 0
1928 else:
1928 else:
1929 has_readline = 1
1929 has_readline = 1
1930 if not has_readline:
1930 if not has_readline:
1931 msg = """\
1931 msg = """\
1932 Proper color support under MS Windows requires Gary Bishop's readline library.
1932 Proper color support under MS Windows requires Gary Bishop's readline library.
1933 You can find it at:
1933 You can find it at:
1934 http://sourceforge.net/projects/uncpythontools
1934 http://sourceforge.net/projects/uncpythontools
1935 Gary's readline needs the ctypes module, from:
1935 Gary's readline needs the ctypes module, from:
1936 http://starship.python.net/crew/theller/ctypes
1936 http://starship.python.net/crew/theller/ctypes
1937
1937
1938 Defaulting color scheme to 'NoColor'"""
1938 Defaulting color scheme to 'NoColor'"""
1939 new_scheme = 'NoColor'
1939 new_scheme = 'NoColor'
1940 warn(msg)
1940 warn(msg)
1941
1941
1942 # Set prompt colors
1942 # Set prompt colors
1943 try:
1943 try:
1944 self.shell.outputcache.set_colors(new_scheme)
1944 self.shell.outputcache.set_colors(new_scheme)
1945 except:
1945 except:
1946 warn('Error changing prompt color schemes.\n'
1946 warn('Error changing prompt color schemes.\n'
1947 + str(sys.exc_info()[1]))
1947 + str(sys.exc_info()[1]))
1948 else:
1948 else:
1949 self.shell.rc.colors = \
1949 self.shell.rc.colors = \
1950 self.shell.outputcache.color_table.active_scheme_name
1950 self.shell.outputcache.color_table.active_scheme_name
1951 # Set exception colors
1951 # Set exception colors
1952 try:
1952 try:
1953 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1953 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1954 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1954 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1955 except:
1955 except:
1956 warn('Error changing exception color schemes.\n'
1956 warn('Error changing exception color schemes.\n'
1957 + str(sys.exc_info()[1]))
1957 + str(sys.exc_info()[1]))
1958 # Set info (for 'object?') colors
1958 # Set info (for 'object?') colors
1959 if self.shell.rc.color_info:
1959 if self.shell.rc.color_info:
1960 try:
1960 try:
1961 self.shell.inspector.set_active_scheme(new_scheme)
1961 self.shell.inspector.set_active_scheme(new_scheme)
1962 except:
1962 except:
1963 warn('Error changing object inspector color schemes.\n'
1963 warn('Error changing object inspector color schemes.\n'
1964 + str(sys.exc_info()[1]))
1964 + str(sys.exc_info()[1]))
1965 else:
1965 else:
1966 self.shell.inspector.set_active_scheme('NoColor')
1966 self.shell.inspector.set_active_scheme('NoColor')
1967
1967
1968 def magic_color_info(self,parameter_s = ''):
1968 def magic_color_info(self,parameter_s = ''):
1969 """Toggle color_info.
1969 """Toggle color_info.
1970
1970
1971 The color_info configuration parameter controls whether colors are
1971 The color_info configuration parameter controls whether colors are
1972 used for displaying object details (by things like %psource, %pfile or
1972 used for displaying object details (by things like %psource, %pfile or
1973 the '?' system). This function toggles this value with each call.
1973 the '?' system). This function toggles this value with each call.
1974
1974
1975 Note that unless you have a fairly recent pager (less works better
1975 Note that unless you have a fairly recent pager (less works better
1976 than more) in your system, using colored object information displays
1976 than more) in your system, using colored object information displays
1977 will not work properly. Test it and see."""
1977 will not work properly. Test it and see."""
1978
1978
1979 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1979 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1980 self.magic_colors(self.shell.rc.colors)
1980 self.magic_colors(self.shell.rc.colors)
1981 print 'Object introspection functions have now coloring:',
1981 print 'Object introspection functions have now coloring:',
1982 print ['OFF','ON'][self.shell.rc.color_info]
1982 print ['OFF','ON'][self.shell.rc.color_info]
1983
1983
1984 def magic_Pprint(self, parameter_s=''):
1984 def magic_Pprint(self, parameter_s=''):
1985 """Toggle pretty printing on/off."""
1985 """Toggle pretty printing on/off."""
1986
1986
1987 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1987 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1988 print 'Pretty printing has been turned', \
1988 print 'Pretty printing has been turned', \
1989 ['OFF','ON'][self.shell.outputcache.Pprint]
1989 ['OFF','ON'][self.shell.outputcache.Pprint]
1990
1990
1991 def magic_Exit(self, parameter_s=''):
1991 def magic_Exit(self, parameter_s=''):
1992 """Exit IPython without confirmation."""
1992 """Exit IPython without confirmation."""
1993
1993
1994 self.shell.exit_now = True
1994 self.shell.exit_now = True
1995
1995
1996 def magic_Quit(self, parameter_s=''):
1996 def magic_Quit(self, parameter_s=''):
1997 """Exit IPython without confirmation (like %Exit)."""
1997 """Exit IPython without confirmation (like %Exit)."""
1998
1998
1999 self.shell.exit_now = True
1999 self.shell.exit_now = True
2000
2000
2001 #......................................................................
2001 #......................................................................
2002 # Functions to implement unix shell-type things
2002 # Functions to implement unix shell-type things
2003
2003
2004 def magic_alias(self, parameter_s = ''):
2004 def magic_alias(self, parameter_s = ''):
2005 """Define an alias for a system command.
2005 """Define an alias for a system command.
2006
2006
2007 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2007 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2008
2008
2009 Then, typing 'alias_name params' will execute the system command 'cmd
2009 Then, typing 'alias_name params' will execute the system command 'cmd
2010 params' (from your underlying operating system).
2010 params' (from your underlying operating system).
2011
2011
2012 Aliases have lower precedence than magic functions and Python normal
2012 Aliases have lower precedence than magic functions and Python normal
2013 variables, so if 'foo' is both a Python variable and an alias, the
2013 variables, so if 'foo' is both a Python variable and an alias, the
2014 alias can not be executed until 'del foo' removes the Python variable.
2014 alias can not be executed until 'del foo' removes the Python variable.
2015
2015
2016 You can use the %l specifier in an alias definition to represent the
2016 You can use the %l specifier in an alias definition to represent the
2017 whole line when the alias is called. For example:
2017 whole line when the alias is called. For example:
2018
2018
2019 In [2]: alias all echo "Input in brackets: <%l>"\\
2019 In [2]: alias all echo "Input in brackets: <%l>"\\
2020 In [3]: all hello world\\
2020 In [3]: all hello world\\
2021 Input in brackets: <hello world>
2021 Input in brackets: <hello world>
2022
2022
2023 You can also define aliases with parameters using %s specifiers (one
2023 You can also define aliases with parameters using %s specifiers (one
2024 per parameter):
2024 per parameter):
2025
2025
2026 In [1]: alias parts echo first %s second %s\\
2026 In [1]: alias parts echo first %s second %s\\
2027 In [2]: %parts A B\\
2027 In [2]: %parts A B\\
2028 first A second B\\
2028 first A second B\\
2029 In [3]: %parts A\\
2029 In [3]: %parts A\\
2030 Incorrect number of arguments: 2 expected.\\
2030 Incorrect number of arguments: 2 expected.\\
2031 parts is an alias to: 'echo first %s second %s'
2031 parts is an alias to: 'echo first %s second %s'
2032
2032
2033 Note that %l and %s are mutually exclusive. You can only use one or
2033 Note that %l and %s are mutually exclusive. You can only use one or
2034 the other in your aliases.
2034 the other in your aliases.
2035
2035
2036 Aliases expand Python variables just like system calls using ! or !!
2036 Aliases expand Python variables just like system calls using ! or !!
2037 do: all expressions prefixed with '$' get expanded. For details of
2037 do: all expressions prefixed with '$' get expanded. For details of
2038 the semantic rules, see PEP-215:
2038 the semantic rules, see PEP-215:
2039 http://www.python.org/peps/pep-0215.html. This is the library used by
2039 http://www.python.org/peps/pep-0215.html. This is the library used by
2040 IPython for variable expansion. If you want to access a true shell
2040 IPython for variable expansion. If you want to access a true shell
2041 variable, an extra $ is necessary to prevent its expansion by IPython:
2041 variable, an extra $ is necessary to prevent its expansion by IPython:
2042
2042
2043 In [6]: alias show echo\\
2043 In [6]: alias show echo\\
2044 In [7]: PATH='A Python string'\\
2044 In [7]: PATH='A Python string'\\
2045 In [8]: show $PATH\\
2045 In [8]: show $PATH\\
2046 A Python string\\
2046 A Python string\\
2047 In [9]: show $$PATH\\
2047 In [9]: show $$PATH\\
2048 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2048 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2049
2049
2050 You can use the alias facility to acess all of $PATH. See the %rehash
2050 You can use the alias facility to acess all of $PATH. See the %rehash
2051 and %rehashx functions, which automatically create aliases for the
2051 and %rehashx functions, which automatically create aliases for the
2052 contents of your $PATH.
2052 contents of your $PATH.
2053
2053
2054 If called with no parameters, %alias prints the current alias table."""
2054 If called with no parameters, %alias prints the current alias table."""
2055
2055
2056 par = parameter_s.strip()
2056 par = parameter_s.strip()
2057 if not par:
2057 if not par:
2058 if self.shell.rc.automagic:
2058 if self.shell.rc.automagic:
2059 prechar = ''
2059 prechar = ''
2060 else:
2060 else:
2061 prechar = self.shell.ESC_MAGIC
2061 prechar = self.shell.ESC_MAGIC
2062 print 'Alias\t\tSystem Command\n'+'-'*30
2062 print 'Alias\t\tSystem Command\n'+'-'*30
2063 atab = self.shell.alias_table
2063 atab = self.shell.alias_table
2064 aliases = atab.keys()
2064 aliases = atab.keys()
2065 aliases.sort()
2065 aliases.sort()
2066 for alias in aliases:
2066 for alias in aliases:
2067 print prechar+alias+'\t\t'+atab[alias][1]
2067 print prechar+alias+'\t\t'+atab[alias][1]
2068 print '-'*30+'\nTotal number of aliases:',len(aliases)
2068 print '-'*30+'\nTotal number of aliases:',len(aliases)
2069 return
2069 return
2070 try:
2070 try:
2071 alias,cmd = par.split(None,1)
2071 alias,cmd = par.split(None,1)
2072 except:
2072 except:
2073 print OInspect.getdoc(self.magic_alias)
2073 print OInspect.getdoc(self.magic_alias)
2074 else:
2074 else:
2075 nargs = cmd.count('%s')
2075 nargs = cmd.count('%s')
2076 if nargs>0 and cmd.find('%l')>=0:
2076 if nargs>0 and cmd.find('%l')>=0:
2077 error('The %s and %l specifiers are mutually exclusive '
2077 error('The %s and %l specifiers are mutually exclusive '
2078 'in alias definitions.')
2078 'in alias definitions.')
2079 else: # all looks OK
2079 else: # all looks OK
2080 self.shell.alias_table[alias] = (nargs,cmd)
2080 self.shell.alias_table[alias] = (nargs,cmd)
2081 self.shell.alias_table_validate(verbose=1)
2081 self.shell.alias_table_validate(verbose=1)
2082 # end magic_alias
2082 # end magic_alias
2083
2083
2084 def magic_unalias(self, parameter_s = ''):
2084 def magic_unalias(self, parameter_s = ''):
2085 """Remove an alias"""
2085 """Remove an alias"""
2086
2086
2087 aname = parameter_s.strip()
2087 aname = parameter_s.strip()
2088 if aname in self.shell.alias_table:
2088 if aname in self.shell.alias_table:
2089 del self.shell.alias_table[aname]
2089 del self.shell.alias_table[aname]
2090
2090
2091 def magic_rehash(self, parameter_s = ''):
2091 def magic_rehash(self, parameter_s = ''):
2092 """Update the alias table with all entries in $PATH.
2092 """Update the alias table with all entries in $PATH.
2093
2093
2094 This version does no checks on execute permissions or whether the
2094 This version does no checks on execute permissions or whether the
2095 contents of $PATH are truly files (instead of directories or something
2095 contents of $PATH are truly files (instead of directories or something
2096 else). For such a safer (but slower) version, use %rehashx."""
2096 else). For such a safer (but slower) version, use %rehashx."""
2097
2097
2098 # This function (and rehashx) manipulate the alias_table directly
2098 # This function (and rehashx) manipulate the alias_table directly
2099 # rather than calling magic_alias, for speed reasons. A rehash on a
2099 # rather than calling magic_alias, for speed reasons. A rehash on a
2100 # typical Linux box involves several thousand entries, so efficiency
2100 # typical Linux box involves several thousand entries, so efficiency
2101 # here is a top concern.
2101 # here is a top concern.
2102
2102
2103 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2103 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2104 alias_table = self.shell.alias_table
2104 alias_table = self.shell.alias_table
2105 for pdir in path:
2105 for pdir in path:
2106 for ff in os.listdir(pdir):
2106 for ff in os.listdir(pdir):
2107 # each entry in the alias table must be (N,name), where
2107 # each entry in the alias table must be (N,name), where
2108 # N is the number of positional arguments of the alias.
2108 # N is the number of positional arguments of the alias.
2109 alias_table[ff] = (0,ff)
2109 alias_table[ff] = (0,ff)
2110 # Make sure the alias table doesn't contain keywords or builtins
2110 # Make sure the alias table doesn't contain keywords or builtins
2111 self.shell.alias_table_validate()
2111 self.shell.alias_table_validate()
2112 # Call again init_auto_alias() so we get 'rm -i' and other modified
2112 # Call again init_auto_alias() so we get 'rm -i' and other modified
2113 # aliases since %rehash will probably clobber them
2113 # aliases since %rehash will probably clobber them
2114 self.shell.init_auto_alias()
2114 self.shell.init_auto_alias()
2115
2115
2116 def magic_rehashx(self, parameter_s = ''):
2116 def magic_rehashx(self, parameter_s = ''):
2117 """Update the alias table with all executable files in $PATH.
2117 """Update the alias table with all executable files in $PATH.
2118
2118
2119 This version explicitly checks that every entry in $PATH is a file
2119 This version explicitly checks that every entry in $PATH is a file
2120 with execute access (os.X_OK), so it is much slower than %rehash.
2120 with execute access (os.X_OK), so it is much slower than %rehash.
2121
2121
2122 Under Windows, it checks executability as a match agains a
2122 Under Windows, it checks executability as a match agains a
2123 '|'-separated string of extensions, stored in the IPython config
2123 '|'-separated string of extensions, stored in the IPython config
2124 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2124 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2125
2125
2126 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2126 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2127 alias_table = self.shell.alias_table
2127 alias_table = self.shell.alias_table
2128
2128
2129 if os.name == 'posix':
2129 if os.name == 'posix':
2130 isexec = lambda fname:os.path.isfile(fname) and \
2130 isexec = lambda fname:os.path.isfile(fname) and \
2131 os.access(fname,os.X_OK)
2131 os.access(fname,os.X_OK)
2132 else:
2132 else:
2133
2133
2134 try:
2134 try:
2135 winext = os.environ['pathext'].replace(';','|').replace('.','')
2135 winext = os.environ['pathext'].replace(';','|').replace('.','')
2136 except KeyError:
2136 except KeyError:
2137 winext = 'exe|com|bat'
2137 winext = 'exe|com|bat'
2138
2138
2139 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2139 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2140 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2140 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2141 savedir = os.getcwd()
2141 savedir = os.getcwd()
2142 try:
2142 try:
2143 # write the whole loop for posix/Windows so we don't have an if in
2143 # write the whole loop for posix/Windows so we don't have an if in
2144 # the innermost part
2144 # the innermost part
2145 if os.name == 'posix':
2145 if os.name == 'posix':
2146 for pdir in path:
2146 for pdir in path:
2147 os.chdir(pdir)
2147 os.chdir(pdir)
2148 for ff in os.listdir(pdir):
2148 for ff in os.listdir(pdir):
2149 if isexec(ff):
2149 if isexec(ff):
2150 # each entry in the alias table must be (N,name),
2150 # each entry in the alias table must be (N,name),
2151 # where N is the number of positional arguments of the
2151 # where N is the number of positional arguments of the
2152 # alias.
2152 # alias.
2153 alias_table[ff] = (0,ff)
2153 alias_table[ff] = (0,ff)
2154 else:
2154 else:
2155 for pdir in path:
2155 for pdir in path:
2156 os.chdir(pdir)
2156 os.chdir(pdir)
2157 for ff in os.listdir(pdir):
2157 for ff in os.listdir(pdir):
2158 if isexec(ff):
2158 if isexec(ff):
2159 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2159 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2160 # Make sure the alias table doesn't contain keywords or builtins
2160 # Make sure the alias table doesn't contain keywords or builtins
2161 self.shell.alias_table_validate()
2161 self.shell.alias_table_validate()
2162 # Call again init_auto_alias() so we get 'rm -i' and other
2162 # Call again init_auto_alias() so we get 'rm -i' and other
2163 # modified aliases since %rehashx will probably clobber them
2163 # modified aliases since %rehashx will probably clobber them
2164 self.shell.init_auto_alias()
2164 self.shell.init_auto_alias()
2165 finally:
2165 finally:
2166 os.chdir(savedir)
2166 os.chdir(savedir)
2167
2167
2168 def magic_pwd(self, parameter_s = ''):
2168 def magic_pwd(self, parameter_s = ''):
2169 """Return the current working directory path."""
2169 """Return the current working directory path."""
2170 return os.getcwd()
2170 return os.getcwd()
2171
2171
2172 def magic_cd(self, parameter_s=''):
2172 def magic_cd(self, parameter_s=''):
2173 """Change the current working directory.
2173 """Change the current working directory.
2174
2174
2175 This command automatically maintains an internal list of directories
2175 This command automatically maintains an internal list of directories
2176 you visit during your IPython session, in the variable _dh. The
2176 you visit during your IPython session, in the variable _dh. The
2177 command %dhist shows this history nicely formatted.
2177 command %dhist shows this history nicely formatted.
2178
2178
2179 Usage:
2179 Usage:
2180
2180
2181 cd 'dir': changes to directory 'dir'.
2181 cd 'dir': changes to directory 'dir'.
2182
2182
2183 cd -: changes to the last visited directory.
2183 cd -: changes to the last visited directory.
2184
2184
2185 cd -<n>: changes to the n-th directory in the directory history.
2185 cd -<n>: changes to the n-th directory in the directory history.
2186
2186
2187 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2187 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2188 (note: cd <bookmark_name> is enough if there is no
2188 (note: cd <bookmark_name> is enough if there is no
2189 directory <bookmark_name>, but a bookmark with the name exists.)
2189 directory <bookmark_name>, but a bookmark with the name exists.)
2190
2190
2191 Options:
2191 Options:
2192
2192
2193 -q: quiet. Do not print the working directory after the cd command is
2193 -q: quiet. Do not print the working directory after the cd command is
2194 executed. By default IPython's cd command does print this directory,
2194 executed. By default IPython's cd command does print this directory,
2195 since the default prompts do not display path information.
2195 since the default prompts do not display path information.
2196
2196
2197 Note that !cd doesn't work for this purpose because the shell where
2197 Note that !cd doesn't work for this purpose because the shell where
2198 !command runs is immediately discarded after executing 'command'."""
2198 !command runs is immediately discarded after executing 'command'."""
2199
2199
2200 parameter_s = parameter_s.strip()
2200 parameter_s = parameter_s.strip()
2201 bkms = self.shell.persist.get("bookmarks",{})
2201 bkms = self.shell.persist.get("bookmarks",{})
2202
2202
2203 numcd = re.match(r'(-)(\d+)$',parameter_s)
2203 numcd = re.match(r'(-)(\d+)$',parameter_s)
2204 # jump in directory history by number
2204 # jump in directory history by number
2205 if numcd:
2205 if numcd:
2206 nn = int(numcd.group(2))
2206 nn = int(numcd.group(2))
2207 try:
2207 try:
2208 ps = self.shell.user_ns['_dh'][nn]
2208 ps = self.shell.user_ns['_dh'][nn]
2209 except IndexError:
2209 except IndexError:
2210 print 'The requested directory does not exist in history.'
2210 print 'The requested directory does not exist in history.'
2211 return
2211 return
2212 else:
2212 else:
2213 opts = {}
2213 opts = {}
2214 else:
2214 else:
2215 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2215 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2216 # jump to previous
2216 # jump to previous
2217 if ps == '-':
2217 if ps == '-':
2218 try:
2218 try:
2219 ps = self.shell.user_ns['_dh'][-2]
2219 ps = self.shell.user_ns['_dh'][-2]
2220 except IndexError:
2220 except IndexError:
2221 print 'No previous directory to change to.'
2221 print 'No previous directory to change to.'
2222 return
2222 return
2223 # jump to bookmark
2223 # jump to bookmark
2224 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2224 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2225 if bkms.has_key(ps):
2225 if bkms.has_key(ps):
2226 target = bkms[ps]
2226 target = bkms[ps]
2227 print '(bookmark:%s) -> %s' % (ps,target)
2227 print '(bookmark:%s) -> %s' % (ps,target)
2228 ps = target
2228 ps = target
2229 else:
2229 else:
2230 if bkms:
2230 if bkms:
2231 error("Bookmark '%s' not found. "
2231 error("Bookmark '%s' not found. "
2232 "Use '%bookmark -l' to see your bookmarks." % ps)
2232 "Use '%bookmark -l' to see your bookmarks." % ps)
2233 else:
2233 else:
2234 print "Bookmarks not set - use %bookmark <bookmarkname>"
2234 print "Bookmarks not set - use %bookmark <bookmarkname>"
2235 return
2235 return
2236
2236
2237 # at this point ps should point to the target dir
2237 # at this point ps should point to the target dir
2238 if ps:
2238 if ps:
2239 try:
2239 try:
2240 os.chdir(os.path.expanduser(ps))
2240 os.chdir(os.path.expanduser(ps))
2241 except OSError:
2241 except OSError:
2242 print sys.exc_info()[1]
2242 print sys.exc_info()[1]
2243 else:
2243 else:
2244 self.shell.user_ns['_dh'].append(os.getcwd())
2244 self.shell.user_ns['_dh'].append(os.getcwd())
2245 else:
2245 else:
2246 os.chdir(self.home_dir)
2246 os.chdir(self.home_dir)
2247 self.shell.user_ns['_dh'].append(os.getcwd())
2247 self.shell.user_ns['_dh'].append(os.getcwd())
2248 if not 'q' in opts:
2248 if not 'q' in opts:
2249 print self.shell.user_ns['_dh'][-1]
2249 print self.shell.user_ns['_dh'][-1]
2250
2250
2251 def magic_dhist(self, parameter_s=''):
2251 def magic_dhist(self, parameter_s=''):
2252 """Print your history of visited directories.
2252 """Print your history of visited directories.
2253
2253
2254 %dhist -> print full history\\
2254 %dhist -> print full history\\
2255 %dhist n -> print last n entries only\\
2255 %dhist n -> print last n entries only\\
2256 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2256 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2257
2257
2258 This history is automatically maintained by the %cd command, and
2258 This history is automatically maintained by the %cd command, and
2259 always available as the global list variable _dh. You can use %cd -<n>
2259 always available as the global list variable _dh. You can use %cd -<n>
2260 to go to directory number <n>."""
2260 to go to directory number <n>."""
2261
2261
2262 dh = self.shell.user_ns['_dh']
2262 dh = self.shell.user_ns['_dh']
2263 if parameter_s:
2263 if parameter_s:
2264 try:
2264 try:
2265 args = map(int,parameter_s.split())
2265 args = map(int,parameter_s.split())
2266 except:
2266 except:
2267 self.arg_err(Magic.magic_dhist)
2267 self.arg_err(Magic.magic_dhist)
2268 return
2268 return
2269 if len(args) == 1:
2269 if len(args) == 1:
2270 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2270 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2271 elif len(args) == 2:
2271 elif len(args) == 2:
2272 ini,fin = args
2272 ini,fin = args
2273 else:
2273 else:
2274 self.arg_err(Magic.magic_dhist)
2274 self.arg_err(Magic.magic_dhist)
2275 return
2275 return
2276 else:
2276 else:
2277 ini,fin = 0,len(dh)
2277 ini,fin = 0,len(dh)
2278 nlprint(dh,
2278 nlprint(dh,
2279 header = 'Directory history (kept in _dh)',
2279 header = 'Directory history (kept in _dh)',
2280 start=ini,stop=fin)
2280 start=ini,stop=fin)
2281
2281
2282 def magic_env(self, parameter_s=''):
2282 def magic_env(self, parameter_s=''):
2283 """List environment variables."""
2283 """List environment variables."""
2284
2284
2285 # environ is an instance of UserDict
2285 # environ is an instance of UserDict
2286 return os.environ.data
2286 return os.environ.data
2287
2287
2288 def magic_pushd(self, parameter_s=''):
2288 def magic_pushd(self, parameter_s=''):
2289 """Place the current dir on stack and change directory.
2289 """Place the current dir on stack and change directory.
2290
2290
2291 Usage:\\
2291 Usage:\\
2292 %pushd ['dirname']
2292 %pushd ['dirname']
2293
2293
2294 %pushd with no arguments does a %pushd to your home directory.
2294 %pushd with no arguments does a %pushd to your home directory.
2295 """
2295 """
2296 if parameter_s == '': parameter_s = '~'
2296 if parameter_s == '': parameter_s = '~'
2297 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2297 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2298 os.path.expanduser(self.dir_stack[0]):
2298 os.path.expanduser(self.dir_stack[0]):
2299 try:
2299 try:
2300 self.magic_cd(parameter_s)
2300 self.magic_cd(parameter_s)
2301 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2301 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2302 self.magic_dirs()
2302 self.magic_dirs()
2303 except:
2303 except:
2304 print 'Invalid directory'
2304 print 'Invalid directory'
2305 else:
2305 else:
2306 print 'You are already there!'
2306 print 'You are already there!'
2307
2307
2308 def magic_popd(self, parameter_s=''):
2308 def magic_popd(self, parameter_s=''):
2309 """Change to directory popped off the top of the stack.
2309 """Change to directory popped off the top of the stack.
2310 """
2310 """
2311 if len (self.dir_stack) > 1:
2311 if len (self.dir_stack) > 1:
2312 self.dir_stack.pop(0)
2312 self.dir_stack.pop(0)
2313 self.magic_cd(self.dir_stack[0])
2313 self.magic_cd(self.dir_stack[0])
2314 print self.dir_stack[0]
2314 print self.dir_stack[0]
2315 else:
2315 else:
2316 print "You can't remove the starting directory from the stack:",\
2316 print "You can't remove the starting directory from the stack:",\
2317 self.dir_stack
2317 self.dir_stack
2318
2318
2319 def magic_dirs(self, parameter_s=''):
2319 def magic_dirs(self, parameter_s=''):
2320 """Return the current directory stack."""
2320 """Return the current directory stack."""
2321
2321
2322 return self.dir_stack[:]
2322 return self.dir_stack[:]
2323
2323
2324 def magic_sc(self, parameter_s=''):
2324 def magic_sc(self, parameter_s=''):
2325 """Shell capture - execute a shell command and capture its output.
2325 """Shell capture - execute a shell command and capture its output.
2326
2326
2327 %sc [options] varname=command
2327 %sc [options] varname=command
2328
2328
2329 IPython will run the given command using commands.getoutput(), and
2329 IPython will run the given command using commands.getoutput(), and
2330 will then update the user's interactive namespace with a variable
2330 will then update the user's interactive namespace with a variable
2331 called varname, containing the value of the call. Your command can
2331 called varname, containing the value of the call. Your command can
2332 contain shell wildcards, pipes, etc.
2332 contain shell wildcards, pipes, etc.
2333
2333
2334 The '=' sign in the syntax is mandatory, and the variable name you
2334 The '=' sign in the syntax is mandatory, and the variable name you
2335 supply must follow Python's standard conventions for valid names.
2335 supply must follow Python's standard conventions for valid names.
2336
2336
2337 Options:
2337 Options:
2338
2338
2339 -l: list output. Split the output on newlines into a list before
2339 -l: list output. Split the output on newlines into a list before
2340 assigning it to the given variable. By default the output is stored
2340 assigning it to the given variable. By default the output is stored
2341 as a single string.
2341 as a single string.
2342
2342
2343 -v: verbose. Print the contents of the variable.
2343 -v: verbose. Print the contents of the variable.
2344
2344
2345 In most cases you should not need to split as a list, because the
2345 In most cases you should not need to split as a list, because the
2346 returned value is a special type of string which can automatically
2346 returned value is a special type of string which can automatically
2347 provide its contents either as a list (split on newlines) or as a
2347 provide its contents either as a list (split on newlines) or as a
2348 space-separated string. These are convenient, respectively, either
2348 space-separated string. These are convenient, respectively, either
2349 for sequential processing or to be passed to a shell command.
2349 for sequential processing or to be passed to a shell command.
2350
2350
2351 For example:
2351 For example:
2352
2352
2353 # Capture into variable a
2353 # Capture into variable a
2354 In [9]: sc a=ls *py
2354 In [9]: sc a=ls *py
2355
2355
2356 # a is a string with embedded newlines
2356 # a is a string with embedded newlines
2357 In [10]: a
2357 In [10]: a
2358 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2358 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2359
2359
2360 # which can be seen as a list:
2360 # which can be seen as a list:
2361 In [11]: a.l
2361 In [11]: a.l
2362 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2362 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2363
2363
2364 # or as a whitespace-separated string:
2364 # or as a whitespace-separated string:
2365 In [12]: a.s
2365 In [12]: a.s
2366 Out[12]: 'setup.py win32_manual_post_install.py'
2366 Out[12]: 'setup.py win32_manual_post_install.py'
2367
2367
2368 # a.s is useful to pass as a single command line:
2368 # a.s is useful to pass as a single command line:
2369 In [13]: !wc -l $a.s
2369 In [13]: !wc -l $a.s
2370 146 setup.py
2370 146 setup.py
2371 130 win32_manual_post_install.py
2371 130 win32_manual_post_install.py
2372 276 total
2372 276 total
2373
2373
2374 # while the list form is useful to loop over:
2374 # while the list form is useful to loop over:
2375 In [14]: for f in a.l:
2375 In [14]: for f in a.l:
2376 ....: !wc -l $f
2376 ....: !wc -l $f
2377 ....:
2377 ....:
2378 146 setup.py
2378 146 setup.py
2379 130 win32_manual_post_install.py
2379 130 win32_manual_post_install.py
2380
2380
2381 Similiarly, the lists returned by the -l option are also special, in
2381 Similiarly, the lists returned by the -l option are also special, in
2382 the sense that you can equally invoke the .s attribute on them to
2382 the sense that you can equally invoke the .s attribute on them to
2383 automatically get a whitespace-separated string from their contents:
2383 automatically get a whitespace-separated string from their contents:
2384
2384
2385 In [1]: sc -l b=ls *py
2385 In [1]: sc -l b=ls *py
2386
2386
2387 In [2]: b
2387 In [2]: b
2388 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2388 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2389
2389
2390 In [3]: b.s
2390 In [3]: b.s
2391 Out[3]: 'setup.py win32_manual_post_install.py'
2391 Out[3]: 'setup.py win32_manual_post_install.py'
2392
2392
2393 In summary, both the lists and strings used for ouptut capture have
2393 In summary, both the lists and strings used for ouptut capture have
2394 the following special attributes:
2394 the following special attributes:
2395
2395
2396 .l (or .list) : value as list.
2396 .l (or .list) : value as list.
2397 .n (or .nlstr): value as newline-separated string.
2397 .n (or .nlstr): value as newline-separated string.
2398 .s (or .spstr): value as space-separated string.
2398 .s (or .spstr): value as space-separated string.
2399 """
2399 """
2400
2400
2401 opts,args = self.parse_options(parameter_s,'lv')
2401 opts,args = self.parse_options(parameter_s,'lv')
2402 # Try to get a variable name and command to run
2402 # Try to get a variable name and command to run
2403 try:
2403 try:
2404 # the variable name must be obtained from the parse_options
2404 # the variable name must be obtained from the parse_options
2405 # output, which uses shlex.split to strip options out.
2405 # output, which uses shlex.split to strip options out.
2406 var,_ = args.split('=',1)
2406 var,_ = args.split('=',1)
2407 var = var.strip()
2407 var = var.strip()
2408 # But the the command has to be extracted from the original input
2408 # But the the command has to be extracted from the original input
2409 # parameter_s, not on what parse_options returns, to avoid the
2409 # parameter_s, not on what parse_options returns, to avoid the
2410 # quote stripping which shlex.split performs on it.
2410 # quote stripping which shlex.split performs on it.
2411 _,cmd = parameter_s.split('=',1)
2411 _,cmd = parameter_s.split('=',1)
2412 except ValueError:
2412 except ValueError:
2413 var,cmd = '',''
2413 var,cmd = '',''
2414 if not var:
2414 if not var:
2415 error('you must specify a variable to assign the command to.')
2415 error('you must specify a variable to assign the command to.')
2416 return
2416 return
2417 # If all looks ok, proceed
2417 # If all looks ok, proceed
2418 out,err = self.shell.getoutputerror(cmd)
2418 out,err = self.shell.getoutputerror(cmd)
2419 if err:
2419 if err:
2420 print >> Term.cerr,err
2420 print >> Term.cerr,err
2421 if opts.has_key('l'):
2421 if opts.has_key('l'):
2422 out = SList(out.split('\n'))
2422 out = SList(out.split('\n'))
2423 else:
2423 else:
2424 out = LSString(out)
2424 out = LSString(out)
2425 if opts.has_key('v'):
2425 if opts.has_key('v'):
2426 print '%s ==\n%s' % (var,pformat(out))
2426 print '%s ==\n%s' % (var,pformat(out))
2427 self.shell.user_ns.update({var:out})
2427 self.shell.user_ns.update({var:out})
2428
2428
2429 def magic_sx(self, parameter_s=''):
2429 def magic_sx(self, parameter_s=''):
2430 """Shell execute - run a shell command and capture its output.
2430 """Shell execute - run a shell command and capture its output.
2431
2431
2432 %sx command
2432 %sx command
2433
2433
2434 IPython will run the given command using commands.getoutput(), and
2434 IPython will run the given command using commands.getoutput(), and
2435 return the result formatted as a list (split on '\\n'). Since the
2435 return the result formatted as a list (split on '\\n'). Since the
2436 output is _returned_, it will be stored in ipython's regular output
2436 output is _returned_, it will be stored in ipython's regular output
2437 cache Out[N] and in the '_N' automatic variables.
2437 cache Out[N] and in the '_N' automatic variables.
2438
2438
2439 Notes:
2439 Notes:
2440
2440
2441 1) If an input line begins with '!!', then %sx is automatically
2441 1) If an input line begins with '!!', then %sx is automatically
2442 invoked. That is, while:
2442 invoked. That is, while:
2443 !ls
2443 !ls
2444 causes ipython to simply issue system('ls'), typing
2444 causes ipython to simply issue system('ls'), typing
2445 !!ls
2445 !!ls
2446 is a shorthand equivalent to:
2446 is a shorthand equivalent to:
2447 %sx ls
2447 %sx ls
2448
2448
2449 2) %sx differs from %sc in that %sx automatically splits into a list,
2449 2) %sx differs from %sc in that %sx automatically splits into a list,
2450 like '%sc -l'. The reason for this is to make it as easy as possible
2450 like '%sc -l'. The reason for this is to make it as easy as possible
2451 to process line-oriented shell output via further python commands.
2451 to process line-oriented shell output via further python commands.
2452 %sc is meant to provide much finer control, but requires more
2452 %sc is meant to provide much finer control, but requires more
2453 typing.
2453 typing.
2454
2454
2455 3) Just like %sc -l, this is a list with special attributes:
2455 3) Just like %sc -l, this is a list with special attributes:
2456
2456
2457 .l (or .list) : value as list.
2457 .l (or .list) : value as list.
2458 .n (or .nlstr): value as newline-separated string.
2458 .n (or .nlstr): value as newline-separated string.
2459 .s (or .spstr): value as whitespace-separated string.
2459 .s (or .spstr): value as whitespace-separated string.
2460
2460
2461 This is very useful when trying to use such lists as arguments to
2461 This is very useful when trying to use such lists as arguments to
2462 system commands."""
2462 system commands."""
2463
2463
2464 if parameter_s:
2464 if parameter_s:
2465 out,err = self.shell.getoutputerror(parameter_s)
2465 out,err = self.shell.getoutputerror(parameter_s)
2466 if err:
2466 if err:
2467 print >> Term.cerr,err
2467 print >> Term.cerr,err
2468 return SList(out.split('\n'))
2468 return SList(out.split('\n'))
2469
2469
2470 def magic_bg(self, parameter_s=''):
2470 def magic_bg(self, parameter_s=''):
2471 """Run a job in the background, in a separate thread.
2471 """Run a job in the background, in a separate thread.
2472
2472
2473 For example,
2473 For example,
2474
2474
2475 %bg myfunc(x,y,z=1)
2475 %bg myfunc(x,y,z=1)
2476
2476
2477 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2477 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2478 execution starts, a message will be printed indicating the job
2478 execution starts, a message will be printed indicating the job
2479 number. If your job number is 5, you can use
2479 number. If your job number is 5, you can use
2480
2480
2481 myvar = jobs.result(5) or myvar = jobs[5].result
2481 myvar = jobs.result(5) or myvar = jobs[5].result
2482
2482
2483 to assign this result to variable 'myvar'.
2483 to assign this result to variable 'myvar'.
2484
2484
2485 IPython has a job manager, accessible via the 'jobs' object. You can
2485 IPython has a job manager, accessible via the 'jobs' object. You can
2486 type jobs? to get more information about it, and use jobs.<TAB> to see
2486 type jobs? to get more information about it, and use jobs.<TAB> to see
2487 its attributes. All attributes not starting with an underscore are
2487 its attributes. All attributes not starting with an underscore are
2488 meant for public use.
2488 meant for public use.
2489
2489
2490 In particular, look at the jobs.new() method, which is used to create
2490 In particular, look at the jobs.new() method, which is used to create
2491 new jobs. This magic %bg function is just a convenience wrapper
2491 new jobs. This magic %bg function is just a convenience wrapper
2492 around jobs.new(), for expression-based jobs. If you want to create a
2492 around jobs.new(), for expression-based jobs. If you want to create a
2493 new job with an explicit function object and arguments, you must call
2493 new job with an explicit function object and arguments, you must call
2494 jobs.new() directly.
2494 jobs.new() directly.
2495
2495
2496 The jobs.new docstring also describes in detail several important
2496 The jobs.new docstring also describes in detail several important
2497 caveats associated with a thread-based model for background job
2497 caveats associated with a thread-based model for background job
2498 execution. Type jobs.new? for details.
2498 execution. Type jobs.new? for details.
2499
2499
2500 You can check the status of all jobs with jobs.status().
2500 You can check the status of all jobs with jobs.status().
2501
2501
2502 The jobs variable is set by IPython into the Python builtin namespace.
2502 The jobs variable is set by IPython into the Python builtin namespace.
2503 If you ever declare a variable named 'jobs', you will shadow this
2503 If you ever declare a variable named 'jobs', you will shadow this
2504 name. You can either delete your global jobs variable to regain
2504 name. You can either delete your global jobs variable to regain
2505 access to the job manager, or make a new name and assign it manually
2505 access to the job manager, or make a new name and assign it manually
2506 to the manager (stored in IPython's namespace). For example, to
2506 to the manager (stored in IPython's namespace). For example, to
2507 assign the job manager to the Jobs name, use:
2507 assign the job manager to the Jobs name, use:
2508
2508
2509 Jobs = __builtins__.jobs"""
2509 Jobs = __builtins__.jobs"""
2510
2510
2511 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2511 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2512
2512
2513 def magic_bookmark(self, parameter_s=''):
2513 def magic_bookmark(self, parameter_s=''):
2514 """Manage IPython's bookmark system.
2514 """Manage IPython's bookmark system.
2515
2515
2516 %bookmark <name> - set bookmark to current dir
2516 %bookmark <name> - set bookmark to current dir
2517 %bookmark <name> <dir> - set bookmark to <dir>
2517 %bookmark <name> <dir> - set bookmark to <dir>
2518 %bookmark -l - list all bookmarks
2518 %bookmark -l - list all bookmarks
2519 %bookmark -d <name> - remove bookmark
2519 %bookmark -d <name> - remove bookmark
2520 %bookmark -r - remove all bookmarks
2520 %bookmark -r - remove all bookmarks
2521
2521
2522 You can later on access a bookmarked folder with:
2522 You can later on access a bookmarked folder with:
2523 %cd -b <name>
2523 %cd -b <name>
2524 or simply '%cd <name>' if there is no directory called <name> AND
2524 or simply '%cd <name>' if there is no directory called <name> AND
2525 there is such a bookmark defined.
2525 there is such a bookmark defined.
2526
2526
2527 Your bookmarks persist through IPython sessions, but they are
2527 Your bookmarks persist through IPython sessions, but they are
2528 associated with each profile."""
2528 associated with each profile."""
2529
2529
2530 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2530 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2531 if len(args) > 2:
2531 if len(args) > 2:
2532 error('You can only give at most two arguments')
2532 error('You can only give at most two arguments')
2533 return
2533 return
2534
2534
2535 bkms = self.shell.persist.get('bookmarks',{})
2535 bkms = self.shell.persist.get('bookmarks',{})
2536
2536
2537 if opts.has_key('d'):
2537 if opts.has_key('d'):
2538 try:
2538 try:
2539 todel = args[0]
2539 todel = args[0]
2540 except IndexError:
2540 except IndexError:
2541 error('You must provide a bookmark to delete')
2541 error('You must provide a bookmark to delete')
2542 else:
2542 else:
2543 try:
2543 try:
2544 del bkms[todel]
2544 del bkms[todel]
2545 except:
2545 except:
2546 error("Can't delete bookmark '%s'" % todel)
2546 error("Can't delete bookmark '%s'" % todel)
2547 elif opts.has_key('r'):
2547 elif opts.has_key('r'):
2548 bkms = {}
2548 bkms = {}
2549 elif opts.has_key('l'):
2549 elif opts.has_key('l'):
2550 bks = bkms.keys()
2550 bks = bkms.keys()
2551 bks.sort()
2551 bks.sort()
2552 if bks:
2552 if bks:
2553 size = max(map(len,bks))
2553 size = max(map(len,bks))
2554 else:
2554 else:
2555 size = 0
2555 size = 0
2556 fmt = '%-'+str(size)+'s -> %s'
2556 fmt = '%-'+str(size)+'s -> %s'
2557 print 'Current bookmarks:'
2557 print 'Current bookmarks:'
2558 for bk in bks:
2558 for bk in bks:
2559 print fmt % (bk,bkms[bk])
2559 print fmt % (bk,bkms[bk])
2560 else:
2560 else:
2561 if not args:
2561 if not args:
2562 error("You must specify the bookmark name")
2562 error("You must specify the bookmark name")
2563 elif len(args)==1:
2563 elif len(args)==1:
2564 bkms[args[0]] = os.getcwd()
2564 bkms[args[0]] = os.getcwd()
2565 elif len(args)==2:
2565 elif len(args)==2:
2566 bkms[args[0]] = args[1]
2566 bkms[args[0]] = args[1]
2567 self.persist['bookmarks'] = bkms
2567 self.persist['bookmarks'] = bkms
2568
2568
2569 def magic_pycat(self, parameter_s=''):
2569 def magic_pycat(self, parameter_s=''):
2570 """Show a syntax-highlighted file through a pager.
2570 """Show a syntax-highlighted file through a pager.
2571
2571
2572 This magic is similar to the cat utility, but it will assume the file
2572 This magic is similar to the cat utility, but it will assume the file
2573 to be Python source and will show it with syntax highlighting. """
2573 to be Python source and will show it with syntax highlighting. """
2574
2574
2575 filename = get_py_filename(parameter_s)
2575 filename = get_py_filename(parameter_s)
2576 page(self.shell.colorize(file_read(filename)),
2576 page(self.shell.colorize(file_read(filename)),
2577 screen_lines=self.shell.rc.screen_length)
2577 screen_lines=self.shell.rc.screen_length)
2578
2578
2579 # end Magic
2579 # end Magic
@@ -1,576 +1,578 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Classes for handling input/output prompts.
3 Classes for handling input/output prompts.
4
4
5 $Id: Prompts.py 958 2005-12-27 23:17:51Z fperez $"""
5 $Id: Prompts.py 960 2005-12-28 06:51:01Z fperez $"""
6
6
7 #*****************************************************************************
7 #*****************************************************************************
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 from IPython import Release
14 from IPython import Release
15 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 __license__ = Release.license
16 __license__ = Release.license
17 __version__ = Release.version
17 __version__ = Release.version
18
18
19 #****************************************************************************
19 #****************************************************************************
20 # Required modules
20 # Required modules
21 import __builtin__
21 import __builtin__
22 import os
22 import os
23 import socket
23 import socket
24 import sys
24 import sys
25 import time
25 import time
26 from pprint import pprint,pformat
26 from pprint import pprint,pformat
27
27
28 # IPython's own
28 # IPython's own
29 from IPython.genutils import *
29 from IPython.genutils import *
30 from IPython.Struct import Struct
30 from IPython.Struct import Struct
31 from IPython.Magic import Macro
31 from IPython.Magic import Macro
32 from IPython.Itpl import ItplNS
32 from IPython.Itpl import ItplNS
33 from IPython import ColorANSI
33 from IPython import ColorANSI
34
34
35 #****************************************************************************
35 #****************************************************************************
36 #Color schemes for Prompts.
36 #Color schemes for Prompts.
37
37
38 PromptColors = ColorANSI.ColorSchemeTable()
38 PromptColors = ColorANSI.ColorSchemeTable()
39 InputColors = ColorANSI.InputTermColors # just a shorthand
39 InputColors = ColorANSI.InputTermColors # just a shorthand
40 Colors = ColorANSI.TermColors # just a shorthand
40 Colors = ColorANSI.TermColors # just a shorthand
41
41
42 PromptColors.add_scheme(ColorANSI.ColorScheme(
42 PromptColors.add_scheme(ColorANSI.ColorScheme(
43 'NoColor',
43 'NoColor',
44 in_prompt = InputColors.NoColor, # Input prompt
44 in_prompt = InputColors.NoColor, # Input prompt
45 in_number = InputColors.NoColor, # Input prompt number
45 in_number = InputColors.NoColor, # Input prompt number
46 in_prompt2 = InputColors.NoColor, # Continuation prompt
46 in_prompt2 = InputColors.NoColor, # Continuation prompt
47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
48
48
49 out_prompt = Colors.NoColor, # Output prompt
49 out_prompt = Colors.NoColor, # Output prompt
50 out_number = Colors.NoColor, # Output prompt number
50 out_number = Colors.NoColor, # Output prompt number
51
51
52 normal = Colors.NoColor # color off (usu. Colors.Normal)
52 normal = Colors.NoColor # color off (usu. Colors.Normal)
53 ))
53 ))
54
54
55 # make some schemes as instances so we can copy them for modification easily:
55 # make some schemes as instances so we can copy them for modification easily:
56 __PColLinux = ColorANSI.ColorScheme(
56 __PColLinux = ColorANSI.ColorScheme(
57 'Linux',
57 'Linux',
58 in_prompt = InputColors.Green,
58 in_prompt = InputColors.Green,
59 in_number = InputColors.LightGreen,
59 in_number = InputColors.LightGreen,
60 in_prompt2 = InputColors.Green,
60 in_prompt2 = InputColors.Green,
61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
62
62
63 out_prompt = Colors.Red,
63 out_prompt = Colors.Red,
64 out_number = Colors.LightRed,
64 out_number = Colors.LightRed,
65
65
66 normal = Colors.Normal
66 normal = Colors.Normal
67 )
67 )
68 # Don't forget to enter it into the table!
68 # Don't forget to enter it into the table!
69 PromptColors.add_scheme(__PColLinux)
69 PromptColors.add_scheme(__PColLinux)
70
70
71 # Slightly modified Linux for light backgrounds
71 # Slightly modified Linux for light backgrounds
72 __PColLightBG = __PColLinux.copy('LightBG')
72 __PColLightBG = __PColLinux.copy('LightBG')
73
73
74 __PColLightBG.colors.update(
74 __PColLightBG.colors.update(
75 in_prompt = InputColors.Blue,
75 in_prompt = InputColors.Blue,
76 in_number = InputColors.LightBlue,
76 in_number = InputColors.LightBlue,
77 in_prompt2 = InputColors.Blue
77 in_prompt2 = InputColors.Blue
78 )
78 )
79 PromptColors.add_scheme(__PColLightBG)
79 PromptColors.add_scheme(__PColLightBG)
80
80
81 del Colors,InputColors
81 del Colors,InputColors
82
82
83 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
84 def multiple_replace(dict, text):
84 def multiple_replace(dict, text):
85 """ Replace in 'text' all occurences of any key in the given
85 """ Replace in 'text' all occurences of any key in the given
86 dictionary by its corresponding value. Returns the new string."""
86 dictionary by its corresponding value. Returns the new string."""
87
87
88 # Function by Xavier Defrang, originally found at:
88 # Function by Xavier Defrang, originally found at:
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90
90
91 # Create a regular expression from the dictionary keys
91 # Create a regular expression from the dictionary keys
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 # For each match, look-up corresponding value in dictionary
93 # For each match, look-up corresponding value in dictionary
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95
95
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 # Special characters that can be used in prompt templates, mainly bash-like
97 # Special characters that can be used in prompt templates, mainly bash-like
98
98
99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
100 # never be expanded out into '~'. Basically anything which can never be a
100 # never be expanded out into '~'. Basically anything which can never be a
101 # reasonable directory name will do, we just want the $HOME -> '~' operation
101 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 # to become a no-op. We pre-compute $HOME here so it's not done on every
102 # to become a no-op. We pre-compute $HOME here so it's not done on every
103 # prompt call.
103 # prompt call.
104
104
105 # FIXME:
105 # FIXME:
106
106
107 # - This should be turned into a class which does proper namespace management,
107 # - This should be turned into a class which does proper namespace management,
108 # since the prompt specials need to be evaluated in a certain namespace.
108 # since the prompt specials need to be evaluated in a certain namespace.
109 # Currently it's just globals, which need to be managed manually by code
109 # Currently it's just globals, which need to be managed manually by code
110 # below.
110 # below.
111
111
112 # - I also need to split up the color schemes from the prompt specials
112 # - I also need to split up the color schemes from the prompt specials
113 # somehow. I don't have a clean design for that quite yet.
113 # somehow. I don't have a clean design for that quite yet.
114
114
115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116
116
117 # We precompute a few more strings here for the prompt_specials, which are
117 # We precompute a few more strings here for the prompt_specials, which are
118 # fixed once ipython starts. This reduces the runtime overhead of computing
118 # fixed once ipython starts. This reduces the runtime overhead of computing
119 # prompt strings.
119 # prompt strings.
120 USER = os.environ.get("USER")
120 USER = os.environ.get("USER")
121 HOSTNAME = socket.gethostname()
121 HOSTNAME = socket.gethostname()
122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124
124
125 prompt_specials_color = {
125 prompt_specials_color = {
126 # Prompt/history count
126 # Prompt/history count
127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 # Prompt/history count, with the actual digits replaced by dots. Used
129 # Prompt/history count, with the actual digits replaced by dots. Used
130 # mainly in continuation prompts (prompt_in2)
130 # mainly in continuation prompts (prompt_in2)
131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
132 # Current working directory
132 # Current working directory
133 '\\w': '${os.getcwd()}',
133 '\\w': '${os.getcwd()}',
134 # Current time
134 # Current time
135 '\\t' : '${time.strftime("%H:%M:%S")}',
135 '\\t' : '${time.strftime("%H:%M:%S")}',
136 # Basename of current working directory.
136 # Basename of current working directory.
137 # (use os.sep to make this portable across OSes)
137 # (use os.sep to make this portable across OSes)
138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
139 # These X<N> are an extension to the normal bash prompts. They return
139 # These X<N> are an extension to the normal bash prompts. They return
140 # N terms of the path, after replacing $HOME with '~'
140 # N terms of the path, after replacing $HOME with '~'
141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
142 '\\X1': '${self.cwd_filt(1)}',
142 '\\X1': '${self.cwd_filt(1)}',
143 '\\X2': '${self.cwd_filt(2)}',
143 '\\X2': '${self.cwd_filt(2)}',
144 '\\X3': '${self.cwd_filt(3)}',
144 '\\X3': '${self.cwd_filt(3)}',
145 '\\X4': '${self.cwd_filt(4)}',
145 '\\X4': '${self.cwd_filt(4)}',
146 '\\X5': '${self.cwd_filt(5)}',
146 '\\X5': '${self.cwd_filt(5)}',
147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
148 # N+1 in the list. Somewhat like %cN in tcsh.
148 # N+1 in the list. Somewhat like %cN in tcsh.
149 '\\Y0': '${self.cwd_filt2(0)}',
149 '\\Y0': '${self.cwd_filt2(0)}',
150 '\\Y1': '${self.cwd_filt2(1)}',
150 '\\Y1': '${self.cwd_filt2(1)}',
151 '\\Y2': '${self.cwd_filt2(2)}',
151 '\\Y2': '${self.cwd_filt2(2)}',
152 '\\Y3': '${self.cwd_filt2(3)}',
152 '\\Y3': '${self.cwd_filt2(3)}',
153 '\\Y4': '${self.cwd_filt2(4)}',
153 '\\Y4': '${self.cwd_filt2(4)}',
154 '\\Y5': '${self.cwd_filt2(5)}',
154 '\\Y5': '${self.cwd_filt2(5)}',
155 # Hostname up to first .
155 # Hostname up to first .
156 '\\h': HOSTNAME_SHORT,
156 '\\h': HOSTNAME_SHORT,
157 # Full hostname
157 # Full hostname
158 '\\H': HOSTNAME,
158 '\\H': HOSTNAME,
159 # Username of current user
159 # Username of current user
160 '\\u': USER,
160 '\\u': USER,
161 # Escaped '\'
161 # Escaped '\'
162 '\\\\': '\\',
162 '\\\\': '\\',
163 # Newline
163 # Newline
164 '\\n': '\n',
164 '\\n': '\n',
165 # Carriage return
165 # Carriage return
166 '\\r': '\r',
166 '\\r': '\r',
167 # Release version
167 # Release version
168 '\\v': __version__,
168 '\\v': __version__,
169 # Root symbol ($ or #)
169 # Root symbol ($ or #)
170 '\\$': ROOT_SYMBOL,
170 '\\$': ROOT_SYMBOL,
171 }
171 }
172
172
173 # A copy of the prompt_specials dictionary but with all color escapes removed,
173 # A copy of the prompt_specials dictionary but with all color escapes removed,
174 # so we can correctly compute the prompt length for the auto_rewrite method.
174 # so we can correctly compute the prompt length for the auto_rewrite method.
175 prompt_specials_nocolor = prompt_specials_color.copy()
175 prompt_specials_nocolor = prompt_specials_color.copy()
176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
178
178
179 # Add in all the InputTermColors color escapes as valid prompt characters.
179 # Add in all the InputTermColors color escapes as valid prompt characters.
180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
181 # with a color name which may begin with a letter used by any other of the
181 # with a color name which may begin with a letter used by any other of the
182 # allowed specials. This of course means that \\C will never be allowed for
182 # allowed specials. This of course means that \\C will never be allowed for
183 # anything else.
183 # anything else.
184 input_colors = ColorANSI.InputTermColors
184 input_colors = ColorANSI.InputTermColors
185 for _color in dir(input_colors):
185 for _color in dir(input_colors):
186 if _color[0] != '_':
186 if _color[0] != '_':
187 c_name = '\\C_'+_color
187 c_name = '\\C_'+_color
188 prompt_specials_color[c_name] = getattr(input_colors,_color)
188 prompt_specials_color[c_name] = getattr(input_colors,_color)
189 prompt_specials_nocolor[c_name] = ''
189 prompt_specials_nocolor[c_name] = ''
190
190
191 # we default to no color for safety. Note that prompt_specials is a global
191 # we default to no color for safety. Note that prompt_specials is a global
192 # variable used by all prompt objects.
192 # variable used by all prompt objects.
193 prompt_specials = prompt_specials_nocolor
193 prompt_specials = prompt_specials_nocolor
194
194
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196 def str_safe(arg):
196 def str_safe(arg):
197 """Convert to a string, without ever raising an exception.
197 """Convert to a string, without ever raising an exception.
198
198
199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
200 error message."""
200 error message."""
201
201
202 try:
202 try:
203 out = str(arg)
203 out = str(arg)
204 except UnicodeError:
204 except UnicodeError:
205 try:
205 try:
206 out = arg.encode('utf_8','replace')
206 out = arg.encode('utf_8','replace')
207 except Exception,msg:
207 except Exception,msg:
208 # let's keep this little duplication here, so that the most common
208 # let's keep this little duplication here, so that the most common
209 # case doesn't suffer from a double try wrapping.
209 # case doesn't suffer from a double try wrapping.
210 out = '<ERROR: %s>' % msg
210 out = '<ERROR: %s>' % msg
211 except Exception,msg:
211 except Exception,msg:
212 out = '<ERROR: %s>' % msg
212 out = '<ERROR: %s>' % msg
213 return out
213 return out
214
214
215 class BasePrompt:
215 class BasePrompt:
216 """Interactive prompt similar to Mathematica's."""
216 """Interactive prompt similar to Mathematica's."""
217 def __init__(self,cache,sep,prompt,pad_left=False):
217 def __init__(self,cache,sep,prompt,pad_left=False):
218
218
219 # Hack: we access information about the primary prompt through the
219 # Hack: we access information about the primary prompt through the
220 # cache argument. We need this, because we want the secondary prompt
220 # cache argument. We need this, because we want the secondary prompt
221 # to be aligned with the primary one. Color table info is also shared
221 # to be aligned with the primary one. Color table info is also shared
222 # by all prompt classes through the cache. Nice OO spaghetti code!
222 # by all prompt classes through the cache. Nice OO spaghetti code!
223 self.cache = cache
223 self.cache = cache
224 self.sep = sep
224 self.sep = sep
225
225
226 # regexp to count the number of spaces at the end of a prompt
226 # regexp to count the number of spaces at the end of a prompt
227 # expression, useful for prompt auto-rewriting
227 # expression, useful for prompt auto-rewriting
228 self.rspace = re.compile(r'(\s*)$')
228 self.rspace = re.compile(r'(\s*)$')
229 # Flag to left-pad prompt strings to match the length of the primary
229 # Flag to left-pad prompt strings to match the length of the primary
230 # prompt
230 # prompt
231 self.pad_left = pad_left
231 self.pad_left = pad_left
232 # Set template to create each actual prompt (where numbers change)
232 # Set template to create each actual prompt (where numbers change)
233 self.p_template = prompt
233 self.p_template = prompt
234 self.set_p_str()
234 self.set_p_str()
235
235
236 def set_p_str(self):
236 def set_p_str(self):
237 """ Set the interpolating prompt strings.
237 """ Set the interpolating prompt strings.
238
238
239 This must be called every time the color settings change, because the
239 This must be called every time the color settings change, because the
240 prompt_specials global may have changed."""
240 prompt_specials global may have changed."""
241
241
242 import os,time # needed in locals for prompt string handling
242 import os,time # needed in locals for prompt string handling
243 loc = locals()
243 loc = locals()
244 self.p_str = ItplNS('%s%s%s' %
244 self.p_str = ItplNS('%s%s%s' %
245 ('${self.sep}${self.col_p}',
245 ('${self.sep}${self.col_p}',
246 multiple_replace(prompt_specials, self.p_template),
246 multiple_replace(prompt_specials, self.p_template),
247 '${self.col_norm}'),self.cache.user_ns,loc)
247 '${self.col_norm}'),self.cache.user_ns,loc)
248
248
249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
250 self.p_template),
250 self.p_template),
251 self.cache.user_ns,loc)
251 self.cache.user_ns,loc)
252
252
253 def write(self,msg): # dbg
253 def write(self,msg): # dbg
254 sys.stdout.write(msg)
254 sys.stdout.write(msg)
255 return ''
255 return ''
256
256
257 def __str__(self):
257 def __str__(self):
258 """Return a string form of the prompt.
258 """Return a string form of the prompt.
259
259
260 This for is useful for continuation and output prompts, since it is
260 This for is useful for continuation and output prompts, since it is
261 left-padded to match lengths with the primary one (if the
261 left-padded to match lengths with the primary one (if the
262 self.pad_left attribute is set)."""
262 self.pad_left attribute is set)."""
263
263
264 out_str = str_safe(self.p_str)
264 out_str = str_safe(self.p_str)
265 if self.pad_left:
265 if self.pad_left:
266 # We must find the amount of padding required to match lengths,
266 # We must find the amount of padding required to match lengths,
267 # taking the color escapes (which are invisible on-screen) into
267 # taking the color escapes (which are invisible on-screen) into
268 # account.
268 # account.
269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
271 return format % out_str
271 return format % out_str
272 else:
272 else:
273 return out_str
273 return out_str
274
274
275 # these path filters are put in as methods so that we can control the
275 # these path filters are put in as methods so that we can control the
276 # namespace where the prompt strings get evaluated
276 # namespace where the prompt strings get evaluated
277 def cwd_filt(self,depth):
277 def cwd_filt(self,depth):
278 """Return the last depth elements of the current working directory.
278 """Return the last depth elements of the current working directory.
279
279
280 $HOME is always replaced with '~'.
280 $HOME is always replaced with '~'.
281 If depth==0, the full path is returned."""
281 If depth==0, the full path is returned."""
282
282
283 cwd = os.getcwd().replace(HOME,"~")
283 cwd = os.getcwd().replace(HOME,"~")
284 out = os.sep.join(cwd.split(os.sep)[-depth:])
284 out = os.sep.join(cwd.split(os.sep)[-depth:])
285 if out:
285 if out:
286 return out
286 return out
287 else:
287 else:
288 return os.sep
288 return os.sep
289
289
290 def cwd_filt2(self,depth):
290 def cwd_filt2(self,depth):
291 """Return the last depth elements of the current working directory.
291 """Return the last depth elements of the current working directory.
292
292
293 $HOME is always replaced with '~'.
293 $HOME is always replaced with '~'.
294 If depth==0, the full path is returned."""
294 If depth==0, the full path is returned."""
295
295
296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
297 if '~' in cwd and len(cwd) == depth+1:
297 if '~' in cwd and len(cwd) == depth+1:
298 depth += 1
298 depth += 1
299 out = os.sep.join(cwd[-depth:])
299 out = os.sep.join(cwd[-depth:])
300 if out:
300 if out:
301 return out
301 return out
302 else:
302 else:
303 return os.sep
303 return os.sep
304
304
305 class Prompt1(BasePrompt):
305 class Prompt1(BasePrompt):
306 """Input interactive prompt similar to Mathematica's."""
306 """Input interactive prompt similar to Mathematica's."""
307
307
308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
310
310
311 def set_colors(self):
311 def set_colors(self):
312 self.set_p_str()
312 self.set_p_str()
313 Colors = self.cache.color_table.active_colors # shorthand
313 Colors = self.cache.color_table.active_colors # shorthand
314 self.col_p = Colors.in_prompt
314 self.col_p = Colors.in_prompt
315 self.col_num = Colors.in_number
315 self.col_num = Colors.in_number
316 self.col_norm = Colors.in_normal
316 self.col_norm = Colors.in_normal
317 # We need a non-input version of these escapes for the '--->'
317 # We need a non-input version of these escapes for the '--->'
318 # auto-call prompts used in the auto_rewrite() method.
318 # auto-call prompts used in the auto_rewrite() method.
319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
320 self.col_norm_ni = Colors.normal
320 self.col_norm_ni = Colors.normal
321
321
322 def __str__(self):
322 def __str__(self):
323 self.cache.prompt_count += 1
323 self.cache.prompt_count += 1
324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
325 return str_safe(self.p_str)
325 return str_safe(self.p_str)
326
326
327 def auto_rewrite(self):
327 def auto_rewrite(self):
328 """Print a string of the form '--->' which lines up with the previous
328 """Print a string of the form '--->' which lines up with the previous
329 input string. Useful for systems which re-write the user input when
329 input string. Useful for systems which re-write the user input when
330 handling automatically special syntaxes."""
330 handling automatically special syntaxes."""
331
331
332 curr = str(self.cache.last_prompt)
332 curr = str(self.cache.last_prompt)
333 nrspaces = len(self.rspace.search(curr).group())
333 nrspaces = len(self.rspace.search(curr).group())
334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
335 ' '*nrspaces,self.col_norm_ni)
335 ' '*nrspaces,self.col_norm_ni)
336
336
337 class PromptOut(BasePrompt):
337 class PromptOut(BasePrompt):
338 """Output interactive prompt similar to Mathematica's."""
338 """Output interactive prompt similar to Mathematica's."""
339
339
340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
342 if not self.p_template:
342 if not self.p_template:
343 self.__str__ = lambda: ''
343 self.__str__ = lambda: ''
344
344
345 def set_colors(self):
345 def set_colors(self):
346 self.set_p_str()
346 self.set_p_str()
347 Colors = self.cache.color_table.active_colors # shorthand
347 Colors = self.cache.color_table.active_colors # shorthand
348 self.col_p = Colors.out_prompt
348 self.col_p = Colors.out_prompt
349 self.col_num = Colors.out_number
349 self.col_num = Colors.out_number
350 self.col_norm = Colors.normal
350 self.col_norm = Colors.normal
351
351
352 class Prompt2(BasePrompt):
352 class Prompt2(BasePrompt):
353 """Interactive continuation prompt."""
353 """Interactive continuation prompt."""
354
354
355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
356 self.cache = cache
356 self.cache = cache
357 self.p_template = prompt
357 self.p_template = prompt
358 self.pad_left = pad_left
358 self.pad_left = pad_left
359 self.set_p_str()
359 self.set_p_str()
360
360
361 def set_p_str(self):
361 def set_p_str(self):
362 import os,time # needed in locals for prompt string handling
362 import os,time # needed in locals for prompt string handling
363 loc = locals()
363 loc = locals()
364 self.p_str = ItplNS('%s%s%s' %
364 self.p_str = ItplNS('%s%s%s' %
365 ('${self.col_p2}',
365 ('${self.col_p2}',
366 multiple_replace(prompt_specials, self.p_template),
366 multiple_replace(prompt_specials, self.p_template),
367 '$self.col_norm'),
367 '$self.col_norm'),
368 self.cache.user_ns,loc)
368 self.cache.user_ns,loc)
369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
370 self.p_template),
370 self.p_template),
371 self.cache.user_ns,loc)
371 self.cache.user_ns,loc)
372
372
373 def set_colors(self):
373 def set_colors(self):
374 self.set_p_str()
374 self.set_p_str()
375 Colors = self.cache.color_table.active_colors
375 Colors = self.cache.color_table.active_colors
376 self.col_p2 = Colors.in_prompt2
376 self.col_p2 = Colors.in_prompt2
377 self.col_norm = Colors.in_normal
377 self.col_norm = Colors.in_normal
378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
379 # updated their prompt_in2 definitions. Remove eventually.
379 # updated their prompt_in2 definitions. Remove eventually.
380 self.col_p = Colors.out_prompt
380 self.col_p = Colors.out_prompt
381 self.col_num = Colors.out_number
381 self.col_num = Colors.out_number
382
382
383 #-----------------------------------------------------------------------------
383 #-----------------------------------------------------------------------------
384 class CachedOutput:
384 class CachedOutput:
385 """Class for printing output from calculations while keeping a cache of
385 """Class for printing output from calculations while keeping a cache of
386 reults. It dynamically creates global variables prefixed with _ which
386 reults. It dynamically creates global variables prefixed with _ which
387 contain these results.
387 contain these results.
388
388
389 Meant to be used as a sys.displayhook replacement, providing numbered
389 Meant to be used as a sys.displayhook replacement, providing numbered
390 prompts and cache services.
390 prompts and cache services.
391
391
392 Initialize with initial and final values for cache counter (this defines
392 Initialize with initial and final values for cache counter (this defines
393 the maximum size of the cache."""
393 the maximum size of the cache."""
394
394
395 def __init__(self,cache_size,Pprint,colors='NoColor',input_sep='\n',
395 def __init__(self,cache_size,Pprint,colors='NoColor',input_sep='\n',
396 output_sep='\n',output_sep2='',user_ns={},
396 output_sep='\n',output_sep2='',user_ns={},
397 ps1 = None, ps2 = None,ps_out = None,
397 ps1 = None, ps2 = None,ps_out = None,
398 input_hist = None,pad_left=True):
398 input_hist = None,pad_left=True):
399
399
400 cache_size_min = 20
400 cache_size_min = 20
401 if cache_size <= 0:
401 if cache_size <= 0:
402 self.do_full_cache = 0
402 self.do_full_cache = 0
403 cache_size = 0
403 cache_size = 0
404 elif cache_size < cache_size_min:
404 elif cache_size < cache_size_min:
405 self.do_full_cache = 0
405 self.do_full_cache = 0
406 cache_size = 0
406 cache_size = 0
407 warn('caching was disabled (min value for cache size is %s).' %
407 warn('caching was disabled (min value for cache size is %s).' %
408 cache_size_min,level=3)
408 cache_size_min,level=3)
409 else:
409 else:
410 self.do_full_cache = 1
410 self.do_full_cache = 1
411
411
412 self.cache_size = cache_size
412 self.cache_size = cache_size
413 self.input_sep = input_sep
413 self.input_sep = input_sep
414
414
415 # we need a reference to the user-level namespace
415 # we need a reference to the user-level namespace
416 self.user_ns = user_ns
416 self.user_ns = user_ns
417 # and to the user's input
417 # and to the user's input
418 self.input_hist = input_hist
418 self.input_hist = input_hist
419
419
420 # Set input prompt strings and colors
420 # Set input prompt strings and colors
421 if cache_size == 0:
421 if cache_size == 0:
422 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
422 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
423 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
423 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
424 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
424 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
425 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
425 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
426 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
426 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
427
427
428 self.color_table = PromptColors
428 self.color_table = PromptColors
429 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
429 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
430 pad_left=pad_left)
430 pad_left=pad_left)
431 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
431 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
432 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
432 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
433 pad_left=pad_left)
433 pad_left=pad_left)
434 self.set_colors(colors)
434 self.set_colors(colors)
435
435
436 # other more normal stuff
436 # other more normal stuff
437 # b/c each call to the In[] prompt raises it by 1, even the first.
437 # b/c each call to the In[] prompt raises it by 1, even the first.
438 self.prompt_count = 0
438 self.prompt_count = 0
439 self.cache_count = 1
439 self.cache_count = 1
440 # Store the last prompt string each time, we need it for aligning
440 # Store the last prompt string each time, we need it for aligning
441 # continuation and auto-rewrite prompts
441 # continuation and auto-rewrite prompts
442 self.last_prompt = ''
442 self.last_prompt = ''
443 self.entries = [None] # output counter starts at 1 for the user
443 self.entries = [None] # output counter starts at 1 for the user
444 self.Pprint = Pprint
444 self.Pprint = Pprint
445 self.output_sep = output_sep
445 self.output_sep = output_sep
446 self.output_sep2 = output_sep2
446 self.output_sep2 = output_sep2
447 self._,self.__,self.___ = '','',''
447 self._,self.__,self.___ = '','',''
448 self.pprint_types = map(type,[(),[],{}])
448 self.pprint_types = map(type,[(),[],{}])
449
449
450 # these are deliberately global:
450 # these are deliberately global:
451 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
451 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
452 self.user_ns.update(to_user_ns)
452 self.user_ns.update(to_user_ns)
453
453
454 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
454 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
455 if p_str is None:
455 if p_str is None:
456 if self.do_full_cache:
456 if self.do_full_cache:
457 return cache_def
457 return cache_def
458 else:
458 else:
459 return no_cache_def
459 return no_cache_def
460 else:
460 else:
461 return p_str
461 return p_str
462
462
463 def set_colors(self,colors):
463 def set_colors(self,colors):
464 """Set the active color scheme and configure colors for the three
464 """Set the active color scheme and configure colors for the three
465 prompt subsystems."""
465 prompt subsystems."""
466
466
467 # FIXME: the prompt_specials global should be gobbled inside this
467 # FIXME: the prompt_specials global should be gobbled inside this
468 # class instead. Do it when cleaning up the whole 3-prompt system.
468 # class instead. Do it when cleaning up the whole 3-prompt system.
469 global prompt_specials
469 global prompt_specials
470 if colors.lower()=='nocolor':
470 if colors.lower()=='nocolor':
471 prompt_specials = prompt_specials_nocolor
471 prompt_specials = prompt_specials_nocolor
472 else:
472 else:
473 prompt_specials = prompt_specials_color
473 prompt_specials = prompt_specials_color
474
474
475 self.color_table.set_active_scheme(colors)
475 self.color_table.set_active_scheme(colors)
476 self.prompt1.set_colors()
476 self.prompt1.set_colors()
477 self.prompt2.set_colors()
477 self.prompt2.set_colors()
478 self.prompt_out.set_colors()
478 self.prompt_out.set_colors()
479
479
480 def __call__(self,arg=None):
480 def __call__(self,arg=None):
481 """Printing with history cache management.
481 """Printing with history cache management.
482
482
483 This is invoked everytime the interpreter needs to print, and is
483 This is invoked everytime the interpreter needs to print, and is
484 activated by setting the variable sys.displayhook to it."""
484 activated by setting the variable sys.displayhook to it."""
485
485
486 # If something injected a '_' variable in __builtin__, delete
486 # If something injected a '_' variable in __builtin__, delete
487 # ipython's automatic one so we don't clobber that. gettext() in
487 # ipython's automatic one so we don't clobber that. gettext() in
488 # particular uses _, so we need to stay away from it.
488 # particular uses _, so we need to stay away from it.
489 if '_' in __builtin__.__dict__:
489 if '_' in __builtin__.__dict__:
490 try:
490 try:
491 del self.user_ns['_']
491 del self.user_ns['_']
492 except KeyError:
492 except KeyError:
493 pass
493 pass
494 if arg is not None:
494 if arg is not None:
495 cout_write = Term.cout.write # fast lookup
495 cout_write = Term.cout.write # fast lookup
496 # first handle the cache and counters
496 # first handle the cache and counters
497 self.update(arg)
497 # but avoid recursive reference when displaying _oh/Out
498 if arg is not self.user_ns['_oh']:
499 self.update(arg)
498 # do not print output if input ends in ';'
500 # do not print output if input ends in ';'
499 if self.input_hist[self.prompt_count].endswith(';\n'):
501 if self.input_hist[self.prompt_count].endswith(';\n'):
500 return
502 return
501 # don't use print, puts an extra space
503 # don't use print, puts an extra space
502 cout_write(self.output_sep)
504 cout_write(self.output_sep)
503 if self.do_full_cache:
505 if self.do_full_cache:
504 cout_write(str(self.prompt_out))
506 cout_write(str(self.prompt_out))
505
507
506 if isinstance(arg,Macro):
508 if isinstance(arg,Macro):
507 print 'Executing Macro...'
509 print 'Executing Macro...'
508 # in case the macro takes a long time to execute
510 # in case the macro takes a long time to execute
509 Term.cout.flush()
511 Term.cout.flush()
510 exec arg.value in self.user_ns
512 exec arg.value in self.user_ns
511 return None
513 return None
512
514
513 # and now call a possibly user-defined print mechanism
515 # and now call a possibly user-defined print mechanism
514 self.display(arg)
516 self.display(arg)
515 cout_write(self.output_sep2)
517 cout_write(self.output_sep2)
516 Term.cout.flush()
518 Term.cout.flush()
517
519
518 def _display(self,arg):
520 def _display(self,arg):
519 """Default printer method, uses pprint.
521 """Default printer method, uses pprint.
520
522
521 This can be over-ridden by the users to implement special formatting
523 This can be over-ridden by the users to implement special formatting
522 of certain types of output."""
524 of certain types of output."""
523
525
524 if self.Pprint:
526 if self.Pprint:
525 out = pformat(arg)
527 out = pformat(arg)
526 if '\n' in out:
528 if '\n' in out:
527 # So that multi-line strings line up with the left column of
529 # So that multi-line strings line up with the left column of
528 # the screen, instead of having the output prompt mess up
530 # the screen, instead of having the output prompt mess up
529 # their first line.
531 # their first line.
530 Term.cout.write('\n')
532 Term.cout.write('\n')
531 print >>Term.cout, out
533 print >>Term.cout, out
532 else:
534 else:
533 print >>Term.cout, arg
535 print >>Term.cout, arg
534
536
535 # Assign the default display method:
537 # Assign the default display method:
536 display = _display
538 display = _display
537
539
538 def update(self,arg):
540 def update(self,arg):
539 #print '***cache_count', self.cache_count # dbg
541 #print '***cache_count', self.cache_count # dbg
540 if self.cache_count >= self.cache_size and self.do_full_cache:
542 if self.cache_count >= self.cache_size and self.do_full_cache:
541 self.flush()
543 self.flush()
542 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
544 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
543 # we cause buggy behavior for things like gettext).
545 # we cause buggy behavior for things like gettext).
544 if '_' not in __builtin__.__dict__:
546 if '_' not in __builtin__.__dict__:
545 self.___ = self.__
547 self.___ = self.__
546 self.__ = self._
548 self.__ = self._
547 self._ = arg
549 self._ = arg
548 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
550 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
549
551
550 # hackish access to top-level namespace to create _1,_2... dynamically
552 # hackish access to top-level namespace to create _1,_2... dynamically
551 to_main = {}
553 to_main = {}
552 if self.do_full_cache:
554 if self.do_full_cache:
553 self.cache_count += 1
555 self.cache_count += 1
554 self.entries.append(arg)
556 self.entries.append(arg)
555 new_result = '_'+`self.prompt_count`
557 new_result = '_'+`self.prompt_count`
556 to_main[new_result] = self.entries[-1]
558 to_main[new_result] = self.entries[-1]
557 self.user_ns.update(to_main)
559 self.user_ns.update(to_main)
558 self.user_ns['_oh'][self.prompt_count] = arg
560 self.user_ns['_oh'][self.prompt_count] = arg
559
561
560 def flush(self):
562 def flush(self):
561 if not self.do_full_cache:
563 if not self.do_full_cache:
562 raise ValueError,"You shouldn't have reached the cache flush "\
564 raise ValueError,"You shouldn't have reached the cache flush "\
563 "if full caching is not enabled!"
565 "if full caching is not enabled!"
564 warn('Output cache limit (currently '+\
566 warn('Output cache limit (currently '+\
565 `self.cache_count`+' entries) hit.\n'
567 `self.cache_count`+' entries) hit.\n'
566 'Flushing cache and resetting history counter...\n'
568 'Flushing cache and resetting history counter...\n'
567 'The only history variables available will be _,__,___ and _1\n'
569 'The only history variables available will be _,__,___ and _1\n'
568 'with the current result.')
570 'with the current result.')
569 # delete auto-generated vars from global namespace
571 # delete auto-generated vars from global namespace
570 for n in range(1,self.prompt_count + 1):
572 for n in range(1,self.prompt_count + 1):
571 key = '_'+`n`
573 key = '_'+`n`
572 try:
574 try:
573 del self.user_ns[key]
575 del self.user_ns[key]
574 except: pass
576 except: pass
575 self.prompt_count = 1
577 self.prompt_count = 1
576 self.cache_count = 1
578 self.cache_count = 1
@@ -1,1609 +1,1609 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 958 2005-12-27 23:17:51Z fperez $"""
8 $Id: genutils.py 960 2005-12-28 06:51:01Z 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 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
40 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
41 # 2.2-friendly
41 # 2.2-friendly
42 try:
42 try:
43 basestring
43 basestring
44 except NameError:
44 except NameError:
45 import types
45 import types
46 basestring = (types.StringType, types.UnicodeType)
46 basestring = (types.StringType, types.UnicodeType)
47 True = 1==1
47 True = 1==1
48 False = 1==0
48 False = 1==0
49
49
50 def enumerate(obj):
50 def enumerate(obj):
51 i = -1
51 i = -1
52 for item in obj:
52 for item in obj:
53 i += 1
53 i += 1
54 yield i, item
54 yield i, item
55
55
56 # add these to the builtin namespace, so that all modules find them
56 # add these to the builtin namespace, so that all modules find them
57 import __builtin__
57 import __builtin__
58 __builtin__.basestring = basestring
58 __builtin__.basestring = basestring
59 __builtin__.True = True
59 __builtin__.True = True
60 __builtin__.False = False
60 __builtin__.False = False
61 __builtin__.enumerate = enumerate
61 __builtin__.enumerate = enumerate
62
62
63 # Try to use shlex.split for converting an input string into a sys.argv-type
63 # Try to use shlex.split for converting an input string into a sys.argv-type
64 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
64 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
65 try:
65 try:
66 shlex_split = shlex.split
66 shlex_split = shlex.split
67 except AttributeError:
67 except AttributeError:
68 _quotesre = re.compile(r'[\'"](.*)[\'"]')
68 _quotesre = re.compile(r'[\'"](.*)[\'"]')
69 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
69 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
70 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
70 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
71 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
71 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
72 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
72 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
73 % os.sep)
73 % os.sep)
74
74
75 def shlex_split(s):
75 def shlex_split(s):
76 """Simplified backport to Python 2.2 of shlex.split().
76 """Simplified backport to Python 2.2 of shlex.split().
77
77
78 This is a quick and dirty hack, since the shlex module under 2.2 lacks
78 This is a quick and dirty hack, since the shlex module under 2.2 lacks
79 several of the features needed to really match the functionality of
79 several of the features needed to really match the functionality of
80 shlex.split() in 2.3."""
80 shlex.split() in 2.3."""
81
81
82 lex = shlex.shlex(StringIO(s))
82 lex = shlex.shlex(StringIO(s))
83 # Try to get options, extensions and path separators as characters
83 # Try to get options, extensions and path separators as characters
84 lex.wordchars = _wordchars
84 lex.wordchars = _wordchars
85 lex.commenters = ''
85 lex.commenters = ''
86 # Make a list out of the lexer by hand, since in 2.2 it's not an
86 # Make a list out of the lexer by hand, since in 2.2 it's not an
87 # iterator.
87 # iterator.
88 lout = []
88 lout = []
89 while 1:
89 while 1:
90 token = lex.get_token()
90 token = lex.get_token()
91 if token == '':
91 if token == '':
92 break
92 break
93 # Try to handle quoted tokens correctly
93 # Try to handle quoted tokens correctly
94 quotes = _quotesre.match(token)
94 quotes = _quotesre.match(token)
95 if quotes:
95 if quotes:
96 token = quotes.group(1)
96 token = quotes.group(1)
97 lout.append(token)
97 lout.append(token)
98 return lout
98 return lout
99
99
100 #****************************************************************************
100 #****************************************************************************
101 # Exceptions
101 # Exceptions
102 class Error(Exception):
102 class Error(Exception):
103 """Base class for exceptions in this module."""
103 """Base class for exceptions in this module."""
104 pass
104 pass
105
105
106 #----------------------------------------------------------------------------
106 #----------------------------------------------------------------------------
107 class IOStream:
107 class IOStream:
108 def __init__(self,stream,fallback):
108 def __init__(self,stream,fallback):
109 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
109 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
110 stream = fallback
110 stream = fallback
111 self.stream = stream
111 self.stream = stream
112 self._swrite = stream.write
112 self._swrite = stream.write
113 self.flush = stream.flush
113 self.flush = stream.flush
114
114
115 def write(self,data):
115 def write(self,data):
116 try:
116 try:
117 self._swrite(data)
117 self._swrite(data)
118 except:
118 except:
119 try:
119 try:
120 # print handles some unicode issues which may trip a plain
120 # print handles some unicode issues which may trip a plain
121 # write() call. Attempt to emulate write() by using a
121 # write() call. Attempt to emulate write() by using a
122 # trailing comma
122 # trailing comma
123 print >> self.stream, data,
123 print >> self.stream, data,
124 except:
124 except:
125 # if we get here, something is seriously broken.
125 # if we get here, something is seriously broken.
126 print >> sys.stderr, \
126 print >> sys.stderr, \
127 'ERROR - failed to write data to stream:', stream
127 'ERROR - failed to write data to stream:', stream
128
128
129 class IOTerm:
129 class IOTerm:
130 """ Term holds the file or file-like objects for handling I/O operations.
130 """ Term holds the file or file-like objects for handling I/O operations.
131
131
132 These are normally just sys.stdin, sys.stdout and sys.stderr but for
132 These are normally just sys.stdin, sys.stdout and sys.stderr but for
133 Windows they can can replaced to allow editing the strings before they are
133 Windows they can can replaced to allow editing the strings before they are
134 displayed."""
134 displayed."""
135
135
136 # In the future, having IPython channel all its I/O operations through
136 # In the future, having IPython channel all its I/O operations through
137 # this class will make it easier to embed it into other environments which
137 # this class will make it easier to embed it into other environments which
138 # are not a normal terminal (such as a GUI-based shell)
138 # are not a normal terminal (such as a GUI-based shell)
139 def __init__(self,cin=None,cout=None,cerr=None):
139 def __init__(self,cin=None,cout=None,cerr=None):
140 self.cin = IOStream(cin,sys.stdin)
140 self.cin = IOStream(cin,sys.stdin)
141 self.cout = IOStream(cout,sys.stdout)
141 self.cout = IOStream(cout,sys.stdout)
142 self.cerr = IOStream(cerr,sys.stderr)
142 self.cerr = IOStream(cerr,sys.stderr)
143
143
144 # Global variable to be used for all I/O
144 # Global variable to be used for all I/O
145 Term = IOTerm()
145 Term = IOTerm()
146
146
147 # Windows-specific code to load Gary Bishop's readline and configure it
147 # Windows-specific code to load Gary Bishop's readline and configure it
148 # automatically for the users
148 # automatically for the users
149 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
149 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
150 # windows. Cygwin returns 'cygwin' for sys.platform.
150 # windows. Cygwin returns 'cygwin' for sys.platform.
151 if os.name == 'nt':
151 if os.name == 'nt':
152 try:
152 try:
153 import readline
153 import readline
154 except ImportError:
154 except ImportError:
155 pass
155 pass
156 else:
156 else:
157 try:
157 try:
158 _out = readline.GetOutputFile()
158 _out = readline.GetOutputFile()
159 except AttributeError:
159 except AttributeError:
160 pass
160 pass
161 else:
161 else:
162 # Remake Term to use the readline i/o facilities
162 # Remake Term to use the readline i/o facilities
163 Term = IOTerm(cout=_out,cerr=_out)
163 Term = IOTerm(cout=_out,cerr=_out)
164 del _out
164 del _out
165
165
166 #****************************************************************************
166 #****************************************************************************
167 # Generic warning/error printer, used by everything else
167 # Generic warning/error printer, used by everything else
168 def warn(msg,level=2,exit_val=1):
168 def warn(msg,level=2,exit_val=1):
169 """Standard warning printer. Gives formatting consistency.
169 """Standard warning printer. Gives formatting consistency.
170
170
171 Output is sent to Term.cerr (sys.stderr by default).
171 Output is sent to Term.cerr (sys.stderr by default).
172
172
173 Options:
173 Options:
174
174
175 -level(2): allows finer control:
175 -level(2): allows finer control:
176 0 -> Do nothing, dummy function.
176 0 -> Do nothing, dummy function.
177 1 -> Print message.
177 1 -> Print message.
178 2 -> Print 'WARNING:' + message. (Default level).
178 2 -> Print 'WARNING:' + message. (Default level).
179 3 -> Print 'ERROR:' + message.
179 3 -> Print 'ERROR:' + message.
180 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
180 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
181
181
182 -exit_val (1): exit value returned by sys.exit() for a level 4
182 -exit_val (1): exit value returned by sys.exit() for a level 4
183 warning. Ignored for all other levels."""
183 warning. Ignored for all other levels."""
184
184
185 if level>0:
185 if level>0:
186 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
186 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
187 print >> Term.cerr, '%s%s' % (header[level],msg)
187 print >> Term.cerr, '%s%s' % (header[level],msg)
188 if level == 4:
188 if level == 4:
189 print >> Term.cerr,'Exiting.\n'
189 print >> Term.cerr,'Exiting.\n'
190 sys.exit(exit_val)
190 sys.exit(exit_val)
191
191
192 def info(msg):
192 def info(msg):
193 """Equivalent to warn(msg,level=1)."""
193 """Equivalent to warn(msg,level=1)."""
194
194
195 warn(msg,level=1)
195 warn(msg,level=1)
196
196
197 def error(msg):
197 def error(msg):
198 """Equivalent to warn(msg,level=3)."""
198 """Equivalent to warn(msg,level=3)."""
199
199
200 warn(msg,level=3)
200 warn(msg,level=3)
201
201
202 def fatal(msg,exit_val=1):
202 def fatal(msg,exit_val=1):
203 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
203 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
204
204
205 warn(msg,exit_val=exit_val,level=4)
205 warn(msg,exit_val=exit_val,level=4)
206
206
207 #----------------------------------------------------------------------------
207 #----------------------------------------------------------------------------
208 StringTypes = types.StringTypes
208 StringTypes = types.StringTypes
209
209
210 # Basic timing functionality
210 # Basic timing functionality
211
211
212 # If possible (Unix), use the resource module instead of time.clock()
212 # If possible (Unix), use the resource module instead of time.clock()
213 try:
213 try:
214 import resource
214 import resource
215 def clock():
215 def clock():
216 """clock() -> floating point number
216 """clock() -> floating point number
217
217
218 Return the CPU time in seconds (user time only, system time is
218 Return the CPU time in seconds (user time only, system time is
219 ignored) since the start of the process. This is done via a call to
219 ignored) since the start of the process. This is done via a call to
220 resource.getrusage, so it avoids the wraparound problems in
220 resource.getrusage, so it avoids the wraparound problems in
221 time.clock()."""
221 time.clock()."""
222
222
223 return resource.getrusage(resource.RUSAGE_SELF)[0]
223 return resource.getrusage(resource.RUSAGE_SELF)[0]
224
224
225 def clock2():
225 def clock2():
226 """clock2() -> (t_user,t_system)
226 """clock2() -> (t_user,t_system)
227
227
228 Similar to clock(), but return a tuple of user/system times."""
228 Similar to clock(), but return a tuple of user/system times."""
229 return resource.getrusage(resource.RUSAGE_SELF)[:2]
229 return resource.getrusage(resource.RUSAGE_SELF)[:2]
230
230
231 except ImportError:
231 except ImportError:
232 clock = time.clock
232 clock = time.clock
233 def clock2():
233 def clock2():
234 """Under windows, system CPU time can't be measured.
234 """Under windows, system CPU time can't be measured.
235
235
236 This just returns clock() and zero."""
236 This just returns clock() and zero."""
237 return time.clock(),0.0
237 return time.clock(),0.0
238
238
239 def timings_out(reps,func,*args,**kw):
239 def timings_out(reps,func,*args,**kw):
240 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
240 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
241
241
242 Execute a function reps times, return a tuple with the elapsed total
242 Execute a function reps times, return a tuple with the elapsed total
243 CPU time in seconds, the time per call and the function's output.
243 CPU time in seconds, the time per call and the function's output.
244
244
245 Under Unix, the return value is the sum of user+system time consumed by
245 Under Unix, the return value is the sum of user+system time consumed by
246 the process, computed via the resource module. This prevents problems
246 the process, computed via the resource module. This prevents problems
247 related to the wraparound effect which the time.clock() function has.
247 related to the wraparound effect which the time.clock() function has.
248
248
249 Under Windows the return value is in wall clock seconds. See the
249 Under Windows the return value is in wall clock seconds. See the
250 documentation for the time module for more details."""
250 documentation for the time module for more details."""
251
251
252 reps = int(reps)
252 reps = int(reps)
253 assert reps >=1, 'reps must be >= 1'
253 assert reps >=1, 'reps must be >= 1'
254 if reps==1:
254 if reps==1:
255 start = clock()
255 start = clock()
256 out = func(*args,**kw)
256 out = func(*args,**kw)
257 tot_time = clock()-start
257 tot_time = clock()-start
258 else:
258 else:
259 rng = xrange(reps-1) # the last time is executed separately to store output
259 rng = xrange(reps-1) # the last time is executed separately to store output
260 start = clock()
260 start = clock()
261 for dummy in rng: func(*args,**kw)
261 for dummy in rng: func(*args,**kw)
262 out = func(*args,**kw) # one last time
262 out = func(*args,**kw) # one last time
263 tot_time = clock()-start
263 tot_time = clock()-start
264 av_time = tot_time / reps
264 av_time = tot_time / reps
265 return tot_time,av_time,out
265 return tot_time,av_time,out
266
266
267 def timings(reps,func,*args,**kw):
267 def timings(reps,func,*args,**kw):
268 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
268 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
269
269
270 Execute a function reps times, return a tuple with the elapsed total CPU
270 Execute a function reps times, return a tuple with the elapsed total CPU
271 time in seconds and the time per call. These are just the first two values
271 time in seconds and the time per call. These are just the first two values
272 in timings_out()."""
272 in timings_out()."""
273
273
274 return timings_out(reps,func,*args,**kw)[0:2]
274 return timings_out(reps,func,*args,**kw)[0:2]
275
275
276 def timing(func,*args,**kw):
276 def timing(func,*args,**kw):
277 """timing(func,*args,**kw) -> t_total
277 """timing(func,*args,**kw) -> t_total
278
278
279 Execute a function once, return the elapsed total CPU time in
279 Execute a function once, return the elapsed total CPU time in
280 seconds. This is just the first value in timings_out()."""
280 seconds. This is just the first value in timings_out()."""
281
281
282 return timings_out(1,func,*args,**kw)[0]
282 return timings_out(1,func,*args,**kw)[0]
283
283
284 #****************************************************************************
284 #****************************************************************************
285 # file and system
285 # file and system
286
286
287 def system(cmd,verbose=0,debug=0,header=''):
287 def system(cmd,verbose=0,debug=0,header=''):
288 """Execute a system command, return its exit status.
288 """Execute a system command, return its exit status.
289
289
290 Options:
290 Options:
291
291
292 - verbose (0): print the command to be executed.
292 - verbose (0): print the command to be executed.
293
293
294 - debug (0): only print, do not actually execute.
294 - debug (0): only print, do not actually execute.
295
295
296 - header (''): Header to print on screen prior to the executed command (it
296 - header (''): Header to print on screen prior to the executed command (it
297 is only prepended to the command, no newlines are added).
297 is only prepended to the command, no newlines are added).
298
298
299 Note: a stateful version of this function is available through the
299 Note: a stateful version of this function is available through the
300 SystemExec class."""
300 SystemExec class."""
301
301
302 stat = 0
302 stat = 0
303 if verbose or debug: print header+cmd
303 if verbose or debug: print header+cmd
304 sys.stdout.flush()
304 sys.stdout.flush()
305 if not debug: stat = os.system(cmd)
305 if not debug: stat = os.system(cmd)
306 return stat
306 return stat
307
307
308 def shell(cmd,verbose=0,debug=0,header=''):
308 def shell(cmd,verbose=0,debug=0,header=''):
309 """Execute a command in the system shell, always return None.
309 """Execute a command in the system shell, always return None.
310
310
311 Options:
311 Options:
312
312
313 - verbose (0): print the command to be executed.
313 - verbose (0): print the command to be executed.
314
314
315 - debug (0): only print, do not actually execute.
315 - debug (0): only print, do not actually execute.
316
316
317 - header (''): Header to print on screen prior to the executed command (it
317 - header (''): Header to print on screen prior to the executed command (it
318 is only prepended to the command, no newlines are added).
318 is only prepended to the command, no newlines are added).
319
319
320 Note: this is similar to genutils.system(), but it returns None so it can
320 Note: this is similar to genutils.system(), but it returns None so it can
321 be conveniently used in interactive loops without getting the return value
321 be conveniently used in interactive loops without getting the return value
322 (typically 0) printed many times."""
322 (typically 0) printed many times."""
323
323
324 stat = 0
324 stat = 0
325 if verbose or debug: print header+cmd
325 if verbose or debug: print header+cmd
326 # flush stdout so we don't mangle python's buffering
326 # flush stdout so we don't mangle python's buffering
327 sys.stdout.flush()
327 sys.stdout.flush()
328 if not debug:
328 if not debug:
329 os.system(cmd)
329 os.system(cmd)
330
330
331 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
331 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
332 """Dummy substitute for perl's backquotes.
332 """Dummy substitute for perl's backquotes.
333
333
334 Executes a command and returns the output.
334 Executes a command and returns the output.
335
335
336 Accepts the same arguments as system(), plus:
336 Accepts the same arguments as system(), plus:
337
337
338 - split(0): if true, the output is returned as a list split on newlines.
338 - split(0): if true, the output is returned as a list split on newlines.
339
339
340 Note: a stateful version of this function is available through the
340 Note: a stateful version of this function is available through the
341 SystemExec class."""
341 SystemExec class."""
342
342
343 if verbose or debug: print header+cmd
343 if verbose or debug: print header+cmd
344 if not debug:
344 if not debug:
345 output = commands.getoutput(cmd)
345 output = commands.getoutput(cmd)
346 if split:
346 if split:
347 return output.split('\n')
347 return output.split('\n')
348 else:
348 else:
349 return output
349 return output
350
350
351 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
351 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
352 """Return (standard output,standard error) of executing cmd in a shell.
352 """Return (standard output,standard error) of executing cmd in a shell.
353
353
354 Accepts the same arguments as system(), plus:
354 Accepts the same arguments as system(), plus:
355
355
356 - split(0): if true, each of stdout/err is returned as a list split on
356 - split(0): if true, each of stdout/err is returned as a list split on
357 newlines.
357 newlines.
358
358
359 Note: a stateful version of this function is available through the
359 Note: a stateful version of this function is available through the
360 SystemExec class."""
360 SystemExec class."""
361
361
362 if verbose or debug: print header+cmd
362 if verbose or debug: print header+cmd
363 if not cmd:
363 if not cmd:
364 if split:
364 if split:
365 return [],[]
365 return [],[]
366 else:
366 else:
367 return '',''
367 return '',''
368 if not debug:
368 if not debug:
369 pin,pout,perr = os.popen3(cmd)
369 pin,pout,perr = os.popen3(cmd)
370 tout = pout.read().rstrip()
370 tout = pout.read().rstrip()
371 terr = perr.read().rstrip()
371 terr = perr.read().rstrip()
372 pin.close()
372 pin.close()
373 pout.close()
373 pout.close()
374 perr.close()
374 perr.close()
375 if split:
375 if split:
376 return tout.split('\n'),terr.split('\n')
376 return tout.split('\n'),terr.split('\n')
377 else:
377 else:
378 return tout,terr
378 return tout,terr
379
379
380 # for compatibility with older naming conventions
380 # for compatibility with older naming conventions
381 xsys = system
381 xsys = system
382 bq = getoutput
382 bq = getoutput
383
383
384 class SystemExec:
384 class SystemExec:
385 """Access the system and getoutput functions through a stateful interface.
385 """Access the system and getoutput functions through a stateful interface.
386
386
387 Note: here we refer to the system and getoutput functions from this
387 Note: here we refer to the system and getoutput functions from this
388 library, not the ones from the standard python library.
388 library, not the ones from the standard python library.
389
389
390 This class offers the system and getoutput functions as methods, but the
390 This class offers the system and getoutput functions as methods, but the
391 verbose, debug and header parameters can be set for the instance (at
391 verbose, debug and header parameters can be set for the instance (at
392 creation time or later) so that they don't need to be specified on each
392 creation time or later) so that they don't need to be specified on each
393 call.
393 call.
394
394
395 For efficiency reasons, there's no way to override the parameters on a
395 For efficiency reasons, there's no way to override the parameters on a
396 per-call basis other than by setting instance attributes. If you need
396 per-call basis other than by setting instance attributes. If you need
397 local overrides, it's best to directly call system() or getoutput().
397 local overrides, it's best to directly call system() or getoutput().
398
398
399 The following names are provided as alternate options:
399 The following names are provided as alternate options:
400 - xsys: alias to system
400 - xsys: alias to system
401 - bq: alias to getoutput
401 - bq: alias to getoutput
402
402
403 An instance can then be created as:
403 An instance can then be created as:
404 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
404 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
405
405
406 And used as:
406 And used as:
407 >>> sysexec.xsys('pwd')
407 >>> sysexec.xsys('pwd')
408 >>> dirlist = sysexec.bq('ls -l')
408 >>> dirlist = sysexec.bq('ls -l')
409 """
409 """
410
410
411 def __init__(self,verbose=0,debug=0,header='',split=0):
411 def __init__(self,verbose=0,debug=0,header='',split=0):
412 """Specify the instance's values for verbose, debug and header."""
412 """Specify the instance's values for verbose, debug and header."""
413 setattr_list(self,'verbose debug header split')
413 setattr_list(self,'verbose debug header split')
414
414
415 def system(self,cmd):
415 def system(self,cmd):
416 """Stateful interface to system(), with the same keyword parameters."""
416 """Stateful interface to system(), with the same keyword parameters."""
417
417
418 system(cmd,self.verbose,self.debug,self.header)
418 system(cmd,self.verbose,self.debug,self.header)
419
419
420 def shell(self,cmd):
420 def shell(self,cmd):
421 """Stateful interface to shell(), with the same keyword parameters."""
421 """Stateful interface to shell(), with the same keyword parameters."""
422
422
423 shell(cmd,self.verbose,self.debug,self.header)
423 shell(cmd,self.verbose,self.debug,self.header)
424
424
425 xsys = system # alias
425 xsys = system # alias
426
426
427 def getoutput(self,cmd):
427 def getoutput(self,cmd):
428 """Stateful interface to getoutput()."""
428 """Stateful interface to getoutput()."""
429
429
430 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
430 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
431
431
432 def getoutputerror(self,cmd):
432 def getoutputerror(self,cmd):
433 """Stateful interface to getoutputerror()."""
433 """Stateful interface to getoutputerror()."""
434
434
435 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
435 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
436
436
437 bq = getoutput # alias
437 bq = getoutput # alias
438
438
439 #-----------------------------------------------------------------------------
439 #-----------------------------------------------------------------------------
440 def mutex_opts(dict,ex_op):
440 def mutex_opts(dict,ex_op):
441 """Check for presence of mutually exclusive keys in a dict.
441 """Check for presence of mutually exclusive keys in a dict.
442
442
443 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
443 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
444 for op1,op2 in ex_op:
444 for op1,op2 in ex_op:
445 if op1 in dict and op2 in dict:
445 if op1 in dict and op2 in dict:
446 raise ValueError,'\n*** ERROR in Arguments *** '\
446 raise ValueError,'\n*** ERROR in Arguments *** '\
447 'Options '+op1+' and '+op2+' are mutually exclusive.'
447 'Options '+op1+' and '+op2+' are mutually exclusive.'
448
448
449 #-----------------------------------------------------------------------------
449 #-----------------------------------------------------------------------------
450 def get_py_filename(name):
450 def get_py_filename(name):
451 """Return a valid python filename in the current directory.
451 """Return a valid python filename in the current directory.
452
452
453 If the given name is not a file, it adds '.py' and searches again.
453 If the given name is not a file, it adds '.py' and searches again.
454 Raises IOError with an informative message if the file isn't found."""
454 Raises IOError with an informative message if the file isn't found."""
455
455
456 name = os.path.expanduser(name)
456 name = os.path.expanduser(name)
457 if not os.path.isfile(name) and not name.endswith('.py'):
457 if not os.path.isfile(name) and not name.endswith('.py'):
458 name += '.py'
458 name += '.py'
459 if os.path.isfile(name):
459 if os.path.isfile(name):
460 return name
460 return name
461 else:
461 else:
462 raise IOError,'File `%s` not found.' % name
462 raise IOError,'File `%s` not found.' % name
463
463
464 #-----------------------------------------------------------------------------
464 #-----------------------------------------------------------------------------
465 def filefind(fname,alt_dirs = None):
465 def filefind(fname,alt_dirs = None):
466 """Return the given filename either in the current directory, if it
466 """Return the given filename either in the current directory, if it
467 exists, or in a specified list of directories.
467 exists, or in a specified list of directories.
468
468
469 ~ expansion is done on all file and directory names.
469 ~ expansion is done on all file and directory names.
470
470
471 Upon an unsuccessful search, raise an IOError exception."""
471 Upon an unsuccessful search, raise an IOError exception."""
472
472
473 if alt_dirs is None:
473 if alt_dirs is None:
474 try:
474 try:
475 alt_dirs = get_home_dir()
475 alt_dirs = get_home_dir()
476 except HomeDirError:
476 except HomeDirError:
477 alt_dirs = os.getcwd()
477 alt_dirs = os.getcwd()
478 search = [fname] + list_strings(alt_dirs)
478 search = [fname] + list_strings(alt_dirs)
479 search = map(os.path.expanduser,search)
479 search = map(os.path.expanduser,search)
480 #print 'search list for',fname,'list:',search # dbg
480 #print 'search list for',fname,'list:',search # dbg
481 fname = search[0]
481 fname = search[0]
482 if os.path.isfile(fname):
482 if os.path.isfile(fname):
483 return fname
483 return fname
484 for direc in search[1:]:
484 for direc in search[1:]:
485 testname = os.path.join(direc,fname)
485 testname = os.path.join(direc,fname)
486 #print 'testname',testname # dbg
486 #print 'testname',testname # dbg
487 if os.path.isfile(testname):
487 if os.path.isfile(testname):
488 return testname
488 return testname
489 raise IOError,'File' + `fname` + \
489 raise IOError,'File' + `fname` + \
490 ' not found in current or supplied directories:' + `alt_dirs`
490 ' not found in current or supplied directories:' + `alt_dirs`
491
491
492 #----------------------------------------------------------------------------
492 #----------------------------------------------------------------------------
493 def file_read(filename):
493 def file_read(filename):
494 """Read a file and close it. Returns the file source."""
494 """Read a file and close it. Returns the file source."""
495 fobj=open(filename,'r');
495 fobj=open(filename,'r');
496 source = fobj.read();
496 source = fobj.read();
497 fobj.close()
497 fobj.close()
498 return source
498 return source
499
499
500 #----------------------------------------------------------------------------
500 #----------------------------------------------------------------------------
501 def target_outdated(target,deps):
501 def target_outdated(target,deps):
502 """Determine whether a target is out of date.
502 """Determine whether a target is out of date.
503
503
504 target_outdated(target,deps) -> 1/0
504 target_outdated(target,deps) -> 1/0
505
505
506 deps: list of filenames which MUST exist.
506 deps: list of filenames which MUST exist.
507 target: single filename which may or may not exist.
507 target: single filename which may or may not exist.
508
508
509 If target doesn't exist or is older than any file listed in deps, return
509 If target doesn't exist or is older than any file listed in deps, return
510 true, otherwise return false.
510 true, otherwise return false.
511 """
511 """
512 try:
512 try:
513 target_time = os.path.getmtime(target)
513 target_time = os.path.getmtime(target)
514 except os.error:
514 except os.error:
515 return 1
515 return 1
516 for dep in deps:
516 for dep in deps:
517 dep_time = os.path.getmtime(dep)
517 dep_time = os.path.getmtime(dep)
518 if dep_time > target_time:
518 if dep_time > target_time:
519 #print "For target",target,"Dep failed:",dep # dbg
519 #print "For target",target,"Dep failed:",dep # dbg
520 #print "times (dep,tar):",dep_time,target_time # dbg
520 #print "times (dep,tar):",dep_time,target_time # dbg
521 return 1
521 return 1
522 return 0
522 return 0
523
523
524 #-----------------------------------------------------------------------------
524 #-----------------------------------------------------------------------------
525 def target_update(target,deps,cmd):
525 def target_update(target,deps,cmd):
526 """Update a target with a given command given a list of dependencies.
526 """Update a target with a given command given a list of dependencies.
527
527
528 target_update(target,deps,cmd) -> runs cmd if target is outdated.
528 target_update(target,deps,cmd) -> runs cmd if target is outdated.
529
529
530 This is just a wrapper around target_outdated() which calls the given
530 This is just a wrapper around target_outdated() which calls the given
531 command if target is outdated."""
531 command if target is outdated."""
532
532
533 if target_outdated(target,deps):
533 if target_outdated(target,deps):
534 xsys(cmd)
534 xsys(cmd)
535
535
536 #----------------------------------------------------------------------------
536 #----------------------------------------------------------------------------
537 def unquote_ends(istr):
537 def unquote_ends(istr):
538 """Remove a single pair of quotes from the endpoints of a string."""
538 """Remove a single pair of quotes from the endpoints of a string."""
539
539
540 if not istr:
540 if not istr:
541 return istr
541 return istr
542 if (istr[0]=="'" and istr[-1]=="'") or \
542 if (istr[0]=="'" and istr[-1]=="'") or \
543 (istr[0]=='"' and istr[-1]=='"'):
543 (istr[0]=='"' and istr[-1]=='"'):
544 return istr[1:-1]
544 return istr[1:-1]
545 else:
545 else:
546 return istr
546 return istr
547
547
548 #----------------------------------------------------------------------------
548 #----------------------------------------------------------------------------
549 def process_cmdline(argv,names=[],defaults={},usage=''):
549 def process_cmdline(argv,names=[],defaults={},usage=''):
550 """ Process command-line options and arguments.
550 """ Process command-line options and arguments.
551
551
552 Arguments:
552 Arguments:
553
553
554 - argv: list of arguments, typically sys.argv.
554 - argv: list of arguments, typically sys.argv.
555
555
556 - names: list of option names. See DPyGetOpt docs for details on options
556 - names: list of option names. See DPyGetOpt docs for details on options
557 syntax.
557 syntax.
558
558
559 - defaults: dict of default values.
559 - defaults: dict of default values.
560
560
561 - usage: optional usage notice to print if a wrong argument is passed.
561 - usage: optional usage notice to print if a wrong argument is passed.
562
562
563 Return a dict of options and a list of free arguments."""
563 Return a dict of options and a list of free arguments."""
564
564
565 getopt = DPyGetOpt.DPyGetOpt()
565 getopt = DPyGetOpt.DPyGetOpt()
566 getopt.setIgnoreCase(0)
566 getopt.setIgnoreCase(0)
567 getopt.parseConfiguration(names)
567 getopt.parseConfiguration(names)
568
568
569 try:
569 try:
570 getopt.processArguments(argv)
570 getopt.processArguments(argv)
571 except:
571 except:
572 print usage
572 print usage
573 warn(`sys.exc_value`,level=4)
573 warn(`sys.exc_value`,level=4)
574
574
575 defaults.update(getopt.optionValues)
575 defaults.update(getopt.optionValues)
576 args = getopt.freeValues
576 args = getopt.freeValues
577
577
578 return defaults,args
578 return defaults,args
579
579
580 #----------------------------------------------------------------------------
580 #----------------------------------------------------------------------------
581 def optstr2types(ostr):
581 def optstr2types(ostr):
582 """Convert a string of option names to a dict of type mappings.
582 """Convert a string of option names to a dict of type mappings.
583
583
584 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
584 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
585
585
586 This is used to get the types of all the options in a string formatted
586 This is used to get the types of all the options in a string formatted
587 with the conventions of DPyGetOpt. The 'type' None is used for options
587 with the conventions of DPyGetOpt. The 'type' None is used for options
588 which are strings (they need no further conversion). This function's main
588 which are strings (they need no further conversion). This function's main
589 use is to get a typemap for use with read_dict().
589 use is to get a typemap for use with read_dict().
590 """
590 """
591
591
592 typeconv = {None:'',int:'',float:''}
592 typeconv = {None:'',int:'',float:''}
593 typemap = {'s':None,'i':int,'f':float}
593 typemap = {'s':None,'i':int,'f':float}
594 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
594 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
595
595
596 for w in ostr.split():
596 for w in ostr.split():
597 oname,alias,otype = opt_re.match(w).groups()
597 oname,alias,otype = opt_re.match(w).groups()
598 if otype == '' or alias == '!': # simple switches are integers too
598 if otype == '' or alias == '!': # simple switches are integers too
599 otype = 'i'
599 otype = 'i'
600 typeconv[typemap[otype]] += oname + ' '
600 typeconv[typemap[otype]] += oname + ' '
601 return typeconv
601 return typeconv
602
602
603 #----------------------------------------------------------------------------
603 #----------------------------------------------------------------------------
604 def read_dict(filename,type_conv=None,**opt):
604 def read_dict(filename,type_conv=None,**opt):
605
605
606 """Read a dictionary of key=value pairs from an input file, optionally
606 """Read a dictionary of key=value pairs from an input file, optionally
607 performing conversions on the resulting values.
607 performing conversions on the resulting values.
608
608
609 read_dict(filename,type_conv,**opt) -> dict
609 read_dict(filename,type_conv,**opt) -> dict
610
610
611 Only one value per line is accepted, the format should be
611 Only one value per line is accepted, the format should be
612 # optional comments are ignored
612 # optional comments are ignored
613 key value\n
613 key value\n
614
614
615 Args:
615 Args:
616
616
617 - type_conv: A dictionary specifying which keys need to be converted to
617 - type_conv: A dictionary specifying which keys need to be converted to
618 which types. By default all keys are read as strings. This dictionary
618 which types. By default all keys are read as strings. This dictionary
619 should have as its keys valid conversion functions for strings
619 should have as its keys valid conversion functions for strings
620 (int,long,float,complex, or your own). The value for each key
620 (int,long,float,complex, or your own). The value for each key
621 (converter) should be a whitespace separated string containing the names
621 (converter) should be a whitespace separated string containing the names
622 of all the entries in the file to be converted using that function. For
622 of all the entries in the file to be converted using that function. For
623 keys to be left alone, use None as the conversion function (only needed
623 keys to be left alone, use None as the conversion function (only needed
624 with purge=1, see below).
624 with purge=1, see below).
625
625
626 - opt: dictionary with extra options as below (default in parens)
626 - opt: dictionary with extra options as below (default in parens)
627
627
628 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
628 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
629 of the dictionary to be returned. If purge is going to be used, the
629 of the dictionary to be returned. If purge is going to be used, the
630 set of keys to be left as strings also has to be explicitly specified
630 set of keys to be left as strings also has to be explicitly specified
631 using the (non-existent) conversion function None.
631 using the (non-existent) conversion function None.
632
632
633 fs(None): field separator. This is the key/value separator to be used
633 fs(None): field separator. This is the key/value separator to be used
634 when parsing the file. The None default means any whitespace [behavior
634 when parsing the file. The None default means any whitespace [behavior
635 of string.split()].
635 of string.split()].
636
636
637 strip(0): if 1, strip string values of leading/trailinig whitespace.
637 strip(0): if 1, strip string values of leading/trailinig whitespace.
638
638
639 warn(1): warning level if requested keys are not found in file.
639 warn(1): warning level if requested keys are not found in file.
640 - 0: silently ignore.
640 - 0: silently ignore.
641 - 1: inform but proceed.
641 - 1: inform but proceed.
642 - 2: raise KeyError exception.
642 - 2: raise KeyError exception.
643
643
644 no_empty(0): if 1, remove keys with whitespace strings as a value.
644 no_empty(0): if 1, remove keys with whitespace strings as a value.
645
645
646 unique([]): list of keys (or space separated string) which can't be
646 unique([]): list of keys (or space separated string) which can't be
647 repeated. If one such key is found in the file, each new instance
647 repeated. If one such key is found in the file, each new instance
648 overwrites the previous one. For keys not listed here, the behavior is
648 overwrites the previous one. For keys not listed here, the behavior is
649 to make a list of all appearances.
649 to make a list of all appearances.
650
650
651 Example:
651 Example:
652 If the input file test.ini has:
652 If the input file test.ini has:
653 i 3
653 i 3
654 x 4.5
654 x 4.5
655 y 5.5
655 y 5.5
656 s hi ho
656 s hi ho
657 Then:
657 Then:
658
658
659 >>> type_conv={int:'i',float:'x',None:'s'}
659 >>> type_conv={int:'i',float:'x',None:'s'}
660 >>> read_dict('test.ini')
660 >>> read_dict('test.ini')
661 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
661 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
662 >>> read_dict('test.ini',type_conv)
662 >>> read_dict('test.ini',type_conv)
663 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
663 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
664 >>> read_dict('test.ini',type_conv,purge=1)
664 >>> read_dict('test.ini',type_conv,purge=1)
665 {'i': 3, 's': 'hi ho', 'x': 4.5}
665 {'i': 3, 's': 'hi ho', 'x': 4.5}
666 """
666 """
667
667
668 # starting config
668 # starting config
669 opt.setdefault('purge',0)
669 opt.setdefault('purge',0)
670 opt.setdefault('fs',None) # field sep defaults to any whitespace
670 opt.setdefault('fs',None) # field sep defaults to any whitespace
671 opt.setdefault('strip',0)
671 opt.setdefault('strip',0)
672 opt.setdefault('warn',1)
672 opt.setdefault('warn',1)
673 opt.setdefault('no_empty',0)
673 opt.setdefault('no_empty',0)
674 opt.setdefault('unique','')
674 opt.setdefault('unique','')
675 if type(opt['unique']) in StringTypes:
675 if type(opt['unique']) in StringTypes:
676 unique_keys = qw(opt['unique'])
676 unique_keys = qw(opt['unique'])
677 elif type(opt['unique']) in (types.TupleType,types.ListType):
677 elif type(opt['unique']) in (types.TupleType,types.ListType):
678 unique_keys = opt['unique']
678 unique_keys = opt['unique']
679 else:
679 else:
680 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
680 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
681
681
682 dict = {}
682 dict = {}
683 # first read in table of values as strings
683 # first read in table of values as strings
684 file = open(filename,'r')
684 file = open(filename,'r')
685 for line in file.readlines():
685 for line in file.readlines():
686 line = line.strip()
686 line = line.strip()
687 if len(line) and line[0]=='#': continue
687 if len(line) and line[0]=='#': continue
688 if len(line)>0:
688 if len(line)>0:
689 lsplit = line.split(opt['fs'],1)
689 lsplit = line.split(opt['fs'],1)
690 try:
690 try:
691 key,val = lsplit
691 key,val = lsplit
692 except ValueError:
692 except ValueError:
693 key,val = lsplit[0],''
693 key,val = lsplit[0],''
694 key = key.strip()
694 key = key.strip()
695 if opt['strip']: val = val.strip()
695 if opt['strip']: val = val.strip()
696 if val == "''" or val == '""': val = ''
696 if val == "''" or val == '""': val = ''
697 if opt['no_empty'] and (val=='' or val.isspace()):
697 if opt['no_empty'] and (val=='' or val.isspace()):
698 continue
698 continue
699 # if a key is found more than once in the file, build a list
699 # if a key is found more than once in the file, build a list
700 # unless it's in the 'unique' list. In that case, last found in file
700 # unless it's in the 'unique' list. In that case, last found in file
701 # takes precedence. User beware.
701 # takes precedence. User beware.
702 try:
702 try:
703 if dict[key] and key in unique_keys:
703 if dict[key] and key in unique_keys:
704 dict[key] = val
704 dict[key] = val
705 elif type(dict[key]) is types.ListType:
705 elif type(dict[key]) is types.ListType:
706 dict[key].append(val)
706 dict[key].append(val)
707 else:
707 else:
708 dict[key] = [dict[key],val]
708 dict[key] = [dict[key],val]
709 except KeyError:
709 except KeyError:
710 dict[key] = val
710 dict[key] = val
711 # purge if requested
711 # purge if requested
712 if opt['purge']:
712 if opt['purge']:
713 accepted_keys = qwflat(type_conv.values())
713 accepted_keys = qwflat(type_conv.values())
714 for key in dict.keys():
714 for key in dict.keys():
715 if key in accepted_keys: continue
715 if key in accepted_keys: continue
716 del(dict[key])
716 del(dict[key])
717 # now convert if requested
717 # now convert if requested
718 if type_conv==None: return dict
718 if type_conv==None: return dict
719 conversions = type_conv.keys()
719 conversions = type_conv.keys()
720 try: conversions.remove(None)
720 try: conversions.remove(None)
721 except: pass
721 except: pass
722 for convert in conversions:
722 for convert in conversions:
723 for val in qw(type_conv[convert]):
723 for val in qw(type_conv[convert]):
724 try:
724 try:
725 dict[val] = convert(dict[val])
725 dict[val] = convert(dict[val])
726 except KeyError,e:
726 except KeyError,e:
727 if opt['warn'] == 0:
727 if opt['warn'] == 0:
728 pass
728 pass
729 elif opt['warn'] == 1:
729 elif opt['warn'] == 1:
730 print >>sys.stderr, 'Warning: key',val,\
730 print >>sys.stderr, 'Warning: key',val,\
731 'not found in file',filename
731 'not found in file',filename
732 elif opt['warn'] == 2:
732 elif opt['warn'] == 2:
733 raise KeyError,e
733 raise KeyError,e
734 else:
734 else:
735 raise ValueError,'Warning level must be 0,1 or 2'
735 raise ValueError,'Warning level must be 0,1 or 2'
736
736
737 return dict
737 return dict
738
738
739 #----------------------------------------------------------------------------
739 #----------------------------------------------------------------------------
740 def flag_calls(func):
740 def flag_calls(func):
741 """Wrap a function to detect and flag when it gets called.
741 """Wrap a function to detect and flag when it gets called.
742
742
743 This is a decorator which takes a function and wraps it in a function with
743 This is a decorator which takes a function and wraps it in a function with
744 a 'called' attribute. wrapper.called is initialized to False.
744 a 'called' attribute. wrapper.called is initialized to False.
745
745
746 The wrapper.called attribute is set to False right before each call to the
746 The wrapper.called attribute is set to False right before each call to the
747 wrapped function, so if the call fails it remains False. After the call
747 wrapped function, so if the call fails it remains False. After the call
748 completes, wrapper.called is set to True and the output is returned.
748 completes, wrapper.called is set to True and the output is returned.
749
749
750 Testing for truth in wrapper.called allows you to determine if a call to
750 Testing for truth in wrapper.called allows you to determine if a call to
751 func() was attempted and succeeded."""
751 func() was attempted and succeeded."""
752
752
753 def wrapper(*args,**kw):
753 def wrapper(*args,**kw):
754 wrapper.called = False
754 wrapper.called = False
755 out = func(*args,**kw)
755 out = func(*args,**kw)
756 wrapper.called = True
756 wrapper.called = True
757 return out
757 return out
758
758
759 wrapper.called = False
759 wrapper.called = False
760 wrapper.__doc__ = func.__doc__
760 wrapper.__doc__ = func.__doc__
761 return wrapper
761 return wrapper
762
762
763 #----------------------------------------------------------------------------
763 #----------------------------------------------------------------------------
764 class HomeDirError(Error):
764 class HomeDirError(Error):
765 pass
765 pass
766
766
767 def get_home_dir():
767 def get_home_dir():
768 """Return the closest possible equivalent to a 'home' directory.
768 """Return the closest possible equivalent to a 'home' directory.
769
769
770 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
770 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
771
771
772 Currently only Posix and NT are implemented, a HomeDirError exception is
772 Currently only Posix and NT are implemented, a HomeDirError exception is
773 raised for all other OSes. """
773 raised for all other OSes. """
774
774
775 isdir = os.path.isdir
775 isdir = os.path.isdir
776 env = os.environ
776 env = os.environ
777 try:
777 try:
778 homedir = env['HOME']
778 homedir = env['HOME']
779 if not isdir(homedir):
779 if not isdir(homedir):
780 # in case a user stuck some string which does NOT resolve to a
780 # in case a user stuck some string which does NOT resolve to a
781 # valid path, it's as good as if we hadn't foud it
781 # valid path, it's as good as if we hadn't foud it
782 raise KeyError
782 raise KeyError
783 return homedir
783 return homedir
784 except KeyError:
784 except KeyError:
785 if os.name == 'posix':
785 if os.name == 'posix':
786 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
786 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
787 elif os.name == 'nt':
787 elif os.name == 'nt':
788 # For some strange reason, win9x returns 'nt' for os.name.
788 # For some strange reason, win9x returns 'nt' for os.name.
789 try:
789 try:
790 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
790 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
791 if not isdir(homedir):
791 if not isdir(homedir):
792 homedir = os.path.join(env['USERPROFILE'])
792 homedir = os.path.join(env['USERPROFILE'])
793 if not isdir(homedir):
793 if not isdir(homedir):
794 raise HomeDirError
794 raise HomeDirError
795 return homedir
795 return homedir
796 except:
796 except:
797 try:
797 try:
798 # Use the registry to get the 'My Documents' folder.
798 # Use the registry to get the 'My Documents' folder.
799 import _winreg as wreg
799 import _winreg as wreg
800 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
800 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
801 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
801 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
802 homedir = wreg.QueryValueEx(key,'Personal')[0]
802 homedir = wreg.QueryValueEx(key,'Personal')[0]
803 key.Close()
803 key.Close()
804 if not isdir(homedir):
804 if not isdir(homedir):
805 e = ('Invalid "Personal" folder registry key '
805 e = ('Invalid "Personal" folder registry key '
806 'typically "My Documents".\n'
806 'typically "My Documents".\n'
807 'Value: %s\n'
807 'Value: %s\n'
808 'This is not a valid directory on your system.' %
808 'This is not a valid directory on your system.' %
809 homedir)
809 homedir)
810 raise HomeDirError(e)
810 raise HomeDirError(e)
811 return homedir
811 return homedir
812 except HomeDirError:
812 except HomeDirError:
813 raise
813 raise
814 except:
814 except:
815 return 'C:\\'
815 return 'C:\\'
816 elif os.name == 'dos':
816 elif os.name == 'dos':
817 # Desperate, may do absurd things in classic MacOS. May work under DOS.
817 # Desperate, may do absurd things in classic MacOS. May work under DOS.
818 return 'C:\\'
818 return 'C:\\'
819 else:
819 else:
820 raise HomeDirError,'support for your operating system not implemented.'
820 raise HomeDirError,'support for your operating system not implemented.'
821
821
822 #****************************************************************************
822 #****************************************************************************
823 # strings and text
823 # strings and text
824
824
825 class LSString(str):
825 class LSString(str):
826 """String derivative with a special access attributes.
826 """String derivative with a special access attributes.
827
827
828 These are normal strings, but with the special attributes:
828 These are normal strings, but with the special attributes:
829
829
830 .l (or .list) : value as list (split on newlines).
830 .l (or .list) : value as list (split on newlines).
831 .n (or .nlstr): original value (the string itself).
831 .n (or .nlstr): original value (the string itself).
832 .s (or .spstr): value as whitespace-separated string.
832 .s (or .spstr): value as whitespace-separated string.
833
833
834 Any values which require transformations are computed only once and
834 Any values which require transformations are computed only once and
835 cached.
835 cached.
836
836
837 Such strings are very useful to efficiently interact with the shell, which
837 Such strings are very useful to efficiently interact with the shell, which
838 typically only understands whitespace-separated options for commands."""
838 typically only understands whitespace-separated options for commands."""
839
839
840 def get_list(self):
840 def get_list(self):
841 try:
841 try:
842 return self.__list
842 return self.__list
843 except AttributeError:
843 except AttributeError:
844 self.__list = self.split('\n')
844 self.__list = self.split('\n')
845 return self.__list
845 return self.__list
846
846
847 l = list = property(get_list)
847 l = list = property(get_list)
848
848
849 def get_spstr(self):
849 def get_spstr(self):
850 try:
850 try:
851 return self.__spstr
851 return self.__spstr
852 except AttributeError:
852 except AttributeError:
853 self.__spstr = self.replace('\n',' ')
853 self.__spstr = self.replace('\n',' ')
854 return self.__spstr
854 return self.__spstr
855
855
856 s = spstr = property(get_spstr)
856 s = spstr = property(get_spstr)
857
857
858 def get_nlstr(self):
858 def get_nlstr(self):
859 return self
859 return self
860
860
861 n = nlstr = property(get_nlstr)
861 n = nlstr = property(get_nlstr)
862
862
863 class SList(list):
863 class SList(list):
864 """List derivative with a special access attributes.
864 """List derivative with a special access attributes.
865
865
866 These are normal lists, but with the special attributes:
866 These are normal lists, but with the special attributes:
867
867
868 .l (or .list) : value as list (the list itself).
868 .l (or .list) : value as list (the list itself).
869 .n (or .nlstr): value as a string, joined on newlines.
869 .n (or .nlstr): value as a string, joined on newlines.
870 .s (or .spstr): value as a string, joined on spaces.
870 .s (or .spstr): value as a string, joined on spaces.
871
871
872 Any values which require transformations are computed only once and
872 Any values which require transformations are computed only once and
873 cached."""
873 cached."""
874
874
875 def get_list(self):
875 def get_list(self):
876 return self
876 return self
877
877
878 l = list = property(get_list)
878 l = list = property(get_list)
879
879
880 def get_spstr(self):
880 def get_spstr(self):
881 try:
881 try:
882 return self.__spstr
882 return self.__spstr
883 except AttributeError:
883 except AttributeError:
884 self.__spstr = ' '.join(self)
884 self.__spstr = ' '.join(self)
885 return self.__spstr
885 return self.__spstr
886
886
887 s = spstr = property(get_spstr)
887 s = spstr = property(get_spstr)
888
888
889 def get_nlstr(self):
889 def get_nlstr(self):
890 try:
890 try:
891 return self.__nlstr
891 return self.__nlstr
892 except AttributeError:
892 except AttributeError:
893 self.__nlstr = '\n'.join(self)
893 self.__nlstr = '\n'.join(self)
894 return self.__nlstr
894 return self.__nlstr
895
895
896 n = nlstr = property(get_nlstr)
896 n = nlstr = property(get_nlstr)
897
897
898 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
898 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
899 """Take multiple lines of input.
899 """Take multiple lines of input.
900
900
901 A list with each line of input as a separate element is returned when a
901 A list with each line of input as a separate element is returned when a
902 termination string is entered (defaults to a single '.'). Input can also
902 termination string is entered (defaults to a single '.'). Input can also
903 terminate via EOF (^D in Unix, ^Z-RET in Windows).
903 terminate via EOF (^D in Unix, ^Z-RET in Windows).
904
904
905 Lines of input which end in \\ are joined into single entries (and a
905 Lines of input which end in \\ are joined into single entries (and a
906 secondary continuation prompt is issued as long as the user terminates
906 secondary continuation prompt is issued as long as the user terminates
907 lines with \\). This allows entering very long strings which are still
907 lines with \\). This allows entering very long strings which are still
908 meant to be treated as single entities.
908 meant to be treated as single entities.
909 """
909 """
910
910
911 try:
911 try:
912 if header:
912 if header:
913 header += '\n'
913 header += '\n'
914 lines = [raw_input(header + ps1)]
914 lines = [raw_input(header + ps1)]
915 except EOFError:
915 except EOFError:
916 return []
916 return []
917 terminate = [terminate_str]
917 terminate = [terminate_str]
918 try:
918 try:
919 while lines[-1:] != terminate:
919 while lines[-1:] != terminate:
920 new_line = raw_input(ps1)
920 new_line = raw_input(ps1)
921 while new_line.endswith('\\'):
921 while new_line.endswith('\\'):
922 new_line = new_line[:-1] + raw_input(ps2)
922 new_line = new_line[:-1] + raw_input(ps2)
923 lines.append(new_line)
923 lines.append(new_line)
924
924
925 return lines[:-1] # don't return the termination command
925 return lines[:-1] # don't return the termination command
926 except EOFError:
926 except EOFError:
927 print
927 print
928 return lines
928 return lines
929
929
930 #----------------------------------------------------------------------------
930 #----------------------------------------------------------------------------
931 def raw_input_ext(prompt='', ps2='... '):
931 def raw_input_ext(prompt='', ps2='... '):
932 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
932 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
933
933
934 line = raw_input(prompt)
934 line = raw_input(prompt)
935 while line.endswith('\\'):
935 while line.endswith('\\'):
936 line = line[:-1] + raw_input(ps2)
936 line = line[:-1] + raw_input(ps2)
937 return line
937 return line
938
938
939 #----------------------------------------------------------------------------
939 #----------------------------------------------------------------------------
940 def ask_yes_no(prompt,default=None):
940 def ask_yes_no(prompt,default=None):
941 """Asks a question and returns an integer 1/0 (y/n) answer.
941 """Asks a question and returns an integer 1/0 (y/n) answer.
942
942
943 If default is given (one of 'y','n'), it is used if the user input is
943 If default is given (one of 'y','n'), it is used if the user input is
944 empty. Otherwise the question is repeated until an answer is given.
944 empty. Otherwise the question is repeated until an answer is given.
945 If EOF occurs 20 times consecutively, the default answer is assumed,
945 If EOF occurs 20 times consecutively, the default answer is assumed,
946 or if there is no default, an exception is raised to prevent infinite
946 or if there is no default, an exception is raised to prevent infinite
947 loops.
947 loops.
948
948
949 Valid answers are: y/yes/n/no (match is not case sensitive)."""
949 Valid answers are: y/yes/n/no (match is not case sensitive)."""
950
950
951 answers = {'y':1,'n':0,'yes':1,'no':0}
951 answers = {'y':True,'n':False,'yes':True,'no':False}
952 ans = None
952 ans = None
953 eofs, max_eofs = 0, 20
953 eofs, max_eofs = 0, 20
954 while ans not in answers.keys():
954 while ans not in answers.keys():
955 try:
955 try:
956 ans = raw_input(prompt+' ').lower()
956 ans = raw_input(prompt+' ').lower()
957 if not ans: # response was an empty string
957 if not ans: # response was an empty string
958 ans = default
958 ans = default
959 eofs = 0
959 eofs = 0
960 except (EOFError,KeyboardInterrupt):
960 except (EOFError,KeyboardInterrupt):
961 eofs = eofs + 1
961 eofs = eofs + 1
962 if eofs >= max_eofs:
962 if eofs >= max_eofs:
963 if default in answers.keys():
963 if default in answers.keys():
964 ans = default
964 ans = default
965 else:
965 else:
966 raise
966 raise
967
967
968 return answers[ans]
968 return answers[ans]
969
969
970 #----------------------------------------------------------------------------
970 #----------------------------------------------------------------------------
971 def marquee(txt='',width=78,mark='*'):
971 def marquee(txt='',width=78,mark='*'):
972 """Return the input string centered in a 'marquee'."""
972 """Return the input string centered in a 'marquee'."""
973 if not txt:
973 if not txt:
974 return (mark*width)[:width]
974 return (mark*width)[:width]
975 nmark = (width-len(txt)-2)/len(mark)/2
975 nmark = (width-len(txt)-2)/len(mark)/2
976 if nmark < 0: nmark =0
976 if nmark < 0: nmark =0
977 marks = mark*nmark
977 marks = mark*nmark
978 return '%s %s %s' % (marks,txt,marks)
978 return '%s %s %s' % (marks,txt,marks)
979
979
980 #----------------------------------------------------------------------------
980 #----------------------------------------------------------------------------
981 class EvalDict:
981 class EvalDict:
982 """
982 """
983 Emulate a dict which evaluates its contents in the caller's frame.
983 Emulate a dict which evaluates its contents in the caller's frame.
984
984
985 Usage:
985 Usage:
986 >>>number = 19
986 >>>number = 19
987 >>>text = "python"
987 >>>text = "python"
988 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
988 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
989 """
989 """
990
990
991 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
991 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
992 # modified (shorter) version of:
992 # modified (shorter) version of:
993 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
993 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
994 # Skip Montanaro (skip@pobox.com).
994 # Skip Montanaro (skip@pobox.com).
995
995
996 def __getitem__(self, name):
996 def __getitem__(self, name):
997 frame = sys._getframe(1)
997 frame = sys._getframe(1)
998 return eval(name, frame.f_globals, frame.f_locals)
998 return eval(name, frame.f_globals, frame.f_locals)
999
999
1000 EvalString = EvalDict # for backwards compatibility
1000 EvalString = EvalDict # for backwards compatibility
1001 #----------------------------------------------------------------------------
1001 #----------------------------------------------------------------------------
1002 def qw(words,flat=0,sep=None,maxsplit=-1):
1002 def qw(words,flat=0,sep=None,maxsplit=-1):
1003 """Similar to Perl's qw() operator, but with some more options.
1003 """Similar to Perl's qw() operator, but with some more options.
1004
1004
1005 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1005 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1006
1006
1007 words can also be a list itself, and with flat=1, the output will be
1007 words can also be a list itself, and with flat=1, the output will be
1008 recursively flattened. Examples:
1008 recursively flattened. Examples:
1009
1009
1010 >>> qw('1 2')
1010 >>> qw('1 2')
1011 ['1', '2']
1011 ['1', '2']
1012 >>> qw(['a b','1 2',['m n','p q']])
1012 >>> qw(['a b','1 2',['m n','p q']])
1013 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1013 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1014 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1014 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1015 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1015 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1016
1016
1017 if type(words) in StringTypes:
1017 if type(words) in StringTypes:
1018 return [word.strip() for word in words.split(sep,maxsplit)
1018 return [word.strip() for word in words.split(sep,maxsplit)
1019 if word and not word.isspace() ]
1019 if word and not word.isspace() ]
1020 if flat:
1020 if flat:
1021 return flatten(map(qw,words,[1]*len(words)))
1021 return flatten(map(qw,words,[1]*len(words)))
1022 return map(qw,words)
1022 return map(qw,words)
1023
1023
1024 #----------------------------------------------------------------------------
1024 #----------------------------------------------------------------------------
1025 def qwflat(words,sep=None,maxsplit=-1):
1025 def qwflat(words,sep=None,maxsplit=-1):
1026 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1026 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1027 return qw(words,1,sep,maxsplit)
1027 return qw(words,1,sep,maxsplit)
1028
1028
1029 #-----------------------------------------------------------------------------
1029 #-----------------------------------------------------------------------------
1030 def list_strings(arg):
1030 def list_strings(arg):
1031 """Always return a list of strings, given a string or list of strings
1031 """Always return a list of strings, given a string or list of strings
1032 as input."""
1032 as input."""
1033
1033
1034 if type(arg) in StringTypes: return [arg]
1034 if type(arg) in StringTypes: return [arg]
1035 else: return arg
1035 else: return arg
1036
1036
1037 #----------------------------------------------------------------------------
1037 #----------------------------------------------------------------------------
1038 def grep(pat,list,case=1):
1038 def grep(pat,list,case=1):
1039 """Simple minded grep-like function.
1039 """Simple minded grep-like function.
1040 grep(pat,list) returns occurrences of pat in list, None on failure.
1040 grep(pat,list) returns occurrences of pat in list, None on failure.
1041
1041
1042 It only does simple string matching, with no support for regexps. Use the
1042 It only does simple string matching, with no support for regexps. Use the
1043 option case=0 for case-insensitive matching."""
1043 option case=0 for case-insensitive matching."""
1044
1044
1045 # This is pretty crude. At least it should implement copying only references
1045 # This is pretty crude. At least it should implement copying only references
1046 # to the original data in case it's big. Now it copies the data for output.
1046 # to the original data in case it's big. Now it copies the data for output.
1047 out=[]
1047 out=[]
1048 if case:
1048 if case:
1049 for term in list:
1049 for term in list:
1050 if term.find(pat)>-1: out.append(term)
1050 if term.find(pat)>-1: out.append(term)
1051 else:
1051 else:
1052 lpat=pat.lower()
1052 lpat=pat.lower()
1053 for term in list:
1053 for term in list:
1054 if term.lower().find(lpat)>-1: out.append(term)
1054 if term.lower().find(lpat)>-1: out.append(term)
1055
1055
1056 if len(out): return out
1056 if len(out): return out
1057 else: return None
1057 else: return None
1058
1058
1059 #----------------------------------------------------------------------------
1059 #----------------------------------------------------------------------------
1060 def dgrep(pat,*opts):
1060 def dgrep(pat,*opts):
1061 """Return grep() on dir()+dir(__builtins__).
1061 """Return grep() on dir()+dir(__builtins__).
1062
1062
1063 A very common use of grep() when working interactively."""
1063 A very common use of grep() when working interactively."""
1064
1064
1065 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1065 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1066
1066
1067 #----------------------------------------------------------------------------
1067 #----------------------------------------------------------------------------
1068 def idgrep(pat):
1068 def idgrep(pat):
1069 """Case-insensitive dgrep()"""
1069 """Case-insensitive dgrep()"""
1070
1070
1071 return dgrep(pat,0)
1071 return dgrep(pat,0)
1072
1072
1073 #----------------------------------------------------------------------------
1073 #----------------------------------------------------------------------------
1074 def igrep(pat,list):
1074 def igrep(pat,list):
1075 """Synonym for case-insensitive grep."""
1075 """Synonym for case-insensitive grep."""
1076
1076
1077 return grep(pat,list,case=0)
1077 return grep(pat,list,case=0)
1078
1078
1079 #----------------------------------------------------------------------------
1079 #----------------------------------------------------------------------------
1080 def indent(str,nspaces=4,ntabs=0):
1080 def indent(str,nspaces=4,ntabs=0):
1081 """Indent a string a given number of spaces or tabstops.
1081 """Indent a string a given number of spaces or tabstops.
1082
1082
1083 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1083 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1084 """
1084 """
1085 if str is None:
1085 if str is None:
1086 return
1086 return
1087 ind = '\t'*ntabs+' '*nspaces
1087 ind = '\t'*ntabs+' '*nspaces
1088 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1088 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1089 if outstr.endswith(os.linesep+ind):
1089 if outstr.endswith(os.linesep+ind):
1090 return outstr[:-len(ind)]
1090 return outstr[:-len(ind)]
1091 else:
1091 else:
1092 return outstr
1092 return outstr
1093
1093
1094 #-----------------------------------------------------------------------------
1094 #-----------------------------------------------------------------------------
1095 def native_line_ends(filename,backup=1):
1095 def native_line_ends(filename,backup=1):
1096 """Convert (in-place) a file to line-ends native to the current OS.
1096 """Convert (in-place) a file to line-ends native to the current OS.
1097
1097
1098 If the optional backup argument is given as false, no backup of the
1098 If the optional backup argument is given as false, no backup of the
1099 original file is left. """
1099 original file is left. """
1100
1100
1101 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1101 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1102
1102
1103 bak_filename = filename + backup_suffixes[os.name]
1103 bak_filename = filename + backup_suffixes[os.name]
1104
1104
1105 original = open(filename).read()
1105 original = open(filename).read()
1106 shutil.copy2(filename,bak_filename)
1106 shutil.copy2(filename,bak_filename)
1107 try:
1107 try:
1108 new = open(filename,'wb')
1108 new = open(filename,'wb')
1109 new.write(os.linesep.join(original.splitlines()))
1109 new.write(os.linesep.join(original.splitlines()))
1110 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1110 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1111 new.close()
1111 new.close()
1112 except:
1112 except:
1113 os.rename(bak_filename,filename)
1113 os.rename(bak_filename,filename)
1114 if not backup:
1114 if not backup:
1115 try:
1115 try:
1116 os.remove(bak_filename)
1116 os.remove(bak_filename)
1117 except:
1117 except:
1118 pass
1118 pass
1119
1119
1120 #----------------------------------------------------------------------------
1120 #----------------------------------------------------------------------------
1121 def get_pager_cmd(pager_cmd = None):
1121 def get_pager_cmd(pager_cmd = None):
1122 """Return a pager command.
1122 """Return a pager command.
1123
1123
1124 Makes some attempts at finding an OS-correct one."""
1124 Makes some attempts at finding an OS-correct one."""
1125
1125
1126 if os.name == 'posix':
1126 if os.name == 'posix':
1127 default_pager_cmd = 'less -r' # -r for color control sequences
1127 default_pager_cmd = 'less -r' # -r for color control sequences
1128 elif os.name in ['nt','dos']:
1128 elif os.name in ['nt','dos']:
1129 default_pager_cmd = 'type'
1129 default_pager_cmd = 'type'
1130
1130
1131 if pager_cmd is None:
1131 if pager_cmd is None:
1132 try:
1132 try:
1133 pager_cmd = os.environ['PAGER']
1133 pager_cmd = os.environ['PAGER']
1134 except:
1134 except:
1135 pager_cmd = default_pager_cmd
1135 pager_cmd = default_pager_cmd
1136 return pager_cmd
1136 return pager_cmd
1137
1137
1138 #-----------------------------------------------------------------------------
1138 #-----------------------------------------------------------------------------
1139 def get_pager_start(pager,start):
1139 def get_pager_start(pager,start):
1140 """Return the string for paging files with an offset.
1140 """Return the string for paging files with an offset.
1141
1141
1142 This is the '+N' argument which less and more (under Unix) accept.
1142 This is the '+N' argument which less and more (under Unix) accept.
1143 """
1143 """
1144
1144
1145 if pager in ['less','more']:
1145 if pager in ['less','more']:
1146 if start:
1146 if start:
1147 start_string = '+' + str(start)
1147 start_string = '+' + str(start)
1148 else:
1148 else:
1149 start_string = ''
1149 start_string = ''
1150 else:
1150 else:
1151 start_string = ''
1151 start_string = ''
1152 return start_string
1152 return start_string
1153
1153
1154 #----------------------------------------------------------------------------
1154 #----------------------------------------------------------------------------
1155 def page_dumb(strng,start=0,screen_lines=25):
1155 def page_dumb(strng,start=0,screen_lines=25):
1156 """Very dumb 'pager' in Python, for when nothing else works.
1156 """Very dumb 'pager' in Python, for when nothing else works.
1157
1157
1158 Only moves forward, same interface as page(), except for pager_cmd and
1158 Only moves forward, same interface as page(), except for pager_cmd and
1159 mode."""
1159 mode."""
1160
1160
1161 out_ln = strng.splitlines()[start:]
1161 out_ln = strng.splitlines()[start:]
1162 screens = chop(out_ln,screen_lines-1)
1162 screens = chop(out_ln,screen_lines-1)
1163 if len(screens) == 1:
1163 if len(screens) == 1:
1164 print >>Term.cout, os.linesep.join(screens[0])
1164 print >>Term.cout, os.linesep.join(screens[0])
1165 else:
1165 else:
1166 for scr in screens[0:-1]:
1166 for scr in screens[0:-1]:
1167 print >>Term.cout, os.linesep.join(scr)
1167 print >>Term.cout, os.linesep.join(scr)
1168 ans = raw_input('---Return to continue, q to quit--- ')
1168 ans = raw_input('---Return to continue, q to quit--- ')
1169 if ans.lower().startswith('q'):
1169 if ans.lower().startswith('q'):
1170 return
1170 return
1171 print >>Term.cout, os.linesep.join(screens[-1])
1171 print >>Term.cout, os.linesep.join(screens[-1])
1172
1172
1173 #----------------------------------------------------------------------------
1173 #----------------------------------------------------------------------------
1174 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1174 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1175 """Print a string, piping through a pager after a certain length.
1175 """Print a string, piping through a pager after a certain length.
1176
1176
1177 The screen_lines parameter specifies the number of *usable* lines of your
1177 The screen_lines parameter specifies the number of *usable* lines of your
1178 terminal screen (total lines minus lines you need to reserve to show other
1178 terminal screen (total lines minus lines you need to reserve to show other
1179 information).
1179 information).
1180
1180
1181 If you set screen_lines to a number <=0, page() will try to auto-determine
1181 If you set screen_lines to a number <=0, page() will try to auto-determine
1182 your screen size and will only use up to (screen_size+screen_lines) for
1182 your screen size and will only use up to (screen_size+screen_lines) for
1183 printing, paging after that. That is, if you want auto-detection but need
1183 printing, paging after that. That is, if you want auto-detection but need
1184 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1184 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1185 auto-detection without any lines reserved simply use screen_lines = 0.
1185 auto-detection without any lines reserved simply use screen_lines = 0.
1186
1186
1187 If a string won't fit in the allowed lines, it is sent through the
1187 If a string won't fit in the allowed lines, it is sent through the
1188 specified pager command. If none given, look for PAGER in the environment,
1188 specified pager command. If none given, look for PAGER in the environment,
1189 and ultimately default to less.
1189 and ultimately default to less.
1190
1190
1191 If no system pager works, the string is sent through a 'dumb pager'
1191 If no system pager works, the string is sent through a 'dumb pager'
1192 written in python, very simplistic.
1192 written in python, very simplistic.
1193 """
1193 """
1194
1194
1195 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1195 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1196 TERM = os.environ.get('TERM','dumb')
1196 TERM = os.environ.get('TERM','dumb')
1197 if TERM in ['dumb','emacs'] and os.name != 'nt':
1197 if TERM in ['dumb','emacs'] and os.name != 'nt':
1198 print strng
1198 print strng
1199 return
1199 return
1200 # chop off the topmost part of the string we don't want to see
1200 # chop off the topmost part of the string we don't want to see
1201 str_lines = strng.split(os.linesep)[start:]
1201 str_lines = strng.split(os.linesep)[start:]
1202 str_toprint = os.linesep.join(str_lines)
1202 str_toprint = os.linesep.join(str_lines)
1203 num_newlines = len(str_lines)
1203 num_newlines = len(str_lines)
1204 len_str = len(str_toprint)
1204 len_str = len(str_toprint)
1205
1205
1206 # Dumb heuristics to guesstimate number of on-screen lines the string
1206 # Dumb heuristics to guesstimate number of on-screen lines the string
1207 # takes. Very basic, but good enough for docstrings in reasonable
1207 # takes. Very basic, but good enough for docstrings in reasonable
1208 # terminals. If someone later feels like refining it, it's not hard.
1208 # terminals. If someone later feels like refining it, it's not hard.
1209 numlines = max(num_newlines,int(len_str/80)+1)
1209 numlines = max(num_newlines,int(len_str/80)+1)
1210
1210
1211 screen_lines_def = 25 # default value if we can't auto-determine
1211 screen_lines_def = 25 # default value if we can't auto-determine
1212
1212
1213 # auto-determine screen size
1213 # auto-determine screen size
1214 if screen_lines <= 0:
1214 if screen_lines <= 0:
1215 if TERM=='xterm':
1215 if TERM=='xterm':
1216 try:
1216 try:
1217 import curses
1217 import curses
1218 if hasattr(curses,'initscr'):
1218 if hasattr(curses,'initscr'):
1219 use_curses = 1
1219 use_curses = 1
1220 else:
1220 else:
1221 use_curses = 0
1221 use_curses = 0
1222 except ImportError:
1222 except ImportError:
1223 use_curses = 0
1223 use_curses = 0
1224 else:
1224 else:
1225 # curses causes problems on many terminals other than xterm.
1225 # curses causes problems on many terminals other than xterm.
1226 use_curses = 0
1226 use_curses = 0
1227 if use_curses:
1227 if use_curses:
1228 scr = curses.initscr()
1228 scr = curses.initscr()
1229 screen_lines_real,screen_cols = scr.getmaxyx()
1229 screen_lines_real,screen_cols = scr.getmaxyx()
1230 curses.endwin()
1230 curses.endwin()
1231 screen_lines += screen_lines_real
1231 screen_lines += screen_lines_real
1232 #print '***Screen size:',screen_lines_real,'lines x',\
1232 #print '***Screen size:',screen_lines_real,'lines x',\
1233 #screen_cols,'columns.' # dbg
1233 #screen_cols,'columns.' # dbg
1234 else:
1234 else:
1235 screen_lines += screen_lines_def
1235 screen_lines += screen_lines_def
1236
1236
1237 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1237 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1238 if numlines <= screen_lines :
1238 if numlines <= screen_lines :
1239 #print '*** normal print' # dbg
1239 #print '*** normal print' # dbg
1240 print >>Term.cout, str_toprint
1240 print >>Term.cout, str_toprint
1241 else:
1241 else:
1242 # Try to open pager and default to internal one if that fails.
1242 # Try to open pager and default to internal one if that fails.
1243 # All failure modes are tagged as 'retval=1', to match the return
1243 # All failure modes are tagged as 'retval=1', to match the return
1244 # value of a failed system command. If any intermediate attempt
1244 # value of a failed system command. If any intermediate attempt
1245 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1245 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1246 pager_cmd = get_pager_cmd(pager_cmd)
1246 pager_cmd = get_pager_cmd(pager_cmd)
1247 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1247 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1248 if os.name == 'nt':
1248 if os.name == 'nt':
1249 if pager_cmd.startswith('type'):
1249 if pager_cmd.startswith('type'):
1250 # The default WinXP 'type' command is failing on complex strings.
1250 # The default WinXP 'type' command is failing on complex strings.
1251 retval = 1
1251 retval = 1
1252 else:
1252 else:
1253 tmpname = tempfile.mktemp('.txt')
1253 tmpname = tempfile.mktemp('.txt')
1254 tmpfile = file(tmpname,'wt')
1254 tmpfile = file(tmpname,'wt')
1255 tmpfile.write(strng)
1255 tmpfile.write(strng)
1256 tmpfile.close()
1256 tmpfile.close()
1257 cmd = "%s < %s" % (pager_cmd,tmpname)
1257 cmd = "%s < %s" % (pager_cmd,tmpname)
1258 if os.system(cmd):
1258 if os.system(cmd):
1259 retval = 1
1259 retval = 1
1260 else:
1260 else:
1261 retval = None
1261 retval = None
1262 os.remove(tmpname)
1262 os.remove(tmpname)
1263 else:
1263 else:
1264 try:
1264 try:
1265 retval = None
1265 retval = None
1266 # if I use popen4, things hang. No idea why.
1266 # if I use popen4, things hang. No idea why.
1267 #pager,shell_out = os.popen4(pager_cmd)
1267 #pager,shell_out = os.popen4(pager_cmd)
1268 pager = os.popen(pager_cmd,'w')
1268 pager = os.popen(pager_cmd,'w')
1269 pager.write(strng)
1269 pager.write(strng)
1270 pager.close()
1270 pager.close()
1271 retval = pager.close() # success returns None
1271 retval = pager.close() # success returns None
1272 except IOError,msg: # broken pipe when user quits
1272 except IOError,msg: # broken pipe when user quits
1273 if msg.args == (32,'Broken pipe'):
1273 if msg.args == (32,'Broken pipe'):
1274 retval = None
1274 retval = None
1275 else:
1275 else:
1276 retval = 1
1276 retval = 1
1277 except OSError:
1277 except OSError:
1278 # Other strange problems, sometimes seen in Win2k/cygwin
1278 # Other strange problems, sometimes seen in Win2k/cygwin
1279 retval = 1
1279 retval = 1
1280 if retval is not None:
1280 if retval is not None:
1281 page_dumb(strng,screen_lines=screen_lines)
1281 page_dumb(strng,screen_lines=screen_lines)
1282
1282
1283 #----------------------------------------------------------------------------
1283 #----------------------------------------------------------------------------
1284 def page_file(fname,start = 0, pager_cmd = None):
1284 def page_file(fname,start = 0, pager_cmd = None):
1285 """Page a file, using an optional pager command and starting line.
1285 """Page a file, using an optional pager command and starting line.
1286 """
1286 """
1287
1287
1288 pager_cmd = get_pager_cmd(pager_cmd)
1288 pager_cmd = get_pager_cmd(pager_cmd)
1289 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1289 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1290
1290
1291 try:
1291 try:
1292 if os.environ['TERM'] in ['emacs','dumb']:
1292 if os.environ['TERM'] in ['emacs','dumb']:
1293 raise EnvironmentError
1293 raise EnvironmentError
1294 xsys(pager_cmd + ' ' + fname)
1294 xsys(pager_cmd + ' ' + fname)
1295 except:
1295 except:
1296 try:
1296 try:
1297 if start > 0:
1297 if start > 0:
1298 start -= 1
1298 start -= 1
1299 page(open(fname).read(),start)
1299 page(open(fname).read(),start)
1300 except:
1300 except:
1301 print 'Unable to show file',`fname`
1301 print 'Unable to show file',`fname`
1302
1302
1303 #----------------------------------------------------------------------------
1303 #----------------------------------------------------------------------------
1304 def snip_print(str,width = 75,print_full = 0,header = ''):
1304 def snip_print(str,width = 75,print_full = 0,header = ''):
1305 """Print a string snipping the midsection to fit in width.
1305 """Print a string snipping the midsection to fit in width.
1306
1306
1307 print_full: mode control:
1307 print_full: mode control:
1308 - 0: only snip long strings
1308 - 0: only snip long strings
1309 - 1: send to page() directly.
1309 - 1: send to page() directly.
1310 - 2: snip long strings and ask for full length viewing with page()
1310 - 2: snip long strings and ask for full length viewing with page()
1311 Return 1 if snipping was necessary, 0 otherwise."""
1311 Return 1 if snipping was necessary, 0 otherwise."""
1312
1312
1313 if print_full == 1:
1313 if print_full == 1:
1314 page(header+str)
1314 page(header+str)
1315 return 0
1315 return 0
1316
1316
1317 print header,
1317 print header,
1318 if len(str) < width:
1318 if len(str) < width:
1319 print str
1319 print str
1320 snip = 0
1320 snip = 0
1321 else:
1321 else:
1322 whalf = int((width -5)/2)
1322 whalf = int((width -5)/2)
1323 print str[:whalf] + ' <...> ' + str[-whalf:]
1323 print str[:whalf] + ' <...> ' + str[-whalf:]
1324 snip = 1
1324 snip = 1
1325 if snip and print_full == 2:
1325 if snip and print_full == 2:
1326 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1326 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1327 page(str)
1327 page(str)
1328 return snip
1328 return snip
1329
1329
1330 #****************************************************************************
1330 #****************************************************************************
1331 # lists, dicts and structures
1331 # lists, dicts and structures
1332
1332
1333 def belong(candidates,checklist):
1333 def belong(candidates,checklist):
1334 """Check whether a list of items appear in a given list of options.
1334 """Check whether a list of items appear in a given list of options.
1335
1335
1336 Returns a list of 1 and 0, one for each candidate given."""
1336 Returns a list of 1 and 0, one for each candidate given."""
1337
1337
1338 return [x in checklist for x in candidates]
1338 return [x in checklist for x in candidates]
1339
1339
1340 #----------------------------------------------------------------------------
1340 #----------------------------------------------------------------------------
1341 def uniq_stable(elems):
1341 def uniq_stable(elems):
1342 """uniq_stable(elems) -> list
1342 """uniq_stable(elems) -> list
1343
1343
1344 Return from an iterable, a list of all the unique elements in the input,
1344 Return from an iterable, a list of all the unique elements in the input,
1345 but maintaining the order in which they first appear.
1345 but maintaining the order in which they first appear.
1346
1346
1347 A naive solution to this problem which just makes a dictionary with the
1347 A naive solution to this problem which just makes a dictionary with the
1348 elements as keys fails to respect the stability condition, since
1348 elements as keys fails to respect the stability condition, since
1349 dictionaries are unsorted by nature.
1349 dictionaries are unsorted by nature.
1350
1350
1351 Note: All elements in the input must be valid dictionary keys for this
1351 Note: All elements in the input must be valid dictionary keys for this
1352 routine to work, as it internally uses a dictionary for efficiency
1352 routine to work, as it internally uses a dictionary for efficiency
1353 reasons."""
1353 reasons."""
1354
1354
1355 unique = []
1355 unique = []
1356 unique_dict = {}
1356 unique_dict = {}
1357 for nn in elems:
1357 for nn in elems:
1358 if nn not in unique_dict:
1358 if nn not in unique_dict:
1359 unique.append(nn)
1359 unique.append(nn)
1360 unique_dict[nn] = None
1360 unique_dict[nn] = None
1361 return unique
1361 return unique
1362
1362
1363 #----------------------------------------------------------------------------
1363 #----------------------------------------------------------------------------
1364 class NLprinter:
1364 class NLprinter:
1365 """Print an arbitrarily nested list, indicating index numbers.
1365 """Print an arbitrarily nested list, indicating index numbers.
1366
1366
1367 An instance of this class called nlprint is available and callable as a
1367 An instance of this class called nlprint is available and callable as a
1368 function.
1368 function.
1369
1369
1370 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1370 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1371 and using 'sep' to separate the index from the value. """
1371 and using 'sep' to separate the index from the value. """
1372
1372
1373 def __init__(self):
1373 def __init__(self):
1374 self.depth = 0
1374 self.depth = 0
1375
1375
1376 def __call__(self,lst,pos='',**kw):
1376 def __call__(self,lst,pos='',**kw):
1377 """Prints the nested list numbering levels."""
1377 """Prints the nested list numbering levels."""
1378 kw.setdefault('indent',' ')
1378 kw.setdefault('indent',' ')
1379 kw.setdefault('sep',': ')
1379 kw.setdefault('sep',': ')
1380 kw.setdefault('start',0)
1380 kw.setdefault('start',0)
1381 kw.setdefault('stop',len(lst))
1381 kw.setdefault('stop',len(lst))
1382 # we need to remove start and stop from kw so they don't propagate
1382 # we need to remove start and stop from kw so they don't propagate
1383 # into a recursive call for a nested list.
1383 # into a recursive call for a nested list.
1384 start = kw['start']; del kw['start']
1384 start = kw['start']; del kw['start']
1385 stop = kw['stop']; del kw['stop']
1385 stop = kw['stop']; del kw['stop']
1386 if self.depth == 0 and 'header' in kw.keys():
1386 if self.depth == 0 and 'header' in kw.keys():
1387 print kw['header']
1387 print kw['header']
1388
1388
1389 for idx in range(start,stop):
1389 for idx in range(start,stop):
1390 elem = lst[idx]
1390 elem = lst[idx]
1391 if type(elem)==type([]):
1391 if type(elem)==type([]):
1392 self.depth += 1
1392 self.depth += 1
1393 self.__call__(elem,itpl('$pos$idx,'),**kw)
1393 self.__call__(elem,itpl('$pos$idx,'),**kw)
1394 self.depth -= 1
1394 self.depth -= 1
1395 else:
1395 else:
1396 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1396 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1397
1397
1398 nlprint = NLprinter()
1398 nlprint = NLprinter()
1399 #----------------------------------------------------------------------------
1399 #----------------------------------------------------------------------------
1400 def all_belong(candidates,checklist):
1400 def all_belong(candidates,checklist):
1401 """Check whether a list of items ALL appear in a given list of options.
1401 """Check whether a list of items ALL appear in a given list of options.
1402
1402
1403 Returns a single 1 or 0 value."""
1403 Returns a single 1 or 0 value."""
1404
1404
1405 return 1-(0 in [x in checklist for x in candidates])
1405 return 1-(0 in [x in checklist for x in candidates])
1406
1406
1407 #----------------------------------------------------------------------------
1407 #----------------------------------------------------------------------------
1408 def sort_compare(lst1,lst2,inplace = 1):
1408 def sort_compare(lst1,lst2,inplace = 1):
1409 """Sort and compare two lists.
1409 """Sort and compare two lists.
1410
1410
1411 By default it does it in place, thus modifying the lists. Use inplace = 0
1411 By default it does it in place, thus modifying the lists. Use inplace = 0
1412 to avoid that (at the cost of temporary copy creation)."""
1412 to avoid that (at the cost of temporary copy creation)."""
1413 if not inplace:
1413 if not inplace:
1414 lst1 = lst1[:]
1414 lst1 = lst1[:]
1415 lst2 = lst2[:]
1415 lst2 = lst2[:]
1416 lst1.sort(); lst2.sort()
1416 lst1.sort(); lst2.sort()
1417 return lst1 == lst2
1417 return lst1 == lst2
1418
1418
1419 #----------------------------------------------------------------------------
1419 #----------------------------------------------------------------------------
1420 def mkdict(**kwargs):
1420 def mkdict(**kwargs):
1421 """Return a dict from a keyword list.
1421 """Return a dict from a keyword list.
1422
1422
1423 It's just syntactic sugar for making ditcionary creation more convenient:
1423 It's just syntactic sugar for making ditcionary creation more convenient:
1424 # the standard way
1424 # the standard way
1425 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1425 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1426 # a cleaner way
1426 # a cleaner way
1427 >>>data = dict(red=1, green=2, blue=3)
1427 >>>data = dict(red=1, green=2, blue=3)
1428
1428
1429 If you need more than this, look at the Struct() class."""
1429 If you need more than this, look at the Struct() class."""
1430
1430
1431 return kwargs
1431 return kwargs
1432
1432
1433 #----------------------------------------------------------------------------
1433 #----------------------------------------------------------------------------
1434 def list2dict(lst):
1434 def list2dict(lst):
1435 """Takes a list of (key,value) pairs and turns it into a dict."""
1435 """Takes a list of (key,value) pairs and turns it into a dict."""
1436
1436
1437 dic = {}
1437 dic = {}
1438 for k,v in lst: dic[k] = v
1438 for k,v in lst: dic[k] = v
1439 return dic
1439 return dic
1440
1440
1441 #----------------------------------------------------------------------------
1441 #----------------------------------------------------------------------------
1442 def list2dict2(lst,default=''):
1442 def list2dict2(lst,default=''):
1443 """Takes a list and turns it into a dict.
1443 """Takes a list and turns it into a dict.
1444 Much slower than list2dict, but more versatile. This version can take
1444 Much slower than list2dict, but more versatile. This version can take
1445 lists with sublists of arbitrary length (including sclars)."""
1445 lists with sublists of arbitrary length (including sclars)."""
1446
1446
1447 dic = {}
1447 dic = {}
1448 for elem in lst:
1448 for elem in lst:
1449 if type(elem) in (types.ListType,types.TupleType):
1449 if type(elem) in (types.ListType,types.TupleType):
1450 size = len(elem)
1450 size = len(elem)
1451 if size == 0:
1451 if size == 0:
1452 pass
1452 pass
1453 elif size == 1:
1453 elif size == 1:
1454 dic[elem] = default
1454 dic[elem] = default
1455 else:
1455 else:
1456 k,v = elem[0], elem[1:]
1456 k,v = elem[0], elem[1:]
1457 if len(v) == 1: v = v[0]
1457 if len(v) == 1: v = v[0]
1458 dic[k] = v
1458 dic[k] = v
1459 else:
1459 else:
1460 dic[elem] = default
1460 dic[elem] = default
1461 return dic
1461 return dic
1462
1462
1463 #----------------------------------------------------------------------------
1463 #----------------------------------------------------------------------------
1464 def flatten(seq):
1464 def flatten(seq):
1465 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1465 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1466
1466
1467 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1467 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1468
1468
1469 # if the x=0 isn't made, a *global* variable x is left over after calling
1469 # if the x=0 isn't made, a *global* variable x is left over after calling
1470 # this function, with the value of the last element in the return
1470 # this function, with the value of the last element in the return
1471 # list. This does seem like a bug big time to me.
1471 # list. This does seem like a bug big time to me.
1472
1472
1473 # the problem is fixed with the x=0, which seems to force the creation of
1473 # the problem is fixed with the x=0, which seems to force the creation of
1474 # a local name
1474 # a local name
1475
1475
1476 x = 0
1476 x = 0
1477 return [x for subseq in seq for x in subseq]
1477 return [x for subseq in seq for x in subseq]
1478
1478
1479 #----------------------------------------------------------------------------
1479 #----------------------------------------------------------------------------
1480 def get_slice(seq,start=0,stop=None,step=1):
1480 def get_slice(seq,start=0,stop=None,step=1):
1481 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1481 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1482 if stop == None:
1482 if stop == None:
1483 stop = len(seq)
1483 stop = len(seq)
1484 item = lambda i: seq[i]
1484 item = lambda i: seq[i]
1485 return map(item,xrange(start,stop,step))
1485 return map(item,xrange(start,stop,step))
1486
1486
1487 #----------------------------------------------------------------------------
1487 #----------------------------------------------------------------------------
1488 def chop(seq,size):
1488 def chop(seq,size):
1489 """Chop a sequence into chunks of the given size."""
1489 """Chop a sequence into chunks of the given size."""
1490 chunk = lambda i: seq[i:i+size]
1490 chunk = lambda i: seq[i:i+size]
1491 return map(chunk,xrange(0,len(seq),size))
1491 return map(chunk,xrange(0,len(seq),size))
1492
1492
1493 #----------------------------------------------------------------------------
1493 #----------------------------------------------------------------------------
1494 def with(object, **args):
1494 def with(object, **args):
1495 """Set multiple attributes for an object, similar to Pascal's with.
1495 """Set multiple attributes for an object, similar to Pascal's with.
1496
1496
1497 Example:
1497 Example:
1498 with(jim,
1498 with(jim,
1499 born = 1960,
1499 born = 1960,
1500 haircolour = 'Brown',
1500 haircolour = 'Brown',
1501 eyecolour = 'Green')
1501 eyecolour = 'Green')
1502
1502
1503 Credit: Greg Ewing, in
1503 Credit: Greg Ewing, in
1504 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1504 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1505
1505
1506 object.__dict__.update(args)
1506 object.__dict__.update(args)
1507
1507
1508 #----------------------------------------------------------------------------
1508 #----------------------------------------------------------------------------
1509 def setattr_list(obj,alist,nspace = None):
1509 def setattr_list(obj,alist,nspace = None):
1510 """Set a list of attributes for an object taken from a namespace.
1510 """Set a list of attributes for an object taken from a namespace.
1511
1511
1512 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1512 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1513 alist with their values taken from nspace, which must be a dict (something
1513 alist with their values taken from nspace, which must be a dict (something
1514 like locals() will often do) If nspace isn't given, locals() of the
1514 like locals() will often do) If nspace isn't given, locals() of the
1515 *caller* is used, so in most cases you can omit it.
1515 *caller* is used, so in most cases you can omit it.
1516
1516
1517 Note that alist can be given as a string, which will be automatically
1517 Note that alist can be given as a string, which will be automatically
1518 split into a list on whitespace. If given as a list, it must be a list of
1518 split into a list on whitespace. If given as a list, it must be a list of
1519 *strings* (the variable names themselves), not of variables."""
1519 *strings* (the variable names themselves), not of variables."""
1520
1520
1521 # this grabs the local variables from the *previous* call frame -- that is
1521 # this grabs the local variables from the *previous* call frame -- that is
1522 # the locals from the function that called setattr_list().
1522 # the locals from the function that called setattr_list().
1523 # - snipped from weave.inline()
1523 # - snipped from weave.inline()
1524 if nspace is None:
1524 if nspace is None:
1525 call_frame = sys._getframe().f_back
1525 call_frame = sys._getframe().f_back
1526 nspace = call_frame.f_locals
1526 nspace = call_frame.f_locals
1527
1527
1528 if type(alist) in StringTypes:
1528 if type(alist) in StringTypes:
1529 alist = alist.split()
1529 alist = alist.split()
1530 for attr in alist:
1530 for attr in alist:
1531 val = eval(attr,nspace)
1531 val = eval(attr,nspace)
1532 setattr(obj,attr,val)
1532 setattr(obj,attr,val)
1533
1533
1534 #----------------------------------------------------------------------------
1534 #----------------------------------------------------------------------------
1535 def getattr_list(obj,alist,*args):
1535 def getattr_list(obj,alist,*args):
1536 """getattr_list(obj,alist[, default]) -> attribute list.
1536 """getattr_list(obj,alist[, default]) -> attribute list.
1537
1537
1538 Get a list of named attributes for an object. When a default argument is
1538 Get a list of named attributes for an object. When a default argument is
1539 given, it is returned when the attribute doesn't exist; without it, an
1539 given, it is returned when the attribute doesn't exist; without it, an
1540 exception is raised in that case.
1540 exception is raised in that case.
1541
1541
1542 Note that alist can be given as a string, which will be automatically
1542 Note that alist can be given as a string, which will be automatically
1543 split into a list on whitespace. If given as a list, it must be a list of
1543 split into a list on whitespace. If given as a list, it must be a list of
1544 *strings* (the variable names themselves), not of variables."""
1544 *strings* (the variable names themselves), not of variables."""
1545
1545
1546 if type(alist) in StringTypes:
1546 if type(alist) in StringTypes:
1547 alist = alist.split()
1547 alist = alist.split()
1548 if args:
1548 if args:
1549 if len(args)==1:
1549 if len(args)==1:
1550 default = args[0]
1550 default = args[0]
1551 return map(lambda attr: getattr(obj,attr,default),alist)
1551 return map(lambda attr: getattr(obj,attr,default),alist)
1552 else:
1552 else:
1553 raise ValueError,'getattr_list() takes only one optional argument'
1553 raise ValueError,'getattr_list() takes only one optional argument'
1554 else:
1554 else:
1555 return map(lambda attr: getattr(obj,attr),alist)
1555 return map(lambda attr: getattr(obj,attr),alist)
1556
1556
1557 #----------------------------------------------------------------------------
1557 #----------------------------------------------------------------------------
1558 def map_method(method,object_list,*argseq,**kw):
1558 def map_method(method,object_list,*argseq,**kw):
1559 """map_method(method,object_list,*args,**kw) -> list
1559 """map_method(method,object_list,*args,**kw) -> list
1560
1560
1561 Return a list of the results of applying the methods to the items of the
1561 Return a list of the results of applying the methods to the items of the
1562 argument sequence(s). If more than one sequence is given, the method is
1562 argument sequence(s). If more than one sequence is given, the method is
1563 called with an argument list consisting of the corresponding item of each
1563 called with an argument list consisting of the corresponding item of each
1564 sequence. All sequences must be of the same length.
1564 sequence. All sequences must be of the same length.
1565
1565
1566 Keyword arguments are passed verbatim to all objects called.
1566 Keyword arguments are passed verbatim to all objects called.
1567
1567
1568 This is Python code, so it's not nearly as fast as the builtin map()."""
1568 This is Python code, so it's not nearly as fast as the builtin map()."""
1569
1569
1570 out_list = []
1570 out_list = []
1571 idx = 0
1571 idx = 0
1572 for object in object_list:
1572 for object in object_list:
1573 try:
1573 try:
1574 handler = getattr(object, method)
1574 handler = getattr(object, method)
1575 except AttributeError:
1575 except AttributeError:
1576 out_list.append(None)
1576 out_list.append(None)
1577 else:
1577 else:
1578 if argseq:
1578 if argseq:
1579 args = map(lambda lst:lst[idx],argseq)
1579 args = map(lambda lst:lst[idx],argseq)
1580 #print 'ob',object,'hand',handler,'ar',args # dbg
1580 #print 'ob',object,'hand',handler,'ar',args # dbg
1581 out_list.append(handler(args,**kw))
1581 out_list.append(handler(args,**kw))
1582 else:
1582 else:
1583 out_list.append(handler(**kw))
1583 out_list.append(handler(**kw))
1584 idx += 1
1584 idx += 1
1585 return out_list
1585 return out_list
1586
1586
1587 #----------------------------------------------------------------------------
1587 #----------------------------------------------------------------------------
1588 # Proposed popitem() extension, written as a method
1588 # Proposed popitem() extension, written as a method
1589
1589
1590 class NotGiven: pass
1590 class NotGiven: pass
1591
1591
1592 def popkey(dct,key,default=NotGiven):
1592 def popkey(dct,key,default=NotGiven):
1593 """Return dct[key] and delete dct[key].
1593 """Return dct[key] and delete dct[key].
1594
1594
1595 If default is given, return it if dct[key] doesn't exist, otherwise raise
1595 If default is given, return it if dct[key] doesn't exist, otherwise raise
1596 KeyError. """
1596 KeyError. """
1597
1597
1598 try:
1598 try:
1599 val = dct[key]
1599 val = dct[key]
1600 except KeyError:
1600 except KeyError:
1601 if default is NotGiven:
1601 if default is NotGiven:
1602 raise
1602 raise
1603 else:
1603 else:
1604 return default
1604 return default
1605 else:
1605 else:
1606 del dct[key]
1606 del dct[key]
1607 return val
1607 return val
1608 #*************************** end of file <genutils.py> **********************
1608 #*************************** end of file <genutils.py> **********************
1609
1609
@@ -1,72 +1,95 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 def calljed(self,filename, linenum):
22 def calljed(self,filename, linenum):
23 "My editor hook calls the jed editor directly."
23 "My editor hook calls the jed editor directly."
24 print "Calling my own editor, jed ..."
24 print "Calling my own editor, jed ..."
25 os.system('jed +%d %s' % (linenum,filename))
25 os.system('jed +%d %s' % (linenum,filename))
26
26
27 You can then execute the following line of code to make it the new IPython
27 You can then execute the following line of code to make it the new IPython
28 editor hook, after having imported 'myiphooks':
28 editor hook, after having imported 'myiphooks':
29
29
30 ip_set_hook('editor',myiphooks.calljed)
30 ip_set_hook('editor',myiphooks.calljed)
31
31
32 The ip_set_hook function is put by IPython into the builtin namespace, so it
32 The ip_set_hook function is put by IPython into the builtin namespace, so it
33 is always available from all running code.
33 is always available from all running code.
34
34
35 $Id: hooks.py 535 2005-03-02 08:42:25Z fperez $"""
35 $Id: hooks.py 960 2005-12-28 06:51:01Z fperez $"""
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 from IPython import Release
44 from IPython import Release
45 __author__ = '%s <%s>' % Release.authors['Fernando']
45 __author__ = '%s <%s>' % Release.authors['Fernando']
46 __license__ = Release.license
46 __license__ = Release.license
47 __version__ = Release.version
47 __version__ = Release.version
48
48
49 import os
49 import os
50
50
51 # List here all the default hooks. For now it's just the editor, but over
51 # List here all the default hooks. For now it's just the editor functions
52 # time we'll move here all the public API for user-accessible things.
52 # but over time we'll move here all the public API for user-accessible things.
53 __all__ = ['editor']
53 __all__ = ['editor', 'fix_error_editor']
54
54
55 def editor(self,filename, linenum):
55 def editor(self,filename, linenum):
56 """Open the default editor at the given filename and linenumber.
56 """Open the default editor at the given filename and linenumber.
57
57
58 This is IPython's default editor hook, you can use it as an example to
58 This is IPython's default editor hook, you can use it as an example to
59 write your own modified one. To set your own editor function as the
59 write your own modified one. To set your own editor function as the
60 new editor hook, call ip_set_hook('editor',yourfunc)."""
60 new editor hook, call ip_set_hook('editor',yourfunc)."""
61
61
62 # IPython configures a default editor at startup by reading $EDITOR from
62 # IPython configures a default editor at startup by reading $EDITOR from
63 # the environment, and falling back on vi (unix) or notepad (win32).
63 # the environment, and falling back on vi (unix) or notepad (win32).
64 editor = self.rc.editor
64 editor = self.rc.editor
65
65
66 # marker for at which line to open the file (for existing objects)
66 # marker for at which line to open the file (for existing objects)
67 if linenum is None or editor=='notepad':
67 if linenum is None or editor=='notepad':
68 linemark = ''
68 linemark = ''
69 else:
69 else:
70 linemark = '+%d' % linenum
70 linemark = '+%d' % linenum
71 # Call the actual editor
71 # Call the actual editor
72 os.system('%s %s %s' % (editor,linemark,filename))
72 os.system('%s %s %s' % (editor,linemark,filename))
73
74 import tempfile
75 def fix_error_editor(self,filename,linenum,column,msg):
76 """Open the editor at the given filename, linenumber, column and
77 show an error message. This is used for correcting syntax errors.
78 The current implementation only has special support for the VIM editor,
79 and falls back on the 'editor' hook if VIM is not used.
80
81 Call ip_set_hook('fix_error_editor',youfunc) to use your own function,
82 """
83 def vim_quickfix_file():
84 t = tempfile.NamedTemporaryFile()
85 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
86 t.flush()
87 return t
88 if os.path.basename(self.rc.editor) != 'vim':
89 self.hooks.editor(filename,linenum)
90 return
91 t = vim_quickfix_file()
92 try:
93 os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name)
94 finally:
95 t.close()
@@ -1,1904 +1,1964 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 959 2005-12-28 02:04:41Z fperez $
9 $Id: iplib.py 960 2005-12-28 06:51:01Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import traceback
58 import traceback
59 import types
59 import types
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic,magic2python
70 from IPython.Magic import Magic,magic2python
71 from IPython.Struct import Struct
71 from IPython.Struct import Struct
72 from IPython.background_jobs import BackgroundJobManager
72 from IPython.background_jobs import BackgroundJobManager
73 from IPython.usage import cmd_line_usage,interactive_usage
73 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.genutils import *
74 from IPython.genutils import *
75
75
76 # store the builtin raw_input globally, and use this always, in case user code
76 # store the builtin raw_input globally, and use this always, in case user code
77 # overwrites it (like wx.py.PyShell does)
77 # overwrites it (like wx.py.PyShell does)
78 raw_input_original = raw_input
78 raw_input_original = raw_input
79
79
80 #****************************************************************************
80 #****************************************************************************
81 # Some utility function definitions
81 # Some utility function definitions
82
82
83 # This can be replaced with an isspace() call once we drop 2.2 compatibility
83 # This can be replaced with an isspace() call once we drop 2.2 compatibility
84 _isspace_match = re.compile(r'^\s+$').match
84 _isspace_match = re.compile(r'^\s+$').match
85 def isspace(s):
85 def isspace(s):
86 return bool(_isspace_match(s))
86 return bool(_isspace_match(s))
87
87
88 def esc_quotes(strng):
88 def esc_quotes(strng):
89 """Return the input string with single and double quotes escaped out"""
89 """Return the input string with single and double quotes escaped out"""
90
90
91 return strng.replace('"','\\"').replace("'","\\'")
91 return strng.replace('"','\\"').replace("'","\\'")
92
92
93 def import_fail_info(mod_name,fns=None):
93 def import_fail_info(mod_name,fns=None):
94 """Inform load failure for a module."""
94 """Inform load failure for a module."""
95
95
96 if fns == None:
96 if fns == None:
97 warn("Loading of %s failed.\n" % (mod_name,))
97 warn("Loading of %s failed.\n" % (mod_name,))
98 else:
98 else:
99 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
99 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
100
100
101 def qw_lol(indata):
101 def qw_lol(indata):
102 """qw_lol('a b') -> [['a','b']],
102 """qw_lol('a b') -> [['a','b']],
103 otherwise it's just a call to qw().
103 otherwise it's just a call to qw().
104
104
105 We need this to make sure the modules_some keys *always* end up as a
105 We need this to make sure the modules_some keys *always* end up as a
106 list of lists."""
106 list of lists."""
107
107
108 if type(indata) in StringTypes:
108 if type(indata) in StringTypes:
109 return [qw(indata)]
109 return [qw(indata)]
110 else:
110 else:
111 return qw(indata)
111 return qw(indata)
112
112
113 def ipmagic(arg_s):
113 def ipmagic(arg_s):
114 """Call a magic function by name.
114 """Call a magic function by name.
115
115
116 Input: a string containing the name of the magic function to call and any
116 Input: a string containing the name of the magic function to call and any
117 additional arguments to be passed to the magic.
117 additional arguments to be passed to the magic.
118
118
119 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
119 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
120 prompt:
120 prompt:
121
121
122 In[1]: %name -opt foo bar
122 In[1]: %name -opt foo bar
123
123
124 To call a magic without arguments, simply use ipmagic('name').
124 To call a magic without arguments, simply use ipmagic('name').
125
125
126 This provides a proper Python function to call IPython's magics in any
126 This provides a proper Python function to call IPython's magics in any
127 valid Python code you can type at the interpreter, including loops and
127 valid Python code you can type at the interpreter, including loops and
128 compound statements. It is added by IPython to the Python builtin
128 compound statements. It is added by IPython to the Python builtin
129 namespace upon initialization."""
129 namespace upon initialization."""
130
130
131 args = arg_s.split(' ',1)
131 args = arg_s.split(' ',1)
132 magic_name = args[0]
132 magic_name = args[0]
133 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
133 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
134 magic_name = magic_name[1:]
134 magic_name = magic_name[1:]
135 try:
135 try:
136 magic_args = args[1]
136 magic_args = args[1]
137 except IndexError:
137 except IndexError:
138 magic_args = ''
138 magic_args = ''
139 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
139 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
140 if fn is None:
140 if fn is None:
141 error("Magic function `%s` not found." % magic_name)
141 error("Magic function `%s` not found." % magic_name)
142 else:
142 else:
143 magic_args = __IPYTHON__.var_expand(magic_args)
143 magic_args = __IPYTHON__.var_expand(magic_args)
144 return fn(magic_args)
144 return fn(magic_args)
145
145
146 def ipalias(arg_s):
146 def ipalias(arg_s):
147 """Call an alias by name.
147 """Call an alias by name.
148
148
149 Input: a string containing the name of the alias to call and any
149 Input: a string containing the name of the alias to call and any
150 additional arguments to be passed to the magic.
150 additional arguments to be passed to the magic.
151
151
152 ipalias('name -opt foo bar') is equivalent to typing at the ipython
152 ipalias('name -opt foo bar') is equivalent to typing at the ipython
153 prompt:
153 prompt:
154
154
155 In[1]: name -opt foo bar
155 In[1]: name -opt foo bar
156
156
157 To call an alias without arguments, simply use ipalias('name').
157 To call an alias without arguments, simply use ipalias('name').
158
158
159 This provides a proper Python function to call IPython's aliases in any
159 This provides a proper Python function to call IPython's aliases in any
160 valid Python code you can type at the interpreter, including loops and
160 valid Python code you can type at the interpreter, including loops and
161 compound statements. It is added by IPython to the Python builtin
161 compound statements. It is added by IPython to the Python builtin
162 namespace upon initialization."""
162 namespace upon initialization."""
163
163
164 args = arg_s.split(' ',1)
164 args = arg_s.split(' ',1)
165 alias_name = args[0]
165 alias_name = args[0]
166 try:
166 try:
167 alias_args = args[1]
167 alias_args = args[1]
168 except IndexError:
168 except IndexError:
169 alias_args = ''
169 alias_args = ''
170 if alias_name in __IPYTHON__.alias_table:
170 if alias_name in __IPYTHON__.alias_table:
171 __IPYTHON__.call_alias(alias_name,alias_args)
171 __IPYTHON__.call_alias(alias_name,alias_args)
172 else:
172 else:
173 error("Alias `%s` not found." % alias_name)
173 error("Alias `%s` not found." % alias_name)
174
174
175 def softspace(file, newvalue):
175 def softspace(file, newvalue):
176 """Copied from code.py, to remove the dependency"""
176 """Copied from code.py, to remove the dependency"""
177 oldvalue = 0
177 oldvalue = 0
178 try:
178 try:
179 oldvalue = file.softspace
179 oldvalue = file.softspace
180 except AttributeError:
180 except AttributeError:
181 pass
181 pass
182 try:
182 try:
183 file.softspace = newvalue
183 file.softspace = newvalue
184 except (AttributeError, TypeError):
184 except (AttributeError, TypeError):
185 # "attribute-less object" or "read-only attributes"
185 # "attribute-less object" or "read-only attributes"
186 pass
186 pass
187 return oldvalue
187 return oldvalue
188
188
189
189
190 #****************************************************************************
190 #****************************************************************************
191 # Local use exceptions
191 # Local use exceptions
192 class SpaceInInput(exceptions.Exception): pass
192 class SpaceInInput(exceptions.Exception): pass
193
193
194 class IPythonExit(exceptions.Exception): pass
194 class IPythonExit(exceptions.Exception): pass
195
195
196 #****************************************************************************
196 #****************************************************************************
197 # Local use classes
197 # Local use classes
198 class Bunch: pass
198 class Bunch: pass
199
199
200 class InputList(list):
200 class InputList(list):
201 """Class to store user input.
201 """Class to store user input.
202
202
203 It's basically a list, but slices return a string instead of a list, thus
203 It's basically a list, but slices return a string instead of a list, thus
204 allowing things like (assuming 'In' is an instance):
204 allowing things like (assuming 'In' is an instance):
205
205
206 exec In[4:7]
206 exec In[4:7]
207
207
208 or
208 or
209
209
210 exec In[5:9] + In[14] + In[21:25]"""
210 exec In[5:9] + In[14] + In[21:25]"""
211
211
212 def __getslice__(self,i,j):
212 def __getslice__(self,i,j):
213 return ''.join(list.__getslice__(self,i,j))
213 return ''.join(list.__getslice__(self,i,j))
214
214
215 class SyntaxTB(ultraTB.ListTB):
216 """Extension which holds some state: the last exception value"""
217
218 def __init__(self,color_scheme = 'NoColor'):
219 ultraTB.ListTB.__init__(self,color_scheme)
220 self.last_syntax_error = None
221
222 def __call__(self, etype, value, elist):
223 self.last_syntax_error = value
224 ultraTB.ListTB.__call__(self,etype,value,elist)
225
226 def clear_err_state(self):
227 """Return the current error state and clear it"""
228 e = self.last_syntax_error
229 self.last_syntax_error = None
230 return e
231
215 #****************************************************************************
232 #****************************************************************************
216 # Main IPython class
233 # Main IPython class
217 class InteractiveShell(Logger, Magic):
234 class InteractiveShell(Logger, Magic):
218 """An enhanced console for Python."""
235 """An enhanced console for Python."""
219
236
220 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
237 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
221 user_ns = None,user_global_ns=None,banner2='',
238 user_ns = None,user_global_ns=None,banner2='',
222 custom_exceptions=((),None),embedded=False):
239 custom_exceptions=((),None),embedded=False):
223
240
224 # Put a reference to self in builtins so that any form of embedded or
241 # Put a reference to self in builtins so that any form of embedded or
225 # imported code can test for being inside IPython.
242 # imported code can test for being inside IPython.
226 __builtin__.__IPYTHON__ = self
243 __builtin__.__IPYTHON__ = self
227
244
228 # And load into builtins ipmagic/ipalias as well
245 # And load into builtins ipmagic/ipalias as well
229 __builtin__.ipmagic = ipmagic
246 __builtin__.ipmagic = ipmagic
230 __builtin__.ipalias = ipalias
247 __builtin__.ipalias = ipalias
231
248
232 # Add to __builtin__ other parts of IPython's public API
249 # Add to __builtin__ other parts of IPython's public API
233 __builtin__.ip_set_hook = self.set_hook
250 __builtin__.ip_set_hook = self.set_hook
234
251
235 # Keep in the builtins a flag for when IPython is active. We set it
252 # Keep in the builtins a flag for when IPython is active. We set it
236 # with setdefault so that multiple nested IPythons don't clobber one
253 # with setdefault so that multiple nested IPythons don't clobber one
237 # another. Each will increase its value by one upon being activated,
254 # another. Each will increase its value by one upon being activated,
238 # which also gives us a way to determine the nesting level.
255 # which also gives us a way to determine the nesting level.
239 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
256 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
240
257
241 # Do the intuitively correct thing for quit/exit: we remove the
258 # Do the intuitively correct thing for quit/exit: we remove the
242 # builtins if they exist, and our own prefilter routine will handle
259 # builtins if they exist, and our own prefilter routine will handle
243 # these special cases
260 # these special cases
244 try:
261 try:
245 del __builtin__.exit, __builtin__.quit
262 del __builtin__.exit, __builtin__.quit
246 except AttributeError:
263 except AttributeError:
247 pass
264 pass
248
265
249 # We need to know whether the instance is meant for embedding, since
266 # We need to know whether the instance is meant for embedding, since
250 # global/local namespaces need to be handled differently in that case
267 # global/local namespaces need to be handled differently in that case
251 self.embedded = embedded
268 self.embedded = embedded
252
269
253 # command compiler
270 # command compiler
254 self.compile = codeop.CommandCompiler()
271 self.compile = codeop.CommandCompiler()
255
272
256 # User input buffer
273 # User input buffer
257 self.buffer = []
274 self.buffer = []
258
275
259 # Default name given in compilation of code
276 # Default name given in compilation of code
260 self.filename = '<ipython console>'
277 self.filename = '<ipython console>'
261
278
262 # Create the namespace where the user will operate. user_ns is
279 # Create the namespace where the user will operate. user_ns is
263 # normally the only one used, and it is passed to the exec calls as
280 # normally the only one used, and it is passed to the exec calls as
264 # the locals argument. But we do carry a user_global_ns namespace
281 # the locals argument. But we do carry a user_global_ns namespace
265 # given as the exec 'globals' argument, This is useful in embedding
282 # given as the exec 'globals' argument, This is useful in embedding
266 # situations where the ipython shell opens in a context where the
283 # situations where the ipython shell opens in a context where the
267 # distinction between locals and globals is meaningful.
284 # distinction between locals and globals is meaningful.
268
285
269 # FIXME. For some strange reason, __builtins__ is showing up at user
286 # FIXME. For some strange reason, __builtins__ is showing up at user
270 # level as a dict instead of a module. This is a manual fix, but I
287 # level as a dict instead of a module. This is a manual fix, but I
271 # should really track down where the problem is coming from. Alex
288 # should really track down where the problem is coming from. Alex
272 # Schmolck reported this problem first.
289 # Schmolck reported this problem first.
273
290
274 # A useful post by Alex Martelli on this topic:
291 # A useful post by Alex Martelli on this topic:
275 # Re: inconsistent value from __builtins__
292 # Re: inconsistent value from __builtins__
276 # Von: Alex Martelli <aleaxit@yahoo.com>
293 # Von: Alex Martelli <aleaxit@yahoo.com>
277 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
294 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
278 # Gruppen: comp.lang.python
295 # Gruppen: comp.lang.python
279 # Referenzen: 1
296 # Referenzen: 1
280
297
281 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
298 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
282 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
299 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
283 # > <type 'dict'>
300 # > <type 'dict'>
284 # > >>> print type(__builtins__)
301 # > >>> print type(__builtins__)
285 # > <type 'module'>
302 # > <type 'module'>
286 # > Is this difference in return value intentional?
303 # > Is this difference in return value intentional?
287
304
288 # Well, it's documented that '__builtins__' can be either a dictionary
305 # Well, it's documented that '__builtins__' can be either a dictionary
289 # or a module, and it's been that way for a long time. Whether it's
306 # or a module, and it's been that way for a long time. Whether it's
290 # intentional (or sensible), I don't know. In any case, the idea is
307 # intentional (or sensible), I don't know. In any case, the idea is
291 # that if you need to access the built-in namespace directly, you
308 # that if you need to access the built-in namespace directly, you
292 # should start with "import __builtin__" (note, no 's') which will
309 # should start with "import __builtin__" (note, no 's') which will
293 # definitely give you a module. Yeah, it's somewhat confusing:-(.
310 # definitely give you a module. Yeah, it's somewhat confusing:-(.
294
311
295 if user_ns is None:
312 if user_ns is None:
296 # Set __name__ to __main__ to better match the behavior of the
313 # Set __name__ to __main__ to better match the behavior of the
297 # normal interpreter.
314 # normal interpreter.
298 user_ns = {'__name__' :'__main__',
315 user_ns = {'__name__' :'__main__',
299 '__builtins__' : __builtin__,
316 '__builtins__' : __builtin__,
300 }
317 }
301
318
302 if user_global_ns is None:
319 if user_global_ns is None:
303 user_global_ns = {}
320 user_global_ns = {}
304
321
305 # Assign namespaces
322 # Assign namespaces
306 # This is the namespace where all normal user variables live
323 # This is the namespace where all normal user variables live
307 self.user_ns = user_ns
324 self.user_ns = user_ns
308 # Embedded instances require a separate namespace for globals.
325 # Embedded instances require a separate namespace for globals.
309 # Normally this one is unused by non-embedded instances.
326 # Normally this one is unused by non-embedded instances.
310 self.user_global_ns = user_global_ns
327 self.user_global_ns = user_global_ns
311 # A namespace to keep track of internal data structures to prevent
328 # A namespace to keep track of internal data structures to prevent
312 # them from cluttering user-visible stuff. Will be updated later
329 # them from cluttering user-visible stuff. Will be updated later
313 self.internal_ns = {}
330 self.internal_ns = {}
314
331
315 # Namespace of system aliases. Each entry in the alias
332 # Namespace of system aliases. Each entry in the alias
316 # table must be a 2-tuple of the form (N,name), where N is the number
333 # table must be a 2-tuple of the form (N,name), where N is the number
317 # of positional arguments of the alias.
334 # of positional arguments of the alias.
318 self.alias_table = {}
335 self.alias_table = {}
319
336
320 # A table holding all the namespaces IPython deals with, so that
337 # A table holding all the namespaces IPython deals with, so that
321 # introspection facilities can search easily.
338 # introspection facilities can search easily.
322 self.ns_table = {'user':user_ns,
339 self.ns_table = {'user':user_ns,
323 'user_global':user_global_ns,
340 'user_global':user_global_ns,
324 'alias':self.alias_table,
341 'alias':self.alias_table,
325 'internal':self.internal_ns,
342 'internal':self.internal_ns,
326 'builtin':__builtin__.__dict__
343 'builtin':__builtin__.__dict__
327 }
344 }
328
345
329 # The user namespace MUST have a pointer to the shell itself.
346 # The user namespace MUST have a pointer to the shell itself.
330 self.user_ns[name] = self
347 self.user_ns[name] = self
331
348
332 # We need to insert into sys.modules something that looks like a
349 # We need to insert into sys.modules something that looks like a
333 # module but which accesses the IPython namespace, for shelve and
350 # module but which accesses the IPython namespace, for shelve and
334 # pickle to work interactively. Normally they rely on getting
351 # pickle to work interactively. Normally they rely on getting
335 # everything out of __main__, but for embedding purposes each IPython
352 # everything out of __main__, but for embedding purposes each IPython
336 # instance has its own private namespace, so we can't go shoving
353 # instance has its own private namespace, so we can't go shoving
337 # everything into __main__.
354 # everything into __main__.
338
355
339 # note, however, that we should only do this for non-embedded
356 # note, however, that we should only do this for non-embedded
340 # ipythons, which really mimic the __main__.__dict__ with their own
357 # ipythons, which really mimic the __main__.__dict__ with their own
341 # namespace. Embedded instances, on the other hand, should not do
358 # namespace. Embedded instances, on the other hand, should not do
342 # this because they need to manage the user local/global namespaces
359 # this because they need to manage the user local/global namespaces
343 # only, but they live within a 'normal' __main__ (meaning, they
360 # only, but they live within a 'normal' __main__ (meaning, they
344 # shouldn't overtake the execution environment of the script they're
361 # shouldn't overtake the execution environment of the script they're
345 # embedded in).
362 # embedded in).
346
363
347 if not embedded:
364 if not embedded:
348 try:
365 try:
349 main_name = self.user_ns['__name__']
366 main_name = self.user_ns['__name__']
350 except KeyError:
367 except KeyError:
351 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
368 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
352 else:
369 else:
353 #print "pickle hack in place" # dbg
370 #print "pickle hack in place" # dbg
354 sys.modules[main_name] = FakeModule(self.user_ns)
371 sys.modules[main_name] = FakeModule(self.user_ns)
355
372
356 # List of input with multi-line handling.
373 # List of input with multi-line handling.
357 # Fill its zero entry, user counter starts at 1
374 # Fill its zero entry, user counter starts at 1
358 self.input_hist = InputList(['\n'])
375 self.input_hist = InputList(['\n'])
359
376
360 # list of visited directories
377 # list of visited directories
361 try:
378 try:
362 self.dir_hist = [os.getcwd()]
379 self.dir_hist = [os.getcwd()]
363 except IOError, e:
380 except IOError, e:
364 self.dir_hist = []
381 self.dir_hist = []
365
382
366 # dict of output history
383 # dict of output history
367 self.output_hist = {}
384 self.output_hist = {}
368
385
369 # dict of things NOT to alias (keywords, builtins and some magics)
386 # dict of things NOT to alias (keywords, builtins and some magics)
370 no_alias = {}
387 no_alias = {}
371 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
388 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
372 for key in keyword.kwlist + no_alias_magics:
389 for key in keyword.kwlist + no_alias_magics:
373 no_alias[key] = 1
390 no_alias[key] = 1
374 no_alias.update(__builtin__.__dict__)
391 no_alias.update(__builtin__.__dict__)
375 self.no_alias = no_alias
392 self.no_alias = no_alias
376
393
377 # make global variables for user access to these
394 # make global variables for user access to these
378 self.user_ns['_ih'] = self.input_hist
395 self.user_ns['_ih'] = self.input_hist
379 self.user_ns['_oh'] = self.output_hist
396 self.user_ns['_oh'] = self.output_hist
380 self.user_ns['_dh'] = self.dir_hist
397 self.user_ns['_dh'] = self.dir_hist
381
398
382 # user aliases to input and output histories
399 # user aliases to input and output histories
383 self.user_ns['In'] = self.input_hist
400 self.user_ns['In'] = self.input_hist
384 self.user_ns['Out'] = self.output_hist
401 self.user_ns['Out'] = self.output_hist
385
402
386 # Store the actual shell's name
403 # Store the actual shell's name
387 self.name = name
404 self.name = name
388
405
389 # Object variable to store code object waiting execution. This is
406 # Object variable to store code object waiting execution. This is
390 # used mainly by the multithreaded shells, but it can come in handy in
407 # used mainly by the multithreaded shells, but it can come in handy in
391 # other situations. No need to use a Queue here, since it's a single
408 # other situations. No need to use a Queue here, since it's a single
392 # item which gets cleared once run.
409 # item which gets cleared once run.
393 self.code_to_run = None
410 self.code_to_run = None
394
411
395 # Job manager (for jobs run as background threads)
412 # Job manager (for jobs run as background threads)
396 self.jobs = BackgroundJobManager()
413 self.jobs = BackgroundJobManager()
397 # Put the job manager into builtins so it's always there.
414 # Put the job manager into builtins so it's always there.
398 __builtin__.jobs = self.jobs
415 __builtin__.jobs = self.jobs
399
416
400 # escapes for automatic behavior on the command line
417 # escapes for automatic behavior on the command line
401 self.ESC_SHELL = '!'
418 self.ESC_SHELL = '!'
402 self.ESC_HELP = '?'
419 self.ESC_HELP = '?'
403 self.ESC_MAGIC = '%'
420 self.ESC_MAGIC = '%'
404 self.ESC_QUOTE = ','
421 self.ESC_QUOTE = ','
405 self.ESC_QUOTE2 = ';'
422 self.ESC_QUOTE2 = ';'
406 self.ESC_PAREN = '/'
423 self.ESC_PAREN = '/'
407
424
408 # And their associated handlers
425 # And their associated handlers
409 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
426 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
410 self.ESC_QUOTE:self.handle_auto,
427 self.ESC_QUOTE:self.handle_auto,
411 self.ESC_QUOTE2:self.handle_auto,
428 self.ESC_QUOTE2:self.handle_auto,
412 self.ESC_MAGIC:self.handle_magic,
429 self.ESC_MAGIC:self.handle_magic,
413 self.ESC_HELP:self.handle_help,
430 self.ESC_HELP:self.handle_help,
414 self.ESC_SHELL:self.handle_shell_escape,
431 self.ESC_SHELL:self.handle_shell_escape,
415 }
432 }
416
433
417 # class initializations
434 # class initializations
418 Logger.__init__(self,log_ns = self.user_ns)
435 Logger.__init__(self,log_ns = self.user_ns)
419 Magic.__init__(self,self)
436 Magic.__init__(self,self)
420
437
421 # an ugly hack to get a pointer to the shell, so I can start writing
438 # an ugly hack to get a pointer to the shell, so I can start writing
422 # magic code via this pointer instead of the current mixin salad.
439 # magic code via this pointer instead of the current mixin salad.
423 Magic.set_shell(self,self)
440 Magic.set_shell(self,self)
424
441
425 # Python source parser/formatter for syntax highlighting
442 # Python source parser/formatter for syntax highlighting
426 pyformat = PyColorize.Parser().format
443 pyformat = PyColorize.Parser().format
427 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
444 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
428
445
429 # hooks holds pointers used for user-side customizations
446 # hooks holds pointers used for user-side customizations
430 self.hooks = Struct()
447 self.hooks = Struct()
431
448
432 # Set all default hooks, defined in the IPython.hooks module.
449 # Set all default hooks, defined in the IPython.hooks module.
433 hooks = IPython.hooks
450 hooks = IPython.hooks
434 for hook_name in hooks.__all__:
451 for hook_name in hooks.__all__:
435 self.set_hook(hook_name,getattr(hooks,hook_name))
452 self.set_hook(hook_name,getattr(hooks,hook_name))
436
453
437 # Flag to mark unconditional exit
454 # Flag to mark unconditional exit
438 self.exit_now = False
455 self.exit_now = False
439
456
440 self.usage_min = """\
457 self.usage_min = """\
441 An enhanced console for Python.
458 An enhanced console for Python.
442 Some of its features are:
459 Some of its features are:
443 - Readline support if the readline library is present.
460 - Readline support if the readline library is present.
444 - Tab completion in the local namespace.
461 - Tab completion in the local namespace.
445 - Logging of input, see command-line options.
462 - Logging of input, see command-line options.
446 - System shell escape via ! , eg !ls.
463 - System shell escape via ! , eg !ls.
447 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
464 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
448 - Keeps track of locally defined variables via %who, %whos.
465 - Keeps track of locally defined variables via %who, %whos.
449 - Show object information with a ? eg ?x or x? (use ?? for more info).
466 - Show object information with a ? eg ?x or x? (use ?? for more info).
450 """
467 """
451 if usage: self.usage = usage
468 if usage: self.usage = usage
452 else: self.usage = self.usage_min
469 else: self.usage = self.usage_min
453
470
454 # Storage
471 # Storage
455 self.rc = rc # This will hold all configuration information
472 self.rc = rc # This will hold all configuration information
456 self.inputcache = []
473 self.inputcache = []
457 self._boundcache = []
474 self._boundcache = []
458 self.pager = 'less'
475 self.pager = 'less'
459 # temporary files used for various purposes. Deleted at exit.
476 # temporary files used for various purposes. Deleted at exit.
460 self.tempfiles = []
477 self.tempfiles = []
461
478
462 # Keep track of readline usage (later set by init_readline)
479 # Keep track of readline usage (later set by init_readline)
463 self.has_readline = False
480 self.has_readline = False
464
481
465 # for pushd/popd management
482 # for pushd/popd management
466 try:
483 try:
467 self.home_dir = get_home_dir()
484 self.home_dir = get_home_dir()
468 except HomeDirError,msg:
485 except HomeDirError,msg:
469 fatal(msg)
486 fatal(msg)
470
487
471 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
488 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
472
489
473 # Functions to call the underlying shell.
490 # Functions to call the underlying shell.
474
491
475 # utility to expand user variables via Itpl
492 # utility to expand user variables via Itpl
476 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
493 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
477 self.user_ns))
494 self.user_ns))
478 # The first is similar to os.system, but it doesn't return a value,
495 # The first is similar to os.system, but it doesn't return a value,
479 # and it allows interpolation of variables in the user's namespace.
496 # and it allows interpolation of variables in the user's namespace.
480 self.system = lambda cmd: shell(self.var_expand(cmd),
497 self.system = lambda cmd: shell(self.var_expand(cmd),
481 header='IPython system call: ',
498 header='IPython system call: ',
482 verbose=self.rc.system_verbose)
499 verbose=self.rc.system_verbose)
483 # These are for getoutput and getoutputerror:
500 # These are for getoutput and getoutputerror:
484 self.getoutput = lambda cmd: \
501 self.getoutput = lambda cmd: \
485 getoutput(self.var_expand(cmd),
502 getoutput(self.var_expand(cmd),
486 header='IPython system call: ',
503 header='IPython system call: ',
487 verbose=self.rc.system_verbose)
504 verbose=self.rc.system_verbose)
488 self.getoutputerror = lambda cmd: \
505 self.getoutputerror = lambda cmd: \
489 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
506 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
490 self.user_ns)),
507 self.user_ns)),
491 header='IPython system call: ',
508 header='IPython system call: ',
492 verbose=self.rc.system_verbose)
509 verbose=self.rc.system_verbose)
493
510
494 # RegExp for splitting line contents into pre-char//first
511 # RegExp for splitting line contents into pre-char//first
495 # word-method//rest. For clarity, each group in on one line.
512 # word-method//rest. For clarity, each group in on one line.
496
513
497 # WARNING: update the regexp if the above escapes are changed, as they
514 # WARNING: update the regexp if the above escapes are changed, as they
498 # are hardwired in.
515 # are hardwired in.
499
516
500 # Don't get carried away with trying to make the autocalling catch too
517 # Don't get carried away with trying to make the autocalling catch too
501 # much: it's better to be conservative rather than to trigger hidden
518 # much: it's better to be conservative rather than to trigger hidden
502 # evals() somewhere and end up causing side effects.
519 # evals() somewhere and end up causing side effects.
503
520
504 self.line_split = re.compile(r'^([\s*,;/])'
521 self.line_split = re.compile(r'^([\s*,;/])'
505 r'([\?\w\.]+\w*\s*)'
522 r'([\?\w\.]+\w*\s*)'
506 r'(\(?.*$)')
523 r'(\(?.*$)')
507
524
508 # Original re, keep around for a while in case changes break something
525 # Original re, keep around for a while in case changes break something
509 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
526 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
510 # r'(\s*[\?\w\.]+\w*\s*)'
527 # r'(\s*[\?\w\.]+\w*\s*)'
511 # r'(\(?.*$)')
528 # r'(\(?.*$)')
512
529
513 # RegExp to identify potential function names
530 # RegExp to identify potential function names
514 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
531 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
515 # RegExp to exclude strings with this start from autocalling
532 # RegExp to exclude strings with this start from autocalling
516 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
533 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
517
534
518 # try to catch also methods for stuff in lists/tuples/dicts: off
535 # try to catch also methods for stuff in lists/tuples/dicts: off
519 # (experimental). For this to work, the line_split regexp would need
536 # (experimental). For this to work, the line_split regexp would need
520 # to be modified so it wouldn't break things at '['. That line is
537 # to be modified so it wouldn't break things at '['. That line is
521 # nasty enough that I shouldn't change it until I can test it _well_.
538 # nasty enough that I shouldn't change it until I can test it _well_.
522 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
539 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
523
540
524 # keep track of where we started running (mainly for crash post-mortem)
541 # keep track of where we started running (mainly for crash post-mortem)
525 self.starting_dir = os.getcwd()
542 self.starting_dir = os.getcwd()
526
543
527 # Attributes for Logger mixin class, make defaults here
544 # Attributes for Logger mixin class, make defaults here
528 self._dolog = False
545 self._dolog = False
529 self.LOG = ''
546 self.LOG = ''
530 self.LOGDEF = '.InteractiveShell.log'
547 self.LOGDEF = '.InteractiveShell.log'
531 self.LOGMODE = 'over'
548 self.LOGMODE = 'over'
532 self.LOGHEAD = Itpl(
549 self.LOGHEAD = Itpl(
533 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
550 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
534 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
551 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
535 #log# opts = $self.rc.opts
552 #log# opts = $self.rc.opts
536 #log# args = $self.rc.args
553 #log# args = $self.rc.args
537 #log# It is safe to make manual edits below here.
554 #log# It is safe to make manual edits below here.
538 #log#-----------------------------------------------------------------------
555 #log#-----------------------------------------------------------------------
539 """)
556 """)
540 # Various switches which can be set
557 # Various switches which can be set
541 self.CACHELENGTH = 5000 # this is cheap, it's just text
558 self.CACHELENGTH = 5000 # this is cheap, it's just text
542 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
559 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
543 self.banner2 = banner2
560 self.banner2 = banner2
544
561
545 # TraceBack handlers:
562 # TraceBack handlers:
546 # Need two, one for syntax errors and one for other exceptions.
563 # Need two, one for syntax errors and one for other exceptions.
547 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
564 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
548 # This one is initialized with an offset, meaning we always want to
565 # The interactive one is initialized with an offset, meaning we always
549 # remove the topmost item in the traceback, which is our own internal
566 # want to remove the topmost item in the traceback, which is our own
550 # code. Valid modes: ['Plain','Context','Verbose']
567 # internal code. Valid modes: ['Plain','Context','Verbose']
551 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
568 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
552 color_scheme='NoColor',
569 color_scheme='NoColor',
553 tb_offset = 1)
570 tb_offset = 1)
554 # and add any custom exception handlers the user may have specified
571 # and add any custom exception handlers the user may have specified
555 self.set_custom_exc(*custom_exceptions)
572 self.set_custom_exc(*custom_exceptions)
556
573
557 # Object inspector
574 # Object inspector
558 self.inspector = OInspect.Inspector(OInspect.InspectColors,
575 self.inspector = OInspect.Inspector(OInspect.InspectColors,
559 PyColorize.ANSICodeColors,
576 PyColorize.ANSICodeColors,
560 'NoColor')
577 'NoColor')
561 # indentation management
578 # indentation management
562 self.autoindent = False
579 self.autoindent = False
563 self.indent_current_nsp = 0
580 self.indent_current_nsp = 0
564 self.indent_current = '' # actual indent string
581 self.indent_current = '' # actual indent string
565
582
566 # Make some aliases automatically
583 # Make some aliases automatically
567 # Prepare list of shell aliases to auto-define
584 # Prepare list of shell aliases to auto-define
568 if os.name == 'posix':
585 if os.name == 'posix':
569 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
586 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
570 'mv mv -i','rm rm -i','cp cp -i',
587 'mv mv -i','rm rm -i','cp cp -i',
571 'cat cat','less less','clear clear',
588 'cat cat','less less','clear clear',
572 # a better ls
589 # a better ls
573 'ls ls -F',
590 'ls ls -F',
574 # long ls
591 # long ls
575 'll ls -lF',
592 'll ls -lF',
576 # color ls
593 # color ls
577 'lc ls -F -o --color',
594 'lc ls -F -o --color',
578 # ls normal files only
595 # ls normal files only
579 'lf ls -F -o --color %l | grep ^-',
596 'lf ls -F -o --color %l | grep ^-',
580 # ls symbolic links
597 # ls symbolic links
581 'lk ls -F -o --color %l | grep ^l',
598 'lk ls -F -o --color %l | grep ^l',
582 # directories or links to directories,
599 # directories or links to directories,
583 'ldir ls -F -o --color %l | grep /$',
600 'ldir ls -F -o --color %l | grep /$',
584 # things which are executable
601 # things which are executable
585 'lx ls -F -o --color %l | grep ^-..x',
602 'lx ls -F -o --color %l | grep ^-..x',
586 )
603 )
587 elif os.name in ['nt','dos']:
604 elif os.name in ['nt','dos']:
588 auto_alias = ('dir dir /on', 'ls dir /on',
605 auto_alias = ('dir dir /on', 'ls dir /on',
589 'ddir dir /ad /on', 'ldir dir /ad /on',
606 'ddir dir /ad /on', 'ldir dir /ad /on',
590 'mkdir mkdir','rmdir rmdir','echo echo',
607 'mkdir mkdir','rmdir rmdir','echo echo',
591 'ren ren','cls cls','copy copy')
608 'ren ren','cls cls','copy copy')
592 else:
609 else:
593 auto_alias = ()
610 auto_alias = ()
594 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
611 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
595 # Call the actual (public) initializer
612 # Call the actual (public) initializer
596 self.init_auto_alias()
613 self.init_auto_alias()
597 # end __init__
614 # end __init__
598
615
599 def set_hook(self,name,hook):
616 def set_hook(self,name,hook):
600 """set_hook(name,hook) -> sets an internal IPython hook.
617 """set_hook(name,hook) -> sets an internal IPython hook.
601
618
602 IPython exposes some of its internal API as user-modifiable hooks. By
619 IPython exposes some of its internal API as user-modifiable hooks. By
603 resetting one of these hooks, you can modify IPython's behavior to
620 resetting one of these hooks, you can modify IPython's behavior to
604 call at runtime your own routines."""
621 call at runtime your own routines."""
605
622
606 # At some point in the future, this should validate the hook before it
623 # At some point in the future, this should validate the hook before it
607 # accepts it. Probably at least check that the hook takes the number
624 # accepts it. Probably at least check that the hook takes the number
608 # of args it's supposed to.
625 # of args it's supposed to.
609 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
626 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
610
627
611 def set_custom_exc(self,exc_tuple,handler):
628 def set_custom_exc(self,exc_tuple,handler):
612 """set_custom_exc(exc_tuple,handler)
629 """set_custom_exc(exc_tuple,handler)
613
630
614 Set a custom exception handler, which will be called if any of the
631 Set a custom exception handler, which will be called if any of the
615 exceptions in exc_tuple occur in the mainloop (specifically, in the
632 exceptions in exc_tuple occur in the mainloop (specifically, in the
616 runcode() method.
633 runcode() method.
617
634
618 Inputs:
635 Inputs:
619
636
620 - exc_tuple: a *tuple* of valid exceptions to call the defined
637 - exc_tuple: a *tuple* of valid exceptions to call the defined
621 handler for. It is very important that you use a tuple, and NOT A
638 handler for. It is very important that you use a tuple, and NOT A
622 LIST here, because of the way Python's except statement works. If
639 LIST here, because of the way Python's except statement works. If
623 you only want to trap a single exception, use a singleton tuple:
640 you only want to trap a single exception, use a singleton tuple:
624
641
625 exc_tuple == (MyCustomException,)
642 exc_tuple == (MyCustomException,)
626
643
627 - handler: this must be defined as a function with the following
644 - handler: this must be defined as a function with the following
628 basic interface: def my_handler(self,etype,value,tb).
645 basic interface: def my_handler(self,etype,value,tb).
629
646
630 This will be made into an instance method (via new.instancemethod)
647 This will be made into an instance method (via new.instancemethod)
631 of IPython itself, and it will be called if any of the exceptions
648 of IPython itself, and it will be called if any of the exceptions
632 listed in the exc_tuple are caught. If the handler is None, an
649 listed in the exc_tuple are caught. If the handler is None, an
633 internal basic one is used, which just prints basic info.
650 internal basic one is used, which just prints basic info.
634
651
635 WARNING: by putting in your own exception handler into IPython's main
652 WARNING: by putting in your own exception handler into IPython's main
636 execution loop, you run a very good chance of nasty crashes. This
653 execution loop, you run a very good chance of nasty crashes. This
637 facility should only be used if you really know what you are doing."""
654 facility should only be used if you really know what you are doing."""
638
655
639 assert type(exc_tuple)==type(()) , \
656 assert type(exc_tuple)==type(()) , \
640 "The custom exceptions must be given AS A TUPLE."
657 "The custom exceptions must be given AS A TUPLE."
641
658
642 def dummy_handler(self,etype,value,tb):
659 def dummy_handler(self,etype,value,tb):
643 print '*** Simple custom exception handler ***'
660 print '*** Simple custom exception handler ***'
644 print 'Exception type :',etype
661 print 'Exception type :',etype
645 print 'Exception value:',value
662 print 'Exception value:',value
646 print 'Traceback :',tb
663 print 'Traceback :',tb
647 print 'Source code :','\n'.join(self.buffer)
664 print 'Source code :','\n'.join(self.buffer)
648
665
649 if handler is None: handler = dummy_handler
666 if handler is None: handler = dummy_handler
650
667
651 self.CustomTB = new.instancemethod(handler,self,self.__class__)
668 self.CustomTB = new.instancemethod(handler,self,self.__class__)
652 self.custom_exceptions = exc_tuple
669 self.custom_exceptions = exc_tuple
653
670
654 def set_custom_completer(self,completer,pos=0):
671 def set_custom_completer(self,completer,pos=0):
655 """set_custom_completer(completer,pos=0)
672 """set_custom_completer(completer,pos=0)
656
673
657 Adds a new custom completer function.
674 Adds a new custom completer function.
658
675
659 The position argument (defaults to 0) is the index in the completers
676 The position argument (defaults to 0) is the index in the completers
660 list where you want the completer to be inserted."""
677 list where you want the completer to be inserted."""
661
678
662 newcomp = new.instancemethod(completer,self.Completer,
679 newcomp = new.instancemethod(completer,self.Completer,
663 self.Completer.__class__)
680 self.Completer.__class__)
664 self.Completer.matchers.insert(pos,newcomp)
681 self.Completer.matchers.insert(pos,newcomp)
665
682
666 def complete(self,text):
683 def complete(self,text):
667 """Return a sorted list of all possible completions on text.
684 """Return a sorted list of all possible completions on text.
668
685
669 Inputs:
686 Inputs:
670
687
671 - text: a string of text to be completed on.
688 - text: a string of text to be completed on.
672
689
673 This is a wrapper around the completion mechanism, similar to what
690 This is a wrapper around the completion mechanism, similar to what
674 readline does at the command line when the TAB key is hit. By
691 readline does at the command line when the TAB key is hit. By
675 exposing it as a method, it can be used by other non-readline
692 exposing it as a method, it can be used by other non-readline
676 environments (such as GUIs) for text completion.
693 environments (such as GUIs) for text completion.
677
694
678 Simple usage example:
695 Simple usage example:
679
696
680 In [1]: x = 'hello'
697 In [1]: x = 'hello'
681
698
682 In [2]: __IP.complete('x.l')
699 In [2]: __IP.complete('x.l')
683 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
700 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
684
701
685 complete = self.Completer.complete
702 complete = self.Completer.complete
686 state = 0
703 state = 0
687 # use a dict so we get unique keys, since ipyhton's multiple
704 # use a dict so we get unique keys, since ipyhton's multiple
688 # completers can return duplicates.
705 # completers can return duplicates.
689 comps = {}
706 comps = {}
690 while True:
707 while True:
691 newcomp = complete(text,state)
708 newcomp = complete(text,state)
692 if newcomp is None:
709 if newcomp is None:
693 break
710 break
694 comps[newcomp] = 1
711 comps[newcomp] = 1
695 state += 1
712 state += 1
696 outcomps = comps.keys()
713 outcomps = comps.keys()
697 outcomps.sort()
714 outcomps.sort()
698 return outcomps
715 return outcomps
699
716
700 def set_completer_frame(self, frame):
717 def set_completer_frame(self, frame):
701 if frame:
718 if frame:
702 self.Completer.namespace = frame.f_locals
719 self.Completer.namespace = frame.f_locals
703 self.Completer.global_namespace = frame.f_globals
720 self.Completer.global_namespace = frame.f_globals
704 else:
721 else:
705 self.Completer.namespace = self.user_ns
722 self.Completer.namespace = self.user_ns
706 self.Completer.global_namespace = self.user_global_ns
723 self.Completer.global_namespace = self.user_global_ns
707
724
708 def post_config_initialization(self):
725 def post_config_initialization(self):
709 """Post configuration init method
726 """Post configuration init method
710
727
711 This is called after the configuration files have been processed to
728 This is called after the configuration files have been processed to
712 'finalize' the initialization."""
729 'finalize' the initialization."""
713
730
714 rc = self.rc
731 rc = self.rc
715
732
716 # Load readline proper
733 # Load readline proper
717 if rc.readline:
734 if rc.readline:
718 self.init_readline()
735 self.init_readline()
719
736
720 # Set user colors (don't do it in the constructor above so that it
737 # Set user colors (don't do it in the constructor above so that it
721 # doesn't crash if colors option is invalid)
738 # doesn't crash if colors option is invalid)
722 self.magic_colors(rc.colors)
739 self.magic_colors(rc.colors)
723
740
724 # Load user aliases
741 # Load user aliases
725 for alias in rc.alias:
742 for alias in rc.alias:
726 self.magic_alias(alias)
743 self.magic_alias(alias)
727
744
728 # dynamic data that survives through sessions
745 # dynamic data that survives through sessions
729 # XXX make the filename a config option?
746 # XXX make the filename a config option?
730 persist_base = 'persist'
747 persist_base = 'persist'
731 if rc.profile:
748 if rc.profile:
732 persist_base += '_%s' % rc.profile
749 persist_base += '_%s' % rc.profile
733 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
750 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
734
751
735 try:
752 try:
736 self.persist = pickle.load(file(self.persist_fname))
753 self.persist = pickle.load(file(self.persist_fname))
737 except:
754 except:
738 self.persist = {}
755 self.persist = {}
739
756
740 def init_auto_alias(self):
757 def init_auto_alias(self):
741 """Define some aliases automatically.
758 """Define some aliases automatically.
742
759
743 These are ALL parameter-less aliases"""
760 These are ALL parameter-less aliases"""
744 for alias,cmd in self.auto_alias:
761 for alias,cmd in self.auto_alias:
745 self.alias_table[alias] = (0,cmd)
762 self.alias_table[alias] = (0,cmd)
746
763
747 def alias_table_validate(self,verbose=0):
764 def alias_table_validate(self,verbose=0):
748 """Update information about the alias table.
765 """Update information about the alias table.
749
766
750 In particular, make sure no Python keywords/builtins are in it."""
767 In particular, make sure no Python keywords/builtins are in it."""
751
768
752 no_alias = self.no_alias
769 no_alias = self.no_alias
753 for k in self.alias_table.keys():
770 for k in self.alias_table.keys():
754 if k in no_alias:
771 if k in no_alias:
755 del self.alias_table[k]
772 del self.alias_table[k]
756 if verbose:
773 if verbose:
757 print ("Deleting alias <%s>, it's a Python "
774 print ("Deleting alias <%s>, it's a Python "
758 "keyword or builtin." % k)
775 "keyword or builtin." % k)
759
776
760 def set_autoindent(self,value=None):
777 def set_autoindent(self,value=None):
761 """Set the autoindent flag, checking for readline support.
778 """Set the autoindent flag, checking for readline support.
762
779
763 If called with no arguments, it acts as a toggle."""
780 If called with no arguments, it acts as a toggle."""
764
781
765 if not self.has_readline:
782 if not self.has_readline:
766 if os.name == 'posix':
783 if os.name == 'posix':
767 warn("The auto-indent feature requires the readline library")
784 warn("The auto-indent feature requires the readline library")
768 self.autoindent = 0
785 self.autoindent = 0
769 return
786 return
770 if value is None:
787 if value is None:
771 self.autoindent = not self.autoindent
788 self.autoindent = not self.autoindent
772 else:
789 else:
773 self.autoindent = value
790 self.autoindent = value
774
791
775 def rc_set_toggle(self,rc_field,value=None):
792 def rc_set_toggle(self,rc_field,value=None):
776 """Set or toggle a field in IPython's rc config. structure.
793 """Set or toggle a field in IPython's rc config. structure.
777
794
778 If called with no arguments, it acts as a toggle.
795 If called with no arguments, it acts as a toggle.
779
796
780 If called with a non-existent field, the resulting AttributeError
797 If called with a non-existent field, the resulting AttributeError
781 exception will propagate out."""
798 exception will propagate out."""
782
799
783 rc_val = getattr(self.rc,rc_field)
800 rc_val = getattr(self.rc,rc_field)
784 if value is None:
801 if value is None:
785 value = not rc_val
802 value = not rc_val
786 setattr(self.rc,rc_field,value)
803 setattr(self.rc,rc_field,value)
787
804
788 def user_setup(self,ipythondir,rc_suffix,mode='install'):
805 def user_setup(self,ipythondir,rc_suffix,mode='install'):
789 """Install the user configuration directory.
806 """Install the user configuration directory.
790
807
791 Can be called when running for the first time or to upgrade the user's
808 Can be called when running for the first time or to upgrade the user's
792 .ipython/ directory with the mode parameter. Valid modes are 'install'
809 .ipython/ directory with the mode parameter. Valid modes are 'install'
793 and 'upgrade'."""
810 and 'upgrade'."""
794
811
795 def wait():
812 def wait():
796 try:
813 try:
797 raw_input("Please press <RETURN> to start IPython.")
814 raw_input("Please press <RETURN> to start IPython.")
798 except EOFError:
815 except EOFError:
799 print >> Term.cout
816 print >> Term.cout
800 print '*'*70
817 print '*'*70
801
818
802 cwd = os.getcwd() # remember where we started
819 cwd = os.getcwd() # remember where we started
803 glb = glob.glob
820 glb = glob.glob
804 print '*'*70
821 print '*'*70
805 if mode == 'install':
822 if mode == 'install':
806 print \
823 print \
807 """Welcome to IPython. I will try to create a personal configuration directory
824 """Welcome to IPython. I will try to create a personal configuration directory
808 where you can customize many aspects of IPython's functionality in:\n"""
825 where you can customize many aspects of IPython's functionality in:\n"""
809 else:
826 else:
810 print 'I am going to upgrade your configuration in:'
827 print 'I am going to upgrade your configuration in:'
811
828
812 print ipythondir
829 print ipythondir
813
830
814 rcdirend = os.path.join('IPython','UserConfig')
831 rcdirend = os.path.join('IPython','UserConfig')
815 cfg = lambda d: os.path.join(d,rcdirend)
832 cfg = lambda d: os.path.join(d,rcdirend)
816 try:
833 try:
817 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
834 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
818 except IOError:
835 except IOError:
819 warning = """
836 warning = """
820 Installation error. IPython's directory was not found.
837 Installation error. IPython's directory was not found.
821
838
822 Check the following:
839 Check the following:
823
840
824 The ipython/IPython directory should be in a directory belonging to your
841 The ipython/IPython directory should be in a directory belonging to your
825 PYTHONPATH environment variable (that is, it should be in a directory
842 PYTHONPATH environment variable (that is, it should be in a directory
826 belonging to sys.path). You can copy it explicitly there or just link to it.
843 belonging to sys.path). You can copy it explicitly there or just link to it.
827
844
828 IPython will proceed with builtin defaults.
845 IPython will proceed with builtin defaults.
829 """
846 """
830 warn(warning)
847 warn(warning)
831 wait()
848 wait()
832 return
849 return
833
850
834 if mode == 'install':
851 if mode == 'install':
835 try:
852 try:
836 shutil.copytree(rcdir,ipythondir)
853 shutil.copytree(rcdir,ipythondir)
837 os.chdir(ipythondir)
854 os.chdir(ipythondir)
838 rc_files = glb("ipythonrc*")
855 rc_files = glb("ipythonrc*")
839 for rc_file in rc_files:
856 for rc_file in rc_files:
840 os.rename(rc_file,rc_file+rc_suffix)
857 os.rename(rc_file,rc_file+rc_suffix)
841 except:
858 except:
842 warning = """
859 warning = """
843
860
844 There was a problem with the installation:
861 There was a problem with the installation:
845 %s
862 %s
846 Try to correct it or contact the developers if you think it's a bug.
863 Try to correct it or contact the developers if you think it's a bug.
847 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
864 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
848 warn(warning)
865 warn(warning)
849 wait()
866 wait()
850 return
867 return
851
868
852 elif mode == 'upgrade':
869 elif mode == 'upgrade':
853 try:
870 try:
854 os.chdir(ipythondir)
871 os.chdir(ipythondir)
855 except:
872 except:
856 print """
873 print """
857 Can not upgrade: changing to directory %s failed. Details:
874 Can not upgrade: changing to directory %s failed. Details:
858 %s
875 %s
859 """ % (ipythondir,sys.exc_info()[1])
876 """ % (ipythondir,sys.exc_info()[1])
860 wait()
877 wait()
861 return
878 return
862 else:
879 else:
863 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
880 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
864 for new_full_path in sources:
881 for new_full_path in sources:
865 new_filename = os.path.basename(new_full_path)
882 new_filename = os.path.basename(new_full_path)
866 if new_filename.startswith('ipythonrc'):
883 if new_filename.startswith('ipythonrc'):
867 new_filename = new_filename + rc_suffix
884 new_filename = new_filename + rc_suffix
868 # The config directory should only contain files, skip any
885 # The config directory should only contain files, skip any
869 # directories which may be there (like CVS)
886 # directories which may be there (like CVS)
870 if os.path.isdir(new_full_path):
887 if os.path.isdir(new_full_path):
871 continue
888 continue
872 if os.path.exists(new_filename):
889 if os.path.exists(new_filename):
873 old_file = new_filename+'.old'
890 old_file = new_filename+'.old'
874 if os.path.exists(old_file):
891 if os.path.exists(old_file):
875 os.remove(old_file)
892 os.remove(old_file)
876 os.rename(new_filename,old_file)
893 os.rename(new_filename,old_file)
877 shutil.copy(new_full_path,new_filename)
894 shutil.copy(new_full_path,new_filename)
878 else:
895 else:
879 raise ValueError,'unrecognized mode for install:',`mode`
896 raise ValueError,'unrecognized mode for install:',`mode`
880
897
881 # Fix line-endings to those native to each platform in the config
898 # Fix line-endings to those native to each platform in the config
882 # directory.
899 # directory.
883 try:
900 try:
884 os.chdir(ipythondir)
901 os.chdir(ipythondir)
885 except:
902 except:
886 print """
903 print """
887 Problem: changing to directory %s failed.
904 Problem: changing to directory %s failed.
888 Details:
905 Details:
889 %s
906 %s
890
907
891 Some configuration files may have incorrect line endings. This should not
908 Some configuration files may have incorrect line endings. This should not
892 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
909 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
893 wait()
910 wait()
894 else:
911 else:
895 for fname in glb('ipythonrc*'):
912 for fname in glb('ipythonrc*'):
896 try:
913 try:
897 native_line_ends(fname,backup=0)
914 native_line_ends(fname,backup=0)
898 except IOError:
915 except IOError:
899 pass
916 pass
900
917
901 if mode == 'install':
918 if mode == 'install':
902 print """
919 print """
903 Successful installation!
920 Successful installation!
904
921
905 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
922 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
906 IPython manual (there are both HTML and PDF versions supplied with the
923 IPython manual (there are both HTML and PDF versions supplied with the
907 distribution) to make sure that your system environment is properly configured
924 distribution) to make sure that your system environment is properly configured
908 to take advantage of IPython's features."""
925 to take advantage of IPython's features."""
909 else:
926 else:
910 print """
927 print """
911 Successful upgrade!
928 Successful upgrade!
912
929
913 All files in your directory:
930 All files in your directory:
914 %(ipythondir)s
931 %(ipythondir)s
915 which would have been overwritten by the upgrade were backed up with a .old
932 which would have been overwritten by the upgrade were backed up with a .old
916 extension. If you had made particular customizations in those files you may
933 extension. If you had made particular customizations in those files you may
917 want to merge them back into the new files.""" % locals()
934 want to merge them back into the new files.""" % locals()
918 wait()
935 wait()
919 os.chdir(cwd)
936 os.chdir(cwd)
920 # end user_setup()
937 # end user_setup()
921
938
922 def atexit_operations(self):
939 def atexit_operations(self):
923 """This will be executed at the time of exit.
940 """This will be executed at the time of exit.
924
941
925 Saving of persistent data should be performed here. """
942 Saving of persistent data should be performed here. """
926
943
927 # input history
944 # input history
928 self.savehist()
945 self.savehist()
929
946
930 # Cleanup all tempfiles left around
947 # Cleanup all tempfiles left around
931 for tfile in self.tempfiles:
948 for tfile in self.tempfiles:
932 try:
949 try:
933 os.unlink(tfile)
950 os.unlink(tfile)
934 except OSError:
951 except OSError:
935 pass
952 pass
936
953
937 # save the "persistent data" catch-all dictionary
954 # save the "persistent data" catch-all dictionary
938 try:
955 try:
939 pickle.dump(self.persist, open(self.persist_fname,"w"))
956 pickle.dump(self.persist, open(self.persist_fname,"w"))
940 except:
957 except:
941 print "*** ERROR *** persistent data saving failed."
958 print "*** ERROR *** persistent data saving failed."
942
959
943 def savehist(self):
960 def savehist(self):
944 """Save input history to a file (via readline library)."""
961 """Save input history to a file (via readline library)."""
945 try:
962 try:
946 self.readline.write_history_file(self.histfile)
963 self.readline.write_history_file(self.histfile)
947 except:
964 except:
948 print 'Unable to save IPython command history to file: ' + \
965 print 'Unable to save IPython command history to file: ' + \
949 `self.histfile`
966 `self.histfile`
950
967
951 def pre_readline(self):
968 def pre_readline(self):
952 """readline hook to be used at the start of each line.
969 """readline hook to be used at the start of each line.
953
970
954 Currently it handles auto-indent only."""
971 Currently it handles auto-indent only."""
955
972
956 self.readline.insert_text(self.indent_current)
973 self.readline.insert_text(self.indent_current)
957
974
958 def init_readline(self):
975 def init_readline(self):
959 """Command history completion/saving/reloading."""
976 """Command history completion/saving/reloading."""
960 try:
977 try:
961 import readline
978 import readline
962 except ImportError:
979 except ImportError:
963 self.has_readline = 0
980 self.has_readline = 0
964 self.readline = None
981 self.readline = None
965 # no point in bugging windows users with this every time:
982 # no point in bugging windows users with this every time:
966 if os.name == 'posix':
983 if os.name == 'posix':
967 warn('Readline services not available on this platform.')
984 warn('Readline services not available on this platform.')
968 else:
985 else:
969 import atexit
986 import atexit
970 from IPython.completer import IPCompleter
987 from IPython.completer import IPCompleter
971 self.Completer = IPCompleter(self,
988 self.Completer = IPCompleter(self,
972 self.user_ns,
989 self.user_ns,
973 self.user_global_ns,
990 self.user_global_ns,
974 self.rc.readline_omit__names,
991 self.rc.readline_omit__names,
975 self.alias_table)
992 self.alias_table)
976
993
977 # Platform-specific configuration
994 # Platform-specific configuration
978 if os.name == 'nt':
995 if os.name == 'nt':
979 self.readline_startup_hook = readline.set_pre_input_hook
996 self.readline_startup_hook = readline.set_pre_input_hook
980 else:
997 else:
981 self.readline_startup_hook = readline.set_startup_hook
998 self.readline_startup_hook = readline.set_startup_hook
982
999
983 # Load user's initrc file (readline config)
1000 # Load user's initrc file (readline config)
984 inputrc_name = os.environ.get('INPUTRC')
1001 inputrc_name = os.environ.get('INPUTRC')
985 if inputrc_name is None:
1002 if inputrc_name is None:
986 home_dir = get_home_dir()
1003 home_dir = get_home_dir()
987 if home_dir is not None:
1004 if home_dir is not None:
988 inputrc_name = os.path.join(home_dir,'.inputrc')
1005 inputrc_name = os.path.join(home_dir,'.inputrc')
989 if os.path.isfile(inputrc_name):
1006 if os.path.isfile(inputrc_name):
990 try:
1007 try:
991 readline.read_init_file(inputrc_name)
1008 readline.read_init_file(inputrc_name)
992 except:
1009 except:
993 warn('Problems reading readline initialization file <%s>'
1010 warn('Problems reading readline initialization file <%s>'
994 % inputrc_name)
1011 % inputrc_name)
995
1012
996 self.has_readline = 1
1013 self.has_readline = 1
997 self.readline = readline
1014 self.readline = readline
998 # save this in sys so embedded copies can restore it properly
1015 # save this in sys so embedded copies can restore it properly
999 sys.ipcompleter = self.Completer.complete
1016 sys.ipcompleter = self.Completer.complete
1000 readline.set_completer(self.Completer.complete)
1017 readline.set_completer(self.Completer.complete)
1001
1018
1002 # Configure readline according to user's prefs
1019 # Configure readline according to user's prefs
1003 for rlcommand in self.rc.readline_parse_and_bind:
1020 for rlcommand in self.rc.readline_parse_and_bind:
1004 readline.parse_and_bind(rlcommand)
1021 readline.parse_and_bind(rlcommand)
1005
1022
1006 # remove some chars from the delimiters list
1023 # remove some chars from the delimiters list
1007 delims = readline.get_completer_delims()
1024 delims = readline.get_completer_delims()
1008 delims = delims.translate(string._idmap,
1025 delims = delims.translate(string._idmap,
1009 self.rc.readline_remove_delims)
1026 self.rc.readline_remove_delims)
1010 readline.set_completer_delims(delims)
1027 readline.set_completer_delims(delims)
1011 # otherwise we end up with a monster history after a while:
1028 # otherwise we end up with a monster history after a while:
1012 readline.set_history_length(1000)
1029 readline.set_history_length(1000)
1013 try:
1030 try:
1014 #print '*** Reading readline history' # dbg
1031 #print '*** Reading readline history' # dbg
1015 readline.read_history_file(self.histfile)
1032 readline.read_history_file(self.histfile)
1016 except IOError:
1033 except IOError:
1017 pass # It doesn't exist yet.
1034 pass # It doesn't exist yet.
1018
1035
1019 atexit.register(self.atexit_operations)
1036 atexit.register(self.atexit_operations)
1020 del atexit
1037 del atexit
1021
1038
1022 # Configure auto-indent for all platforms
1039 # Configure auto-indent for all platforms
1023 self.set_autoindent(self.rc.autoindent)
1040 self.set_autoindent(self.rc.autoindent)
1024
1041
1042 def _should_recompile(self,e):
1043 """Utility routine for edit_syntax_error"""
1044
1045 if e.filename in ('<ipython console>','<input>','<string>',
1046 '<console>'):
1047 return False
1048 try:
1049 if not ask_yes_no('Return to editor to correct syntax error? '
1050 '[Y/n] ','y'):
1051 return False
1052 except EOFError:
1053 return False
1054 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1055 return True
1056
1057 def edit_syntax_error(self):
1058 """The bottom half of the syntax error handler called in the main loop.
1059
1060 Loop until syntax error is fixed or user cancels.
1061 """
1062
1063 while self.SyntaxTB.last_syntax_error:
1064 # copy and clear last_syntax_error
1065 err = self.SyntaxTB.clear_err_state()
1066 if not self._should_recompile(err):
1067 return
1068 try:
1069 # may set last_syntax_error again if a SyntaxError is raised
1070 self.safe_execfile(err.filename,self.shell.user_ns)
1071 except:
1072 self.showtraceback()
1073 else:
1074 f = file(err.filename)
1075 try:
1076 sys.displayhook(f.read())
1077 finally:
1078 f.close()
1079
1025 def showsyntaxerror(self, filename=None):
1080 def showsyntaxerror(self, filename=None):
1026 """Display the syntax error that just occurred.
1081 """Display the syntax error that just occurred.
1027
1082
1028 This doesn't display a stack trace because there isn't one.
1083 This doesn't display a stack trace because there isn't one.
1029
1084
1030 If a filename is given, it is stuffed in the exception instead
1085 If a filename is given, it is stuffed in the exception instead
1031 of what was there before (because Python's parser always uses
1086 of what was there before (because Python's parser always uses
1032 "<string>" when reading from a string).
1087 "<string>" when reading from a string).
1033 """
1088 """
1034 type, value, sys.last_traceback = sys.exc_info()
1089 type, value, sys.last_traceback = sys.exc_info()
1035 sys.last_type = type
1090 sys.last_type = type
1036 sys.last_value = value
1091 sys.last_value = value
1037 if filename and type is SyntaxError:
1092 if filename and type is SyntaxError:
1038 # Work hard to stuff the correct filename in the exception
1093 # Work hard to stuff the correct filename in the exception
1039 try:
1094 try:
1040 msg, (dummy_filename, lineno, offset, line) = value
1095 msg, (dummy_filename, lineno, offset, line) = value
1041 except:
1096 except:
1042 # Not the format we expect; leave it alone
1097 # Not the format we expect; leave it alone
1043 pass
1098 pass
1044 else:
1099 else:
1045 # Stuff in the right filename
1100 # Stuff in the right filename
1046 try:
1101 try:
1047 # Assume SyntaxError is a class exception
1102 # Assume SyntaxError is a class exception
1048 value = SyntaxError(msg, (filename, lineno, offset, line))
1103 value = SyntaxError(msg, (filename, lineno, offset, line))
1049 except:
1104 except:
1050 # If that failed, assume SyntaxError is a string
1105 # If that failed, assume SyntaxError is a string
1051 value = msg, (filename, lineno, offset, line)
1106 value = msg, (filename, lineno, offset, line)
1052 self.SyntaxTB(type,value,[])
1107 self.SyntaxTB(type,value,[])
1053
1108
1054 def debugger(self):
1109 def debugger(self):
1055 """Call the pdb debugger."""
1110 """Call the pdb debugger."""
1056
1111
1057 if not self.rc.pdb:
1112 if not self.rc.pdb:
1058 return
1113 return
1059 pdb.pm()
1114 pdb.pm()
1060
1115
1061 def showtraceback(self,exc_tuple = None,filename=None):
1116 def showtraceback(self,exc_tuple = None,filename=None):
1062 """Display the exception that just occurred."""
1117 """Display the exception that just occurred."""
1063
1118
1064 # Though this won't be called by syntax errors in the input line,
1119 # Though this won't be called by syntax errors in the input line,
1065 # there may be SyntaxError cases whith imported code.
1120 # there may be SyntaxError cases whith imported code.
1066 if exc_tuple is None:
1121 if exc_tuple is None:
1067 type, value, tb = sys.exc_info()
1122 type, value, tb = sys.exc_info()
1068 else:
1123 else:
1069 type, value, tb = exc_tuple
1124 type, value, tb = exc_tuple
1070 if type is SyntaxError:
1125 if type is SyntaxError:
1071 self.showsyntaxerror(filename)
1126 self.showsyntaxerror(filename)
1072 else:
1127 else:
1073 sys.last_type = type
1128 sys.last_type = type
1074 sys.last_value = value
1129 sys.last_value = value
1075 sys.last_traceback = tb
1130 sys.last_traceback = tb
1076 self.InteractiveTB()
1131 self.InteractiveTB()
1077 if self.InteractiveTB.call_pdb and self.has_readline:
1132 if self.InteractiveTB.call_pdb and self.has_readline:
1078 # pdb mucks up readline, fix it back
1133 # pdb mucks up readline, fix it back
1079 self.readline.set_completer(self.Completer.complete)
1134 self.readline.set_completer(self.Completer.complete)
1080
1135
1081 def update_cache(self, line):
1136 def update_cache(self, line):
1082 """puts line into cache"""
1137 """puts line into cache"""
1083 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1138 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1084 if len(self.inputcache) >= self.CACHELENGTH:
1139 if len(self.inputcache) >= self.CACHELENGTH:
1085 self.inputcache.pop() # This doesn't :-)
1140 self.inputcache.pop() # This doesn't :-)
1086
1141
1087 def mainloop(self,banner=None):
1142 def mainloop(self,banner=None):
1088 """Creates the local namespace and starts the mainloop.
1143 """Creates the local namespace and starts the mainloop.
1089
1144
1090 If an optional banner argument is given, it will override the
1145 If an optional banner argument is given, it will override the
1091 internally created default banner."""
1146 internally created default banner."""
1092
1147
1093 if self.rc.c: # Emulate Python's -c option
1148 if self.rc.c: # Emulate Python's -c option
1094 self.exec_init_cmd()
1149 self.exec_init_cmd()
1095 if banner is None:
1150 if banner is None:
1096 if self.rc.banner:
1151 if self.rc.banner:
1097 banner = self.BANNER+self.banner2
1152 banner = self.BANNER+self.banner2
1098 else:
1153 else:
1099 banner = ''
1154 banner = ''
1100 self.interact(banner)
1155 self.interact(banner)
1101
1156
1102 def exec_init_cmd(self):
1157 def exec_init_cmd(self):
1103 """Execute a command given at the command line.
1158 """Execute a command given at the command line.
1104
1159
1105 This emulates Python's -c option."""
1160 This emulates Python's -c option."""
1106
1161
1107 sys.argv = ['-c']
1162 sys.argv = ['-c']
1108 self.push(self.rc.c)
1163 self.push(self.rc.c)
1109
1164
1110 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1165 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1111 """Embeds IPython into a running python program.
1166 """Embeds IPython into a running python program.
1112
1167
1113 Input:
1168 Input:
1114
1169
1115 - header: An optional header message can be specified.
1170 - header: An optional header message can be specified.
1116
1171
1117 - local_ns, global_ns: working namespaces. If given as None, the
1172 - local_ns, global_ns: working namespaces. If given as None, the
1118 IPython-initialized one is updated with __main__.__dict__, so that
1173 IPython-initialized one is updated with __main__.__dict__, so that
1119 program variables become visible but user-specific configuration
1174 program variables become visible but user-specific configuration
1120 remains possible.
1175 remains possible.
1121
1176
1122 - stack_depth: specifies how many levels in the stack to go to
1177 - stack_depth: specifies how many levels in the stack to go to
1123 looking for namespaces (when local_ns and global_ns are None). This
1178 looking for namespaces (when local_ns and global_ns are None). This
1124 allows an intermediate caller to make sure that this function gets
1179 allows an intermediate caller to make sure that this function gets
1125 the namespace from the intended level in the stack. By default (0)
1180 the namespace from the intended level in the stack. By default (0)
1126 it will get its locals and globals from the immediate caller.
1181 it will get its locals and globals from the immediate caller.
1127
1182
1128 Warning: it's possible to use this in a program which is being run by
1183 Warning: it's possible to use this in a program which is being run by
1129 IPython itself (via %run), but some funny things will happen (a few
1184 IPython itself (via %run), but some funny things will happen (a few
1130 globals get overwritten). In the future this will be cleaned up, as
1185 globals get overwritten). In the future this will be cleaned up, as
1131 there is no fundamental reason why it can't work perfectly."""
1186 there is no fundamental reason why it can't work perfectly."""
1132
1187
1133 # Get locals and globals from caller
1188 # Get locals and globals from caller
1134 if local_ns is None or global_ns is None:
1189 if local_ns is None or global_ns is None:
1135 call_frame = sys._getframe(stack_depth).f_back
1190 call_frame = sys._getframe(stack_depth).f_back
1136
1191
1137 if local_ns is None:
1192 if local_ns is None:
1138 local_ns = call_frame.f_locals
1193 local_ns = call_frame.f_locals
1139 if global_ns is None:
1194 if global_ns is None:
1140 global_ns = call_frame.f_globals
1195 global_ns = call_frame.f_globals
1141
1196
1142 # Update namespaces and fire up interpreter
1197 # Update namespaces and fire up interpreter
1143 self.user_ns = local_ns
1198 self.user_ns = local_ns
1144 self.user_global_ns = global_ns
1199 self.user_global_ns = global_ns
1145
1200
1146 # Patch for global embedding to make sure that things don't overwrite
1201 # Patch for global embedding to make sure that things don't overwrite
1147 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1202 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1148 # FIXME. Test this a bit more carefully (the if.. is new)
1203 # FIXME. Test this a bit more carefully (the if.. is new)
1149 if local_ns is None and global_ns is None:
1204 if local_ns is None and global_ns is None:
1150 self.user_global_ns.update(__main__.__dict__)
1205 self.user_global_ns.update(__main__.__dict__)
1151
1206
1152 # make sure the tab-completer has the correct frame information, so it
1207 # make sure the tab-completer has the correct frame information, so it
1153 # actually completes using the frame's locals/globals
1208 # actually completes using the frame's locals/globals
1154 self.set_completer_frame(call_frame)
1209 self.set_completer_frame(call_frame)
1155
1210
1156 self.interact(header)
1211 self.interact(header)
1157
1212
1158 def interact(self, banner=None):
1213 def interact(self, banner=None):
1159 """Closely emulate the interactive Python console.
1214 """Closely emulate the interactive Python console.
1160
1215
1161 The optional banner argument specify the banner to print
1216 The optional banner argument specify the banner to print
1162 before the first interaction; by default it prints a banner
1217 before the first interaction; by default it prints a banner
1163 similar to the one printed by the real Python interpreter,
1218 similar to the one printed by the real Python interpreter,
1164 followed by the current class name in parentheses (so as not
1219 followed by the current class name in parentheses (so as not
1165 to confuse this with the real interpreter -- since it's so
1220 to confuse this with the real interpreter -- since it's so
1166 close!).
1221 close!).
1167
1222
1168 """
1223 """
1169 cprt = 'Type "copyright", "credits" or "license" for more information.'
1224 cprt = 'Type "copyright", "credits" or "license" for more information.'
1170 if banner is None:
1225 if banner is None:
1171 self.write("Python %s on %s\n%s\n(%s)\n" %
1226 self.write("Python %s on %s\n%s\n(%s)\n" %
1172 (sys.version, sys.platform, cprt,
1227 (sys.version, sys.platform, cprt,
1173 self.__class__.__name__))
1228 self.__class__.__name__))
1174 else:
1229 else:
1175 self.write(banner)
1230 self.write(banner)
1176
1231
1177 more = 0
1232 more = 0
1178
1233
1179 # Mark activity in the builtins
1234 # Mark activity in the builtins
1180 __builtin__.__dict__['__IPYTHON__active'] += 1
1235 __builtin__.__dict__['__IPYTHON__active'] += 1
1181
1236
1182 # compiled regexps for autoindent management
1237 # compiled regexps for autoindent management
1183 ini_spaces_re = re.compile(r'^(\s+)')
1238 ini_spaces_re = re.compile(r'^(\s+)')
1184 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1239 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1185
1240
1186 # exit_now is set by a call to %Exit or %Quit
1241 # exit_now is set by a call to %Exit or %Quit
1187 while not self.exit_now:
1242 while not self.exit_now:
1188 try:
1243 try:
1189 if more:
1244 if more:
1190 prompt = self.outputcache.prompt2
1245 prompt = self.outputcache.prompt2
1191 if self.autoindent:
1246 if self.autoindent:
1192 self.readline_startup_hook(self.pre_readline)
1247 self.readline_startup_hook(self.pre_readline)
1193 else:
1248 else:
1194 prompt = self.outputcache.prompt1
1249 prompt = self.outputcache.prompt1
1195 try:
1250 try:
1196 line = self.raw_input(prompt,more)
1251 line = self.raw_input(prompt,more)
1197 if self.autoindent:
1252 if self.autoindent:
1198 self.readline_startup_hook(None)
1253 self.readline_startup_hook(None)
1199 except EOFError:
1254 except EOFError:
1200 if self.autoindent:
1255 if self.autoindent:
1201 self.readline_startup_hook(None)
1256 self.readline_startup_hook(None)
1202 self.write("\n")
1257 self.write("\n")
1203 self.exit()
1258 self.exit()
1204 except IPythonExit:
1259 except IPythonExit:
1205 self.exit()
1260 self.exit()
1206 else:
1261 else:
1207 more = self.push(line)
1262 more = self.push(line)
1208 # Auto-indent management
1263 # Auto-indent management
1209 if self.autoindent:
1264 if self.autoindent:
1210 if line:
1265 if line:
1211 ini_spaces = ini_spaces_re.match(line)
1266 ini_spaces = ini_spaces_re.match(line)
1212 if ini_spaces:
1267 if ini_spaces:
1213 nspaces = ini_spaces.end()
1268 nspaces = ini_spaces.end()
1214 else:
1269 else:
1215 nspaces = 0
1270 nspaces = 0
1216 self.indent_current_nsp = nspaces
1271 self.indent_current_nsp = nspaces
1217
1272
1218 if line[-1] == ':':
1273 if line[-1] == ':':
1219 self.indent_current_nsp += 4
1274 self.indent_current_nsp += 4
1220 elif dedent_re.match(line):
1275 elif dedent_re.match(line):
1221 self.indent_current_nsp -= 4
1276 self.indent_current_nsp -= 4
1222 else:
1277 else:
1223 self.indent_current_nsp = 0
1278 self.indent_current_nsp = 0
1279
1224 # indent_current is the actual string to be inserted
1280 # indent_current is the actual string to be inserted
1225 # by the readline hooks for indentation
1281 # by the readline hooks for indentation
1226 self.indent_current = ' '* self.indent_current_nsp
1282 self.indent_current = ' '* self.indent_current_nsp
1227
1283
1284 if (self.SyntaxTB.last_syntax_error and
1285 self.rc.autoedit_syntax):
1286 self.edit_syntax_error()
1287
1228 except KeyboardInterrupt:
1288 except KeyboardInterrupt:
1229 self.write("\nKeyboardInterrupt\n")
1289 self.write("\nKeyboardInterrupt\n")
1230 self.resetbuffer()
1290 self.resetbuffer()
1231 more = 0
1291 more = 0
1232 # keep cache in sync with the prompt counter:
1292 # keep cache in sync with the prompt counter:
1233 self.outputcache.prompt_count -= 1
1293 self.outputcache.prompt_count -= 1
1234
1294
1235 if self.autoindent:
1295 if self.autoindent:
1236 self.indent_current_nsp = 0
1296 self.indent_current_nsp = 0
1237 self.indent_current = ' '* self.indent_current_nsp
1297 self.indent_current = ' '* self.indent_current_nsp
1238
1298
1239 except bdb.BdbQuit:
1299 except bdb.BdbQuit:
1240 warn("The Python debugger has exited with a BdbQuit exception.\n"
1300 warn("The Python debugger has exited with a BdbQuit exception.\n"
1241 "Because of how pdb handles the stack, it is impossible\n"
1301 "Because of how pdb handles the stack, it is impossible\n"
1242 "for IPython to properly format this particular exception.\n"
1302 "for IPython to properly format this particular exception.\n"
1243 "IPython will resume normal operation.")
1303 "IPython will resume normal operation.")
1244
1304
1245 # We are off again...
1305 # We are off again...
1246 __builtin__.__dict__['__IPYTHON__active'] -= 1
1306 __builtin__.__dict__['__IPYTHON__active'] -= 1
1247
1307
1248 def excepthook(self, type, value, tb):
1308 def excepthook(self, type, value, tb):
1249 """One more defense for GUI apps that call sys.excepthook.
1309 """One more defense for GUI apps that call sys.excepthook.
1250
1310
1251 GUI frameworks like wxPython trap exceptions and call
1311 GUI frameworks like wxPython trap exceptions and call
1252 sys.excepthook themselves. I guess this is a feature that
1312 sys.excepthook themselves. I guess this is a feature that
1253 enables them to keep running after exceptions that would
1313 enables them to keep running after exceptions that would
1254 otherwise kill their mainloop. This is a bother for IPython
1314 otherwise kill their mainloop. This is a bother for IPython
1255 which excepts to catch all of the program exceptions with a try:
1315 which excepts to catch all of the program exceptions with a try:
1256 except: statement.
1316 except: statement.
1257
1317
1258 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1318 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1259 any app directly invokes sys.excepthook, it will look to the user like
1319 any app directly invokes sys.excepthook, it will look to the user like
1260 IPython crashed. In order to work around this, we can disable the
1320 IPython crashed. In order to work around this, we can disable the
1261 CrashHandler and replace it with this excepthook instead, which prints a
1321 CrashHandler and replace it with this excepthook instead, which prints a
1262 regular traceback using our InteractiveTB. In this fashion, apps which
1322 regular traceback using our InteractiveTB. In this fashion, apps which
1263 call sys.excepthook will generate a regular-looking exception from
1323 call sys.excepthook will generate a regular-looking exception from
1264 IPython, and the CrashHandler will only be triggered by real IPython
1324 IPython, and the CrashHandler will only be triggered by real IPython
1265 crashes.
1325 crashes.
1266
1326
1267 This hook should be used sparingly, only in places which are not likely
1327 This hook should be used sparingly, only in places which are not likely
1268 to be true IPython errors.
1328 to be true IPython errors.
1269 """
1329 """
1270
1330
1271 self.InteractiveTB(type, value, tb, tb_offset=0)
1331 self.InteractiveTB(type, value, tb, tb_offset=0)
1272 if self.InteractiveTB.call_pdb and self.has_readline:
1332 if self.InteractiveTB.call_pdb and self.has_readline:
1273 self.readline.set_completer(self.Completer.complete)
1333 self.readline.set_completer(self.Completer.complete)
1274
1334
1275 def call_alias(self,alias,rest=''):
1335 def call_alias(self,alias,rest=''):
1276 """Call an alias given its name and the rest of the line.
1336 """Call an alias given its name and the rest of the line.
1277
1337
1278 This function MUST be given a proper alias, because it doesn't make
1338 This function MUST be given a proper alias, because it doesn't make
1279 any checks when looking up into the alias table. The caller is
1339 any checks when looking up into the alias table. The caller is
1280 responsible for invoking it only with a valid alias."""
1340 responsible for invoking it only with a valid alias."""
1281
1341
1282 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1342 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1283 nargs,cmd = self.alias_table[alias]
1343 nargs,cmd = self.alias_table[alias]
1284 # Expand the %l special to be the user's input line
1344 # Expand the %l special to be the user's input line
1285 if cmd.find('%l') >= 0:
1345 if cmd.find('%l') >= 0:
1286 cmd = cmd.replace('%l',rest)
1346 cmd = cmd.replace('%l',rest)
1287 rest = ''
1347 rest = ''
1288 if nargs==0:
1348 if nargs==0:
1289 # Simple, argument-less aliases
1349 # Simple, argument-less aliases
1290 cmd = '%s %s' % (cmd,rest)
1350 cmd = '%s %s' % (cmd,rest)
1291 else:
1351 else:
1292 # Handle aliases with positional arguments
1352 # Handle aliases with positional arguments
1293 args = rest.split(None,nargs)
1353 args = rest.split(None,nargs)
1294 if len(args)< nargs:
1354 if len(args)< nargs:
1295 error('Alias <%s> requires %s arguments, %s given.' %
1355 error('Alias <%s> requires %s arguments, %s given.' %
1296 (alias,nargs,len(args)))
1356 (alias,nargs,len(args)))
1297 return
1357 return
1298 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1358 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1299 # Now call the macro, evaluating in the user's namespace
1359 # Now call the macro, evaluating in the user's namespace
1300 try:
1360 try:
1301 self.system(cmd)
1361 self.system(cmd)
1302 except:
1362 except:
1303 self.showtraceback()
1363 self.showtraceback()
1304
1364
1305 def runlines(self,lines):
1365 def runlines(self,lines):
1306 """Run a string of one or more lines of source.
1366 """Run a string of one or more lines of source.
1307
1367
1308 This method is capable of running a string containing multiple source
1368 This method is capable of running a string containing multiple source
1309 lines, as if they had been entered at the IPython prompt. Since it
1369 lines, as if they had been entered at the IPython prompt. Since it
1310 exposes IPython's processing machinery, the given strings can contain
1370 exposes IPython's processing machinery, the given strings can contain
1311 magic calls (%magic), special shell access (!cmd), etc."""
1371 magic calls (%magic), special shell access (!cmd), etc."""
1312
1372
1313 # We must start with a clean buffer, in case this is run from an
1373 # We must start with a clean buffer, in case this is run from an
1314 # interactive IPython session (via a magic, for example).
1374 # interactive IPython session (via a magic, for example).
1315 self.resetbuffer()
1375 self.resetbuffer()
1316 lines = lines.split('\n')
1376 lines = lines.split('\n')
1317 more = 0
1377 more = 0
1318 for line in lines:
1378 for line in lines:
1319 # skip blank lines so we don't mess up the prompt counter, but do
1379 # skip blank lines so we don't mess up the prompt counter, but do
1320 # NOT skip even a blank line if we are in a code block (more is
1380 # NOT skip even a blank line if we are in a code block (more is
1321 # true)
1381 # true)
1322 if line or more:
1382 if line or more:
1323 more = self.push((self.prefilter(line,more)))
1383 more = self.push((self.prefilter(line,more)))
1324 # IPython's runsource returns None if there was an error
1384 # IPython's runsource returns None if there was an error
1325 # compiling the code. This allows us to stop processing right
1385 # compiling the code. This allows us to stop processing right
1326 # away, so the user gets the error message at the right place.
1386 # away, so the user gets the error message at the right place.
1327 if more is None:
1387 if more is None:
1328 break
1388 break
1329 # final newline in case the input didn't have it, so that the code
1389 # final newline in case the input didn't have it, so that the code
1330 # actually does get executed
1390 # actually does get executed
1331 if more:
1391 if more:
1332 self.push('\n')
1392 self.push('\n')
1333
1393
1334 def runsource(self, source, filename='<input>', symbol='single'):
1394 def runsource(self, source, filename='<input>', symbol='single'):
1335 """Compile and run some source in the interpreter.
1395 """Compile and run some source in the interpreter.
1336
1396
1337 Arguments are as for compile_command().
1397 Arguments are as for compile_command().
1338
1398
1339 One several things can happen:
1399 One several things can happen:
1340
1400
1341 1) The input is incorrect; compile_command() raised an
1401 1) The input is incorrect; compile_command() raised an
1342 exception (SyntaxError or OverflowError). A syntax traceback
1402 exception (SyntaxError or OverflowError). A syntax traceback
1343 will be printed by calling the showsyntaxerror() method.
1403 will be printed by calling the showsyntaxerror() method.
1344
1404
1345 2) The input is incomplete, and more input is required;
1405 2) The input is incomplete, and more input is required;
1346 compile_command() returned None. Nothing happens.
1406 compile_command() returned None. Nothing happens.
1347
1407
1348 3) The input is complete; compile_command() returned a code
1408 3) The input is complete; compile_command() returned a code
1349 object. The code is executed by calling self.runcode() (which
1409 object. The code is executed by calling self.runcode() (which
1350 also handles run-time exceptions, except for SystemExit).
1410 also handles run-time exceptions, except for SystemExit).
1351
1411
1352 The return value is:
1412 The return value is:
1353
1413
1354 - True in case 2
1414 - True in case 2
1355
1415
1356 - False in the other cases, unless an exception is raised, where
1416 - False in the other cases, unless an exception is raised, where
1357 None is returned instead. This can be used by external callers to
1417 None is returned instead. This can be used by external callers to
1358 know whether to continue feeding input or not.
1418 know whether to continue feeding input or not.
1359
1419
1360 The return value can be used to decide whether to use sys.ps1 or
1420 The return value can be used to decide whether to use sys.ps1 or
1361 sys.ps2 to prompt the next line."""
1421 sys.ps2 to prompt the next line."""
1362
1422
1363 try:
1423 try:
1364 code = self.compile(source,filename,symbol)
1424 code = self.compile(source,filename,symbol)
1365 except (OverflowError, SyntaxError, ValueError):
1425 except (OverflowError, SyntaxError, ValueError):
1366 # Case 1
1426 # Case 1
1367 self.showsyntaxerror(filename)
1427 self.showsyntaxerror(filename)
1368 return None
1428 return None
1369
1429
1370 if code is None:
1430 if code is None:
1371 # Case 2
1431 # Case 2
1372 return True
1432 return True
1373
1433
1374 # Case 3
1434 # Case 3
1375 # We store the code object so that threaded shells and
1435 # We store the code object so that threaded shells and
1376 # custom exception handlers can access all this info if needed.
1436 # custom exception handlers can access all this info if needed.
1377 # The source corresponding to this can be obtained from the
1437 # The source corresponding to this can be obtained from the
1378 # buffer attribute as '\n'.join(self.buffer).
1438 # buffer attribute as '\n'.join(self.buffer).
1379 self.code_to_run = code
1439 self.code_to_run = code
1380 # now actually execute the code object
1440 # now actually execute the code object
1381 if self.runcode(code) == 0:
1441 if self.runcode(code) == 0:
1382 return False
1442 return False
1383 else:
1443 else:
1384 return None
1444 return None
1385
1445
1386 def runcode(self,code_obj):
1446 def runcode(self,code_obj):
1387 """Execute a code object.
1447 """Execute a code object.
1388
1448
1389 When an exception occurs, self.showtraceback() is called to display a
1449 When an exception occurs, self.showtraceback() is called to display a
1390 traceback.
1450 traceback.
1391
1451
1392 Return value: a flag indicating whether the code to be run completed
1452 Return value: a flag indicating whether the code to be run completed
1393 successfully:
1453 successfully:
1394
1454
1395 - 0: successful execution.
1455 - 0: successful execution.
1396 - 1: an error occurred.
1456 - 1: an error occurred.
1397 """
1457 """
1398
1458
1399 # Set our own excepthook in case the user code tries to call it
1459 # Set our own excepthook in case the user code tries to call it
1400 # directly, so that the IPython crash handler doesn't get triggered
1460 # directly, so that the IPython crash handler doesn't get triggered
1401 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1461 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1402 outflag = 1 # happens in more places, so it's easier as default
1462 outflag = 1 # happens in more places, so it's easier as default
1403 try:
1463 try:
1404 try:
1464 try:
1405 # Embedded instances require separate global/local namespaces
1465 # Embedded instances require separate global/local namespaces
1406 # so they can see both the surrounding (local) namespace and
1466 # so they can see both the surrounding (local) namespace and
1407 # the module-level globals when called inside another function.
1467 # the module-level globals when called inside another function.
1408 if self.embedded:
1468 if self.embedded:
1409 exec code_obj in self.user_global_ns, self.user_ns
1469 exec code_obj in self.user_global_ns, self.user_ns
1410 # Normal (non-embedded) instances should only have a single
1470 # Normal (non-embedded) instances should only have a single
1411 # namespace for user code execution, otherwise functions won't
1471 # namespace for user code execution, otherwise functions won't
1412 # see interactive top-level globals.
1472 # see interactive top-level globals.
1413 else:
1473 else:
1414 exec code_obj in self.user_ns
1474 exec code_obj in self.user_ns
1415 finally:
1475 finally:
1416 # Reset our crash handler in place
1476 # Reset our crash handler in place
1417 sys.excepthook = old_excepthook
1477 sys.excepthook = old_excepthook
1418 except SystemExit:
1478 except SystemExit:
1419 self.resetbuffer()
1479 self.resetbuffer()
1420 self.showtraceback()
1480 self.showtraceback()
1421 warn("Type exit or quit to exit IPython "
1481 warn("Type exit or quit to exit IPython "
1422 "(%Exit or %Quit do so unconditionally).",level=1)
1482 "(%Exit or %Quit do so unconditionally).",level=1)
1423 except self.custom_exceptions:
1483 except self.custom_exceptions:
1424 etype,value,tb = sys.exc_info()
1484 etype,value,tb = sys.exc_info()
1425 self.CustomTB(etype,value,tb)
1485 self.CustomTB(etype,value,tb)
1426 except:
1486 except:
1427 self.showtraceback()
1487 self.showtraceback()
1428 else:
1488 else:
1429 outflag = 0
1489 outflag = 0
1430 if softspace(sys.stdout, 0):
1490 if softspace(sys.stdout, 0):
1431 print
1491 print
1432 # Flush out code object which has been run (and source)
1492 # Flush out code object which has been run (and source)
1433 self.code_to_run = None
1493 self.code_to_run = None
1434 return outflag
1494 return outflag
1435
1495
1436 def push(self, line):
1496 def push(self, line):
1437 """Push a line to the interpreter.
1497 """Push a line to the interpreter.
1438
1498
1439 The line should not have a trailing newline; it may have
1499 The line should not have a trailing newline; it may have
1440 internal newlines. The line is appended to a buffer and the
1500 internal newlines. The line is appended to a buffer and the
1441 interpreter's runsource() method is called with the
1501 interpreter's runsource() method is called with the
1442 concatenated contents of the buffer as source. If this
1502 concatenated contents of the buffer as source. If this
1443 indicates that the command was executed or invalid, the buffer
1503 indicates that the command was executed or invalid, the buffer
1444 is reset; otherwise, the command is incomplete, and the buffer
1504 is reset; otherwise, the command is incomplete, and the buffer
1445 is left as it was after the line was appended. The return
1505 is left as it was after the line was appended. The return
1446 value is 1 if more input is required, 0 if the line was dealt
1506 value is 1 if more input is required, 0 if the line was dealt
1447 with in some way (this is the same as runsource()).
1507 with in some way (this is the same as runsource()).
1448
1508
1449 """
1509 """
1450 self.buffer.append(line)
1510 self.buffer.append(line)
1451 more = self.runsource('\n'.join(self.buffer), self.filename)
1511 more = self.runsource('\n'.join(self.buffer), self.filename)
1452 if not more:
1512 if not more:
1453 self.resetbuffer()
1513 self.resetbuffer()
1454 return more
1514 return more
1455
1515
1456 def resetbuffer(self):
1516 def resetbuffer(self):
1457 """Reset the input buffer."""
1517 """Reset the input buffer."""
1458 self.buffer[:] = []
1518 self.buffer[:] = []
1459
1519
1460 def raw_input(self,prompt='',continue_prompt=False):
1520 def raw_input(self,prompt='',continue_prompt=False):
1461 """Write a prompt and read a line.
1521 """Write a prompt and read a line.
1462
1522
1463 The returned line does not include the trailing newline.
1523 The returned line does not include the trailing newline.
1464 When the user enters the EOF key sequence, EOFError is raised.
1524 When the user enters the EOF key sequence, EOFError is raised.
1465
1525
1466 Optional inputs:
1526 Optional inputs:
1467
1527
1468 - prompt(''): a string to be printed to prompt the user.
1528 - prompt(''): a string to be printed to prompt the user.
1469
1529
1470 - continue_prompt(False): whether this line is the first one or a
1530 - continue_prompt(False): whether this line is the first one or a
1471 continuation in a sequence of inputs.
1531 continuation in a sequence of inputs.
1472 """
1532 """
1473
1533
1474 line = raw_input_original(prompt)
1534 line = raw_input_original(prompt)
1475 # Try to be reasonably smart about not re-indenting pasted input more
1535 # Try to be reasonably smart about not re-indenting pasted input more
1476 # than necessary. We do this by trimming out the auto-indent initial
1536 # than necessary. We do this by trimming out the auto-indent initial
1477 # spaces, if the user's actual input started itself with whitespace.
1537 # spaces, if the user's actual input started itself with whitespace.
1478 if self.autoindent:
1538 if self.autoindent:
1479 line2 = line[self.indent_current_nsp:]
1539 line2 = line[self.indent_current_nsp:]
1480 if line2[0:1] in (' ','\t'):
1540 if line2[0:1] in (' ','\t'):
1481 line = line2
1541 line = line2
1482 return self.prefilter(line,continue_prompt)
1542 return self.prefilter(line,continue_prompt)
1483
1543
1484 def split_user_input(self,line):
1544 def split_user_input(self,line):
1485 """Split user input into pre-char, function part and rest."""
1545 """Split user input into pre-char, function part and rest."""
1486
1546
1487 lsplit = self.line_split.match(line)
1547 lsplit = self.line_split.match(line)
1488 if lsplit is None: # no regexp match returns None
1548 if lsplit is None: # no regexp match returns None
1489 try:
1549 try:
1490 iFun,theRest = line.split(None,1)
1550 iFun,theRest = line.split(None,1)
1491 except ValueError:
1551 except ValueError:
1492 iFun,theRest = line,''
1552 iFun,theRest = line,''
1493 pre = re.match('^(\s*)(.*)',line).groups()[0]
1553 pre = re.match('^(\s*)(.*)',line).groups()[0]
1494 else:
1554 else:
1495 pre,iFun,theRest = lsplit.groups()
1555 pre,iFun,theRest = lsplit.groups()
1496
1556
1497 #print 'line:<%s>' % line # dbg
1557 #print 'line:<%s>' % line # dbg
1498 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1558 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1499 return pre,iFun.strip(),theRest
1559 return pre,iFun.strip(),theRest
1500
1560
1501 def _prefilter(self, line, continue_prompt):
1561 def _prefilter(self, line, continue_prompt):
1502 """Calls different preprocessors, depending on the form of line."""
1562 """Calls different preprocessors, depending on the form of line."""
1503
1563
1504 # All handlers *must* return a value, even if it's blank ('').
1564 # All handlers *must* return a value, even if it's blank ('').
1505
1565
1506 # Lines are NOT logged here. Handlers should process the line as
1566 # Lines are NOT logged here. Handlers should process the line as
1507 # needed, update the cache AND log it (so that the input cache array
1567 # needed, update the cache AND log it (so that the input cache array
1508 # stays synced).
1568 # stays synced).
1509
1569
1510 # This function is _very_ delicate, and since it's also the one which
1570 # This function is _very_ delicate, and since it's also the one which
1511 # determines IPython's response to user input, it must be as efficient
1571 # determines IPython's response to user input, it must be as efficient
1512 # as possible. For this reason it has _many_ returns in it, trying
1572 # as possible. For this reason it has _many_ returns in it, trying
1513 # always to exit as quickly as it can figure out what it needs to do.
1573 # always to exit as quickly as it can figure out what it needs to do.
1514
1574
1515 # This function is the main responsible for maintaining IPython's
1575 # This function is the main responsible for maintaining IPython's
1516 # behavior respectful of Python's semantics. So be _very_ careful if
1576 # behavior respectful of Python's semantics. So be _very_ careful if
1517 # making changes to anything here.
1577 # making changes to anything here.
1518
1578
1519 #.....................................................................
1579 #.....................................................................
1520 # Code begins
1580 # Code begins
1521
1581
1522 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1582 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1523
1583
1524 # save the line away in case we crash, so the post-mortem handler can
1584 # save the line away in case we crash, so the post-mortem handler can
1525 # record it
1585 # record it
1526 self._last_input_line = line
1586 self._last_input_line = line
1527
1587
1528 #print '***line: <%s>' % line # dbg
1588 #print '***line: <%s>' % line # dbg
1529
1589
1530 # the input history needs to track even empty lines
1590 # the input history needs to track even empty lines
1531 if not line.strip():
1591 if not line.strip():
1532 if not continue_prompt:
1592 if not continue_prompt:
1533 self.outputcache.prompt_count -= 1
1593 self.outputcache.prompt_count -= 1
1534 return self.handle_normal(line,continue_prompt)
1594 return self.handle_normal(line,continue_prompt)
1535 #return self.handle_normal('',continue_prompt)
1595 #return self.handle_normal('',continue_prompt)
1536
1596
1537 # print '***cont',continue_prompt # dbg
1597 # print '***cont',continue_prompt # dbg
1538 # special handlers are only allowed for single line statements
1598 # special handlers are only allowed for single line statements
1539 if continue_prompt and not self.rc.multi_line_specials:
1599 if continue_prompt and not self.rc.multi_line_specials:
1540 return self.handle_normal(line,continue_prompt)
1600 return self.handle_normal(line,continue_prompt)
1541
1601
1542 # For the rest, we need the structure of the input
1602 # For the rest, we need the structure of the input
1543 pre,iFun,theRest = self.split_user_input(line)
1603 pre,iFun,theRest = self.split_user_input(line)
1544 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1604 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1545
1605
1546 # First check for explicit escapes in the last/first character
1606 # First check for explicit escapes in the last/first character
1547 handler = None
1607 handler = None
1548 if line[-1] == self.ESC_HELP:
1608 if line[-1] == self.ESC_HELP:
1549 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1609 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1550 if handler is None:
1610 if handler is None:
1551 # look at the first character of iFun, NOT of line, so we skip
1611 # look at the first character of iFun, NOT of line, so we skip
1552 # leading whitespace in multiline input
1612 # leading whitespace in multiline input
1553 handler = self.esc_handlers.get(iFun[0:1])
1613 handler = self.esc_handlers.get(iFun[0:1])
1554 if handler is not None:
1614 if handler is not None:
1555 return handler(line,continue_prompt,pre,iFun,theRest)
1615 return handler(line,continue_prompt,pre,iFun,theRest)
1556 # Emacs ipython-mode tags certain input lines
1616 # Emacs ipython-mode tags certain input lines
1557 if line.endswith('# PYTHON-MODE'):
1617 if line.endswith('# PYTHON-MODE'):
1558 return self.handle_emacs(line,continue_prompt)
1618 return self.handle_emacs(line,continue_prompt)
1559
1619
1560 # Next, check if we can automatically execute this thing
1620 # Next, check if we can automatically execute this thing
1561
1621
1562 # Allow ! in multi-line statements if multi_line_specials is on:
1622 # Allow ! in multi-line statements if multi_line_specials is on:
1563 if continue_prompt and self.rc.multi_line_specials and \
1623 if continue_prompt and self.rc.multi_line_specials and \
1564 iFun.startswith(self.ESC_SHELL):
1624 iFun.startswith(self.ESC_SHELL):
1565 return self.handle_shell_escape(line,continue_prompt,
1625 return self.handle_shell_escape(line,continue_prompt,
1566 pre=pre,iFun=iFun,
1626 pre=pre,iFun=iFun,
1567 theRest=theRest)
1627 theRest=theRest)
1568
1628
1569 # Let's try to find if the input line is a magic fn
1629 # Let's try to find if the input line is a magic fn
1570 oinfo = None
1630 oinfo = None
1571 if hasattr(self,'magic_'+iFun):
1631 if hasattr(self,'magic_'+iFun):
1572 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1632 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1573 if oinfo['ismagic']:
1633 if oinfo['ismagic']:
1574 # Be careful not to call magics when a variable assignment is
1634 # Be careful not to call magics when a variable assignment is
1575 # being made (ls='hi', for example)
1635 # being made (ls='hi', for example)
1576 if self.rc.automagic and \
1636 if self.rc.automagic and \
1577 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1637 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1578 (self.rc.multi_line_specials or not continue_prompt):
1638 (self.rc.multi_line_specials or not continue_prompt):
1579 return self.handle_magic(line,continue_prompt,
1639 return self.handle_magic(line,continue_prompt,
1580 pre,iFun,theRest)
1640 pre,iFun,theRest)
1581 else:
1641 else:
1582 return self.handle_normal(line,continue_prompt)
1642 return self.handle_normal(line,continue_prompt)
1583
1643
1584 # If the rest of the line begins with an (in)equality, assginment or
1644 # If the rest of the line begins with an (in)equality, assginment or
1585 # function call, we should not call _ofind but simply execute it.
1645 # function call, we should not call _ofind but simply execute it.
1586 # This avoids spurious geattr() accesses on objects upon assignment.
1646 # This avoids spurious geattr() accesses on objects upon assignment.
1587 #
1647 #
1588 # It also allows users to assign to either alias or magic names true
1648 # It also allows users to assign to either alias or magic names true
1589 # python variables (the magic/alias systems always take second seat to
1649 # python variables (the magic/alias systems always take second seat to
1590 # true python code).
1650 # true python code).
1591 if theRest and theRest[0] in '!=()':
1651 if theRest and theRest[0] in '!=()':
1592 return self.handle_normal(line,continue_prompt)
1652 return self.handle_normal(line,continue_prompt)
1593
1653
1594 if oinfo is None:
1654 if oinfo is None:
1595 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1655 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1596
1656
1597 if not oinfo['found']:
1657 if not oinfo['found']:
1598 if iFun in ('quit','exit'):
1658 if iFun in ('quit','exit'):
1599 raise IPythonExit
1659 raise IPythonExit
1600 return self.handle_normal(line,continue_prompt)
1660 return self.handle_normal(line,continue_prompt)
1601 else:
1661 else:
1602 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1662 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1603 if oinfo['isalias']:
1663 if oinfo['isalias']:
1604 return self.handle_alias(line,continue_prompt,
1664 return self.handle_alias(line,continue_prompt,
1605 pre,iFun,theRest)
1665 pre,iFun,theRest)
1606
1666
1607 if self.rc.autocall and \
1667 if self.rc.autocall and \
1608 not self.re_exclude_auto.match(theRest) and \
1668 not self.re_exclude_auto.match(theRest) and \
1609 self.re_fun_name.match(iFun) and \
1669 self.re_fun_name.match(iFun) and \
1610 callable(oinfo['obj']) :
1670 callable(oinfo['obj']) :
1611 #print 'going auto' # dbg
1671 #print 'going auto' # dbg
1612 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1672 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1613 else:
1673 else:
1614 #print 'was callable?', callable(oinfo['obj']) # dbg
1674 #print 'was callable?', callable(oinfo['obj']) # dbg
1615 return self.handle_normal(line,continue_prompt)
1675 return self.handle_normal(line,continue_prompt)
1616
1676
1617 # If we get here, we have a normal Python line. Log and return.
1677 # If we get here, we have a normal Python line. Log and return.
1618 return self.handle_normal(line,continue_prompt)
1678 return self.handle_normal(line,continue_prompt)
1619
1679
1620 def _prefilter_dumb(self, line, continue_prompt):
1680 def _prefilter_dumb(self, line, continue_prompt):
1621 """simple prefilter function, for debugging"""
1681 """simple prefilter function, for debugging"""
1622 return self.handle_normal(line,continue_prompt)
1682 return self.handle_normal(line,continue_prompt)
1623
1683
1624 # Set the default prefilter() function (this can be user-overridden)
1684 # Set the default prefilter() function (this can be user-overridden)
1625 prefilter = _prefilter
1685 prefilter = _prefilter
1626
1686
1627 def handle_normal(self,line,continue_prompt=None,
1687 def handle_normal(self,line,continue_prompt=None,
1628 pre=None,iFun=None,theRest=None):
1688 pre=None,iFun=None,theRest=None):
1629 """Handle normal input lines. Use as a template for handlers."""
1689 """Handle normal input lines. Use as a template for handlers."""
1630
1690
1631 # With autoindent on, we need some way to exit the input loop, and I
1691 # With autoindent on, we need some way to exit the input loop, and I
1632 # don't want to force the user to have to backspace all the way to
1692 # don't want to force the user to have to backspace all the way to
1633 # clear the line. The rule will be in this case, that either two
1693 # clear the line. The rule will be in this case, that either two
1634 # lines of pure whitespace in a row, or a line of pure whitespace but
1694 # lines of pure whitespace in a row, or a line of pure whitespace but
1635 # of a size different to the indent level, will exit the input loop.
1695 # of a size different to the indent level, will exit the input loop.
1636 if (continue_prompt and self.autoindent and isspace(line) and
1696 if (continue_prompt and self.autoindent and isspace(line) and
1637 (line != self.indent_current or isspace(self.buffer[-1]))):
1697 (line != self.indent_current or isspace(self.buffer[-1]))):
1638 line = ''
1698 line = ''
1639
1699
1640 self.log(line,continue_prompt)
1700 self.log(line,continue_prompt)
1641 self.update_cache(line)
1701 self.update_cache(line)
1642 return line
1702 return line
1643
1703
1644 def handle_alias(self,line,continue_prompt=None,
1704 def handle_alias(self,line,continue_prompt=None,
1645 pre=None,iFun=None,theRest=None):
1705 pre=None,iFun=None,theRest=None):
1646 """Handle alias input lines. """
1706 """Handle alias input lines. """
1647
1707
1648 theRest = esc_quotes(theRest)
1708 theRest = esc_quotes(theRest)
1649 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1709 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1650 self.log(line_out,continue_prompt)
1710 self.log(line_out,continue_prompt)
1651 self.update_cache(line_out)
1711 self.update_cache(line_out)
1652 return line_out
1712 return line_out
1653
1713
1654 def handle_shell_escape(self, line, continue_prompt=None,
1714 def handle_shell_escape(self, line, continue_prompt=None,
1655 pre=None,iFun=None,theRest=None):
1715 pre=None,iFun=None,theRest=None):
1656 """Execute the line in a shell, empty return value"""
1716 """Execute the line in a shell, empty return value"""
1657
1717
1658 #print 'line in :', `line` # dbg
1718 #print 'line in :', `line` # dbg
1659 # Example of a special handler. Others follow a similar pattern.
1719 # Example of a special handler. Others follow a similar pattern.
1660 if continue_prompt: # multi-line statements
1720 if continue_prompt: # multi-line statements
1661 if iFun.startswith('!!'):
1721 if iFun.startswith('!!'):
1662 print 'SyntaxError: !! is not allowed in multiline statements'
1722 print 'SyntaxError: !! is not allowed in multiline statements'
1663 return pre
1723 return pre
1664 else:
1724 else:
1665 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1725 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1666 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1726 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1667 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1727 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1668 else: # single-line input
1728 else: # single-line input
1669 if line.startswith('!!'):
1729 if line.startswith('!!'):
1670 # rewrite iFun/theRest to properly hold the call to %sx and
1730 # rewrite iFun/theRest to properly hold the call to %sx and
1671 # the actual command to be executed, so handle_magic can work
1731 # the actual command to be executed, so handle_magic can work
1672 # correctly
1732 # correctly
1673 theRest = '%s %s' % (iFun[2:],theRest)
1733 theRest = '%s %s' % (iFun[2:],theRest)
1674 iFun = 'sx'
1734 iFun = 'sx'
1675 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1735 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1676 continue_prompt,pre,iFun,theRest)
1736 continue_prompt,pre,iFun,theRest)
1677 else:
1737 else:
1678 cmd = esc_quotes(line[1:])
1738 cmd = esc_quotes(line[1:])
1679 line_out = '%s.system("%s")' % (self.name,cmd)
1739 line_out = '%s.system("%s")' % (self.name,cmd)
1680 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1740 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1681 # update cache/log and return
1741 # update cache/log and return
1682 self.log(line_out,continue_prompt)
1742 self.log(line_out,continue_prompt)
1683 self.update_cache(line_out) # readline cache gets normal line
1743 self.update_cache(line_out) # readline cache gets normal line
1684 #print 'line out r:', `line_out` # dbg
1744 #print 'line out r:', `line_out` # dbg
1685 #print 'line out s:', line_out # dbg
1745 #print 'line out s:', line_out # dbg
1686 return line_out
1746 return line_out
1687
1747
1688 def handle_magic(self, line, continue_prompt=None,
1748 def handle_magic(self, line, continue_prompt=None,
1689 pre=None,iFun=None,theRest=None):
1749 pre=None,iFun=None,theRest=None):
1690 """Execute magic functions.
1750 """Execute magic functions.
1691
1751
1692 Also log them with a prepended # so the log is clean Python."""
1752 Also log them with a prepended # so the log is clean Python."""
1693
1753
1694 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1754 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1695 self.log(cmd,continue_prompt)
1755 self.log(cmd,continue_prompt)
1696 self.update_cache(line)
1756 self.update_cache(line)
1697 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1757 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1698 return cmd
1758 return cmd
1699
1759
1700 def handle_auto(self, line, continue_prompt=None,
1760 def handle_auto(self, line, continue_prompt=None,
1701 pre=None,iFun=None,theRest=None):
1761 pre=None,iFun=None,theRest=None):
1702 """Hande lines which can be auto-executed, quoting if requested."""
1762 """Hande lines which can be auto-executed, quoting if requested."""
1703
1763
1704 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1764 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1705
1765
1706 # This should only be active for single-line input!
1766 # This should only be active for single-line input!
1707 if continue_prompt:
1767 if continue_prompt:
1708 return line
1768 return line
1709
1769
1710 if pre == self.ESC_QUOTE:
1770 if pre == self.ESC_QUOTE:
1711 # Auto-quote splitting on whitespace
1771 # Auto-quote splitting on whitespace
1712 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1772 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1713 elif pre == self.ESC_QUOTE2:
1773 elif pre == self.ESC_QUOTE2:
1714 # Auto-quote whole string
1774 # Auto-quote whole string
1715 newcmd = '%s("%s")' % (iFun,theRest)
1775 newcmd = '%s("%s")' % (iFun,theRest)
1716 else:
1776 else:
1717 # Auto-paren
1777 # Auto-paren
1718 if theRest[0:1] in ('=','['):
1778 if theRest[0:1] in ('=','['):
1719 # Don't autocall in these cases. They can be either
1779 # Don't autocall in these cases. They can be either
1720 # rebindings of an existing callable's name, or item access
1780 # rebindings of an existing callable's name, or item access
1721 # for an object which is BOTH callable and implements
1781 # for an object which is BOTH callable and implements
1722 # __getitem__.
1782 # __getitem__.
1723 return '%s %s' % (iFun,theRest)
1783 return '%s %s' % (iFun,theRest)
1724 if theRest.endswith(';'):
1784 if theRest.endswith(';'):
1725 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1785 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1726 else:
1786 else:
1727 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1787 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1728
1788
1729 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1789 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1730 # log what is now valid Python, not the actual user input (without the
1790 # log what is now valid Python, not the actual user input (without the
1731 # final newline)
1791 # final newline)
1732 self.log(newcmd,continue_prompt)
1792 self.log(newcmd,continue_prompt)
1733 return newcmd
1793 return newcmd
1734
1794
1735 def handle_help(self, line, continue_prompt=None,
1795 def handle_help(self, line, continue_prompt=None,
1736 pre=None,iFun=None,theRest=None):
1796 pre=None,iFun=None,theRest=None):
1737 """Try to get some help for the object.
1797 """Try to get some help for the object.
1738
1798
1739 obj? or ?obj -> basic information.
1799 obj? or ?obj -> basic information.
1740 obj?? or ??obj -> more details.
1800 obj?? or ??obj -> more details.
1741 """
1801 """
1742
1802
1743 # We need to make sure that we don't process lines which would be
1803 # We need to make sure that we don't process lines which would be
1744 # otherwise valid python, such as "x=1 # what?"
1804 # otherwise valid python, such as "x=1 # what?"
1745 try:
1805 try:
1746 codeop.compile_command(line)
1806 codeop.compile_command(line)
1747 except SyntaxError:
1807 except SyntaxError:
1748 # We should only handle as help stuff which is NOT valid syntax
1808 # We should only handle as help stuff which is NOT valid syntax
1749 if line[0]==self.ESC_HELP:
1809 if line[0]==self.ESC_HELP:
1750 line = line[1:]
1810 line = line[1:]
1751 elif line[-1]==self.ESC_HELP:
1811 elif line[-1]==self.ESC_HELP:
1752 line = line[:-1]
1812 line = line[:-1]
1753 self.log('#?'+line)
1813 self.log('#?'+line)
1754 self.update_cache(line)
1814 self.update_cache(line)
1755 if line:
1815 if line:
1756 self.magic_pinfo(line)
1816 self.magic_pinfo(line)
1757 else:
1817 else:
1758 page(self.usage,screen_lines=self.rc.screen_length)
1818 page(self.usage,screen_lines=self.rc.screen_length)
1759 return '' # Empty string is needed here!
1819 return '' # Empty string is needed here!
1760 except:
1820 except:
1761 # Pass any other exceptions through to the normal handler
1821 # Pass any other exceptions through to the normal handler
1762 return self.handle_normal(line,continue_prompt)
1822 return self.handle_normal(line,continue_prompt)
1763 else:
1823 else:
1764 # If the code compiles ok, we should handle it normally
1824 # If the code compiles ok, we should handle it normally
1765 return self.handle_normal(line,continue_prompt)
1825 return self.handle_normal(line,continue_prompt)
1766
1826
1767 def handle_emacs(self,line,continue_prompt=None,
1827 def handle_emacs(self,line,continue_prompt=None,
1768 pre=None,iFun=None,theRest=None):
1828 pre=None,iFun=None,theRest=None):
1769 """Handle input lines marked by python-mode."""
1829 """Handle input lines marked by python-mode."""
1770
1830
1771 # Currently, nothing is done. Later more functionality can be added
1831 # Currently, nothing is done. Later more functionality can be added
1772 # here if needed.
1832 # here if needed.
1773
1833
1774 # The input cache shouldn't be updated
1834 # The input cache shouldn't be updated
1775
1835
1776 return line
1836 return line
1777
1837
1778 def write(self,data):
1838 def write(self,data):
1779 """Write a string to the default output"""
1839 """Write a string to the default output"""
1780 Term.cout.write(data)
1840 Term.cout.write(data)
1781
1841
1782 def write_err(self,data):
1842 def write_err(self,data):
1783 """Write a string to the default error output"""
1843 """Write a string to the default error output"""
1784 Term.cerr.write(data)
1844 Term.cerr.write(data)
1785
1845
1786 def exit(self):
1846 def exit(self):
1787 """Handle interactive exit.
1847 """Handle interactive exit.
1788
1848
1789 This method sets the exit_now attribute."""
1849 This method sets the exit_now attribute."""
1790
1850
1791 if self.rc.confirm_exit:
1851 if self.rc.confirm_exit:
1792 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1852 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1793 self.exit_now = True
1853 self.exit_now = True
1794 else:
1854 else:
1795 self.exit_now = True
1855 self.exit_now = True
1796 return self.exit_now
1856 return self.exit_now
1797
1857
1798 def safe_execfile(self,fname,*where,**kw):
1858 def safe_execfile(self,fname,*where,**kw):
1799 fname = os.path.expanduser(fname)
1859 fname = os.path.expanduser(fname)
1800
1860
1801 # find things also in current directory
1861 # find things also in current directory
1802 dname = os.path.dirname(fname)
1862 dname = os.path.dirname(fname)
1803 if not sys.path.count(dname):
1863 if not sys.path.count(dname):
1804 sys.path.append(dname)
1864 sys.path.append(dname)
1805
1865
1806 try:
1866 try:
1807 xfile = open(fname)
1867 xfile = open(fname)
1808 except:
1868 except:
1809 print >> Term.cerr, \
1869 print >> Term.cerr, \
1810 'Could not open file <%s> for safe execution.' % fname
1870 'Could not open file <%s> for safe execution.' % fname
1811 return None
1871 return None
1812
1872
1813 kw.setdefault('islog',0)
1873 kw.setdefault('islog',0)
1814 kw.setdefault('quiet',1)
1874 kw.setdefault('quiet',1)
1815 kw.setdefault('exit_ignore',0)
1875 kw.setdefault('exit_ignore',0)
1816 first = xfile.readline()
1876 first = xfile.readline()
1817 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1877 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1818 xfile.close()
1878 xfile.close()
1819 # line by line execution
1879 # line by line execution
1820 if first.startswith(_LOGHEAD) or kw['islog']:
1880 if first.startswith(_LOGHEAD) or kw['islog']:
1821 print 'Loading log file <%s> one line at a time...' % fname
1881 print 'Loading log file <%s> one line at a time...' % fname
1822 if kw['quiet']:
1882 if kw['quiet']:
1823 stdout_save = sys.stdout
1883 stdout_save = sys.stdout
1824 sys.stdout = StringIO.StringIO()
1884 sys.stdout = StringIO.StringIO()
1825 try:
1885 try:
1826 globs,locs = where[0:2]
1886 globs,locs = where[0:2]
1827 except:
1887 except:
1828 try:
1888 try:
1829 globs = locs = where[0]
1889 globs = locs = where[0]
1830 except:
1890 except:
1831 globs = locs = globals()
1891 globs = locs = globals()
1832 badblocks = []
1892 badblocks = []
1833
1893
1834 # we also need to identify indented blocks of code when replaying
1894 # we also need to identify indented blocks of code when replaying
1835 # logs and put them together before passing them to an exec
1895 # logs and put them together before passing them to an exec
1836 # statement. This takes a bit of regexp and look-ahead work in the
1896 # statement. This takes a bit of regexp and look-ahead work in the
1837 # file. It's easiest if we swallow the whole thing in memory
1897 # file. It's easiest if we swallow the whole thing in memory
1838 # first, and manually walk through the lines list moving the
1898 # first, and manually walk through the lines list moving the
1839 # counter ourselves.
1899 # counter ourselves.
1840 indent_re = re.compile('\s+\S')
1900 indent_re = re.compile('\s+\S')
1841 xfile = open(fname)
1901 xfile = open(fname)
1842 filelines = xfile.readlines()
1902 filelines = xfile.readlines()
1843 xfile.close()
1903 xfile.close()
1844 nlines = len(filelines)
1904 nlines = len(filelines)
1845 lnum = 0
1905 lnum = 0
1846 while lnum < nlines:
1906 while lnum < nlines:
1847 line = filelines[lnum]
1907 line = filelines[lnum]
1848 lnum += 1
1908 lnum += 1
1849 # don't re-insert logger status info into cache
1909 # don't re-insert logger status info into cache
1850 if line.startswith('#log#'):
1910 if line.startswith('#log#'):
1851 continue
1911 continue
1852 elif line.startswith('#%s'% self.ESC_MAGIC):
1912 elif line.startswith('#%s'% self.ESC_MAGIC):
1853 self.update_cache(line[1:])
1913 self.update_cache(line[1:])
1854 line = magic2python(line)
1914 line = magic2python(line)
1855 elif line.startswith('#!'):
1915 elif line.startswith('#!'):
1856 self.update_cache(line[1:])
1916 self.update_cache(line[1:])
1857 else:
1917 else:
1858 # build a block of code (maybe a single line) for execution
1918 # build a block of code (maybe a single line) for execution
1859 block = line
1919 block = line
1860 try:
1920 try:
1861 next = filelines[lnum] # lnum has already incremented
1921 next = filelines[lnum] # lnum has already incremented
1862 except:
1922 except:
1863 next = None
1923 next = None
1864 while next and indent_re.match(next):
1924 while next and indent_re.match(next):
1865 block += next
1925 block += next
1866 lnum += 1
1926 lnum += 1
1867 try:
1927 try:
1868 next = filelines[lnum]
1928 next = filelines[lnum]
1869 except:
1929 except:
1870 next = None
1930 next = None
1871 # now execute the block of one or more lines
1931 # now execute the block of one or more lines
1872 try:
1932 try:
1873 exec block in globs,locs
1933 exec block in globs,locs
1874 self.update_cache(block.rstrip())
1934 self.update_cache(block.rstrip())
1875 except SystemExit:
1935 except SystemExit:
1876 pass
1936 pass
1877 except:
1937 except:
1878 badblocks.append(block.rstrip())
1938 badblocks.append(block.rstrip())
1879 if kw['quiet']: # restore stdout
1939 if kw['quiet']: # restore stdout
1880 sys.stdout.close()
1940 sys.stdout.close()
1881 sys.stdout = stdout_save
1941 sys.stdout = stdout_save
1882 print 'Finished replaying log file <%s>' % fname
1942 print 'Finished replaying log file <%s>' % fname
1883 if badblocks:
1943 if badblocks:
1884 print >> sys.stderr, ('\nThe following lines/blocks in file '
1944 print >> sys.stderr, ('\nThe following lines/blocks in file '
1885 '<%s> reported errors:' % fname)
1945 '<%s> reported errors:' % fname)
1886
1946
1887 for badline in badblocks:
1947 for badline in badblocks:
1888 print >> sys.stderr, badline
1948 print >> sys.stderr, badline
1889 else: # regular file execution
1949 else: # regular file execution
1890 try:
1950 try:
1891 execfile(fname,*where)
1951 execfile(fname,*where)
1892 except SyntaxError:
1952 except SyntaxError:
1893 etype, evalue = sys.exc_info()[0:2]
1953 etype, evalue = sys.exc_info()[0:2]
1894 self.SyntaxTB(etype,evalue,[])
1954 self.SyntaxTB(etype,evalue,[])
1895 warn('Failure executing file: <%s>' % fname)
1955 warn('Failure executing file: <%s>' % fname)
1896 except SystemExit,status:
1956 except SystemExit,status:
1897 if not kw['exit_ignore']:
1957 if not kw['exit_ignore']:
1898 self.InteractiveTB()
1958 self.InteractiveTB()
1899 warn('Failure executing file: <%s>' % fname)
1959 warn('Failure executing file: <%s>' % fname)
1900 except:
1960 except:
1901 self.InteractiveTB()
1961 self.InteractiveTB()
1902 warn('Failure executing file: <%s>' % fname)
1962 warn('Failure executing file: <%s>' % fname)
1903
1963
1904 #************************* end of file <iplib.py> *****************************
1964 #************************* end of file <iplib.py> *****************************
@@ -1,735 +1,737 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 958 2005-12-27 23:17:51Z fperez $"""
9 $Id: ipmaker.py 960 2005-12-28 06:51:01Z 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,qw_lol,import_fail_info
52 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
53 from IPython.usage import cmd_line_usage,interactive_usage
53 from IPython.usage import cmd_line_usage,interactive_usage
54 from IPython.Prompts import CachedOutput
54 from IPython.Prompts import CachedOutput
55 from IPython.genutils import *
55 from IPython.genutils import *
56
56
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
58 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
59 shell_class=InteractiveShell,embedded=False,**kw):
59 shell_class=InteractiveShell,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,embedded=embedded,**kw)
89 IP = shell_class('__IP',user_ns=user_ns,embedded=embedded,**kw)
90
90
91 # Put 'help' in the user namespace
91 # Put 'help' in the user namespace
92 from site import _Helper
92 from site import _Helper
93 IP.user_ns['help'] = _Helper()
93 IP.user_ns['help'] = _Helper()
94
94
95 if DEVDEBUG:
95 if DEVDEBUG:
96 # For developer debugging only (global flag)
96 # For developer debugging only (global flag)
97 from IPython import ultraTB
97 from IPython import ultraTB
98 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
98 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
99 else:
99 else:
100 # IPython itself shouldn't crash. This will produce a detailed
100 # IPython itself shouldn't crash. This will produce a detailed
101 # post-mortem if it does
101 # post-mortem if it does
102 from IPython import CrashHandler
102 from IPython import CrashHandler
103 sys.excepthook = CrashHandler.CrashHandler(IP)
103 sys.excepthook = CrashHandler.CrashHandler(IP)
104
104
105 IP.BANNER_PARTS = ['Python %s\n'
105 IP.BANNER_PARTS = ['Python %s\n'
106 'Type "copyright", "credits" or "license" '
106 'Type "copyright", "credits" or "license" '
107 'for more information.\n'
107 'for more information.\n'
108 % (sys.version.split('\n')[0],),
108 % (sys.version.split('\n')[0],),
109 "IPython %s -- An enhanced Interactive Python."
109 "IPython %s -- An enhanced Interactive Python."
110 % (__version__,),
110 % (__version__,),
111 """? -> Introduction to IPython's features.
111 """? -> Introduction to IPython's features.
112 %magic -> Information about IPython's 'magic' % functions.
112 %magic -> Information about IPython's 'magic' % functions.
113 help -> Python's own help system.
113 help -> Python's own help system.
114 object? -> Details about 'object'. ?object also works, ?? prints more.
114 object? -> Details about 'object'. ?object also works, ?? prints more.
115 """ ]
115 """ ]
116
116
117 IP.usage = interactive_usage
117 IP.usage = interactive_usage
118
118
119 # Platform-dependent suffix and directory names. We use _ipython instead
119 # Platform-dependent suffix and directory names. We use _ipython instead
120 # of .ipython under win32 b/c there's software that breaks with .named
120 # of .ipython under win32 b/c there's software that breaks with .named
121 # directories on that platform.
121 # directories on that platform.
122 if os.name == 'posix':
122 if os.name == 'posix':
123 rc_suffix = ''
123 rc_suffix = ''
124 ipdir_def = '.ipython'
124 ipdir_def = '.ipython'
125 else:
125 else:
126 rc_suffix = '.ini'
126 rc_suffix = '.ini'
127 ipdir_def = '_ipython'
127 ipdir_def = '_ipython'
128
128
129 # default directory for configuration
129 # default directory for configuration
130 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
130 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
131 os.path.join(IP.home_dir,ipdir_def)))
131 os.path.join(IP.home_dir,ipdir_def)))
132
132
133 # we need the directory where IPython itself is installed
133 # we need the directory where IPython itself is installed
134 import IPython
134 import IPython
135 IPython_dir = os.path.dirname(IPython.__file__)
135 IPython_dir = os.path.dirname(IPython.__file__)
136 del IPython
136 del IPython
137
137
138 #-------------------------------------------------------------------------
138 #-------------------------------------------------------------------------
139 # Command line handling
139 # Command line handling
140
140
141 # Valid command line options (uses DPyGetOpt syntax, like Perl's
141 # Valid command line options (uses DPyGetOpt syntax, like Perl's
142 # GetOpt::Long)
142 # GetOpt::Long)
143
143
144 # Any key not listed here gets deleted even if in the file (like session
144 # Any key not listed here gets deleted even if in the file (like session
145 # or profile). That's deliberate, to maintain the rc namespace clean.
145 # or profile). That's deliberate, to maintain the rc namespace clean.
146
146
147 # Each set of options appears twice: under _conv only the names are
147 # Each set of options appears twice: under _conv only the names are
148 # listed, indicating which type they must be converted to when reading the
148 # listed, indicating which type they must be converted to when reading the
149 # ipythonrc file. And under DPyGetOpt they are listed with the regular
149 # ipythonrc file. And under DPyGetOpt they are listed with the regular
150 # DPyGetOpt syntax (=s,=i,:f,etc).
150 # DPyGetOpt syntax (=s,=i,:f,etc).
151
151
152 # Make sure there's a space before each end of line (they get auto-joined!)
152 # Make sure there's a space before each end of line (they get auto-joined!)
153 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
153 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
154 'c=s classic|cl color_info! colors=s confirm_exit! '
154 'c=s classic|cl color_info! colors=s confirm_exit! '
155 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
155 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
157 'quick screen_length|sl=i prompts_pad_left=i '
157 'quick screen_length|sl=i prompts_pad_left=i '
158 'logfile|lf=s logplay|lp=s profile|p=s '
158 'logfile|lf=s logplay|lp=s profile|p=s '
159 'readline! readline_merge_completions! '
159 'readline! readline_merge_completions! '
160 'readline_omit__names! '
160 'readline_omit__names! '
161 'rcfile=s separate_in|si=s separate_out|so=s '
161 'rcfile=s separate_in|si=s separate_out|so=s '
162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
163 'magic_docstrings system_verbose! '
163 'magic_docstrings system_verbose! '
164 'multi_line_specials!')
164 'multi_line_specials! '
165 'autoedit_syntax!')
165
166
166 # Options that can *only* appear at the cmd line (not in rcfiles).
167 # Options that can *only* appear at the cmd line (not in rcfiles).
167
168
168 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
169 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
169 # the 'C-c !' command in emacs automatically appends a -i option at the end.
170 # the 'C-c !' command in emacs automatically appends a -i option at the end.
170 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
171 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
171 'gthread! qthread! wthread! pylab! tk!')
172 'gthread! qthread! wthread! pylab! tk!')
172
173
173 # Build the actual name list to be used by DPyGetOpt
174 # Build the actual name list to be used by DPyGetOpt
174 opts_names = qw(cmdline_opts) + qw(cmdline_only)
175 opts_names = qw(cmdline_opts) + qw(cmdline_only)
175
176
176 # Set sensible command line defaults.
177 # Set sensible command line defaults.
177 # This should have everything from cmdline_opts and cmdline_only
178 # This should have everything from cmdline_opts and cmdline_only
178 opts_def = Struct(autocall = 1,
179 opts_def = Struct(autocall = 1,
179 autoindent=0,
180 autoindent=0,
180 automagic = 1,
181 automagic = 1,
181 banner = 1,
182 banner = 1,
182 cache_size = 1000,
183 cache_size = 1000,
183 c = '',
184 c = '',
184 classic = 0,
185 classic = 0,
185 colors = 'NoColor',
186 colors = 'NoColor',
186 color_info = 0,
187 color_info = 0,
187 confirm_exit = 1,
188 confirm_exit = 1,
188 debug = 0,
189 debug = 0,
189 deep_reload = 0,
190 deep_reload = 0,
190 editor = '0',
191 editor = '0',
191 help = 0,
192 help = 0,
192 ignore = 0,
193 ignore = 0,
193 ipythondir = ipythondir,
194 ipythondir = ipythondir,
194 log = 0,
195 log = 0,
195 logfile = '',
196 logfile = '',
196 logplay = '',
197 logplay = '',
197 multi_line_specials = 1,
198 multi_line_specials = 1,
198 messages = 1,
199 messages = 1,
199 nosep = 0,
200 nosep = 0,
200 pdb = 0,
201 pdb = 0,
201 pprint = 0,
202 pprint = 0,
202 profile = '',
203 profile = '',
203 prompt_in1 = 'In [\\#]: ',
204 prompt_in1 = 'In [\\#]: ',
204 prompt_in2 = ' .\\D.: ',
205 prompt_in2 = ' .\\D.: ',
205 prompt_out = 'Out[\\#]: ',
206 prompt_out = 'Out[\\#]: ',
206 prompts_pad_left = 1,
207 prompts_pad_left = 1,
207 quick = 0,
208 quick = 0,
208 readline = 1,
209 readline = 1,
209 readline_merge_completions = 1,
210 readline_merge_completions = 1,
210 readline_omit__names = 0,
211 readline_omit__names = 0,
211 rcfile = 'ipythonrc' + rc_suffix,
212 rcfile = 'ipythonrc' + rc_suffix,
212 screen_length = 0,
213 screen_length = 0,
213 separate_in = '\n',
214 separate_in = '\n',
214 separate_out = '\n',
215 separate_out = '\n',
215 separate_out2 = '',
216 separate_out2 = '',
216 system_verbose = 0,
217 system_verbose = 0,
217 gthread = 0,
218 gthread = 0,
218 qthread = 0,
219 qthread = 0,
219 wthread = 0,
220 wthread = 0,
220 pylab = 0,
221 pylab = 0,
221 tk = 0,
222 tk = 0,
222 upgrade = 0,
223 upgrade = 0,
223 Version = 0,
224 Version = 0,
224 xmode = 'Verbose',
225 xmode = 'Verbose',
225 wildcards_case_sensitive = 1,
226 wildcards_case_sensitive = 1,
226 magic_docstrings = 0, # undocumented, for doc generation
227 magic_docstrings = 0, # undocumented, for doc generation
228 autoedit_syntax = 0,
227 )
229 )
228
230
229 # Things that will *only* appear in rcfiles (not at the command line).
231 # Things that will *only* appear in rcfiles (not at the command line).
230 # Make sure there's a space before each end of line (they get auto-joined!)
232 # Make sure there's a space before each end of line (they get auto-joined!)
231 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
233 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
232 qw_lol: 'import_some ',
234 qw_lol: 'import_some ',
233 # for things with embedded whitespace:
235 # for things with embedded whitespace:
234 list_strings:'execute alias readline_parse_and_bind ',
236 list_strings:'execute alias readline_parse_and_bind ',
235 # Regular strings need no conversion:
237 # Regular strings need no conversion:
236 None:'readline_remove_delims ',
238 None:'readline_remove_delims ',
237 }
239 }
238 # Default values for these
240 # Default values for these
239 rc_def = Struct(include = [],
241 rc_def = Struct(include = [],
240 import_mod = [],
242 import_mod = [],
241 import_all = [],
243 import_all = [],
242 import_some = [[]],
244 import_some = [[]],
243 execute = [],
245 execute = [],
244 execfile = [],
246 execfile = [],
245 alias = [],
247 alias = [],
246 readline_parse_and_bind = [],
248 readline_parse_and_bind = [],
247 readline_remove_delims = '',
249 readline_remove_delims = '',
248 )
250 )
249
251
250 # Build the type conversion dictionary from the above tables:
252 # Build the type conversion dictionary from the above tables:
251 typeconv = rcfile_opts.copy()
253 typeconv = rcfile_opts.copy()
252 typeconv.update(optstr2types(cmdline_opts))
254 typeconv.update(optstr2types(cmdline_opts))
253
255
254 # FIXME: the None key appears in both, put that back together by hand. Ugly!
256 # FIXME: the None key appears in both, put that back together by hand. Ugly!
255 typeconv[None] += ' ' + rcfile_opts[None]
257 typeconv[None] += ' ' + rcfile_opts[None]
256
258
257 # Remove quotes at ends of all strings (used to protect spaces)
259 # Remove quotes at ends of all strings (used to protect spaces)
258 typeconv[unquote_ends] = typeconv[None]
260 typeconv[unquote_ends] = typeconv[None]
259 del typeconv[None]
261 del typeconv[None]
260
262
261 # Build the list we'll use to make all config decisions with defaults:
263 # Build the list we'll use to make all config decisions with defaults:
262 opts_all = opts_def.copy()
264 opts_all = opts_def.copy()
263 opts_all.update(rc_def)
265 opts_all.update(rc_def)
264
266
265 # Build conflict resolver for recursive loading of config files:
267 # Build conflict resolver for recursive loading of config files:
266 # - preserve means the outermost file maintains the value, it is not
268 # - preserve means the outermost file maintains the value, it is not
267 # overwritten if an included file has the same key.
269 # overwritten if an included file has the same key.
268 # - add_flip applies + to the two values, so it better make sense to add
270 # - add_flip applies + to the two values, so it better make sense to add
269 # those types of keys. But it flips them first so that things loaded
271 # those types of keys. But it flips them first so that things loaded
270 # deeper in the inclusion chain have lower precedence.
272 # deeper in the inclusion chain have lower precedence.
271 conflict = {'preserve': ' '.join([ typeconv[int],
273 conflict = {'preserve': ' '.join([ typeconv[int],
272 typeconv[unquote_ends] ]),
274 typeconv[unquote_ends] ]),
273 'add_flip': ' '.join([ typeconv[qwflat],
275 'add_flip': ' '.join([ typeconv[qwflat],
274 typeconv[qw_lol],
276 typeconv[qw_lol],
275 typeconv[list_strings] ])
277 typeconv[list_strings] ])
276 }
278 }
277
279
278 # Now actually process the command line
280 # Now actually process the command line
279 getopt = DPyGetOpt.DPyGetOpt()
281 getopt = DPyGetOpt.DPyGetOpt()
280 getopt.setIgnoreCase(0)
282 getopt.setIgnoreCase(0)
281
283
282 getopt.parseConfiguration(opts_names)
284 getopt.parseConfiguration(opts_names)
283
285
284 try:
286 try:
285 getopt.processArguments(argv)
287 getopt.processArguments(argv)
286 except:
288 except:
287 print cmd_line_usage
289 print cmd_line_usage
288 warn('\nError in Arguments: ' + `sys.exc_value`)
290 warn('\nError in Arguments: ' + `sys.exc_value`)
289 sys.exit(1)
291 sys.exit(1)
290
292
291 # convert the options dict to a struct for much lighter syntax later
293 # convert the options dict to a struct for much lighter syntax later
292 opts = Struct(getopt.optionValues)
294 opts = Struct(getopt.optionValues)
293 args = getopt.freeValues
295 args = getopt.freeValues
294
296
295 # this is the struct (which has default values at this point) with which
297 # this is the struct (which has default values at this point) with which
296 # we make all decisions:
298 # we make all decisions:
297 opts_all.update(opts)
299 opts_all.update(opts)
298
300
299 # Options that force an immediate exit
301 # Options that force an immediate exit
300 if opts_all.help:
302 if opts_all.help:
301 page(cmd_line_usage)
303 page(cmd_line_usage)
302 sys.exit()
304 sys.exit()
303
305
304 if opts_all.Version:
306 if opts_all.Version:
305 print __version__
307 print __version__
306 sys.exit()
308 sys.exit()
307
309
308 if opts_all.magic_docstrings:
310 if opts_all.magic_docstrings:
309 IP.magic_magic('-latex')
311 IP.magic_magic('-latex')
310 sys.exit()
312 sys.exit()
311
313
312 # Create user config directory if it doesn't exist. This must be done
314 # Create user config directory if it doesn't exist. This must be done
313 # *after* getting the cmd line options.
315 # *after* getting the cmd line options.
314 if not os.path.isdir(opts_all.ipythondir):
316 if not os.path.isdir(opts_all.ipythondir):
315 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
317 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
316
318
317 # upgrade user config files while preserving a copy of the originals
319 # upgrade user config files while preserving a copy of the originals
318 if opts_all.upgrade:
320 if opts_all.upgrade:
319 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
321 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
320
322
321 # check mutually exclusive options in the *original* command line
323 # check mutually exclusive options in the *original* command line
322 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
324 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
323 qw('classic profile'),qw('classic rcfile')])
325 qw('classic profile'),qw('classic rcfile')])
324
326
325 # default logfilename used when -log is called.
327 # default logfilename used when -log is called.
326 IP.LOGDEF = 'ipython.log'
328 IP.LOGDEF = 'ipython.log'
327
329
328 #---------------------------------------------------------------------------
330 #---------------------------------------------------------------------------
329 # Log replay
331 # Log replay
330
332
331 # if -logplay, we need to 'become' the other session. That basically means
333 # if -logplay, we need to 'become' the other session. That basically means
332 # replacing the current command line environment with that of the old
334 # replacing the current command line environment with that of the old
333 # session and moving on.
335 # session and moving on.
334
336
335 # this is needed so that later we know we're in session reload mode, as
337 # this is needed so that later we know we're in session reload mode, as
336 # opts_all will get overwritten:
338 # opts_all will get overwritten:
337 load_logplay = 0
339 load_logplay = 0
338
340
339 if opts_all.logplay:
341 if opts_all.logplay:
340 load_logplay = opts_all.logplay
342 load_logplay = opts_all.logplay
341 opts_debug_save = opts_all.debug
343 opts_debug_save = opts_all.debug
342 try:
344 try:
343 logplay = open(opts_all.logplay)
345 logplay = open(opts_all.logplay)
344 except IOError:
346 except IOError:
345 if opts_all.debug: IP.InteractiveTB()
347 if opts_all.debug: IP.InteractiveTB()
346 warn('Could not open logplay file '+`opts_all.logplay`)
348 warn('Could not open logplay file '+`opts_all.logplay`)
347 # restore state as if nothing had happened and move on, but make
349 # restore state as if nothing had happened and move on, but make
348 # sure that later we don't try to actually load the session file
350 # sure that later we don't try to actually load the session file
349 logplay = None
351 logplay = None
350 load_logplay = 0
352 load_logplay = 0
351 del opts_all.logplay
353 del opts_all.logplay
352 else:
354 else:
353 try:
355 try:
354 logplay.readline()
356 logplay.readline()
355 logplay.readline();
357 logplay.readline();
356 # this reloads that session's command line
358 # this reloads that session's command line
357 cmd = logplay.readline()[6:]
359 cmd = logplay.readline()[6:]
358 exec cmd
360 exec cmd
359 # restore the true debug flag given so that the process of
361 # restore the true debug flag given so that the process of
360 # session loading itself can be monitored.
362 # session loading itself can be monitored.
361 opts.debug = opts_debug_save
363 opts.debug = opts_debug_save
362 # save the logplay flag so later we don't overwrite the log
364 # save the logplay flag so later we don't overwrite the log
363 opts.logplay = load_logplay
365 opts.logplay = load_logplay
364 # now we must update our own structure with defaults
366 # now we must update our own structure with defaults
365 opts_all.update(opts)
367 opts_all.update(opts)
366 # now load args
368 # now load args
367 cmd = logplay.readline()[6:]
369 cmd = logplay.readline()[6:]
368 exec cmd
370 exec cmd
369 logplay.close()
371 logplay.close()
370 except:
372 except:
371 logplay.close()
373 logplay.close()
372 if opts_all.debug: IP.InteractiveTB()
374 if opts_all.debug: IP.InteractiveTB()
373 warn("Logplay file lacking full configuration information.\n"
375 warn("Logplay file lacking full configuration information.\n"
374 "I'll try to read it, but some things may not work.")
376 "I'll try to read it, but some things may not work.")
375
377
376 #-------------------------------------------------------------------------
378 #-------------------------------------------------------------------------
377 # set up output traps: catch all output from files, being run, modules
379 # set up output traps: catch all output from files, being run, modules
378 # loaded, etc. Then give it to the user in a clean form at the end.
380 # loaded, etc. Then give it to the user in a clean form at the end.
379
381
380 msg_out = 'Output messages. '
382 msg_out = 'Output messages. '
381 msg_err = 'Error messages. '
383 msg_err = 'Error messages. '
382 msg_sep = '\n'
384 msg_sep = '\n'
383 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
385 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
384 msg_err,msg_sep,debug,
386 msg_err,msg_sep,debug,
385 quiet_out=1),
387 quiet_out=1),
386 user_exec = OutputTrap('User File Execution',msg_out,
388 user_exec = OutputTrap('User File Execution',msg_out,
387 msg_err,msg_sep,debug),
389 msg_err,msg_sep,debug),
388 logplay = OutputTrap('Log Loader',msg_out,
390 logplay = OutputTrap('Log Loader',msg_out,
389 msg_err,msg_sep,debug),
391 msg_err,msg_sep,debug),
390 summary = ''
392 summary = ''
391 )
393 )
392
394
393 #-------------------------------------------------------------------------
395 #-------------------------------------------------------------------------
394 # Process user ipythonrc-type configuration files
396 # Process user ipythonrc-type configuration files
395
397
396 # turn on output trapping and log to msg.config
398 # turn on output trapping and log to msg.config
397 # remember that with debug on, trapping is actually disabled
399 # remember that with debug on, trapping is actually disabled
398 msg.config.trap_all()
400 msg.config.trap_all()
399
401
400 # look for rcfile in current or default directory
402 # look for rcfile in current or default directory
401 try:
403 try:
402 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
404 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
403 except IOError:
405 except IOError:
404 if opts_all.debug: IP.InteractiveTB()
406 if opts_all.debug: IP.InteractiveTB()
405 warn('Configuration file %s not found. Ignoring request.'
407 warn('Configuration file %s not found. Ignoring request.'
406 % (opts_all.rcfile) )
408 % (opts_all.rcfile) )
407
409
408 # 'profiles' are a shorthand notation for config filenames
410 # 'profiles' are a shorthand notation for config filenames
409 if opts_all.profile:
411 if opts_all.profile:
410 try:
412 try:
411 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
413 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
412 + rc_suffix,
414 + rc_suffix,
413 opts_all.ipythondir)
415 opts_all.ipythondir)
414 except IOError:
416 except IOError:
415 if opts_all.debug: IP.InteractiveTB()
417 if opts_all.debug: IP.InteractiveTB()
416 opts.profile = '' # remove profile from options if invalid
418 opts.profile = '' # remove profile from options if invalid
417 warn('Profile configuration file %s not found. Ignoring request.'
419 warn('Profile configuration file %s not found. Ignoring request.'
418 % (opts_all.profile) )
420 % (opts_all.profile) )
419
421
420 # load the config file
422 # load the config file
421 rcfiledata = None
423 rcfiledata = None
422 if opts_all.quick:
424 if opts_all.quick:
423 print 'Launching IPython in quick mode. No config file read.'
425 print 'Launching IPython in quick mode. No config file read.'
424 elif opts_all.classic:
426 elif opts_all.classic:
425 print 'Launching IPython in classic mode. No config file read.'
427 print 'Launching IPython in classic mode. No config file read.'
426 elif opts_all.rcfile:
428 elif opts_all.rcfile:
427 try:
429 try:
428 cfg_loader = ConfigLoader(conflict)
430 cfg_loader = ConfigLoader(conflict)
429 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
431 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
430 'include',opts_all.ipythondir,
432 'include',opts_all.ipythondir,
431 purge = 1,
433 purge = 1,
432 unique = conflict['preserve'])
434 unique = conflict['preserve'])
433 except:
435 except:
434 IP.InteractiveTB()
436 IP.InteractiveTB()
435 warn('Problems loading configuration file '+
437 warn('Problems loading configuration file '+
436 `opts_all.rcfile`+
438 `opts_all.rcfile`+
437 '\nStarting with default -bare bones- configuration.')
439 '\nStarting with default -bare bones- configuration.')
438 else:
440 else:
439 warn('No valid configuration file found in either currrent directory\n'+
441 warn('No valid configuration file found in either currrent directory\n'+
440 'or in the IPython config. directory: '+`opts_all.ipythondir`+
442 'or in the IPython config. directory: '+`opts_all.ipythondir`+
441 '\nProceeding with internal defaults.')
443 '\nProceeding with internal defaults.')
442
444
443 #------------------------------------------------------------------------
445 #------------------------------------------------------------------------
444 # Set exception handlers in mode requested by user.
446 # Set exception handlers in mode requested by user.
445 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
447 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
446 IP.magic_xmode(opts_all.xmode)
448 IP.magic_xmode(opts_all.xmode)
447 otrap.release_out()
449 otrap.release_out()
448
450
449 #------------------------------------------------------------------------
451 #------------------------------------------------------------------------
450 # Execute user config
452 # Execute user config
451
453
452 # Create a valid config structure with the right precedence order:
454 # Create a valid config structure with the right precedence order:
453 # defaults < rcfile < command line. This needs to be in the instance, so
455 # defaults < rcfile < command line. This needs to be in the instance, so
454 # that method calls below that rely on it find it.
456 # that method calls below that rely on it find it.
455 IP.rc = rc_def.copy()
457 IP.rc = rc_def.copy()
456
458
457 # Work with a local alias inside this routine to avoid unnecessary
459 # Work with a local alias inside this routine to avoid unnecessary
458 # attribute lookups.
460 # attribute lookups.
459 IP_rc = IP.rc
461 IP_rc = IP.rc
460
462
461 IP_rc.update(opts_def)
463 IP_rc.update(opts_def)
462 if rcfiledata:
464 if rcfiledata:
463 # now we can update
465 # now we can update
464 IP_rc.update(rcfiledata)
466 IP_rc.update(rcfiledata)
465 IP_rc.update(opts)
467 IP_rc.update(opts)
466 IP_rc.update(rc_override)
468 IP_rc.update(rc_override)
467
469
468 # Store the original cmd line for reference:
470 # Store the original cmd line for reference:
469 IP_rc.opts = opts
471 IP_rc.opts = opts
470 IP_rc.args = args
472 IP_rc.args = args
471
473
472 # create a *runtime* Struct like rc for holding parameters which may be
474 # create a *runtime* Struct like rc for holding parameters which may be
473 # created and/or modified by runtime user extensions.
475 # created and/or modified by runtime user extensions.
474 IP.runtime_rc = Struct()
476 IP.runtime_rc = Struct()
475
477
476 # from this point on, all config should be handled through IP_rc,
478 # from this point on, all config should be handled through IP_rc,
477 # opts* shouldn't be used anymore.
479 # opts* shouldn't be used anymore.
478
480
479 # add personal .ipython dir to sys.path so that users can put things in
481 # add personal .ipython dir to sys.path so that users can put things in
480 # there for customization
482 # there for customization
481 sys.path.append(IP_rc.ipythondir)
483 sys.path.append(IP_rc.ipythondir)
482 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
484 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
483
485
484 # update IP_rc with some special things that need manual
486 # update IP_rc with some special things that need manual
485 # tweaks. Basically options which affect other options. I guess this
487 # tweaks. Basically options which affect other options. I guess this
486 # should just be written so that options are fully orthogonal and we
488 # should just be written so that options are fully orthogonal and we
487 # wouldn't worry about this stuff!
489 # wouldn't worry about this stuff!
488
490
489 if IP_rc.classic:
491 if IP_rc.classic:
490 IP_rc.quick = 1
492 IP_rc.quick = 1
491 IP_rc.cache_size = 0
493 IP_rc.cache_size = 0
492 IP_rc.pprint = 0
494 IP_rc.pprint = 0
493 IP_rc.prompt_in1 = '>>> '
495 IP_rc.prompt_in1 = '>>> '
494 IP_rc.prompt_in2 = '... '
496 IP_rc.prompt_in2 = '... '
495 IP_rc.prompt_out = ''
497 IP_rc.prompt_out = ''
496 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
498 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
497 IP_rc.colors = 'NoColor'
499 IP_rc.colors = 'NoColor'
498 IP_rc.xmode = 'Plain'
500 IP_rc.xmode = 'Plain'
499
501
500 # configure readline
502 # configure readline
501 # Define the history file for saving commands in between sessions
503 # Define the history file for saving commands in between sessions
502 if IP_rc.profile:
504 if IP_rc.profile:
503 histfname = 'history-%s' % IP_rc.profile
505 histfname = 'history-%s' % IP_rc.profile
504 else:
506 else:
505 histfname = 'history'
507 histfname = 'history'
506 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
508 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
507
509
508 # update exception handlers with rc file status
510 # update exception handlers with rc file status
509 otrap.trap_out() # I don't want these messages ever.
511 otrap.trap_out() # I don't want these messages ever.
510 IP.magic_xmode(IP_rc.xmode)
512 IP.magic_xmode(IP_rc.xmode)
511 otrap.release_out()
513 otrap.release_out()
512
514
513 # activate logging if requested and not reloading a log
515 # activate logging if requested and not reloading a log
514 if IP_rc.logplay:
516 if IP_rc.logplay:
515 IP.magic_logstart(IP_rc.logplay + ' append')
517 IP.magic_logstart(IP_rc.logplay + ' append')
516 elif IP_rc.logfile:
518 elif IP_rc.logfile:
517 IP.magic_logstart(IP_rc.logfile)
519 IP.magic_logstart(IP_rc.logfile)
518 elif IP_rc.log:
520 elif IP_rc.log:
519 IP.magic_logstart()
521 IP.magic_logstart()
520
522
521 # find user editor so that it we don't have to look it up constantly
523 # find user editor so that it we don't have to look it up constantly
522 if IP_rc.editor.strip()=='0':
524 if IP_rc.editor.strip()=='0':
523 try:
525 try:
524 ed = os.environ['EDITOR']
526 ed = os.environ['EDITOR']
525 except KeyError:
527 except KeyError:
526 if os.name == 'posix':
528 if os.name == 'posix':
527 ed = 'vi' # the only one guaranteed to be there!
529 ed = 'vi' # the only one guaranteed to be there!
528 else:
530 else:
529 ed = 'notepad' # same in Windows!
531 ed = 'notepad' # same in Windows!
530 IP_rc.editor = ed
532 IP_rc.editor = ed
531
533
532 # Keep track of whether this is an embedded instance or not (useful for
534 # Keep track of whether this is an embedded instance or not (useful for
533 # post-mortems).
535 # post-mortems).
534 IP_rc.embedded = IP.embedded
536 IP_rc.embedded = IP.embedded
535
537
536 # Recursive reload
538 # Recursive reload
537 try:
539 try:
538 from IPython import deep_reload
540 from IPython import deep_reload
539 if IP_rc.deep_reload:
541 if IP_rc.deep_reload:
540 __builtin__.reload = deep_reload.reload
542 __builtin__.reload = deep_reload.reload
541 else:
543 else:
542 __builtin__.dreload = deep_reload.reload
544 __builtin__.dreload = deep_reload.reload
543 del deep_reload
545 del deep_reload
544 except ImportError:
546 except ImportError:
545 pass
547 pass
546
548
547 # Save the current state of our namespace so that the interactive shell
549 # Save the current state of our namespace so that the interactive shell
548 # can later know which variables have been created by us from config files
550 # can later know which variables have been created by us from config files
549 # and loading. This way, loading a file (in any way) is treated just like
551 # and loading. This way, loading a file (in any way) is treated just like
550 # defining things on the command line, and %who works as expected.
552 # defining things on the command line, and %who works as expected.
551
553
552 # DON'T do anything that affects the namespace beyond this point!
554 # DON'T do anything that affects the namespace beyond this point!
553 IP.internal_ns.update(__main__.__dict__)
555 IP.internal_ns.update(__main__.__dict__)
554
556
555 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
557 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
556
558
557 # Now run through the different sections of the users's config
559 # Now run through the different sections of the users's config
558 if IP_rc.debug:
560 if IP_rc.debug:
559 print 'Trying to execute the following configuration structure:'
561 print 'Trying to execute the following configuration structure:'
560 print '(Things listed first are deeper in the inclusion tree and get'
562 print '(Things listed first are deeper in the inclusion tree and get'
561 print 'loaded first).\n'
563 print 'loaded first).\n'
562 pprint(IP_rc.__dict__)
564 pprint(IP_rc.__dict__)
563
565
564 for mod in IP_rc.import_mod:
566 for mod in IP_rc.import_mod:
565 try:
567 try:
566 exec 'import '+mod in IP.user_ns
568 exec 'import '+mod in IP.user_ns
567 except :
569 except :
568 IP.InteractiveTB()
570 IP.InteractiveTB()
569 import_fail_info(mod)
571 import_fail_info(mod)
570
572
571 for mod_fn in IP_rc.import_some:
573 for mod_fn in IP_rc.import_some:
572 if mod_fn == []: break
574 if mod_fn == []: break
573 mod,fn = mod_fn[0],','.join(mod_fn[1:])
575 mod,fn = mod_fn[0],','.join(mod_fn[1:])
574 try:
576 try:
575 exec 'from '+mod+' import '+fn in IP.user_ns
577 exec 'from '+mod+' import '+fn in IP.user_ns
576 except :
578 except :
577 IP.InteractiveTB()
579 IP.InteractiveTB()
578 import_fail_info(mod,fn)
580 import_fail_info(mod,fn)
579
581
580 for mod in IP_rc.import_all:
582 for mod in IP_rc.import_all:
581 try:
583 try:
582 exec 'from '+mod+' import *' in IP.user_ns
584 exec 'from '+mod+' import *' in IP.user_ns
583 except :
585 except :
584 IP.InteractiveTB()
586 IP.InteractiveTB()
585 import_fail_info(mod)
587 import_fail_info(mod)
586
588
587 for code in IP_rc.execute:
589 for code in IP_rc.execute:
588 try:
590 try:
589 exec code in IP.user_ns
591 exec code in IP.user_ns
590 except:
592 except:
591 IP.InteractiveTB()
593 IP.InteractiveTB()
592 warn('Failure executing code: ' + `code`)
594 warn('Failure executing code: ' + `code`)
593
595
594 # Execute the files the user wants in ipythonrc
596 # Execute the files the user wants in ipythonrc
595 for file in IP_rc.execfile:
597 for file in IP_rc.execfile:
596 try:
598 try:
597 file = filefind(file,sys.path+[IPython_dir])
599 file = filefind(file,sys.path+[IPython_dir])
598 except IOError:
600 except IOError:
599 warn(itpl('File $file not found. Skipping it.'))
601 warn(itpl('File $file not found. Skipping it.'))
600 else:
602 else:
601 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
603 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
602
604
603 # release stdout and stderr and save config log into a global summary
605 # release stdout and stderr and save config log into a global summary
604 msg.config.release_all()
606 msg.config.release_all()
605 if IP_rc.messages:
607 if IP_rc.messages:
606 msg.summary += msg.config.summary_all()
608 msg.summary += msg.config.summary_all()
607
609
608 #------------------------------------------------------------------------
610 #------------------------------------------------------------------------
609 # Setup interactive session
611 # Setup interactive session
610
612
611 # Now we should be fully configured. We can then execute files or load
613 # Now we should be fully configured. We can then execute files or load
612 # things only needed for interactive use. Then we'll open the shell.
614 # things only needed for interactive use. Then we'll open the shell.
613
615
614 # Take a snapshot of the user namespace before opening the shell. That way
616 # Take a snapshot of the user namespace before opening the shell. That way
615 # we'll be able to identify which things were interactively defined and
617 # we'll be able to identify which things were interactively defined and
616 # which were defined through config files.
618 # which were defined through config files.
617 IP.user_config_ns = IP.user_ns.copy()
619 IP.user_config_ns = IP.user_ns.copy()
618
620
619 # Force reading a file as if it were a session log. Slower but safer.
621 # Force reading a file as if it were a session log. Slower but safer.
620 if load_logplay:
622 if load_logplay:
621 print 'Replaying log...'
623 print 'Replaying log...'
622 try:
624 try:
623 if IP_rc.debug:
625 if IP_rc.debug:
624 logplay_quiet = 0
626 logplay_quiet = 0
625 else:
627 else:
626 logplay_quiet = 1
628 logplay_quiet = 1
627
629
628 msg.logplay.trap_all()
630 msg.logplay.trap_all()
629 IP.safe_execfile(load_logplay,IP.user_ns,
631 IP.safe_execfile(load_logplay,IP.user_ns,
630 islog = 1, quiet = logplay_quiet)
632 islog = 1, quiet = logplay_quiet)
631 msg.logplay.release_all()
633 msg.logplay.release_all()
632 if IP_rc.messages:
634 if IP_rc.messages:
633 msg.summary += msg.logplay.summary_all()
635 msg.summary += msg.logplay.summary_all()
634 except:
636 except:
635 warn('Problems replaying logfile %s.' % load_logplay)
637 warn('Problems replaying logfile %s.' % load_logplay)
636 IP.InteractiveTB()
638 IP.InteractiveTB()
637
639
638 # Load remaining files in command line
640 # Load remaining files in command line
639 msg.user_exec.trap_all()
641 msg.user_exec.trap_all()
640
642
641 # Do NOT execute files named in the command line as scripts to be loaded
643 # Do NOT execute files named in the command line as scripts to be loaded
642 # by embedded instances. Doing so has the potential for an infinite
644 # by embedded instances. Doing so has the potential for an infinite
643 # recursion if there are exceptions thrown in the process.
645 # recursion if there are exceptions thrown in the process.
644
646
645 # XXX FIXME: the execution of user files should be moved out to after
647 # XXX FIXME: the execution of user files should be moved out to after
646 # ipython is fully initialized, just as if they were run via %run at the
648 # ipython is fully initialized, just as if they were run via %run at the
647 # ipython prompt. This would also give them the benefit of ipython's
649 # ipython prompt. This would also give them the benefit of ipython's
648 # nice tracebacks.
650 # nice tracebacks.
649
651
650 if not embedded and IP_rc.args:
652 if not embedded and IP_rc.args:
651 name_save = IP.user_ns['__name__']
653 name_save = IP.user_ns['__name__']
652 IP.user_ns['__name__'] = '__main__'
654 IP.user_ns['__name__'] = '__main__'
653 try:
655 try:
654 # Set our own excepthook in case the user code tries to call it
656 # Set our own excepthook in case the user code tries to call it
655 # directly. This prevents triggering the IPython crash handler.
657 # directly. This prevents triggering the IPython crash handler.
656 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
658 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
657 for run in args:
659 for run in args:
658 IP.safe_execfile(run,IP.user_ns)
660 IP.safe_execfile(run,IP.user_ns)
659 finally:
661 finally:
660 # Reset our crash handler in place
662 # Reset our crash handler in place
661 sys.excepthook = old_excepthook
663 sys.excepthook = old_excepthook
662
664
663 IP.user_ns['__name__'] = name_save
665 IP.user_ns['__name__'] = name_save
664
666
665 msg.user_exec.release_all()
667 msg.user_exec.release_all()
666 if IP_rc.messages:
668 if IP_rc.messages:
667 msg.summary += msg.user_exec.summary_all()
669 msg.summary += msg.user_exec.summary_all()
668
670
669 # since we can't specify a null string on the cmd line, 0 is the equivalent:
671 # since we can't specify a null string on the cmd line, 0 is the equivalent:
670 if IP_rc.nosep:
672 if IP_rc.nosep:
671 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
673 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
672 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
674 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
673 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
675 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
674 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
676 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
675 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
677 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
676 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
678 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
677 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
679 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
678
680
679 # Determine how many lines at the bottom of the screen are needed for
681 # Determine how many lines at the bottom of the screen are needed for
680 # showing prompts, so we can know wheter long strings are to be printed or
682 # showing prompts, so we can know wheter long strings are to be printed or
681 # paged:
683 # paged:
682 num_lines_bot = IP_rc.separate_in.count('\n')+1
684 num_lines_bot = IP_rc.separate_in.count('\n')+1
683 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
685 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
684 # Initialize cache, set in/out prompts and printing system
686 # Initialize cache, set in/out prompts and printing system
685 IP.outputcache = CachedOutput(IP_rc.cache_size,
687 IP.outputcache = CachedOutput(IP_rc.cache_size,
686 IP_rc.pprint,
688 IP_rc.pprint,
687 input_sep = IP_rc.separate_in,
689 input_sep = IP_rc.separate_in,
688 output_sep = IP_rc.separate_out,
690 output_sep = IP_rc.separate_out,
689 output_sep2 = IP_rc.separate_out2,
691 output_sep2 = IP_rc.separate_out2,
690 ps1 = IP_rc.prompt_in1,
692 ps1 = IP_rc.prompt_in1,
691 ps2 = IP_rc.prompt_in2,
693 ps2 = IP_rc.prompt_in2,
692 ps_out = IP_rc.prompt_out,
694 ps_out = IP_rc.prompt_out,
693 user_ns = IP.user_ns,
695 user_ns = IP.user_ns,
694 input_hist = IP.input_hist,
696 input_hist = IP.input_hist,
695 pad_left = IP_rc.prompts_pad_left)
697 pad_left = IP_rc.prompts_pad_left)
696
698
697 # user may have over-ridden the default print hook:
699 # user may have over-ridden the default print hook:
698 try:
700 try:
699 IP.outputcache.__class__.display = IP.hooks.display
701 IP.outputcache.__class__.display = IP.hooks.display
700 except AttributeError:
702 except AttributeError:
701 pass
703 pass
702
704
703 # Set calling of pdb on exceptions
705 # Set calling of pdb on exceptions
704 IP.InteractiveTB.call_pdb = IP_rc.pdb
706 IP.InteractiveTB.call_pdb = IP_rc.pdb
705
707
706 # I don't like assigning globally to sys, because it means when embedding
708 # I don't like assigning globally to sys, because it means when embedding
707 # instances, each embedded instance overrides the previous choice. But
709 # instances, each embedded instance overrides the previous choice. But
708 # sys.displayhook seems to be called internally by exec, so I don't see a
710 # sys.displayhook seems to be called internally by exec, so I don't see a
709 # way around it.
711 # way around it.
710 sys.displayhook = IP.outputcache
712 sys.displayhook = IP.outputcache
711
713
712 # we need to know globally if we're caching i/o or not
714 # we need to know globally if we're caching i/o or not
713 IP.do_full_cache = IP.outputcache.do_full_cache
715 IP.do_full_cache = IP.outputcache.do_full_cache
714
716
715 # configure startup banner
717 # configure startup banner
716 if IP_rc.c: # regular python doesn't print the banner with -c
718 if IP_rc.c: # regular python doesn't print the banner with -c
717 IP_rc.banner = 0
719 IP_rc.banner = 0
718 if IP_rc.banner:
720 if IP_rc.banner:
719 BANN_P = IP.BANNER_PARTS
721 BANN_P = IP.BANNER_PARTS
720 else:
722 else:
721 BANN_P = []
723 BANN_P = []
722
724
723 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
725 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
724
726
725 # add message log (possibly empty)
727 # add message log (possibly empty)
726 if msg.summary: BANN_P.append(msg.summary)
728 if msg.summary: BANN_P.append(msg.summary)
727 # Final banner is a string
729 # Final banner is a string
728 IP.BANNER = '\n'.join(BANN_P)
730 IP.BANNER = '\n'.join(BANN_P)
729
731
730 # Finalize the IPython instance. This assumes the rc structure is fully
732 # Finalize the IPython instance. This assumes the rc structure is fully
731 # in place.
733 # in place.
732 IP.post_config_initialization()
734 IP.post_config_initialization()
733
735
734 return IP
736 return IP
735 #************************ end of file <ipmaker.py> **************************
737 #************************ end of file <ipmaker.py> **************************
@@ -1,586 +1,585 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 926 2005-12-01 18:14:21Z fperez $
9 # $Id: usage.py 960 2005-12-28 06:51:01Z 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 -[no]autocall
148 Make IPython automatically call any callable object even if you
148 Make IPython automatically call any callable object even if you
149 didn’t 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.
151
151
152 -[no]autoindent
152 -[no]autoindent
153 Turn automatic indentation on/off.
153 Turn automatic indentation on/off.
154
154
155 -[no]automagic
155 -[no]automagic
156 Make magic commands automatic (without needing their first char-
156 Make magic commands automatic (without needing their first char-
157 acter to be @). Type @magic at the IPython prompt for more
157 acter to be %). Type %magic at the IPython prompt for more
158 information.
158 information.
159
159
160 -[no]autoparens
160 -[no]autoedit_syntax
161 Make IPython automatically call any callable object even if you
161 When a syntax error occurs after editing a file, automatically
162 didn’t type explicit parentheses. For example, ’str 43’ becomes
162 open the file to the trouble causing line for convenient fixing.
163 ’str(43)’ automatically.
164
163
165 -[no]banner
164 -[no]banner
166 Print the intial information banner (default on).
165 Print the intial information banner (default on).
167
166
168 -c <command>
167 -c <command>
169 Execute the given command string, and set sys.argv to [’c’].
168 Execute the given command string, and set sys.argv to [’c’].
170 This is similar to the -c option in the normal Python inter-
169 This is similar to the -c option in the normal Python inter-
171 preter.
170 preter.
172
171
173 -cache_size|cs <n>
172 -cache_size|cs <n>
174 Size of the output cache (maximum number of entries to hold in
173 Size of the output cache (maximum number of entries to hold in
175 memory). The default is 1000, you can change it permanently in
174 memory). The default is 1000, you can change it permanently in
176 your config file. Setting it to 0 completely disables the
175 your config file. Setting it to 0 completely disables the
177 caching system, and the minimum value accepted is 20 (if you
176 caching system, and the minimum value accepted is 20 (if you
178 provide a value less than 20, it is reset to 0 and a warning is
177 provide a value less than 20, it is reset to 0 and a warning is
179 issued). This limit is defined because otherwise you’ll spend
178 issued). This limit is defined because otherwise you’ll spend
180 more time re-flushing a too small cache than working.
179 more time re-flushing a too small cache than working.
181
180
182 -classic|cl
181 -classic|cl
183 Gives IPython a similar feel to the classic Python prompt.
182 Gives IPython a similar feel to the classic Python prompt.
184
183
185 -colors <scheme>
184 -colors <scheme>
186 Color scheme for prompts and exception reporting. Currently
185 Color scheme for prompts and exception reporting. Currently
187 implemented: NoColor, Linux, and LightBG.
186 implemented: NoColor, Linux, and LightBG.
188
187
189 -[no]color_info
188 -[no]color_info
190 IPython can display information about objects via a set of func-
189 IPython can display information about objects via a set of func-
191 tions, and optionally can use colors for this, syntax highlight-
190 tions, and optionally can use colors for this, syntax highlight-
192 ing source code and various other elements. However, because
191 ing source code and various other elements. However, because
193 this information is passed through a pager (like ’less’) and
192 this information is passed through a pager (like ’less’) and
194 many pagers get confused with color codes, this option is off by
193 many pagers get confused with color codes, this option is off by
195 default. You can test it and turn it on permanently in your
194 default. You can test it and turn it on permanently in your
196 ipythonrc file if it works for you. As a reference, the ’less’
195 ipythonrc file if it works for you. As a reference, the ’less’
197 pager supplied with Mandrake 8.2 works ok, but that in RedHat
196 pager supplied with Mandrake 8.2 works ok, but that in RedHat
198 7.2 doesn’t.
197 7.2 doesn’t.
199
198
200 Test it and turn it on permanently if it works with your system.
199 Test it and turn it on permanently if it works with your system.
201 The magic function @color_info allows you to toggle this inter-
200 The magic function @color_info allows you to toggle this inter-
202 actively for testing.
201 actively for testing.
203
202
204 -[no]confirm_exit
203 -[no]confirm_exit
205 Set to confirm when you try to exit IPython with an EOF (Con-
204 Set to confirm when you try to exit IPython with an EOF (Con-
206 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
205 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
207 magic functions @Exit or @Quit you can force a direct exit,
206 magic functions @Exit or @Quit you can force a direct exit,
208 bypassing any confirmation.
207 bypassing any confirmation.
209
208
210 -[no]debug
209 -[no]debug
211 Show information about the loading process. Very useful to pin
210 Show information about the loading process. Very useful to pin
212 down problems with your configuration files or to get details
211 down problems with your configuration files or to get details
213 about session restores.
212 about session restores.
214
213
215 -[no]deep_reload
214 -[no]deep_reload
216 IPython can use the deep_reload module which reloads changes in
215 IPython can use the deep_reload module which reloads changes in
217 modules recursively (it replaces the reload() function, so you
216 modules recursively (it replaces the reload() function, so you
218 don’t need to change anything to use it). deep_reload() forces a
217 don’t need to change anything to use it). deep_reload() forces a
219 full reload of modules whose code may have changed, which the
218 full reload of modules whose code may have changed, which the
220 default reload() function does not.
219 default reload() function does not.
221
220
222 When deep_reload is off, IPython will use the normal reload(),
221 When deep_reload is off, IPython will use the normal reload(),
223 but deep_reload will still be available as dreload(). This fea-
222 but deep_reload will still be available as dreload(). This fea-
224 ture is off by default [which means that you have both normal
223 ture is off by default [which means that you have both normal
225 reload() and dreload()].
224 reload() and dreload()].
226
225
227 -editor <name>
226 -editor <name>
228 Which editor to use with the @edit command. By default, IPython
227 Which editor to use with the @edit command. By default, IPython
229 will honor your EDITOR environment variable (if not set, vi is
228 will honor your EDITOR environment variable (if not set, vi is
230 the Unix default and notepad the Windows one). Since this editor
229 the Unix default and notepad the Windows one). Since this editor
231 is invoked on the fly by IPython and is meant for editing small
230 is invoked on the fly by IPython and is meant for editing small
232 code snippets, you may want to use a small, lightweight editor
231 code snippets, you may want to use a small, lightweight editor
233 here (in case your default EDITOR is something like Emacs).
232 here (in case your default EDITOR is something like Emacs).
234
233
235 -ipythondir <name>
234 -ipythondir <name>
236 The name of your IPython configuration directory IPYTHONDIR.
235 The name of your IPython configuration directory IPYTHONDIR.
237 This can also be specified through the environment variable
236 This can also be specified through the environment variable
238 IPYTHONDIR.
237 IPYTHONDIR.
239
238
240 -log|l Generate a log file of all input. The file is named ipython.log
239 -log|l Generate a log file of all input. The file is named ipython.log
241 in your current directory (which prevents logs from multiple
240 in your current directory (which prevents logs from multiple
242 IPython sessions from trampling each other). You can use this to
241 IPython sessions from trampling each other). You can use this to
243 later restore a session by loading your logfile as a file to be
242 later restore a session by loading your logfile as a file to be
244 executed with option -logplay (see below).
243 executed with option -logplay (see below).
245
244
246 -logfile|lf
245 -logfile|lf
247 Specifu the name of your logfile.
246 Specifu the name of your logfile.
248
247
249 -logplay|lp
248 -logplay|lp
250 Replay a previous log. For restoring a session as close as pos-
249 Replay a previous log. For restoring a session as close as pos-
251 sible to the state you left it in, use this option (don’t just
250 sible to the state you left it in, use this option (don’t just
252 run the logfile). With -logplay, IPython will try to reconstruct
251 run the logfile). With -logplay, IPython will try to reconstruct
253 the previous working environment in full, not just execute the
252 the previous working environment in full, not just execute the
254 commands in the logfile.
253 commands in the logfile.
255 When a session is restored, logging is automatically turned on
254 When a session is restored, logging is automatically turned on
256 again with the name of the logfile it was invoked with (it is
255 again with the name of the logfile it was invoked with (it is
257 read from the log header). So once you’ve turned logging on for
256 read from the log header). So once you’ve turned logging on for
258 a session, you can quit IPython and reload it as many times as
257 a session, you can quit IPython and reload it as many times as
259 you want and it will continue to log its history and restore
258 you want and it will continue to log its history and restore
260 from the beginning every time.
259 from the beginning every time.
261
260
262 Caveats: there are limitations in this option. The history vari-
261 Caveats: there are limitations in this option. The history vari-
263 ables _i*,_* and _dh don’t get restored properly. In the future
262 ables _i*,_* and _dh don’t get restored properly. In the future
264 we will try to implement full session saving by writing and
263 we will try to implement full session saving by writing and
265 retrieving a failed because of inherent limitations of Python’s
264 retrieving a failed because of inherent limitations of Python’s
266 Pickle module, so this may have to wait.
265 Pickle module, so this may have to wait.
267
266
268 -[no]messages
267 -[no]messages
269 Print messages which IPython collects about its startup process
268 Print messages which IPython collects about its startup process
270 (default on).
269 (default on).
271
270
272 -[no]pdb
271 -[no]pdb
273 Automatically call the pdb debugger after every uncaught excep-
272 Automatically call the pdb debugger after every uncaught excep-
274 tion. If you are used to debugging using pdb, this puts you
273 tion. If you are used to debugging using pdb, this puts you
275 automatically inside of it after any call (either in IPython or
274 automatically inside of it after any call (either in IPython or
276 in code called by it) which triggers an exception which goes
275 in code called by it) which triggers an exception which goes
277 uncaught.
276 uncaught.
278
277
279 -[no]pprint
278 -[no]pprint
280 IPython can optionally use the pprint (pretty printer) module
279 IPython can optionally use the pprint (pretty printer) module
281 for displaying results. pprint tends to give a nicer display of
280 for displaying results. pprint tends to give a nicer display of
282 nested data structures. If you like it, you can turn it on per-
281 nested data structures. If you like it, you can turn it on per-
283 manently in your config file (default off).
282 manently in your config file (default off).
284
283
285 -profile|p <name>
284 -profile|p <name>
286 Assume that your config file is ipythonrc-<name> (looks in cur-
285 Assume that your config file is ipythonrc-<name> (looks in cur-
287 rent dir first, then in IPYTHONDIR). This is a quick way to keep
286 rent dir first, then in IPYTHONDIR). This is a quick way to keep
288 and load multiple config files for different tasks, especially
287 and load multiple config files for different tasks, especially
289 if you use the include option of config files. You can keep a
288 if you use the include option of config files. You can keep a
290 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
289 basic IPYTHONDIR/ipythonrc file and then have other ’profiles’
291 which include this one and load extra things for particular
290 which include this one and load extra things for particular
292 tasks. For example:
291 tasks. For example:
293
292
294 1) $HOME/.ipython/ipythonrc : load basic things you always want.
293 1) $HOME/.ipython/ipythonrc : load basic things you always want.
295 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
294 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
296 related modules.
295 related modules.
297 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
296 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
298 plotting modules.
297 plotting modules.
299
298
300 Since it is possible to create an endless loop by having circu-
299 Since it is possible to create an endless loop by having circu-
301 lar file inclusions, IPython will stop if it reaches 15 recur-
300 lar file inclusions, IPython will stop if it reaches 15 recur-
302 sive inclusions.
301 sive inclusions.
303
302
304 -prompt_in1|pi1 <string>
303 -prompt_in1|pi1 <string>
305 Specify the string used for input prompts. Note that if you are
304 Specify the string used for input prompts. Note that if you are
306 using numbered prompts, the number is represented with a ’\#’ in
305 using numbered prompts, the number is represented with a ’\#’ in
307 the string. Don’t forget to quote strings with spaces embedded
306 the string. Don’t forget to quote strings with spaces embedded
308 in them. Default: ’In [\#]:’.
307 in them. Default: ’In [\#]:’.
309
308
310 Most bash-like escapes can be used to customize IPython’s
309 Most bash-like escapes can be used to customize IPython’s
311 prompts, as well as a few additional ones which are IPython-spe-
310 prompts, as well as a few additional ones which are IPython-spe-
312 cific. All valid prompt escapes are described in detail in the
311 cific. All valid prompt escapes are described in detail in the
313 Customization section of the IPython HTML/PDF manual.
312 Customization section of the IPython HTML/PDF manual.
314
313
315 -prompt_in2|pi2 <string>
314 -prompt_in2|pi2 <string>
316 Similar to the previous option, but used for the continuation
315 Similar to the previous option, but used for the continuation
317 prompts. The special sequence ’\D’ is similar to ’\#’, but with
316 prompts. The special sequence ’\D’ is similar to ’\#’, but with
318 all digits replaced dots (so you can have your continuation
317 all digits replaced dots (so you can have your continuation
319 prompt aligned with your input prompt). Default: ’ .\D.:’
318 prompt aligned with your input prompt). Default: ’ .\D.:’
320 (note three spaces at the start for alignment with ’In [\#]’).
319 (note three spaces at the start for alignment with ’In [\#]’).
321
320
322 -prompt_out|po <string>
321 -prompt_out|po <string>
323 String used for output prompts, also uses numbers like
322 String used for output prompts, also uses numbers like
324 prompt_in1. Default: ’Out[\#]:’.
323 prompt_in1. Default: ’Out[\#]:’.
325
324
326 -quick Start in bare bones mode (no config file loaded).
325 -quick Start in bare bones mode (no config file loaded).
327
326
328 -rcfile <name>
327 -rcfile <name>
329 Name of your IPython resource configuration file. normally
328 Name of your IPython resource configuration file. normally
330 IPython loads ipythonrc (from current directory) or
329 IPython loads ipythonrc (from current directory) or
331 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
330 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
332 IPython starts with a bare bones configuration (no modules
331 IPython starts with a bare bones configuration (no modules
333 loaded at all).
332 loaded at all).
334
333
335 -[no]readline
334 -[no]readline
336 Use the readline library, which is needed to support name com-
335 Use the readline library, which is needed to support name com-
337 pletion and command history, among other things. It is enabled
336 pletion and command history, among other things. It is enabled
338 by default, but may cause problems for users of X/Emacs in
337 by default, but may cause problems for users of X/Emacs in
339 Python comint or shell buffers.
338 Python comint or shell buffers.
340
339
341 Note that emacs ’eterm’ buffers (opened with M-x term) support
340 Note that emacs ’eterm’ buffers (opened with M-x term) support
342 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
341 IPython’s readline and syntax coloring fine, only ’emacs’ (M-x
343 shell and C-c !) buffers do not.
342 shell and C-c !) buffers do not.
344
343
345 -screen_length|sl <n>
344 -screen_length|sl <n>
346 Number of lines of your screen. This is used to control print-
345 Number of lines of your screen. This is used to control print-
347 ing of very long strings. Strings longer than this number of
346 ing of very long strings. Strings longer than this number of
348 lines will be sent through a pager instead of directly printed.
347 lines will be sent through a pager instead of directly printed.
349
348
350 The default value for this is 0, which means IPython will auto-
349 The default value for this is 0, which means IPython will auto-
351 detect your screen size every time it needs to print certain
350 detect your screen size every time it needs to print certain
352 potentially long strings (this doesn’t change the behavior of
351 potentially long strings (this doesn’t change the behavior of
353 the ’print’ keyword, it’s only triggered internally). If for
352 the ’print’ keyword, it’s only triggered internally). If for
354 some reason this isn’t working well (it needs curses support),
353 some reason this isn’t working well (it needs curses support),
355 specify it yourself. Otherwise don’t change the default.
354 specify it yourself. Otherwise don’t change the default.
356
355
357 -separate_in|si <string>
356 -separate_in|si <string>
358 Separator before input prompts. Default ’0.
357 Separator before input prompts. Default ’0.
359
358
360 -separate_out|so <string>
359 -separate_out|so <string>
361 Separator before output prompts. Default: 0 (nothing).
360 Separator before output prompts. Default: 0 (nothing).
362
361
363 -separate_out2|so2 <string>
362 -separate_out2|so2 <string>
364 Separator after output prompts. Default: 0 (nothing).
363 Separator after output prompts. Default: 0 (nothing).
365
364
366 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
365 -nosep Shorthand for ’-separate_in 0 -separate_out 0 -separate_out2 0’.
367 Simply removes all input/output separators.
366 Simply removes all input/output separators.
368
367
369 -upgrade
368 -upgrade
370 Allows you to upgrade your IPYTHONDIR configuration when you
369 Allows you to upgrade your IPYTHONDIR configuration when you
371 install a new version of IPython. Since new versions may
370 install a new version of IPython. Since new versions may
372 include new command lines options or example files, this copies
371 include new command lines options or example files, this copies
373 updated ipythonrc-type files. However, it backs up (with a .old
372 updated ipythonrc-type files. However, it backs up (with a .old
374 extension) all files which it overwrites so that you can merge
373 extension) all files which it overwrites so that you can merge
375 back any custimizations you might have in your personal files.
374 back any custimizations you might have in your personal files.
376
375
377 -Version
376 -Version
378 Print version information and exit.
377 Print version information and exit.
379
378
380 -xmode <modename>
379 -xmode <modename>
381 Mode for exception reporting. The valid modes are Plain, Con-
380 Mode for exception reporting. The valid modes are Plain, Con-
382 text, and Verbose.
381 text, and Verbose.
383
382
384 - Plain: similar to python’s normal traceback printing.
383 - Plain: similar to python’s normal traceback printing.
385
384
386 - Context: prints 5 lines of context source code around each
385 - Context: prints 5 lines of context source code around each
387 line in the traceback.
386 line in the traceback.
388
387
389 - Verbose: similar to Context, but additionally prints the vari-
388 - Verbose: similar to Context, but additionally prints the vari-
390 ables currently visible where the exception happened (shortening
389 ables currently visible where the exception happened (shortening
391 their strings if too long). This can potentially be very slow,
390 their strings if too long). This can potentially be very slow,
392 if you happen to have a huge data structure whose string repre-
391 if you happen to have a huge data structure whose string repre-
393 sentation is complex to compute. Your computer may appear to
392 sentation is complex to compute. Your computer may appear to
394 freeze for a while with cpu usage at 100%. If this occurs, you
393 freeze for a while with cpu usage at 100%. If this occurs, you
395 can cancel the traceback with Ctrl-C (maybe hitting it more than
394 can cancel the traceback with Ctrl-C (maybe hitting it more than
396 once).
395 once).
397
396
398
397
399 EMBEDDING
398 EMBEDDING
400 It is possible to start an IPython instance inside your own Python pro-
399 It is possible to start an IPython instance inside your own Python pro-
401 grams. In the documentation example files there are some illustrations
400 grams. In the documentation example files there are some illustrations
402 on how to do this.
401 on how to do this.
403
402
404 This feature allows you to evalutate dynamically the state of your
403 This feature allows you to evalutate dynamically the state of your
405 code, operate with your variables, analyze them, etc. Note however
404 code, operate with your variables, analyze them, etc. Note however
406 that any changes you make to values while in the shell do NOT propagate
405 that any changes you make to values while in the shell do NOT propagate
407 back to the running code, so it is safe to modify your values because
406 back to the running code, so it is safe to modify your values because
408 you won’t break your code in bizarre ways by doing so.
407 you won’t break your code in bizarre ways by doing so.
409 """
408 """
410
409
411 cmd_line_usage = __doc__
410 cmd_line_usage = __doc__
412
411
413 #---------------------------------------------------------------------------
412 #---------------------------------------------------------------------------
414 interactive_usage = """
413 interactive_usage = """
415 IPython -- An enhanced Interactive Python
414 IPython -- An enhanced Interactive Python
416 =========================================
415 =========================================
417
416
418 IPython offers a combination of convenient shell features, special commands
417 IPython offers a combination of convenient shell features, special commands
419 and a history mechanism for both input (command history) and output (results
418 and a history mechanism for both input (command history) and output (results
420 caching, similar to Mathematica). It is intended to be a fully compatible
419 caching, similar to Mathematica). It is intended to be a fully compatible
421 replacement for the standard Python interpreter, while offering vastly
420 replacement for the standard Python interpreter, while offering vastly
422 improved functionality and flexibility.
421 improved functionality and flexibility.
423
422
424 At your system command line, type 'ipython -help' to see the command line
423 At your system command line, type 'ipython -help' to see the command line
425 options available. This document only describes interactive features.
424 options available. This document only describes interactive features.
426
425
427 Warning: IPython relies on the existence of a global variable called __IP which
426 Warning: IPython relies on the existence of a global variable called __IP which
428 controls the shell itself. If you redefine __IP to anything, bizarre behavior
427 controls the shell itself. If you redefine __IP to anything, bizarre behavior
429 will quickly occur.
428 will quickly occur.
430
429
431 MAIN FEATURES
430 MAIN FEATURES
432
431
433 * Access to the standard Python help. As of Python 2.1, a help system is
432 * Access to the standard Python help. As of Python 2.1, a help system is
434 available with access to object docstrings and the Python manuals. Simply
433 available with access to object docstrings and the Python manuals. Simply
435 type 'help' (no quotes) to access it.
434 type 'help' (no quotes) to access it.
436
435
437 * Magic commands: type %magic for information on the magic subsystem.
436 * Magic commands: type %magic for information on the magic subsystem.
438
437
439 * System command aliases, via the %alias command or the ipythonrc config file.
438 * System command aliases, via the %alias command or the ipythonrc config file.
440
439
441 * Dynamic object information:
440 * Dynamic object information:
442
441
443 Typing ?word or word? prints detailed information about an object. If
442 Typing ?word or word? prints detailed information about an object. If
444 certain strings in the object are too long (docstrings, code, etc.) they get
443 certain strings in the object are too long (docstrings, code, etc.) they get
445 snipped in the center for brevity.
444 snipped in the center for brevity.
446
445
447 Typing ??word or word?? gives access to the full information without
446 Typing ??word or word?? gives access to the full information without
448 snipping long strings. Long strings are sent to the screen through the less
447 snipping long strings. Long strings are sent to the screen through the less
449 pager if longer than the screen, printed otherwise.
448 pager if longer than the screen, printed otherwise.
450
449
451 The ?/?? system gives access to the full source code for any object (if
450 The ?/?? system gives access to the full source code for any object (if
452 available), shows function prototypes and other useful information.
451 available), shows function prototypes and other useful information.
453
452
454 If you just want to see an object's docstring, type '%pdoc object' (without
453 If you just want to see an object's docstring, type '%pdoc object' (without
455 quotes, and without % if you have automagic on).
454 quotes, and without % if you have automagic on).
456
455
457 Both %pdoc and ?/?? give you access to documentation even on things which are
456 Both %pdoc and ?/?? give you access to documentation even on things which are
458 not explicitely defined. Try for example typing {}.get? or after import os,
457 not explicitely defined. Try for example typing {}.get? or after import os,
459 type os.path.abspath??. The magic functions %pdef, %source and %file operate
458 type os.path.abspath??. The magic functions %pdef, %source and %file operate
460 similarly.
459 similarly.
461
460
462 * Completion in the local namespace, by typing TAB at the prompt.
461 * Completion in the local namespace, by typing TAB at the prompt.
463
462
464 At any time, hitting tab will complete any available python commands or
463 At any time, hitting tab will complete any available python commands or
465 variable names, and show you a list of the possible completions if there's
464 variable names, and show you a list of the possible completions if there's
466 no unambiguous one. It will also complete filenames in the current directory.
465 no unambiguous one. It will also complete filenames in the current directory.
467
466
468 This feature requires the readline and rlcomplete modules, so it won't work
467 This feature requires the readline and rlcomplete modules, so it won't work
469 if your Python lacks readline support (such as under Windows).
468 if your Python lacks readline support (such as under Windows).
470
469
471 * Search previous command history in two ways (also requires readline):
470 * Search previous command history in two ways (also requires readline):
472
471
473 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
472 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
474 search through only the history items that match what you've typed so
473 search through only the history items that match what you've typed so
475 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
474 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
476 normal arrow keys.
475 normal arrow keys.
477
476
478 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
477 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
479 your history for lines that match what you've typed so far, completing as
478 your history for lines that match what you've typed so far, completing as
480 much as it can.
479 much as it can.
481
480
482 * Persistent command history across sessions (readline required).
481 * Persistent command history across sessions (readline required).
483
482
484 * Logging of input with the ability to save and restore a working session.
483 * Logging of input with the ability to save and restore a working session.
485
484
486 * System escape with !. Typing !ls will run 'ls' in the current directory.
485 * System escape with !. Typing !ls will run 'ls' in the current directory.
487
486
488 * The reload command does a 'deep' reload of a module: changes made to the
487 * The reload command does a 'deep' reload of a module: changes made to the
489 module since you imported will actually be available without having to exit.
488 module since you imported will actually be available without having to exit.
490
489
491 * Verbose and colored exception traceback printouts. See the magic xmode and
490 * Verbose and colored exception traceback printouts. See the magic xmode and
492 xcolor functions for details (just type %magic).
491 xcolor functions for details (just type %magic).
493
492
494 * Input caching system:
493 * Input caching system:
495
494
496 IPython offers numbered prompts (In/Out) with input and output caching. All
495 IPython offers numbered prompts (In/Out) with input and output caching. All
497 input is saved and can be retrieved as variables (besides the usual arrow
496 input is saved and can be retrieved as variables (besides the usual arrow
498 key recall).
497 key recall).
499
498
500 The following GLOBAL variables always exist (so don't overwrite them!):
499 The following GLOBAL variables always exist (so don't overwrite them!):
501 _i: stores previous input.
500 _i: stores previous input.
502 _ii: next previous.
501 _ii: next previous.
503 _iii: next-next previous.
502 _iii: next-next previous.
504 _ih : a list of all input _ih[n] is the input from line n.
503 _ih : a list of all input _ih[n] is the input from line n.
505
504
506 Additionally, global variables named _i<n> are dynamically created (<n>
505 Additionally, global variables named _i<n> are dynamically created (<n>
507 being the prompt counter), such that _i<n> == _ih[<n>]
506 being the prompt counter), such that _i<n> == _ih[<n>]
508
507
509 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
508 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
510
509
511 You can create macros which contain multiple input lines from this history,
510 You can create macros which contain multiple input lines from this history,
512 for later re-execution, with the %macro function.
511 for later re-execution, with the %macro function.
513
512
514 The history function %hist allows you to see any part of your input history
513 The history function %hist allows you to see any part of your input history
515 by printing a range of the _i variables. Note that inputs which contain
514 by printing a range of the _i variables. Note that inputs which contain
516 magic functions (%) appear in the history with a prepended comment. This is
515 magic functions (%) appear in the history with a prepended comment. This is
517 because they aren't really valid Python code, so you can't exec them.
516 because they aren't really valid Python code, so you can't exec them.
518
517
519 * Output caching system:
518 * Output caching system:
520
519
521 For output that is returned from actions, a system similar to the input
520 For output that is returned from actions, a system similar to the input
522 cache exists but using _ instead of _i. Only actions that produce a result
521 cache exists but using _ instead of _i. Only actions that produce a result
523 (NOT assignments, for example) are cached. If you are familiar with
522 (NOT assignments, for example) are cached. If you are familiar with
524 Mathematica, IPython's _ variables behave exactly like Mathematica's %
523 Mathematica, IPython's _ variables behave exactly like Mathematica's %
525 variables.
524 variables.
526
525
527 The following GLOBAL variables always exist (so don't overwrite them!):
526 The following GLOBAL variables always exist (so don't overwrite them!):
528 _ (one underscore): previous output.
527 _ (one underscore): previous output.
529 __ (two underscores): next previous.
528 __ (two underscores): next previous.
530 ___ (three underscores): next-next previous.
529 ___ (three underscores): next-next previous.
531
530
532 Global variables named _<n> are dynamically created (<n> being the prompt
531 Global variables named _<n> are dynamically created (<n> being the prompt
533 counter), such that the result of output <n> is always available as _<n>.
532 counter), such that the result of output <n> is always available as _<n>.
534
533
535 Finally, a global dictionary named _oh exists with entries for all lines
534 Finally, a global dictionary named _oh exists with entries for all lines
536 which generated output.
535 which generated output.
537
536
538 * Directory history:
537 * Directory history:
539
538
540 Your history of visited directories is kept in the global list _dh, and the
539 Your history of visited directories is kept in the global list _dh, and the
541 magic %cd command can be used to go to any entry in that list.
540 magic %cd command can be used to go to any entry in that list.
542
541
543 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
542 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
544
543
545 1. Auto-parentheses
544 1. Auto-parentheses
546 Callable objects (i.e. functions, methods, etc) can be invoked like
545 Callable objects (i.e. functions, methods, etc) can be invoked like
547 this (notice the commas between the arguments):
546 this (notice the commas between the arguments):
548 >>> callable_ob arg1, arg2, arg3
547 >>> callable_ob arg1, arg2, arg3
549 and the input will be translated to this:
548 and the input will be translated to this:
550 --> callable_ob(arg1, arg2, arg3)
549 --> callable_ob(arg1, arg2, arg3)
551 You can force auto-parentheses by using '/' as the first character
550 You can force auto-parentheses by using '/' as the first character
552 of a line. For example:
551 of a line. For example:
553 >>> /globals # becomes 'globals()'
552 >>> /globals # becomes 'globals()'
554 Note that the '/' MUST be the first character on the line! This
553 Note that the '/' MUST be the first character on the line! This
555 won't work:
554 won't work:
556 >>> print /globals # syntax error
555 >>> print /globals # syntax error
557
556
558 In most cases the automatic algorithm should work, so you should
557 In most cases the automatic algorithm should work, so you should
559 rarely need to explicitly invoke /. One notable exception is if you
558 rarely need to explicitly invoke /. One notable exception is if you
560 are trying to call a function with a list of tuples as arguments (the
559 are trying to call a function with a list of tuples as arguments (the
561 parenthesis will confuse IPython):
560 parenthesis will confuse IPython):
562 In [1]: zip (1,2,3),(4,5,6) # won't work
561 In [1]: zip (1,2,3),(4,5,6) # won't work
563 but this will work:
562 but this will work:
564 In [2]: /zip (1,2,3),(4,5,6)
563 In [2]: /zip (1,2,3),(4,5,6)
565 ------> zip ((1,2,3),(4,5,6))
564 ------> zip ((1,2,3),(4,5,6))
566 Out[2]= [(1, 4), (2, 5), (3, 6)]
565 Out[2]= [(1, 4), (2, 5), (3, 6)]
567
566
568 IPython tells you that it has altered your command line by
567 IPython tells you that it has altered your command line by
569 displaying the new command line preceded by -->. e.g.:
568 displaying the new command line preceded by -->. e.g.:
570 In [18]: callable list
569 In [18]: callable list
571 -------> callable (list)
570 -------> callable (list)
572
571
573 2. Auto-Quoting
572 2. Auto-Quoting
574 You can force auto-quoting of a function's arguments by using ',' as
573 You can force auto-quoting of a function's arguments by using ',' as
575 the first character of a line. For example:
574 the first character of a line. For example:
576 >>> ,my_function /home/me # becomes my_function("/home/me")
575 >>> ,my_function /home/me # becomes my_function("/home/me")
577
576
578 If you use ';' instead, the whole argument is quoted as a single
577 If you use ';' instead, the whole argument is quoted as a single
579 string (while ',' splits on whitespace):
578 string (while ',' splits on whitespace):
580 >>> ,my_function a b c # becomes my_function("a","b","c")
579 >>> ,my_function a b c # becomes my_function("a","b","c")
581 >>> ;my_function a b c # becomes my_function("a b c")
580 >>> ;my_function a b c # becomes my_function("a b c")
582
581
583 Note that the ',' MUST be the first character on the line! This
582 Note that the ',' MUST be the first character on the line! This
584 won't work:
583 won't work:
585 >>> x = ,my_function /home/me # syntax error
584 >>> x = ,my_function /home/me # syntax error
586 """
585 """
@@ -1,4562 +1,4567 b''
1 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
1 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
2
2
3 * IPython/iplib.py (handle_normal): add suport for multi-line
3 * IPython/iplib.py (handle_normal): add suport for multi-line
4 input with emtpy lines. This fixes
4 input with emtpy lines. This fixes
5 http://www.scipy.net/roundup/ipython/issue43 and a similar
5 http://www.scipy.net/roundup/ipython/issue43 and a similar
6 discussion on the user list.
6 discussion on the user list.
7 (edit_syntax_error): added support for automatically reopening the
8 editor if the file had a syntax error in it. Thanks to scottt who
9 provided the patch at:
10 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
11 version committed).
7
12
8 WARNING: a behavior change is necessarily introduced to support
13 WARNING: a behavior change is necessarily introduced to support
9 blank lines: now a single blank line with whitespace does NOT
14 blank lines: now a single blank line with whitespace does NOT
10 break the input loop, which means that when autoindent is on, by
15 break the input loop, which means that when autoindent is on, by
11 default hitting return on the next (indented) line does NOT exit.
16 default hitting return on the next (indented) line does NOT exit.
12
17
13 Instead, to exit a multiline input you can either have:
18 Instead, to exit a multiline input you can either have:
14
19
15 - TWO whitespace lines (just hit return again), or
20 - TWO whitespace lines (just hit return again), or
16 - a single whitespace line of a different length than provided
21 - a single whitespace line of a different length than provided
17 by the autoindent (add or remove a space).
22 by the autoindent (add or remove a space).
18
23
19 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
24 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
20 module to better organize all readline-related functionality.
25 module to better organize all readline-related functionality.
21 I've deleted FlexCompleter and put all completion clases here.
26 I've deleted FlexCompleter and put all completion clases here.
22
27
23 * IPython/iplib.py (raw_input): improve indentation management.
28 * IPython/iplib.py (raw_input): improve indentation management.
24 It is now possible to paste indented code with autoindent on, and
29 It is now possible to paste indented code with autoindent on, and
25 the code is interpreted correctly (though it still looks bad on
30 the code is interpreted correctly (though it still looks bad on
26 screen, due to the line-oriented nature of ipython).
31 screen, due to the line-oriented nature of ipython).
27 (MagicCompleter.complete): change behavior so that a TAB key on an
32 (MagicCompleter.complete): change behavior so that a TAB key on an
28 otherwise empty line actually inserts a tab, instead of completing
33 otherwise empty line actually inserts a tab, instead of completing
29 on the entire global namespace. This makes it easier to use the
34 on the entire global namespace. This makes it easier to use the
30 TAB key for indentation. After a request by Hans Meine
35 TAB key for indentation. After a request by Hans Meine
31 <hans_meine-AT-gmx.net>
36 <hans_meine-AT-gmx.net>
32 (_prefilter): add support so that typing plain 'exit' or 'quit'
37 (_prefilter): add support so that typing plain 'exit' or 'quit'
33 does a sensible thing. Originally I tried to deviate as little as
38 does a sensible thing. Originally I tried to deviate as little as
34 possible from the default python behavior, but even that one may
39 possible from the default python behavior, but even that one may
35 change in this direction (thread on python-dev to that effect).
40 change in this direction (thread on python-dev to that effect).
36 Regardless, ipython should do the right thing even if CPython's
41 Regardless, ipython should do the right thing even if CPython's
37 '>>>' prompt doesn't.
42 '>>>' prompt doesn't.
38 (InteractiveShell): removed subclassing code.InteractiveConsole
43 (InteractiveShell): removed subclassing code.InteractiveConsole
39 class. By now we'd overridden just about all of its methods: I've
44 class. By now we'd overridden just about all of its methods: I've
40 copied the remaining two over, and now ipython is a standalone
45 copied the remaining two over, and now ipython is a standalone
41 class. This will provide a clearer picture for the chainsaw
46 class. This will provide a clearer picture for the chainsaw
42 branch refactoring.
47 branch refactoring.
43
48
44 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
49 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
45
50
46 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
51 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
47 failures for objects which break when dir() is called on them.
52 failures for objects which break when dir() is called on them.
48
53
49 * IPython/FlexCompleter.py (Completer.__init__): Added support for
54 * IPython/FlexCompleter.py (Completer.__init__): Added support for
50 distinct local and global namespaces in the completer API. This
55 distinct local and global namespaces in the completer API. This
51 change allows us top properly handle completion with distinct
56 change allows us top properly handle completion with distinct
52 scopes, including in embedded instances (this had never really
57 scopes, including in embedded instances (this had never really
53 worked correctly).
58 worked correctly).
54
59
55 Note: this introduces a change in the constructor for
60 Note: this introduces a change in the constructor for
56 MagicCompleter, as a new global_namespace parameter is now the
61 MagicCompleter, as a new global_namespace parameter is now the
57 second argument (the others were bumped one position).
62 second argument (the others were bumped one position).
58
63
59 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
64 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
60
65
61 * IPython/iplib.py (embed_mainloop): fix tab-completion in
66 * IPython/iplib.py (embed_mainloop): fix tab-completion in
62 embedded instances (which can be done now thanks to Vivian's
67 embedded instances (which can be done now thanks to Vivian's
63 frame-handling fixes for pdb).
68 frame-handling fixes for pdb).
64 (InteractiveShell.__init__): Fix namespace handling problem in
69 (InteractiveShell.__init__): Fix namespace handling problem in
65 embedded instances. We were overwriting __main__ unconditionally,
70 embedded instances. We were overwriting __main__ unconditionally,
66 and this should only be done for 'full' (non-embedded) IPython;
71 and this should only be done for 'full' (non-embedded) IPython;
67 embedded instances must respect the caller's __main__. Thanks to
72 embedded instances must respect the caller's __main__. Thanks to
68 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
73 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
69
74
70 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
75 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
71
76
72 * setup.py: added download_url to setup(). This registers the
77 * setup.py: added download_url to setup(). This registers the
73 download address at PyPI, which is not only useful to humans
78 download address at PyPI, which is not only useful to humans
74 browsing the site, but is also picked up by setuptools (the Eggs
79 browsing the site, but is also picked up by setuptools (the Eggs
75 machinery). Thanks to Ville and R. Kern for the info/discussion
80 machinery). Thanks to Ville and R. Kern for the info/discussion
76 on this.
81 on this.
77
82
78 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
83 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
79
84
80 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
85 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
81 This brings a lot of nice functionality to the pdb mode, which now
86 This brings a lot of nice functionality to the pdb mode, which now
82 has tab-completion, syntax highlighting, and better stack handling
87 has tab-completion, syntax highlighting, and better stack handling
83 than before. Many thanks to Vivian De Smedt
88 than before. Many thanks to Vivian De Smedt
84 <vivian-AT-vdesmedt.com> for the original patches.
89 <vivian-AT-vdesmedt.com> for the original patches.
85
90
86 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
91 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
87
92
88 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
93 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
89 sequence to consistently accept the banner argument. The
94 sequence to consistently accept the banner argument. The
90 inconsistency was tripping SAGE, thanks to Gary Zablackis
95 inconsistency was tripping SAGE, thanks to Gary Zablackis
91 <gzabl-AT-yahoo.com> for the report.
96 <gzabl-AT-yahoo.com> for the report.
92
97
93 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
98 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
94
99
95 * IPython/iplib.py (InteractiveShell.post_config_initialization):
100 * IPython/iplib.py (InteractiveShell.post_config_initialization):
96 Fix bug where a naked 'alias' call in the ipythonrc file would
101 Fix bug where a naked 'alias' call in the ipythonrc file would
97 cause a crash. Bug reported by Jorgen Stenarson.
102 cause a crash. Bug reported by Jorgen Stenarson.
98
103
99 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
104 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
100
105
101 * IPython/ipmaker.py (make_IPython): cleanups which should improve
106 * IPython/ipmaker.py (make_IPython): cleanups which should improve
102 startup time.
107 startup time.
103
108
104 * IPython/iplib.py (runcode): my globals 'fix' for embedded
109 * IPython/iplib.py (runcode): my globals 'fix' for embedded
105 instances had introduced a bug with globals in normal code. Now
110 instances had introduced a bug with globals in normal code. Now
106 it's working in all cases.
111 it's working in all cases.
107
112
108 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
113 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
109 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
114 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
110 has been introduced to set the default case sensitivity of the
115 has been introduced to set the default case sensitivity of the
111 searches. Users can still select either mode at runtime on a
116 searches. Users can still select either mode at runtime on a
112 per-search basis.
117 per-search basis.
113
118
114 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
119 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
115
120
116 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
121 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
117 attributes in wildcard searches for subclasses. Modified version
122 attributes in wildcard searches for subclasses. Modified version
118 of a patch by Jorgen.
123 of a patch by Jorgen.
119
124
120 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
125 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
121
126
122 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
127 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
123 embedded instances. I added a user_global_ns attribute to the
128 embedded instances. I added a user_global_ns attribute to the
124 InteractiveShell class to handle this.
129 InteractiveShell class to handle this.
125
130
126 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
131 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
127
132
128 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
133 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
129 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
134 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
130 (reported under win32, but may happen also in other platforms).
135 (reported under win32, but may happen also in other platforms).
131 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
136 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
132
137
133 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
138 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
134
139
135 * IPython/Magic.py (magic_psearch): new support for wildcard
140 * IPython/Magic.py (magic_psearch): new support for wildcard
136 patterns. Now, typing ?a*b will list all names which begin with a
141 patterns. Now, typing ?a*b will list all names which begin with a
137 and end in b, for example. The %psearch magic has full
142 and end in b, for example. The %psearch magic has full
138 docstrings. Many thanks to Jörgen Stenarson
143 docstrings. Many thanks to Jörgen Stenarson
139 <jorgen.stenarson-AT-bostream.nu>, author of the patches
144 <jorgen.stenarson-AT-bostream.nu>, author of the patches
140 implementing this functionality.
145 implementing this functionality.
141
146
142 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
147 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
143
148
144 * Manual: fixed long-standing annoyance of double-dashes (as in
149 * Manual: fixed long-standing annoyance of double-dashes (as in
145 --prefix=~, for example) being stripped in the HTML version. This
150 --prefix=~, for example) being stripped in the HTML version. This
146 is a latex2html bug, but a workaround was provided. Many thanks
151 is a latex2html bug, but a workaround was provided. Many thanks
147 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
152 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
148 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
153 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
149 rolling. This seemingly small issue had tripped a number of users
154 rolling. This seemingly small issue had tripped a number of users
150 when first installing, so I'm glad to see it gone.
155 when first installing, so I'm glad to see it gone.
151
156
152 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
157 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
153
158
154 * IPython/Extensions/numeric_formats.py: fix missing import,
159 * IPython/Extensions/numeric_formats.py: fix missing import,
155 reported by Stephen Walton.
160 reported by Stephen Walton.
156
161
157 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
162 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
158
163
159 * IPython/demo.py: finish demo module, fully documented now.
164 * IPython/demo.py: finish demo module, fully documented now.
160
165
161 * IPython/genutils.py (file_read): simple little utility to read a
166 * IPython/genutils.py (file_read): simple little utility to read a
162 file and ensure it's closed afterwards.
167 file and ensure it's closed afterwards.
163
168
164 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
169 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
165
170
166 * IPython/demo.py (Demo.__init__): added support for individually
171 * IPython/demo.py (Demo.__init__): added support for individually
167 tagging blocks for automatic execution.
172 tagging blocks for automatic execution.
168
173
169 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
174 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
170 syntax-highlighted python sources, requested by John.
175 syntax-highlighted python sources, requested by John.
171
176
172 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
177 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
173
178
174 * IPython/demo.py (Demo.again): fix bug where again() blocks after
179 * IPython/demo.py (Demo.again): fix bug where again() blocks after
175 finishing.
180 finishing.
176
181
177 * IPython/genutils.py (shlex_split): moved from Magic to here,
182 * IPython/genutils.py (shlex_split): moved from Magic to here,
178 where all 2.2 compatibility stuff lives. I needed it for demo.py.
183 where all 2.2 compatibility stuff lives. I needed it for demo.py.
179
184
180 * IPython/demo.py (Demo.__init__): added support for silent
185 * IPython/demo.py (Demo.__init__): added support for silent
181 blocks, improved marks as regexps, docstrings written.
186 blocks, improved marks as regexps, docstrings written.
182 (Demo.__init__): better docstring, added support for sys.argv.
187 (Demo.__init__): better docstring, added support for sys.argv.
183
188
184 * IPython/genutils.py (marquee): little utility used by the demo
189 * IPython/genutils.py (marquee): little utility used by the demo
185 code, handy in general.
190 code, handy in general.
186
191
187 * IPython/demo.py (Demo.__init__): new class for interactive
192 * IPython/demo.py (Demo.__init__): new class for interactive
188 demos. Not documented yet, I just wrote it in a hurry for
193 demos. Not documented yet, I just wrote it in a hurry for
189 scipy'05. Will docstring later.
194 scipy'05. Will docstring later.
190
195
191 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
196 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
192
197
193 * IPython/Shell.py (sigint_handler): Drastic simplification which
198 * IPython/Shell.py (sigint_handler): Drastic simplification which
194 also seems to make Ctrl-C work correctly across threads! This is
199 also seems to make Ctrl-C work correctly across threads! This is
195 so simple, that I can't beleive I'd missed it before. Needs more
200 so simple, that I can't beleive I'd missed it before. Needs more
196 testing, though.
201 testing, though.
197 (KBINT): Never mind, revert changes. I'm sure I'd tried something
202 (KBINT): Never mind, revert changes. I'm sure I'd tried something
198 like this before...
203 like this before...
199
204
200 * IPython/genutils.py (get_home_dir): add protection against
205 * IPython/genutils.py (get_home_dir): add protection against
201 non-dirs in win32 registry.
206 non-dirs in win32 registry.
202
207
203 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
208 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
204 bug where dict was mutated while iterating (pysh crash).
209 bug where dict was mutated while iterating (pysh crash).
205
210
206 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
211 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
207
212
208 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
213 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
209 spurious newlines added by this routine. After a report by
214 spurious newlines added by this routine. After a report by
210 F. Mantegazza.
215 F. Mantegazza.
211
216
212 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
217 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
213
218
214 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
219 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
215 calls. These were a leftover from the GTK 1.x days, and can cause
220 calls. These were a leftover from the GTK 1.x days, and can cause
216 problems in certain cases (after a report by John Hunter).
221 problems in certain cases (after a report by John Hunter).
217
222
218 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
223 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
219 os.getcwd() fails at init time. Thanks to patch from David Remahl
224 os.getcwd() fails at init time. Thanks to patch from David Remahl
220 <chmod007-AT-mac.com>.
225 <chmod007-AT-mac.com>.
221 (InteractiveShell.__init__): prevent certain special magics from
226 (InteractiveShell.__init__): prevent certain special magics from
222 being shadowed by aliases. Closes
227 being shadowed by aliases. Closes
223 http://www.scipy.net/roundup/ipython/issue41.
228 http://www.scipy.net/roundup/ipython/issue41.
224
229
225 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
230 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
226
231
227 * IPython/iplib.py (InteractiveShell.complete): Added new
232 * IPython/iplib.py (InteractiveShell.complete): Added new
228 top-level completion method to expose the completion mechanism
233 top-level completion method to expose the completion mechanism
229 beyond readline-based environments.
234 beyond readline-based environments.
230
235
231 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
236 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
232
237
233 * tools/ipsvnc (svnversion): fix svnversion capture.
238 * tools/ipsvnc (svnversion): fix svnversion capture.
234
239
235 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
240 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
236 attribute to self, which was missing. Before, it was set by a
241 attribute to self, which was missing. Before, it was set by a
237 routine which in certain cases wasn't being called, so the
242 routine which in certain cases wasn't being called, so the
238 instance could end up missing the attribute. This caused a crash.
243 instance could end up missing the attribute. This caused a crash.
239 Closes http://www.scipy.net/roundup/ipython/issue40.
244 Closes http://www.scipy.net/roundup/ipython/issue40.
240
245
241 2005-08-16 Fernando Perez <fperez@colorado.edu>
246 2005-08-16 Fernando Perez <fperez@colorado.edu>
242
247
243 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
248 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
244 contains non-string attribute. Closes
249 contains non-string attribute. Closes
245 http://www.scipy.net/roundup/ipython/issue38.
250 http://www.scipy.net/roundup/ipython/issue38.
246
251
247 2005-08-14 Fernando Perez <fperez@colorado.edu>
252 2005-08-14 Fernando Perez <fperez@colorado.edu>
248
253
249 * tools/ipsvnc: Minor improvements, to add changeset info.
254 * tools/ipsvnc: Minor improvements, to add changeset info.
250
255
251 2005-08-12 Fernando Perez <fperez@colorado.edu>
256 2005-08-12 Fernando Perez <fperez@colorado.edu>
252
257
253 * IPython/iplib.py (runsource): remove self.code_to_run_src
258 * IPython/iplib.py (runsource): remove self.code_to_run_src
254 attribute. I realized this is nothing more than
259 attribute. I realized this is nothing more than
255 '\n'.join(self.buffer), and having the same data in two different
260 '\n'.join(self.buffer), and having the same data in two different
256 places is just asking for synchronization bugs. This may impact
261 places is just asking for synchronization bugs. This may impact
257 people who have custom exception handlers, so I need to warn
262 people who have custom exception handlers, so I need to warn
258 ipython-dev about it (F. Mantegazza may use them).
263 ipython-dev about it (F. Mantegazza may use them).
259
264
260 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
265 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
261
266
262 * IPython/genutils.py: fix 2.2 compatibility (generators)
267 * IPython/genutils.py: fix 2.2 compatibility (generators)
263
268
264 2005-07-18 Fernando Perez <fperez@colorado.edu>
269 2005-07-18 Fernando Perez <fperez@colorado.edu>
265
270
266 * IPython/genutils.py (get_home_dir): fix to help users with
271 * IPython/genutils.py (get_home_dir): fix to help users with
267 invalid $HOME under win32.
272 invalid $HOME under win32.
268
273
269 2005-07-17 Fernando Perez <fperez@colorado.edu>
274 2005-07-17 Fernando Perez <fperez@colorado.edu>
270
275
271 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
276 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
272 some old hacks and clean up a bit other routines; code should be
277 some old hacks and clean up a bit other routines; code should be
273 simpler and a bit faster.
278 simpler and a bit faster.
274
279
275 * IPython/iplib.py (interact): removed some last-resort attempts
280 * IPython/iplib.py (interact): removed some last-resort attempts
276 to survive broken stdout/stderr. That code was only making it
281 to survive broken stdout/stderr. That code was only making it
277 harder to abstract out the i/o (necessary for gui integration),
282 harder to abstract out the i/o (necessary for gui integration),
278 and the crashes it could prevent were extremely rare in practice
283 and the crashes it could prevent were extremely rare in practice
279 (besides being fully user-induced in a pretty violent manner).
284 (besides being fully user-induced in a pretty violent manner).
280
285
281 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
286 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
282 Nothing major yet, but the code is simpler to read; this should
287 Nothing major yet, but the code is simpler to read; this should
283 make it easier to do more serious modifications in the future.
288 make it easier to do more serious modifications in the future.
284
289
285 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
290 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
286 which broke in .15 (thanks to a report by Ville).
291 which broke in .15 (thanks to a report by Ville).
287
292
288 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
293 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
289 be quite correct, I know next to nothing about unicode). This
294 be quite correct, I know next to nothing about unicode). This
290 will allow unicode strings to be used in prompts, amongst other
295 will allow unicode strings to be used in prompts, amongst other
291 cases. It also will prevent ipython from crashing when unicode
296 cases. It also will prevent ipython from crashing when unicode
292 shows up unexpectedly in many places. If ascii encoding fails, we
297 shows up unexpectedly in many places. If ascii encoding fails, we
293 assume utf_8. Currently the encoding is not a user-visible
298 assume utf_8. Currently the encoding is not a user-visible
294 setting, though it could be made so if there is demand for it.
299 setting, though it could be made so if there is demand for it.
295
300
296 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
301 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
297
302
298 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
303 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
299
304
300 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
305 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
301
306
302 * IPython/genutils.py: Add 2.2 compatibility here, so all other
307 * IPython/genutils.py: Add 2.2 compatibility here, so all other
303 code can work transparently for 2.2/2.3.
308 code can work transparently for 2.2/2.3.
304
309
305 2005-07-16 Fernando Perez <fperez@colorado.edu>
310 2005-07-16 Fernando Perez <fperez@colorado.edu>
306
311
307 * IPython/ultraTB.py (ExceptionColors): Make a global variable
312 * IPython/ultraTB.py (ExceptionColors): Make a global variable
308 out of the color scheme table used for coloring exception
313 out of the color scheme table used for coloring exception
309 tracebacks. This allows user code to add new schemes at runtime.
314 tracebacks. This allows user code to add new schemes at runtime.
310 This is a minimally modified version of the patch at
315 This is a minimally modified version of the patch at
311 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
316 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
312 for the contribution.
317 for the contribution.
313
318
314 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
319 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
315 slightly modified version of the patch in
320 slightly modified version of the patch in
316 http://www.scipy.net/roundup/ipython/issue34, which also allows me
321 http://www.scipy.net/roundup/ipython/issue34, which also allows me
317 to remove the previous try/except solution (which was costlier).
322 to remove the previous try/except solution (which was costlier).
318 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
323 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
319
324
320 2005-06-08 Fernando Perez <fperez@colorado.edu>
325 2005-06-08 Fernando Perez <fperez@colorado.edu>
321
326
322 * IPython/iplib.py (write/write_err): Add methods to abstract all
327 * IPython/iplib.py (write/write_err): Add methods to abstract all
323 I/O a bit more.
328 I/O a bit more.
324
329
325 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
330 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
326 warning, reported by Aric Hagberg, fix by JD Hunter.
331 warning, reported by Aric Hagberg, fix by JD Hunter.
327
332
328 2005-06-02 *** Released version 0.6.15
333 2005-06-02 *** Released version 0.6.15
329
334
330 2005-06-01 Fernando Perez <fperez@colorado.edu>
335 2005-06-01 Fernando Perez <fperez@colorado.edu>
331
336
332 * IPython/iplib.py (MagicCompleter.file_matches): Fix
337 * IPython/iplib.py (MagicCompleter.file_matches): Fix
333 tab-completion of filenames within open-quoted strings. Note that
338 tab-completion of filenames within open-quoted strings. Note that
334 this requires that in ~/.ipython/ipythonrc, users change the
339 this requires that in ~/.ipython/ipythonrc, users change the
335 readline delimiters configuration to read:
340 readline delimiters configuration to read:
336
341
337 readline_remove_delims -/~
342 readline_remove_delims -/~
338
343
339
344
340 2005-05-31 *** Released version 0.6.14
345 2005-05-31 *** Released version 0.6.14
341
346
342 2005-05-29 Fernando Perez <fperez@colorado.edu>
347 2005-05-29 Fernando Perez <fperez@colorado.edu>
343
348
344 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
349 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
345 with files not on the filesystem. Reported by Eliyahu Sandler
350 with files not on the filesystem. Reported by Eliyahu Sandler
346 <eli@gondolin.net>
351 <eli@gondolin.net>
347
352
348 2005-05-22 Fernando Perez <fperez@colorado.edu>
353 2005-05-22 Fernando Perez <fperez@colorado.edu>
349
354
350 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
355 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
351 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
356 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
352
357
353 2005-05-19 Fernando Perez <fperez@colorado.edu>
358 2005-05-19 Fernando Perez <fperez@colorado.edu>
354
359
355 * IPython/iplib.py (safe_execfile): close a file which could be
360 * IPython/iplib.py (safe_execfile): close a file which could be
356 left open (causing problems in win32, which locks open files).
361 left open (causing problems in win32, which locks open files).
357 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
362 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
358
363
359 2005-05-18 Fernando Perez <fperez@colorado.edu>
364 2005-05-18 Fernando Perez <fperez@colorado.edu>
360
365
361 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
366 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
362 keyword arguments correctly to safe_execfile().
367 keyword arguments correctly to safe_execfile().
363
368
364 2005-05-13 Fernando Perez <fperez@colorado.edu>
369 2005-05-13 Fernando Perez <fperez@colorado.edu>
365
370
366 * ipython.1: Added info about Qt to manpage, and threads warning
371 * ipython.1: Added info about Qt to manpage, and threads warning
367 to usage page (invoked with --help).
372 to usage page (invoked with --help).
368
373
369 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
374 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
370 new matcher (it goes at the end of the priority list) to do
375 new matcher (it goes at the end of the priority list) to do
371 tab-completion on named function arguments. Submitted by George
376 tab-completion on named function arguments. Submitted by George
372 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
377 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
373 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
378 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
374 for more details.
379 for more details.
375
380
376 * IPython/Magic.py (magic_run): Added new -e flag to ignore
381 * IPython/Magic.py (magic_run): Added new -e flag to ignore
377 SystemExit exceptions in the script being run. Thanks to a report
382 SystemExit exceptions in the script being run. Thanks to a report
378 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
383 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
379 producing very annoying behavior when running unit tests.
384 producing very annoying behavior when running unit tests.
380
385
381 2005-05-12 Fernando Perez <fperez@colorado.edu>
386 2005-05-12 Fernando Perez <fperez@colorado.edu>
382
387
383 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
388 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
384 which I'd broken (again) due to a changed regexp. In the process,
389 which I'd broken (again) due to a changed regexp. In the process,
385 added ';' as an escape to auto-quote the whole line without
390 added ';' as an escape to auto-quote the whole line without
386 splitting its arguments. Thanks to a report by Jerry McRae
391 splitting its arguments. Thanks to a report by Jerry McRae
387 <qrs0xyc02-AT-sneakemail.com>.
392 <qrs0xyc02-AT-sneakemail.com>.
388
393
389 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
394 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
390 possible crashes caused by a TokenError. Reported by Ed Schofield
395 possible crashes caused by a TokenError. Reported by Ed Schofield
391 <schofield-AT-ftw.at>.
396 <schofield-AT-ftw.at>.
392
397
393 2005-05-06 Fernando Perez <fperez@colorado.edu>
398 2005-05-06 Fernando Perez <fperez@colorado.edu>
394
399
395 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
400 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
396
401
397 2005-04-29 Fernando Perez <fperez@colorado.edu>
402 2005-04-29 Fernando Perez <fperez@colorado.edu>
398
403
399 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
404 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
400 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
405 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
401 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
406 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
402 which provides support for Qt interactive usage (similar to the
407 which provides support for Qt interactive usage (similar to the
403 existing one for WX and GTK). This had been often requested.
408 existing one for WX and GTK). This had been often requested.
404
409
405 2005-04-14 *** Released version 0.6.13
410 2005-04-14 *** Released version 0.6.13
406
411
407 2005-04-08 Fernando Perez <fperez@colorado.edu>
412 2005-04-08 Fernando Perez <fperez@colorado.edu>
408
413
409 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
414 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
410 from _ofind, which gets called on almost every input line. Now,
415 from _ofind, which gets called on almost every input line. Now,
411 we only try to get docstrings if they are actually going to be
416 we only try to get docstrings if they are actually going to be
412 used (the overhead of fetching unnecessary docstrings can be
417 used (the overhead of fetching unnecessary docstrings can be
413 noticeable for certain objects, such as Pyro proxies).
418 noticeable for certain objects, such as Pyro proxies).
414
419
415 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
420 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
416 for completers. For some reason I had been passing them the state
421 for completers. For some reason I had been passing them the state
417 variable, which completers never actually need, and was in
422 variable, which completers never actually need, and was in
418 conflict with the rlcompleter API. Custom completers ONLY need to
423 conflict with the rlcompleter API. Custom completers ONLY need to
419 take the text parameter.
424 take the text parameter.
420
425
421 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
426 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
422 work correctly in pysh. I've also moved all the logic which used
427 work correctly in pysh. I've also moved all the logic which used
423 to be in pysh.py here, which will prevent problems with future
428 to be in pysh.py here, which will prevent problems with future
424 upgrades. However, this time I must warn users to update their
429 upgrades. However, this time I must warn users to update their
425 pysh profile to include the line
430 pysh profile to include the line
426
431
427 import_all IPython.Extensions.InterpreterExec
432 import_all IPython.Extensions.InterpreterExec
428
433
429 because otherwise things won't work for them. They MUST also
434 because otherwise things won't work for them. They MUST also
430 delete pysh.py and the line
435 delete pysh.py and the line
431
436
432 execfile pysh.py
437 execfile pysh.py
433
438
434 from their ipythonrc-pysh.
439 from their ipythonrc-pysh.
435
440
436 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
441 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
437 robust in the face of objects whose dir() returns non-strings
442 robust in the face of objects whose dir() returns non-strings
438 (which it shouldn't, but some broken libs like ITK do). Thanks to
443 (which it shouldn't, but some broken libs like ITK do). Thanks to
439 a patch by John Hunter (implemented differently, though). Also
444 a patch by John Hunter (implemented differently, though). Also
440 minor improvements by using .extend instead of + on lists.
445 minor improvements by using .extend instead of + on lists.
441
446
442 * pysh.py:
447 * pysh.py:
443
448
444 2005-04-06 Fernando Perez <fperez@colorado.edu>
449 2005-04-06 Fernando Perez <fperez@colorado.edu>
445
450
446 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
451 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
447 by default, so that all users benefit from it. Those who don't
452 by default, so that all users benefit from it. Those who don't
448 want it can still turn it off.
453 want it can still turn it off.
449
454
450 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
455 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
451 config file, I'd forgotten about this, so users were getting it
456 config file, I'd forgotten about this, so users were getting it
452 off by default.
457 off by default.
453
458
454 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
459 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
455 consistency. Now magics can be called in multiline statements,
460 consistency. Now magics can be called in multiline statements,
456 and python variables can be expanded in magic calls via $var.
461 and python variables can be expanded in magic calls via $var.
457 This makes the magic system behave just like aliases or !system
462 This makes the magic system behave just like aliases or !system
458 calls.
463 calls.
459
464
460 2005-03-28 Fernando Perez <fperez@colorado.edu>
465 2005-03-28 Fernando Perez <fperez@colorado.edu>
461
466
462 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
467 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
463 expensive string additions for building command. Add support for
468 expensive string additions for building command. Add support for
464 trailing ';' when autocall is used.
469 trailing ';' when autocall is used.
465
470
466 2005-03-26 Fernando Perez <fperez@colorado.edu>
471 2005-03-26 Fernando Perez <fperez@colorado.edu>
467
472
468 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
473 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
469 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
474 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
470 ipython.el robust against prompts with any number of spaces
475 ipython.el robust against prompts with any number of spaces
471 (including 0) after the ':' character.
476 (including 0) after the ':' character.
472
477
473 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
478 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
474 continuation prompt, which misled users to think the line was
479 continuation prompt, which misled users to think the line was
475 already indented. Closes debian Bug#300847, reported to me by
480 already indented. Closes debian Bug#300847, reported to me by
476 Norbert Tretkowski <tretkowski-AT-inittab.de>.
481 Norbert Tretkowski <tretkowski-AT-inittab.de>.
477
482
478 2005-03-23 Fernando Perez <fperez@colorado.edu>
483 2005-03-23 Fernando Perez <fperez@colorado.edu>
479
484
480 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
485 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
481 properly aligned if they have embedded newlines.
486 properly aligned if they have embedded newlines.
482
487
483 * IPython/iplib.py (runlines): Add a public method to expose
488 * IPython/iplib.py (runlines): Add a public method to expose
484 IPython's code execution machinery, so that users can run strings
489 IPython's code execution machinery, so that users can run strings
485 as if they had been typed at the prompt interactively.
490 as if they had been typed at the prompt interactively.
486 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
491 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
487 methods which can call the system shell, but with python variable
492 methods which can call the system shell, but with python variable
488 expansion. The three such methods are: __IPYTHON__.system,
493 expansion. The three such methods are: __IPYTHON__.system,
489 .getoutput and .getoutputerror. These need to be documented in a
494 .getoutput and .getoutputerror. These need to be documented in a
490 'public API' section (to be written) of the manual.
495 'public API' section (to be written) of the manual.
491
496
492 2005-03-20 Fernando Perez <fperez@colorado.edu>
497 2005-03-20 Fernando Perez <fperez@colorado.edu>
493
498
494 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
499 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
495 for custom exception handling. This is quite powerful, and it
500 for custom exception handling. This is quite powerful, and it
496 allows for user-installable exception handlers which can trap
501 allows for user-installable exception handlers which can trap
497 custom exceptions at runtime and treat them separately from
502 custom exceptions at runtime and treat them separately from
498 IPython's default mechanisms. At the request of Frédéric
503 IPython's default mechanisms. At the request of Frédéric
499 Mantegazza <mantegazza-AT-ill.fr>.
504 Mantegazza <mantegazza-AT-ill.fr>.
500 (InteractiveShell.set_custom_completer): public API function to
505 (InteractiveShell.set_custom_completer): public API function to
501 add new completers at runtime.
506 add new completers at runtime.
502
507
503 2005-03-19 Fernando Perez <fperez@colorado.edu>
508 2005-03-19 Fernando Perez <fperez@colorado.edu>
504
509
505 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
510 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
506 allow objects which provide their docstrings via non-standard
511 allow objects which provide their docstrings via non-standard
507 mechanisms (like Pyro proxies) to still be inspected by ipython's
512 mechanisms (like Pyro proxies) to still be inspected by ipython's
508 ? system.
513 ? system.
509
514
510 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
515 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
511 automatic capture system. I tried quite hard to make it work
516 automatic capture system. I tried quite hard to make it work
512 reliably, and simply failed. I tried many combinations with the
517 reliably, and simply failed. I tried many combinations with the
513 subprocess module, but eventually nothing worked in all needed
518 subprocess module, but eventually nothing worked in all needed
514 cases (not blocking stdin for the child, duplicating stdout
519 cases (not blocking stdin for the child, duplicating stdout
515 without blocking, etc). The new %sc/%sx still do capture to these
520 without blocking, etc). The new %sc/%sx still do capture to these
516 magical list/string objects which make shell use much more
521 magical list/string objects which make shell use much more
517 conveninent, so not all is lost.
522 conveninent, so not all is lost.
518
523
519 XXX - FIX MANUAL for the change above!
524 XXX - FIX MANUAL for the change above!
520
525
521 (runsource): I copied code.py's runsource() into ipython to modify
526 (runsource): I copied code.py's runsource() into ipython to modify
522 it a bit. Now the code object and source to be executed are
527 it a bit. Now the code object and source to be executed are
523 stored in ipython. This makes this info accessible to third-party
528 stored in ipython. This makes this info accessible to third-party
524 tools, like custom exception handlers. After a request by Frédéric
529 tools, like custom exception handlers. After a request by Frédéric
525 Mantegazza <mantegazza-AT-ill.fr>.
530 Mantegazza <mantegazza-AT-ill.fr>.
526
531
527 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
532 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
528 history-search via readline (like C-p/C-n). I'd wanted this for a
533 history-search via readline (like C-p/C-n). I'd wanted this for a
529 long time, but only recently found out how to do it. For users
534 long time, but only recently found out how to do it. For users
530 who already have their ipythonrc files made and want this, just
535 who already have their ipythonrc files made and want this, just
531 add:
536 add:
532
537
533 readline_parse_and_bind "\e[A": history-search-backward
538 readline_parse_and_bind "\e[A": history-search-backward
534 readline_parse_and_bind "\e[B": history-search-forward
539 readline_parse_and_bind "\e[B": history-search-forward
535
540
536 2005-03-18 Fernando Perez <fperez@colorado.edu>
541 2005-03-18 Fernando Perez <fperez@colorado.edu>
537
542
538 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
543 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
539 LSString and SList classes which allow transparent conversions
544 LSString and SList classes which allow transparent conversions
540 between list mode and whitespace-separated string.
545 between list mode and whitespace-separated string.
541 (magic_r): Fix recursion problem in %r.
546 (magic_r): Fix recursion problem in %r.
542
547
543 * IPython/genutils.py (LSString): New class to be used for
548 * IPython/genutils.py (LSString): New class to be used for
544 automatic storage of the results of all alias/system calls in _o
549 automatic storage of the results of all alias/system calls in _o
545 and _e (stdout/err). These provide a .l/.list attribute which
550 and _e (stdout/err). These provide a .l/.list attribute which
546 does automatic splitting on newlines. This means that for most
551 does automatic splitting on newlines. This means that for most
547 uses, you'll never need to do capturing of output with %sc/%sx
552 uses, you'll never need to do capturing of output with %sc/%sx
548 anymore, since ipython keeps this always done for you. Note that
553 anymore, since ipython keeps this always done for you. Note that
549 only the LAST results are stored, the _o/e variables are
554 only the LAST results are stored, the _o/e variables are
550 overwritten on each call. If you need to save their contents
555 overwritten on each call. If you need to save their contents
551 further, simply bind them to any other name.
556 further, simply bind them to any other name.
552
557
553 2005-03-17 Fernando Perez <fperez@colorado.edu>
558 2005-03-17 Fernando Perez <fperez@colorado.edu>
554
559
555 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
560 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
556 prompt namespace handling.
561 prompt namespace handling.
557
562
558 2005-03-16 Fernando Perez <fperez@colorado.edu>
563 2005-03-16 Fernando Perez <fperez@colorado.edu>
559
564
560 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
565 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
561 classic prompts to be '>>> ' (final space was missing, and it
566 classic prompts to be '>>> ' (final space was missing, and it
562 trips the emacs python mode).
567 trips the emacs python mode).
563 (BasePrompt.__str__): Added safe support for dynamic prompt
568 (BasePrompt.__str__): Added safe support for dynamic prompt
564 strings. Now you can set your prompt string to be '$x', and the
569 strings. Now you can set your prompt string to be '$x', and the
565 value of x will be printed from your interactive namespace. The
570 value of x will be printed from your interactive namespace. The
566 interpolation syntax includes the full Itpl support, so
571 interpolation syntax includes the full Itpl support, so
567 ${foo()+x+bar()} is a valid prompt string now, and the function
572 ${foo()+x+bar()} is a valid prompt string now, and the function
568 calls will be made at runtime.
573 calls will be made at runtime.
569
574
570 2005-03-15 Fernando Perez <fperez@colorado.edu>
575 2005-03-15 Fernando Perez <fperez@colorado.edu>
571
576
572 * IPython/Magic.py (magic_history): renamed %hist to %history, to
577 * IPython/Magic.py (magic_history): renamed %hist to %history, to
573 avoid name clashes in pylab. %hist still works, it just forwards
578 avoid name clashes in pylab. %hist still works, it just forwards
574 the call to %history.
579 the call to %history.
575
580
576 2005-03-02 *** Released version 0.6.12
581 2005-03-02 *** Released version 0.6.12
577
582
578 2005-03-02 Fernando Perez <fperez@colorado.edu>
583 2005-03-02 Fernando Perez <fperez@colorado.edu>
579
584
580 * IPython/iplib.py (handle_magic): log magic calls properly as
585 * IPython/iplib.py (handle_magic): log magic calls properly as
581 ipmagic() function calls.
586 ipmagic() function calls.
582
587
583 * IPython/Magic.py (magic_time): Improved %time to support
588 * IPython/Magic.py (magic_time): Improved %time to support
584 statements and provide wall-clock as well as CPU time.
589 statements and provide wall-clock as well as CPU time.
585
590
586 2005-02-27 Fernando Perez <fperez@colorado.edu>
591 2005-02-27 Fernando Perez <fperez@colorado.edu>
587
592
588 * IPython/hooks.py: New hooks module, to expose user-modifiable
593 * IPython/hooks.py: New hooks module, to expose user-modifiable
589 IPython functionality in a clean manner. For now only the editor
594 IPython functionality in a clean manner. For now only the editor
590 hook is actually written, and other thigns which I intend to turn
595 hook is actually written, and other thigns which I intend to turn
591 into proper hooks aren't yet there. The display and prefilter
596 into proper hooks aren't yet there. The display and prefilter
592 stuff, for example, should be hooks. But at least now the
597 stuff, for example, should be hooks. But at least now the
593 framework is in place, and the rest can be moved here with more
598 framework is in place, and the rest can be moved here with more
594 time later. IPython had had a .hooks variable for a long time for
599 time later. IPython had had a .hooks variable for a long time for
595 this purpose, but I'd never actually used it for anything.
600 this purpose, but I'd never actually used it for anything.
596
601
597 2005-02-26 Fernando Perez <fperez@colorado.edu>
602 2005-02-26 Fernando Perez <fperez@colorado.edu>
598
603
599 * IPython/ipmaker.py (make_IPython): make the default ipython
604 * IPython/ipmaker.py (make_IPython): make the default ipython
600 directory be called _ipython under win32, to follow more the
605 directory be called _ipython under win32, to follow more the
601 naming peculiarities of that platform (where buggy software like
606 naming peculiarities of that platform (where buggy software like
602 Visual Sourcesafe breaks with .named directories). Reported by
607 Visual Sourcesafe breaks with .named directories). Reported by
603 Ville Vainio.
608 Ville Vainio.
604
609
605 2005-02-23 Fernando Perez <fperez@colorado.edu>
610 2005-02-23 Fernando Perez <fperez@colorado.edu>
606
611
607 * IPython/iplib.py (InteractiveShell.__init__): removed a few
612 * IPython/iplib.py (InteractiveShell.__init__): removed a few
608 auto_aliases for win32 which were causing problems. Users can
613 auto_aliases for win32 which were causing problems. Users can
609 define the ones they personally like.
614 define the ones they personally like.
610
615
611 2005-02-21 Fernando Perez <fperez@colorado.edu>
616 2005-02-21 Fernando Perez <fperez@colorado.edu>
612
617
613 * IPython/Magic.py (magic_time): new magic to time execution of
618 * IPython/Magic.py (magic_time): new magic to time execution of
614 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
619 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
615
620
616 2005-02-19 Fernando Perez <fperez@colorado.edu>
621 2005-02-19 Fernando Perez <fperez@colorado.edu>
617
622
618 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
623 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
619 into keys (for prompts, for example).
624 into keys (for prompts, for example).
620
625
621 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
626 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
622 prompts in case users want them. This introduces a small behavior
627 prompts in case users want them. This introduces a small behavior
623 change: ipython does not automatically add a space to all prompts
628 change: ipython does not automatically add a space to all prompts
624 anymore. To get the old prompts with a space, users should add it
629 anymore. To get the old prompts with a space, users should add it
625 manually to their ipythonrc file, so for example prompt_in1 should
630 manually to their ipythonrc file, so for example prompt_in1 should
626 now read 'In [\#]: ' instead of 'In [\#]:'.
631 now read 'In [\#]: ' instead of 'In [\#]:'.
627 (BasePrompt.__init__): New option prompts_pad_left (only in rc
632 (BasePrompt.__init__): New option prompts_pad_left (only in rc
628 file) to control left-padding of secondary prompts.
633 file) to control left-padding of secondary prompts.
629
634
630 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
635 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
631 the profiler can't be imported. Fix for Debian, which removed
636 the profiler can't be imported. Fix for Debian, which removed
632 profile.py because of License issues. I applied a slightly
637 profile.py because of License issues. I applied a slightly
633 modified version of the original Debian patch at
638 modified version of the original Debian patch at
634 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
639 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
635
640
636 2005-02-17 Fernando Perez <fperez@colorado.edu>
641 2005-02-17 Fernando Perez <fperez@colorado.edu>
637
642
638 * IPython/genutils.py (native_line_ends): Fix bug which would
643 * IPython/genutils.py (native_line_ends): Fix bug which would
639 cause improper line-ends under win32 b/c I was not opening files
644 cause improper line-ends under win32 b/c I was not opening files
640 in binary mode. Bug report and fix thanks to Ville.
645 in binary mode. Bug report and fix thanks to Ville.
641
646
642 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
647 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
643 trying to catch spurious foo[1] autocalls. My fix actually broke
648 trying to catch spurious foo[1] autocalls. My fix actually broke
644 ',/' autoquote/call with explicit escape (bad regexp).
649 ',/' autoquote/call with explicit escape (bad regexp).
645
650
646 2005-02-15 *** Released version 0.6.11
651 2005-02-15 *** Released version 0.6.11
647
652
648 2005-02-14 Fernando Perez <fperez@colorado.edu>
653 2005-02-14 Fernando Perez <fperez@colorado.edu>
649
654
650 * IPython/background_jobs.py: New background job management
655 * IPython/background_jobs.py: New background job management
651 subsystem. This is implemented via a new set of classes, and
656 subsystem. This is implemented via a new set of classes, and
652 IPython now provides a builtin 'jobs' object for background job
657 IPython now provides a builtin 'jobs' object for background job
653 execution. A convenience %bg magic serves as a lightweight
658 execution. A convenience %bg magic serves as a lightweight
654 frontend for starting the more common type of calls. This was
659 frontend for starting the more common type of calls. This was
655 inspired by discussions with B. Granger and the BackgroundCommand
660 inspired by discussions with B. Granger and the BackgroundCommand
656 class described in the book Python Scripting for Computational
661 class described in the book Python Scripting for Computational
657 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
662 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
658 (although ultimately no code from this text was used, as IPython's
663 (although ultimately no code from this text was used, as IPython's
659 system is a separate implementation).
664 system is a separate implementation).
660
665
661 * IPython/iplib.py (MagicCompleter.python_matches): add new option
666 * IPython/iplib.py (MagicCompleter.python_matches): add new option
662 to control the completion of single/double underscore names
667 to control the completion of single/double underscore names
663 separately. As documented in the example ipytonrc file, the
668 separately. As documented in the example ipytonrc file, the
664 readline_omit__names variable can now be set to 2, to omit even
669 readline_omit__names variable can now be set to 2, to omit even
665 single underscore names. Thanks to a patch by Brian Wong
670 single underscore names. Thanks to a patch by Brian Wong
666 <BrianWong-AT-AirgoNetworks.Com>.
671 <BrianWong-AT-AirgoNetworks.Com>.
667 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
672 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
668 be autocalled as foo([1]) if foo were callable. A problem for
673 be autocalled as foo([1]) if foo were callable. A problem for
669 things which are both callable and implement __getitem__.
674 things which are both callable and implement __getitem__.
670 (init_readline): Fix autoindentation for win32. Thanks to a patch
675 (init_readline): Fix autoindentation for win32. Thanks to a patch
671 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
676 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
672
677
673 2005-02-12 Fernando Perez <fperez@colorado.edu>
678 2005-02-12 Fernando Perez <fperez@colorado.edu>
674
679
675 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
680 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
676 which I had written long ago to sort out user error messages which
681 which I had written long ago to sort out user error messages which
677 may occur during startup. This seemed like a good idea initially,
682 may occur during startup. This seemed like a good idea initially,
678 but it has proven a disaster in retrospect. I don't want to
683 but it has proven a disaster in retrospect. I don't want to
679 change much code for now, so my fix is to set the internal 'debug'
684 change much code for now, so my fix is to set the internal 'debug'
680 flag to true everywhere, whose only job was precisely to control
685 flag to true everywhere, whose only job was precisely to control
681 this subsystem. This closes issue 28 (as well as avoiding all
686 this subsystem. This closes issue 28 (as well as avoiding all
682 sorts of strange hangups which occur from time to time).
687 sorts of strange hangups which occur from time to time).
683
688
684 2005-02-07 Fernando Perez <fperez@colorado.edu>
689 2005-02-07 Fernando Perez <fperez@colorado.edu>
685
690
686 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
691 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
687 previous call produced a syntax error.
692 previous call produced a syntax error.
688
693
689 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
694 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
690 classes without constructor.
695 classes without constructor.
691
696
692 2005-02-06 Fernando Perez <fperez@colorado.edu>
697 2005-02-06 Fernando Perez <fperez@colorado.edu>
693
698
694 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
699 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
695 completions with the results of each matcher, so we return results
700 completions with the results of each matcher, so we return results
696 to the user from all namespaces. This breaks with ipython
701 to the user from all namespaces. This breaks with ipython
697 tradition, but I think it's a nicer behavior. Now you get all
702 tradition, but I think it's a nicer behavior. Now you get all
698 possible completions listed, from all possible namespaces (python,
703 possible completions listed, from all possible namespaces (python,
699 filesystem, magics...) After a request by John Hunter
704 filesystem, magics...) After a request by John Hunter
700 <jdhunter-AT-nitace.bsd.uchicago.edu>.
705 <jdhunter-AT-nitace.bsd.uchicago.edu>.
701
706
702 2005-02-05 Fernando Perez <fperez@colorado.edu>
707 2005-02-05 Fernando Perez <fperez@colorado.edu>
703
708
704 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
709 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
705 the call had quote characters in it (the quotes were stripped).
710 the call had quote characters in it (the quotes were stripped).
706
711
707 2005-01-31 Fernando Perez <fperez@colorado.edu>
712 2005-01-31 Fernando Perez <fperez@colorado.edu>
708
713
709 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
714 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
710 Itpl.itpl() to make the code more robust against psyco
715 Itpl.itpl() to make the code more robust against psyco
711 optimizations.
716 optimizations.
712
717
713 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
718 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
714 of causing an exception. Quicker, cleaner.
719 of causing an exception. Quicker, cleaner.
715
720
716 2005-01-28 Fernando Perez <fperez@colorado.edu>
721 2005-01-28 Fernando Perez <fperez@colorado.edu>
717
722
718 * scripts/ipython_win_post_install.py (install): hardcode
723 * scripts/ipython_win_post_install.py (install): hardcode
719 sys.prefix+'python.exe' as the executable path. It turns out that
724 sys.prefix+'python.exe' as the executable path. It turns out that
720 during the post-installation run, sys.executable resolves to the
725 during the post-installation run, sys.executable resolves to the
721 name of the binary installer! I should report this as a distutils
726 name of the binary installer! I should report this as a distutils
722 bug, I think. I updated the .10 release with this tiny fix, to
727 bug, I think. I updated the .10 release with this tiny fix, to
723 avoid annoying the lists further.
728 avoid annoying the lists further.
724
729
725 2005-01-27 *** Released version 0.6.10
730 2005-01-27 *** Released version 0.6.10
726
731
727 2005-01-27 Fernando Perez <fperez@colorado.edu>
732 2005-01-27 Fernando Perez <fperez@colorado.edu>
728
733
729 * IPython/numutils.py (norm): Added 'inf' as optional name for
734 * IPython/numutils.py (norm): Added 'inf' as optional name for
730 L-infinity norm, included references to mathworld.com for vector
735 L-infinity norm, included references to mathworld.com for vector
731 norm definitions.
736 norm definitions.
732 (amin/amax): added amin/amax for array min/max. Similar to what
737 (amin/amax): added amin/amax for array min/max. Similar to what
733 pylab ships with after the recent reorganization of names.
738 pylab ships with after the recent reorganization of names.
734 (spike/spike_odd): removed deprecated spike/spike_odd functions.
739 (spike/spike_odd): removed deprecated spike/spike_odd functions.
735
740
736 * ipython.el: committed Alex's recent fixes and improvements.
741 * ipython.el: committed Alex's recent fixes and improvements.
737 Tested with python-mode from CVS, and it looks excellent. Since
742 Tested with python-mode from CVS, and it looks excellent. Since
738 python-mode hasn't released anything in a while, I'm temporarily
743 python-mode hasn't released anything in a while, I'm temporarily
739 putting a copy of today's CVS (v 4.70) of python-mode in:
744 putting a copy of today's CVS (v 4.70) of python-mode in:
740 http://ipython.scipy.org/tmp/python-mode.el
745 http://ipython.scipy.org/tmp/python-mode.el
741
746
742 * scripts/ipython_win_post_install.py (install): Win32 fix to use
747 * scripts/ipython_win_post_install.py (install): Win32 fix to use
743 sys.executable for the executable name, instead of assuming it's
748 sys.executable for the executable name, instead of assuming it's
744 called 'python.exe' (the post-installer would have produced broken
749 called 'python.exe' (the post-installer would have produced broken
745 setups on systems with a differently named python binary).
750 setups on systems with a differently named python binary).
746
751
747 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
752 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
748 references to os.linesep, to make the code more
753 references to os.linesep, to make the code more
749 platform-independent. This is also part of the win32 coloring
754 platform-independent. This is also part of the win32 coloring
750 fixes.
755 fixes.
751
756
752 * IPython/genutils.py (page_dumb): Remove attempts to chop long
757 * IPython/genutils.py (page_dumb): Remove attempts to chop long
753 lines, which actually cause coloring bugs because the length of
758 lines, which actually cause coloring bugs because the length of
754 the line is very difficult to correctly compute with embedded
759 the line is very difficult to correctly compute with embedded
755 escapes. This was the source of all the coloring problems under
760 escapes. This was the source of all the coloring problems under
756 Win32. I think that _finally_, Win32 users have a properly
761 Win32. I think that _finally_, Win32 users have a properly
757 working ipython in all respects. This would never have happened
762 working ipython in all respects. This would never have happened
758 if not for Gary Bishop and Viktor Ransmayr's great help and work.
763 if not for Gary Bishop and Viktor Ransmayr's great help and work.
759
764
760 2005-01-26 *** Released version 0.6.9
765 2005-01-26 *** Released version 0.6.9
761
766
762 2005-01-25 Fernando Perez <fperez@colorado.edu>
767 2005-01-25 Fernando Perez <fperez@colorado.edu>
763
768
764 * setup.py: finally, we have a true Windows installer, thanks to
769 * setup.py: finally, we have a true Windows installer, thanks to
765 the excellent work of Viktor Ransmayr
770 the excellent work of Viktor Ransmayr
766 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
771 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
767 Windows users. The setup routine is quite a bit cleaner thanks to
772 Windows users. The setup routine is quite a bit cleaner thanks to
768 this, and the post-install script uses the proper functions to
773 this, and the post-install script uses the proper functions to
769 allow a clean de-installation using the standard Windows Control
774 allow a clean de-installation using the standard Windows Control
770 Panel.
775 Panel.
771
776
772 * IPython/genutils.py (get_home_dir): changed to use the $HOME
777 * IPython/genutils.py (get_home_dir): changed to use the $HOME
773 environment variable under all OSes (including win32) if
778 environment variable under all OSes (including win32) if
774 available. This will give consistency to win32 users who have set
779 available. This will give consistency to win32 users who have set
775 this variable for any reason. If os.environ['HOME'] fails, the
780 this variable for any reason. If os.environ['HOME'] fails, the
776 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
781 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
777
782
778 2005-01-24 Fernando Perez <fperez@colorado.edu>
783 2005-01-24 Fernando Perez <fperez@colorado.edu>
779
784
780 * IPython/numutils.py (empty_like): add empty_like(), similar to
785 * IPython/numutils.py (empty_like): add empty_like(), similar to
781 zeros_like() but taking advantage of the new empty() Numeric routine.
786 zeros_like() but taking advantage of the new empty() Numeric routine.
782
787
783 2005-01-23 *** Released version 0.6.8
788 2005-01-23 *** Released version 0.6.8
784
789
785 2005-01-22 Fernando Perez <fperez@colorado.edu>
790 2005-01-22 Fernando Perez <fperez@colorado.edu>
786
791
787 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
792 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
788 automatic show() calls. After discussing things with JDH, it
793 automatic show() calls. After discussing things with JDH, it
789 turns out there are too many corner cases where this can go wrong.
794 turns out there are too many corner cases where this can go wrong.
790 It's best not to try to be 'too smart', and simply have ipython
795 It's best not to try to be 'too smart', and simply have ipython
791 reproduce as much as possible the default behavior of a normal
796 reproduce as much as possible the default behavior of a normal
792 python shell.
797 python shell.
793
798
794 * IPython/iplib.py (InteractiveShell.__init__): Modified the
799 * IPython/iplib.py (InteractiveShell.__init__): Modified the
795 line-splitting regexp and _prefilter() to avoid calling getattr()
800 line-splitting regexp and _prefilter() to avoid calling getattr()
796 on assignments. This closes
801 on assignments. This closes
797 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
802 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
798 readline uses getattr(), so a simple <TAB> keypress is still
803 readline uses getattr(), so a simple <TAB> keypress is still
799 enough to trigger getattr() calls on an object.
804 enough to trigger getattr() calls on an object.
800
805
801 2005-01-21 Fernando Perez <fperez@colorado.edu>
806 2005-01-21 Fernando Perez <fperez@colorado.edu>
802
807
803 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
808 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
804 docstring under pylab so it doesn't mask the original.
809 docstring under pylab so it doesn't mask the original.
805
810
806 2005-01-21 *** Released version 0.6.7
811 2005-01-21 *** Released version 0.6.7
807
812
808 2005-01-21 Fernando Perez <fperez@colorado.edu>
813 2005-01-21 Fernando Perez <fperez@colorado.edu>
809
814
810 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
815 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
811 signal handling for win32 users in multithreaded mode.
816 signal handling for win32 users in multithreaded mode.
812
817
813 2005-01-17 Fernando Perez <fperez@colorado.edu>
818 2005-01-17 Fernando Perez <fperez@colorado.edu>
814
819
815 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
820 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
816 instances with no __init__. After a crash report by Norbert Nemec
821 instances with no __init__. After a crash report by Norbert Nemec
817 <Norbert-AT-nemec-online.de>.
822 <Norbert-AT-nemec-online.de>.
818
823
819 2005-01-14 Fernando Perez <fperez@colorado.edu>
824 2005-01-14 Fernando Perez <fperez@colorado.edu>
820
825
821 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
826 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
822 names for verbose exceptions, when multiple dotted names and the
827 names for verbose exceptions, when multiple dotted names and the
823 'parent' object were present on the same line.
828 'parent' object were present on the same line.
824
829
825 2005-01-11 Fernando Perez <fperez@colorado.edu>
830 2005-01-11 Fernando Perez <fperez@colorado.edu>
826
831
827 * IPython/genutils.py (flag_calls): new utility to trap and flag
832 * IPython/genutils.py (flag_calls): new utility to trap and flag
828 calls in functions. I need it to clean up matplotlib support.
833 calls in functions. I need it to clean up matplotlib support.
829 Also removed some deprecated code in genutils.
834 Also removed some deprecated code in genutils.
830
835
831 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
836 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
832 that matplotlib scripts called with %run, which don't call show()
837 that matplotlib scripts called with %run, which don't call show()
833 themselves, still have their plotting windows open.
838 themselves, still have their plotting windows open.
834
839
835 2005-01-05 Fernando Perez <fperez@colorado.edu>
840 2005-01-05 Fernando Perez <fperez@colorado.edu>
836
841
837 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
842 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
838 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
843 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
839
844
840 2004-12-19 Fernando Perez <fperez@colorado.edu>
845 2004-12-19 Fernando Perez <fperez@colorado.edu>
841
846
842 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
847 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
843 parent_runcode, which was an eyesore. The same result can be
848 parent_runcode, which was an eyesore. The same result can be
844 obtained with Python's regular superclass mechanisms.
849 obtained with Python's regular superclass mechanisms.
845
850
846 2004-12-17 Fernando Perez <fperez@colorado.edu>
851 2004-12-17 Fernando Perez <fperez@colorado.edu>
847
852
848 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
853 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
849 reported by Prabhu.
854 reported by Prabhu.
850 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
855 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
851 sys.stderr) instead of explicitly calling sys.stderr. This helps
856 sys.stderr) instead of explicitly calling sys.stderr. This helps
852 maintain our I/O abstractions clean, for future GUI embeddings.
857 maintain our I/O abstractions clean, for future GUI embeddings.
853
858
854 * IPython/genutils.py (info): added new utility for sys.stderr
859 * IPython/genutils.py (info): added new utility for sys.stderr
855 unified info message handling (thin wrapper around warn()).
860 unified info message handling (thin wrapper around warn()).
856
861
857 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
862 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
858 composite (dotted) names on verbose exceptions.
863 composite (dotted) names on verbose exceptions.
859 (VerboseTB.nullrepr): harden against another kind of errors which
864 (VerboseTB.nullrepr): harden against another kind of errors which
860 Python's inspect module can trigger, and which were crashing
865 Python's inspect module can trigger, and which were crashing
861 IPython. Thanks to a report by Marco Lombardi
866 IPython. Thanks to a report by Marco Lombardi
862 <mlombard-AT-ma010192.hq.eso.org>.
867 <mlombard-AT-ma010192.hq.eso.org>.
863
868
864 2004-12-13 *** Released version 0.6.6
869 2004-12-13 *** Released version 0.6.6
865
870
866 2004-12-12 Fernando Perez <fperez@colorado.edu>
871 2004-12-12 Fernando Perez <fperez@colorado.edu>
867
872
868 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
873 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
869 generated by pygtk upon initialization if it was built without
874 generated by pygtk upon initialization if it was built without
870 threads (for matplotlib users). After a crash reported by
875 threads (for matplotlib users). After a crash reported by
871 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
876 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
872
877
873 * IPython/ipmaker.py (make_IPython): fix small bug in the
878 * IPython/ipmaker.py (make_IPython): fix small bug in the
874 import_some parameter for multiple imports.
879 import_some parameter for multiple imports.
875
880
876 * IPython/iplib.py (ipmagic): simplified the interface of
881 * IPython/iplib.py (ipmagic): simplified the interface of
877 ipmagic() to take a single string argument, just as it would be
882 ipmagic() to take a single string argument, just as it would be
878 typed at the IPython cmd line.
883 typed at the IPython cmd line.
879 (ipalias): Added new ipalias() with an interface identical to
884 (ipalias): Added new ipalias() with an interface identical to
880 ipmagic(). This completes exposing a pure python interface to the
885 ipmagic(). This completes exposing a pure python interface to the
881 alias and magic system, which can be used in loops or more complex
886 alias and magic system, which can be used in loops or more complex
882 code where IPython's automatic line mangling is not active.
887 code where IPython's automatic line mangling is not active.
883
888
884 * IPython/genutils.py (timing): changed interface of timing to
889 * IPython/genutils.py (timing): changed interface of timing to
885 simply run code once, which is the most common case. timings()
890 simply run code once, which is the most common case. timings()
886 remains unchanged, for the cases where you want multiple runs.
891 remains unchanged, for the cases where you want multiple runs.
887
892
888 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
893 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
889 bug where Python2.2 crashes with exec'ing code which does not end
894 bug where Python2.2 crashes with exec'ing code which does not end
890 in a single newline. Python 2.3 is OK, so I hadn't noticed this
895 in a single newline. Python 2.3 is OK, so I hadn't noticed this
891 before.
896 before.
892
897
893 2004-12-10 Fernando Perez <fperez@colorado.edu>
898 2004-12-10 Fernando Perez <fperez@colorado.edu>
894
899
895 * IPython/Magic.py (Magic.magic_prun): changed name of option from
900 * IPython/Magic.py (Magic.magic_prun): changed name of option from
896 -t to -T, to accomodate the new -t flag in %run (the %run and
901 -t to -T, to accomodate the new -t flag in %run (the %run and
897 %prun options are kind of intermixed, and it's not easy to change
902 %prun options are kind of intermixed, and it's not easy to change
898 this with the limitations of python's getopt).
903 this with the limitations of python's getopt).
899
904
900 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
905 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
901 the execution of scripts. It's not as fine-tuned as timeit.py,
906 the execution of scripts. It's not as fine-tuned as timeit.py,
902 but it works from inside ipython (and under 2.2, which lacks
907 but it works from inside ipython (and under 2.2, which lacks
903 timeit.py). Optionally a number of runs > 1 can be given for
908 timeit.py). Optionally a number of runs > 1 can be given for
904 timing very short-running code.
909 timing very short-running code.
905
910
906 * IPython/genutils.py (uniq_stable): new routine which returns a
911 * IPython/genutils.py (uniq_stable): new routine which returns a
907 list of unique elements in any iterable, but in stable order of
912 list of unique elements in any iterable, but in stable order of
908 appearance. I needed this for the ultraTB fixes, and it's a handy
913 appearance. I needed this for the ultraTB fixes, and it's a handy
909 utility.
914 utility.
910
915
911 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
916 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
912 dotted names in Verbose exceptions. This had been broken since
917 dotted names in Verbose exceptions. This had been broken since
913 the very start, now x.y will properly be printed in a Verbose
918 the very start, now x.y will properly be printed in a Verbose
914 traceback, instead of x being shown and y appearing always as an
919 traceback, instead of x being shown and y appearing always as an
915 'undefined global'. Getting this to work was a bit tricky,
920 'undefined global'. Getting this to work was a bit tricky,
916 because by default python tokenizers are stateless. Saved by
921 because by default python tokenizers are stateless. Saved by
917 python's ability to easily add a bit of state to an arbitrary
922 python's ability to easily add a bit of state to an arbitrary
918 function (without needing to build a full-blown callable object).
923 function (without needing to build a full-blown callable object).
919
924
920 Also big cleanup of this code, which had horrendous runtime
925 Also big cleanup of this code, which had horrendous runtime
921 lookups of zillions of attributes for colorization. Moved all
926 lookups of zillions of attributes for colorization. Moved all
922 this code into a few templates, which make it cleaner and quicker.
927 this code into a few templates, which make it cleaner and quicker.
923
928
924 Printout quality was also improved for Verbose exceptions: one
929 Printout quality was also improved for Verbose exceptions: one
925 variable per line, and memory addresses are printed (this can be
930 variable per line, and memory addresses are printed (this can be
926 quite handy in nasty debugging situations, which is what Verbose
931 quite handy in nasty debugging situations, which is what Verbose
927 is for).
932 is for).
928
933
929 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
934 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
930 the command line as scripts to be loaded by embedded instances.
935 the command line as scripts to be loaded by embedded instances.
931 Doing so has the potential for an infinite recursion if there are
936 Doing so has the potential for an infinite recursion if there are
932 exceptions thrown in the process. This fixes a strange crash
937 exceptions thrown in the process. This fixes a strange crash
933 reported by Philippe MULLER <muller-AT-irit.fr>.
938 reported by Philippe MULLER <muller-AT-irit.fr>.
934
939
935 2004-12-09 Fernando Perez <fperez@colorado.edu>
940 2004-12-09 Fernando Perez <fperez@colorado.edu>
936
941
937 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
942 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
938 to reflect new names in matplotlib, which now expose the
943 to reflect new names in matplotlib, which now expose the
939 matlab-compatible interface via a pylab module instead of the
944 matlab-compatible interface via a pylab module instead of the
940 'matlab' name. The new code is backwards compatible, so users of
945 'matlab' name. The new code is backwards compatible, so users of
941 all matplotlib versions are OK. Patch by J. Hunter.
946 all matplotlib versions are OK. Patch by J. Hunter.
942
947
943 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
948 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
944 of __init__ docstrings for instances (class docstrings are already
949 of __init__ docstrings for instances (class docstrings are already
945 automatically printed). Instances with customized docstrings
950 automatically printed). Instances with customized docstrings
946 (indep. of the class) are also recognized and all 3 separate
951 (indep. of the class) are also recognized and all 3 separate
947 docstrings are printed (instance, class, constructor). After some
952 docstrings are printed (instance, class, constructor). After some
948 comments/suggestions by J. Hunter.
953 comments/suggestions by J. Hunter.
949
954
950 2004-12-05 Fernando Perez <fperez@colorado.edu>
955 2004-12-05 Fernando Perez <fperez@colorado.edu>
951
956
952 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
957 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
953 warnings when tab-completion fails and triggers an exception.
958 warnings when tab-completion fails and triggers an exception.
954
959
955 2004-12-03 Fernando Perez <fperez@colorado.edu>
960 2004-12-03 Fernando Perez <fperez@colorado.edu>
956
961
957 * IPython/Magic.py (magic_prun): Fix bug where an exception would
962 * IPython/Magic.py (magic_prun): Fix bug where an exception would
958 be triggered when using 'run -p'. An incorrect option flag was
963 be triggered when using 'run -p'. An incorrect option flag was
959 being set ('d' instead of 'D').
964 being set ('d' instead of 'D').
960 (manpage): fix missing escaped \- sign.
965 (manpage): fix missing escaped \- sign.
961
966
962 2004-11-30 *** Released version 0.6.5
967 2004-11-30 *** Released version 0.6.5
963
968
964 2004-11-30 Fernando Perez <fperez@colorado.edu>
969 2004-11-30 Fernando Perez <fperez@colorado.edu>
965
970
966 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
971 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
967 setting with -d option.
972 setting with -d option.
968
973
969 * setup.py (docfiles): Fix problem where the doc glob I was using
974 * setup.py (docfiles): Fix problem where the doc glob I was using
970 was COMPLETELY BROKEN. It was giving the right files by pure
975 was COMPLETELY BROKEN. It was giving the right files by pure
971 accident, but failed once I tried to include ipython.el. Note:
976 accident, but failed once I tried to include ipython.el. Note:
972 glob() does NOT allow you to do exclusion on multiple endings!
977 glob() does NOT allow you to do exclusion on multiple endings!
973
978
974 2004-11-29 Fernando Perez <fperez@colorado.edu>
979 2004-11-29 Fernando Perez <fperez@colorado.edu>
975
980
976 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
981 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
977 the manpage as the source. Better formatting & consistency.
982 the manpage as the source. Better formatting & consistency.
978
983
979 * IPython/Magic.py (magic_run): Added new -d option, to run
984 * IPython/Magic.py (magic_run): Added new -d option, to run
980 scripts under the control of the python pdb debugger. Note that
985 scripts under the control of the python pdb debugger. Note that
981 this required changing the %prun option -d to -D, to avoid a clash
986 this required changing the %prun option -d to -D, to avoid a clash
982 (since %run must pass options to %prun, and getopt is too dumb to
987 (since %run must pass options to %prun, and getopt is too dumb to
983 handle options with string values with embedded spaces). Thanks
988 handle options with string values with embedded spaces). Thanks
984 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
989 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
985 (magic_who_ls): added type matching to %who and %whos, so that one
990 (magic_who_ls): added type matching to %who and %whos, so that one
986 can filter their output to only include variables of certain
991 can filter their output to only include variables of certain
987 types. Another suggestion by Matthew.
992 types. Another suggestion by Matthew.
988 (magic_whos): Added memory summaries in kb and Mb for arrays.
993 (magic_whos): Added memory summaries in kb and Mb for arrays.
989 (magic_who): Improve formatting (break lines every 9 vars).
994 (magic_who): Improve formatting (break lines every 9 vars).
990
995
991 2004-11-28 Fernando Perez <fperez@colorado.edu>
996 2004-11-28 Fernando Perez <fperez@colorado.edu>
992
997
993 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
998 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
994 cache when empty lines were present.
999 cache when empty lines were present.
995
1000
996 2004-11-24 Fernando Perez <fperez@colorado.edu>
1001 2004-11-24 Fernando Perez <fperez@colorado.edu>
997
1002
998 * IPython/usage.py (__doc__): document the re-activated threading
1003 * IPython/usage.py (__doc__): document the re-activated threading
999 options for WX and GTK.
1004 options for WX and GTK.
1000
1005
1001 2004-11-23 Fernando Perez <fperez@colorado.edu>
1006 2004-11-23 Fernando Perez <fperez@colorado.edu>
1002
1007
1003 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1008 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1004 the -wthread and -gthread options, along with a new -tk one to try
1009 the -wthread and -gthread options, along with a new -tk one to try
1005 and coordinate Tk threading with wx/gtk. The tk support is very
1010 and coordinate Tk threading with wx/gtk. The tk support is very
1006 platform dependent, since it seems to require Tcl and Tk to be
1011 platform dependent, since it seems to require Tcl and Tk to be
1007 built with threads (Fedora1/2 appears NOT to have it, but in
1012 built with threads (Fedora1/2 appears NOT to have it, but in
1008 Prabhu's Debian boxes it works OK). But even with some Tk
1013 Prabhu's Debian boxes it works OK). But even with some Tk
1009 limitations, this is a great improvement.
1014 limitations, this is a great improvement.
1010
1015
1011 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1016 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1012 info in user prompts. Patch by Prabhu.
1017 info in user prompts. Patch by Prabhu.
1013
1018
1014 2004-11-18 Fernando Perez <fperez@colorado.edu>
1019 2004-11-18 Fernando Perez <fperez@colorado.edu>
1015
1020
1016 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1021 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1017 EOFErrors and bail, to avoid infinite loops if a non-terminating
1022 EOFErrors and bail, to avoid infinite loops if a non-terminating
1018 file is fed into ipython. Patch submitted in issue 19 by user,
1023 file is fed into ipython. Patch submitted in issue 19 by user,
1019 many thanks.
1024 many thanks.
1020
1025
1021 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1026 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1022 autoquote/parens in continuation prompts, which can cause lots of
1027 autoquote/parens in continuation prompts, which can cause lots of
1023 problems. Closes roundup issue 20.
1028 problems. Closes roundup issue 20.
1024
1029
1025 2004-11-17 Fernando Perez <fperez@colorado.edu>
1030 2004-11-17 Fernando Perez <fperez@colorado.edu>
1026
1031
1027 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1032 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1028 reported as debian bug #280505. I'm not sure my local changelog
1033 reported as debian bug #280505. I'm not sure my local changelog
1029 entry has the proper debian format (Jack?).
1034 entry has the proper debian format (Jack?).
1030
1035
1031 2004-11-08 *** Released version 0.6.4
1036 2004-11-08 *** Released version 0.6.4
1032
1037
1033 2004-11-08 Fernando Perez <fperez@colorado.edu>
1038 2004-11-08 Fernando Perez <fperez@colorado.edu>
1034
1039
1035 * IPython/iplib.py (init_readline): Fix exit message for Windows
1040 * IPython/iplib.py (init_readline): Fix exit message for Windows
1036 when readline is active. Thanks to a report by Eric Jones
1041 when readline is active. Thanks to a report by Eric Jones
1037 <eric-AT-enthought.com>.
1042 <eric-AT-enthought.com>.
1038
1043
1039 2004-11-07 Fernando Perez <fperez@colorado.edu>
1044 2004-11-07 Fernando Perez <fperez@colorado.edu>
1040
1045
1041 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1046 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1042 sometimes seen by win2k/cygwin users.
1047 sometimes seen by win2k/cygwin users.
1043
1048
1044 2004-11-06 Fernando Perez <fperez@colorado.edu>
1049 2004-11-06 Fernando Perez <fperez@colorado.edu>
1045
1050
1046 * IPython/iplib.py (interact): Change the handling of %Exit from
1051 * IPython/iplib.py (interact): Change the handling of %Exit from
1047 trying to propagate a SystemExit to an internal ipython flag.
1052 trying to propagate a SystemExit to an internal ipython flag.
1048 This is less elegant than using Python's exception mechanism, but
1053 This is less elegant than using Python's exception mechanism, but
1049 I can't get that to work reliably with threads, so under -pylab
1054 I can't get that to work reliably with threads, so under -pylab
1050 %Exit was hanging IPython. Cross-thread exception handling is
1055 %Exit was hanging IPython. Cross-thread exception handling is
1051 really a bitch. Thaks to a bug report by Stephen Walton
1056 really a bitch. Thaks to a bug report by Stephen Walton
1052 <stephen.walton-AT-csun.edu>.
1057 <stephen.walton-AT-csun.edu>.
1053
1058
1054 2004-11-04 Fernando Perez <fperez@colorado.edu>
1059 2004-11-04 Fernando Perez <fperez@colorado.edu>
1055
1060
1056 * IPython/iplib.py (raw_input_original): store a pointer to the
1061 * IPython/iplib.py (raw_input_original): store a pointer to the
1057 true raw_input to harden against code which can modify it
1062 true raw_input to harden against code which can modify it
1058 (wx.py.PyShell does this and would otherwise crash ipython).
1063 (wx.py.PyShell does this and would otherwise crash ipython).
1059 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1064 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1060
1065
1061 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1066 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1062 Ctrl-C problem, which does not mess up the input line.
1067 Ctrl-C problem, which does not mess up the input line.
1063
1068
1064 2004-11-03 Fernando Perez <fperez@colorado.edu>
1069 2004-11-03 Fernando Perez <fperez@colorado.edu>
1065
1070
1066 * IPython/Release.py: Changed licensing to BSD, in all files.
1071 * IPython/Release.py: Changed licensing to BSD, in all files.
1067 (name): lowercase name for tarball/RPM release.
1072 (name): lowercase name for tarball/RPM release.
1068
1073
1069 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1074 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1070 use throughout ipython.
1075 use throughout ipython.
1071
1076
1072 * IPython/Magic.py (Magic._ofind): Switch to using the new
1077 * IPython/Magic.py (Magic._ofind): Switch to using the new
1073 OInspect.getdoc() function.
1078 OInspect.getdoc() function.
1074
1079
1075 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1080 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1076 of the line currently being canceled via Ctrl-C. It's extremely
1081 of the line currently being canceled via Ctrl-C. It's extremely
1077 ugly, but I don't know how to do it better (the problem is one of
1082 ugly, but I don't know how to do it better (the problem is one of
1078 handling cross-thread exceptions).
1083 handling cross-thread exceptions).
1079
1084
1080 2004-10-28 Fernando Perez <fperez@colorado.edu>
1085 2004-10-28 Fernando Perez <fperez@colorado.edu>
1081
1086
1082 * IPython/Shell.py (signal_handler): add signal handlers to trap
1087 * IPython/Shell.py (signal_handler): add signal handlers to trap
1083 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1088 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1084 report by Francesc Alted.
1089 report by Francesc Alted.
1085
1090
1086 2004-10-21 Fernando Perez <fperez@colorado.edu>
1091 2004-10-21 Fernando Perez <fperez@colorado.edu>
1087
1092
1088 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1093 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1089 to % for pysh syntax extensions.
1094 to % for pysh syntax extensions.
1090
1095
1091 2004-10-09 Fernando Perez <fperez@colorado.edu>
1096 2004-10-09 Fernando Perez <fperez@colorado.edu>
1092
1097
1093 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1098 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1094 arrays to print a more useful summary, without calling str(arr).
1099 arrays to print a more useful summary, without calling str(arr).
1095 This avoids the problem of extremely lengthy computations which
1100 This avoids the problem of extremely lengthy computations which
1096 occur if arr is large, and appear to the user as a system lockup
1101 occur if arr is large, and appear to the user as a system lockup
1097 with 100% cpu activity. After a suggestion by Kristian Sandberg
1102 with 100% cpu activity. After a suggestion by Kristian Sandberg
1098 <Kristian.Sandberg@colorado.edu>.
1103 <Kristian.Sandberg@colorado.edu>.
1099 (Magic.__init__): fix bug in global magic escapes not being
1104 (Magic.__init__): fix bug in global magic escapes not being
1100 correctly set.
1105 correctly set.
1101
1106
1102 2004-10-08 Fernando Perez <fperez@colorado.edu>
1107 2004-10-08 Fernando Perez <fperez@colorado.edu>
1103
1108
1104 * IPython/Magic.py (__license__): change to absolute imports of
1109 * IPython/Magic.py (__license__): change to absolute imports of
1105 ipython's own internal packages, to start adapting to the absolute
1110 ipython's own internal packages, to start adapting to the absolute
1106 import requirement of PEP-328.
1111 import requirement of PEP-328.
1107
1112
1108 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1113 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1109 files, and standardize author/license marks through the Release
1114 files, and standardize author/license marks through the Release
1110 module instead of having per/file stuff (except for files with
1115 module instead of having per/file stuff (except for files with
1111 particular licenses, like the MIT/PSF-licensed codes).
1116 particular licenses, like the MIT/PSF-licensed codes).
1112
1117
1113 * IPython/Debugger.py: remove dead code for python 2.1
1118 * IPython/Debugger.py: remove dead code for python 2.1
1114
1119
1115 2004-10-04 Fernando Perez <fperez@colorado.edu>
1120 2004-10-04 Fernando Perez <fperez@colorado.edu>
1116
1121
1117 * IPython/iplib.py (ipmagic): New function for accessing magics
1122 * IPython/iplib.py (ipmagic): New function for accessing magics
1118 via a normal python function call.
1123 via a normal python function call.
1119
1124
1120 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1125 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1121 from '@' to '%', to accomodate the new @decorator syntax of python
1126 from '@' to '%', to accomodate the new @decorator syntax of python
1122 2.4.
1127 2.4.
1123
1128
1124 2004-09-29 Fernando Perez <fperez@colorado.edu>
1129 2004-09-29 Fernando Perez <fperez@colorado.edu>
1125
1130
1126 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1131 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1127 matplotlib.use to prevent running scripts which try to switch
1132 matplotlib.use to prevent running scripts which try to switch
1128 interactive backends from within ipython. This will just crash
1133 interactive backends from within ipython. This will just crash
1129 the python interpreter, so we can't allow it (but a detailed error
1134 the python interpreter, so we can't allow it (but a detailed error
1130 is given to the user).
1135 is given to the user).
1131
1136
1132 2004-09-28 Fernando Perez <fperez@colorado.edu>
1137 2004-09-28 Fernando Perez <fperez@colorado.edu>
1133
1138
1134 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1139 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1135 matplotlib-related fixes so that using @run with non-matplotlib
1140 matplotlib-related fixes so that using @run with non-matplotlib
1136 scripts doesn't pop up spurious plot windows. This requires
1141 scripts doesn't pop up spurious plot windows. This requires
1137 matplotlib >= 0.63, where I had to make some changes as well.
1142 matplotlib >= 0.63, where I had to make some changes as well.
1138
1143
1139 * IPython/ipmaker.py (make_IPython): update version requirement to
1144 * IPython/ipmaker.py (make_IPython): update version requirement to
1140 python 2.2.
1145 python 2.2.
1141
1146
1142 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1147 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1143 banner arg for embedded customization.
1148 banner arg for embedded customization.
1144
1149
1145 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1150 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1146 explicit uses of __IP as the IPython's instance name. Now things
1151 explicit uses of __IP as the IPython's instance name. Now things
1147 are properly handled via the shell.name value. The actual code
1152 are properly handled via the shell.name value. The actual code
1148 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1153 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1149 is much better than before. I'll clean things completely when the
1154 is much better than before. I'll clean things completely when the
1150 magic stuff gets a real overhaul.
1155 magic stuff gets a real overhaul.
1151
1156
1152 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1157 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1153 minor changes to debian dir.
1158 minor changes to debian dir.
1154
1159
1155 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1160 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1156 pointer to the shell itself in the interactive namespace even when
1161 pointer to the shell itself in the interactive namespace even when
1157 a user-supplied dict is provided. This is needed for embedding
1162 a user-supplied dict is provided. This is needed for embedding
1158 purposes (found by tests with Michel Sanner).
1163 purposes (found by tests with Michel Sanner).
1159
1164
1160 2004-09-27 Fernando Perez <fperez@colorado.edu>
1165 2004-09-27 Fernando Perez <fperez@colorado.edu>
1161
1166
1162 * IPython/UserConfig/ipythonrc: remove []{} from
1167 * IPython/UserConfig/ipythonrc: remove []{} from
1163 readline_remove_delims, so that things like [modname.<TAB> do
1168 readline_remove_delims, so that things like [modname.<TAB> do
1164 proper completion. This disables [].TAB, but that's a less common
1169 proper completion. This disables [].TAB, but that's a less common
1165 case than module names in list comprehensions, for example.
1170 case than module names in list comprehensions, for example.
1166 Thanks to a report by Andrea Riciputi.
1171 Thanks to a report by Andrea Riciputi.
1167
1172
1168 2004-09-09 Fernando Perez <fperez@colorado.edu>
1173 2004-09-09 Fernando Perez <fperez@colorado.edu>
1169
1174
1170 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1175 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1171 blocking problems in win32 and osx. Fix by John.
1176 blocking problems in win32 and osx. Fix by John.
1172
1177
1173 2004-09-08 Fernando Perez <fperez@colorado.edu>
1178 2004-09-08 Fernando Perez <fperez@colorado.edu>
1174
1179
1175 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1180 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1176 for Win32 and OSX. Fix by John Hunter.
1181 for Win32 and OSX. Fix by John Hunter.
1177
1182
1178 2004-08-30 *** Released version 0.6.3
1183 2004-08-30 *** Released version 0.6.3
1179
1184
1180 2004-08-30 Fernando Perez <fperez@colorado.edu>
1185 2004-08-30 Fernando Perez <fperez@colorado.edu>
1181
1186
1182 * setup.py (isfile): Add manpages to list of dependent files to be
1187 * setup.py (isfile): Add manpages to list of dependent files to be
1183 updated.
1188 updated.
1184
1189
1185 2004-08-27 Fernando Perez <fperez@colorado.edu>
1190 2004-08-27 Fernando Perez <fperez@colorado.edu>
1186
1191
1187 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1192 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1188 for now. They don't really work with standalone WX/GTK code
1193 for now. They don't really work with standalone WX/GTK code
1189 (though matplotlib IS working fine with both of those backends).
1194 (though matplotlib IS working fine with both of those backends).
1190 This will neeed much more testing. I disabled most things with
1195 This will neeed much more testing. I disabled most things with
1191 comments, so turning it back on later should be pretty easy.
1196 comments, so turning it back on later should be pretty easy.
1192
1197
1193 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1198 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1194 autocalling of expressions like r'foo', by modifying the line
1199 autocalling of expressions like r'foo', by modifying the line
1195 split regexp. Closes
1200 split regexp. Closes
1196 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1201 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1197 Riley <ipythonbugs-AT-sabi.net>.
1202 Riley <ipythonbugs-AT-sabi.net>.
1198 (InteractiveShell.mainloop): honor --nobanner with banner
1203 (InteractiveShell.mainloop): honor --nobanner with banner
1199 extensions.
1204 extensions.
1200
1205
1201 * IPython/Shell.py: Significant refactoring of all classes, so
1206 * IPython/Shell.py: Significant refactoring of all classes, so
1202 that we can really support ALL matplotlib backends and threading
1207 that we can really support ALL matplotlib backends and threading
1203 models (John spotted a bug with Tk which required this). Now we
1208 models (John spotted a bug with Tk which required this). Now we
1204 should support single-threaded, WX-threads and GTK-threads, both
1209 should support single-threaded, WX-threads and GTK-threads, both
1205 for generic code and for matplotlib.
1210 for generic code and for matplotlib.
1206
1211
1207 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1212 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1208 -pylab, to simplify things for users. Will also remove the pylab
1213 -pylab, to simplify things for users. Will also remove the pylab
1209 profile, since now all of matplotlib configuration is directly
1214 profile, since now all of matplotlib configuration is directly
1210 handled here. This also reduces startup time.
1215 handled here. This also reduces startup time.
1211
1216
1212 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1217 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1213 shell wasn't being correctly called. Also in IPShellWX.
1218 shell wasn't being correctly called. Also in IPShellWX.
1214
1219
1215 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1220 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1216 fine-tune banner.
1221 fine-tune banner.
1217
1222
1218 * IPython/numutils.py (spike): Deprecate these spike functions,
1223 * IPython/numutils.py (spike): Deprecate these spike functions,
1219 delete (long deprecated) gnuplot_exec handler.
1224 delete (long deprecated) gnuplot_exec handler.
1220
1225
1221 2004-08-26 Fernando Perez <fperez@colorado.edu>
1226 2004-08-26 Fernando Perez <fperez@colorado.edu>
1222
1227
1223 * ipython.1: Update for threading options, plus some others which
1228 * ipython.1: Update for threading options, plus some others which
1224 were missing.
1229 were missing.
1225
1230
1226 * IPython/ipmaker.py (__call__): Added -wthread option for
1231 * IPython/ipmaker.py (__call__): Added -wthread option for
1227 wxpython thread handling. Make sure threading options are only
1232 wxpython thread handling. Make sure threading options are only
1228 valid at the command line.
1233 valid at the command line.
1229
1234
1230 * scripts/ipython: moved shell selection into a factory function
1235 * scripts/ipython: moved shell selection into a factory function
1231 in Shell.py, to keep the starter script to a minimum.
1236 in Shell.py, to keep the starter script to a minimum.
1232
1237
1233 2004-08-25 Fernando Perez <fperez@colorado.edu>
1238 2004-08-25 Fernando Perez <fperez@colorado.edu>
1234
1239
1235 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1240 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1236 John. Along with some recent changes he made to matplotlib, the
1241 John. Along with some recent changes he made to matplotlib, the
1237 next versions of both systems should work very well together.
1242 next versions of both systems should work very well together.
1238
1243
1239 2004-08-24 Fernando Perez <fperez@colorado.edu>
1244 2004-08-24 Fernando Perez <fperez@colorado.edu>
1240
1245
1241 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1246 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1242 tried to switch the profiling to using hotshot, but I'm getting
1247 tried to switch the profiling to using hotshot, but I'm getting
1243 strange errors from prof.runctx() there. I may be misreading the
1248 strange errors from prof.runctx() there. I may be misreading the
1244 docs, but it looks weird. For now the profiling code will
1249 docs, but it looks weird. For now the profiling code will
1245 continue to use the standard profiler.
1250 continue to use the standard profiler.
1246
1251
1247 2004-08-23 Fernando Perez <fperez@colorado.edu>
1252 2004-08-23 Fernando Perez <fperez@colorado.edu>
1248
1253
1249 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1254 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1250 threaded shell, by John Hunter. It's not quite ready yet, but
1255 threaded shell, by John Hunter. It's not quite ready yet, but
1251 close.
1256 close.
1252
1257
1253 2004-08-22 Fernando Perez <fperez@colorado.edu>
1258 2004-08-22 Fernando Perez <fperez@colorado.edu>
1254
1259
1255 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1260 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1256 in Magic and ultraTB.
1261 in Magic and ultraTB.
1257
1262
1258 * ipython.1: document threading options in manpage.
1263 * ipython.1: document threading options in manpage.
1259
1264
1260 * scripts/ipython: Changed name of -thread option to -gthread,
1265 * scripts/ipython: Changed name of -thread option to -gthread,
1261 since this is GTK specific. I want to leave the door open for a
1266 since this is GTK specific. I want to leave the door open for a
1262 -wthread option for WX, which will most likely be necessary. This
1267 -wthread option for WX, which will most likely be necessary. This
1263 change affects usage and ipmaker as well.
1268 change affects usage and ipmaker as well.
1264
1269
1265 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1270 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1266 handle the matplotlib shell issues. Code by John Hunter
1271 handle the matplotlib shell issues. Code by John Hunter
1267 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1272 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1268 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1273 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1269 broken (and disabled for end users) for now, but it puts the
1274 broken (and disabled for end users) for now, but it puts the
1270 infrastructure in place.
1275 infrastructure in place.
1271
1276
1272 2004-08-21 Fernando Perez <fperez@colorado.edu>
1277 2004-08-21 Fernando Perez <fperez@colorado.edu>
1273
1278
1274 * ipythonrc-pylab: Add matplotlib support.
1279 * ipythonrc-pylab: Add matplotlib support.
1275
1280
1276 * matplotlib_config.py: new files for matplotlib support, part of
1281 * matplotlib_config.py: new files for matplotlib support, part of
1277 the pylab profile.
1282 the pylab profile.
1278
1283
1279 * IPython/usage.py (__doc__): documented the threading options.
1284 * IPython/usage.py (__doc__): documented the threading options.
1280
1285
1281 2004-08-20 Fernando Perez <fperez@colorado.edu>
1286 2004-08-20 Fernando Perez <fperez@colorado.edu>
1282
1287
1283 * ipython: Modified the main calling routine to handle the -thread
1288 * ipython: Modified the main calling routine to handle the -thread
1284 and -mpthread options. This needs to be done as a top-level hack,
1289 and -mpthread options. This needs to be done as a top-level hack,
1285 because it determines which class to instantiate for IPython
1290 because it determines which class to instantiate for IPython
1286 itself.
1291 itself.
1287
1292
1288 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1293 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1289 classes to support multithreaded GTK operation without blocking,
1294 classes to support multithreaded GTK operation without blocking,
1290 and matplotlib with all backends. This is a lot of still very
1295 and matplotlib with all backends. This is a lot of still very
1291 experimental code, and threads are tricky. So it may still have a
1296 experimental code, and threads are tricky. So it may still have a
1292 few rough edges... This code owes a lot to
1297 few rough edges... This code owes a lot to
1293 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1298 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1294 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1299 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1295 to John Hunter for all the matplotlib work.
1300 to John Hunter for all the matplotlib work.
1296
1301
1297 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1302 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1298 options for gtk thread and matplotlib support.
1303 options for gtk thread and matplotlib support.
1299
1304
1300 2004-08-16 Fernando Perez <fperez@colorado.edu>
1305 2004-08-16 Fernando Perez <fperez@colorado.edu>
1301
1306
1302 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1307 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1303 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1308 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1304 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1309 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1305
1310
1306 2004-08-11 Fernando Perez <fperez@colorado.edu>
1311 2004-08-11 Fernando Perez <fperez@colorado.edu>
1307
1312
1308 * setup.py (isfile): Fix build so documentation gets updated for
1313 * setup.py (isfile): Fix build so documentation gets updated for
1309 rpms (it was only done for .tgz builds).
1314 rpms (it was only done for .tgz builds).
1310
1315
1311 2004-08-10 Fernando Perez <fperez@colorado.edu>
1316 2004-08-10 Fernando Perez <fperez@colorado.edu>
1312
1317
1313 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1318 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1314
1319
1315 * iplib.py : Silence syntax error exceptions in tab-completion.
1320 * iplib.py : Silence syntax error exceptions in tab-completion.
1316
1321
1317 2004-08-05 Fernando Perez <fperez@colorado.edu>
1322 2004-08-05 Fernando Perez <fperez@colorado.edu>
1318
1323
1319 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1324 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1320 'color off' mark for continuation prompts. This was causing long
1325 'color off' mark for continuation prompts. This was causing long
1321 continuation lines to mis-wrap.
1326 continuation lines to mis-wrap.
1322
1327
1323 2004-08-01 Fernando Perez <fperez@colorado.edu>
1328 2004-08-01 Fernando Perez <fperez@colorado.edu>
1324
1329
1325 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1330 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1326 for building ipython to be a parameter. All this is necessary
1331 for building ipython to be a parameter. All this is necessary
1327 right now to have a multithreaded version, but this insane
1332 right now to have a multithreaded version, but this insane
1328 non-design will be cleaned up soon. For now, it's a hack that
1333 non-design will be cleaned up soon. For now, it's a hack that
1329 works.
1334 works.
1330
1335
1331 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1336 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1332 args in various places. No bugs so far, but it's a dangerous
1337 args in various places. No bugs so far, but it's a dangerous
1333 practice.
1338 practice.
1334
1339
1335 2004-07-31 Fernando Perez <fperez@colorado.edu>
1340 2004-07-31 Fernando Perez <fperez@colorado.edu>
1336
1341
1337 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1342 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1338 fix completion of files with dots in their names under most
1343 fix completion of files with dots in their names under most
1339 profiles (pysh was OK because the completion order is different).
1344 profiles (pysh was OK because the completion order is different).
1340
1345
1341 2004-07-27 Fernando Perez <fperez@colorado.edu>
1346 2004-07-27 Fernando Perez <fperez@colorado.edu>
1342
1347
1343 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1348 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1344 keywords manually, b/c the one in keyword.py was removed in python
1349 keywords manually, b/c the one in keyword.py was removed in python
1345 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1350 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1346 This is NOT a bug under python 2.3 and earlier.
1351 This is NOT a bug under python 2.3 and earlier.
1347
1352
1348 2004-07-26 Fernando Perez <fperez@colorado.edu>
1353 2004-07-26 Fernando Perez <fperez@colorado.edu>
1349
1354
1350 * IPython/ultraTB.py (VerboseTB.text): Add another
1355 * IPython/ultraTB.py (VerboseTB.text): Add another
1351 linecache.checkcache() call to try to prevent inspect.py from
1356 linecache.checkcache() call to try to prevent inspect.py from
1352 crashing under python 2.3. I think this fixes
1357 crashing under python 2.3. I think this fixes
1353 http://www.scipy.net/roundup/ipython/issue17.
1358 http://www.scipy.net/roundup/ipython/issue17.
1354
1359
1355 2004-07-26 *** Released version 0.6.2
1360 2004-07-26 *** Released version 0.6.2
1356
1361
1357 2004-07-26 Fernando Perez <fperez@colorado.edu>
1362 2004-07-26 Fernando Perez <fperez@colorado.edu>
1358
1363
1359 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1364 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1360 fail for any number.
1365 fail for any number.
1361 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1366 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1362 empty bookmarks.
1367 empty bookmarks.
1363
1368
1364 2004-07-26 *** Released version 0.6.1
1369 2004-07-26 *** Released version 0.6.1
1365
1370
1366 2004-07-26 Fernando Perez <fperez@colorado.edu>
1371 2004-07-26 Fernando Perez <fperez@colorado.edu>
1367
1372
1368 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1373 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1369
1374
1370 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1375 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1371 escaping '()[]{}' in filenames.
1376 escaping '()[]{}' in filenames.
1372
1377
1373 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1378 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1374 Python 2.2 users who lack a proper shlex.split.
1379 Python 2.2 users who lack a proper shlex.split.
1375
1380
1376 2004-07-19 Fernando Perez <fperez@colorado.edu>
1381 2004-07-19 Fernando Perez <fperez@colorado.edu>
1377
1382
1378 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1383 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1379 for reading readline's init file. I follow the normal chain:
1384 for reading readline's init file. I follow the normal chain:
1380 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1385 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1381 report by Mike Heeter. This closes
1386 report by Mike Heeter. This closes
1382 http://www.scipy.net/roundup/ipython/issue16.
1387 http://www.scipy.net/roundup/ipython/issue16.
1383
1388
1384 2004-07-18 Fernando Perez <fperez@colorado.edu>
1389 2004-07-18 Fernando Perez <fperez@colorado.edu>
1385
1390
1386 * IPython/iplib.py (__init__): Add better handling of '\' under
1391 * IPython/iplib.py (__init__): Add better handling of '\' under
1387 Win32 for filenames. After a patch by Ville.
1392 Win32 for filenames. After a patch by Ville.
1388
1393
1389 2004-07-17 Fernando Perez <fperez@colorado.edu>
1394 2004-07-17 Fernando Perez <fperez@colorado.edu>
1390
1395
1391 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1396 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1392 autocalling would be triggered for 'foo is bar' if foo is
1397 autocalling would be triggered for 'foo is bar' if foo is
1393 callable. I also cleaned up the autocall detection code to use a
1398 callable. I also cleaned up the autocall detection code to use a
1394 regexp, which is faster. Bug reported by Alexander Schmolck.
1399 regexp, which is faster. Bug reported by Alexander Schmolck.
1395
1400
1396 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1401 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1397 '?' in them would confuse the help system. Reported by Alex
1402 '?' in them would confuse the help system. Reported by Alex
1398 Schmolck.
1403 Schmolck.
1399
1404
1400 2004-07-16 Fernando Perez <fperez@colorado.edu>
1405 2004-07-16 Fernando Perez <fperez@colorado.edu>
1401
1406
1402 * IPython/GnuplotInteractive.py (__all__): added plot2.
1407 * IPython/GnuplotInteractive.py (__all__): added plot2.
1403
1408
1404 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1409 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1405 plotting dictionaries, lists or tuples of 1d arrays.
1410 plotting dictionaries, lists or tuples of 1d arrays.
1406
1411
1407 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1412 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1408 optimizations.
1413 optimizations.
1409
1414
1410 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1415 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1411 the information which was there from Janko's original IPP code:
1416 the information which was there from Janko's original IPP code:
1412
1417
1413 03.05.99 20:53 porto.ifm.uni-kiel.de
1418 03.05.99 20:53 porto.ifm.uni-kiel.de
1414 --Started changelog.
1419 --Started changelog.
1415 --make clear do what it say it does
1420 --make clear do what it say it does
1416 --added pretty output of lines from inputcache
1421 --added pretty output of lines from inputcache
1417 --Made Logger a mixin class, simplifies handling of switches
1422 --Made Logger a mixin class, simplifies handling of switches
1418 --Added own completer class. .string<TAB> expands to last history
1423 --Added own completer class. .string<TAB> expands to last history
1419 line which starts with string. The new expansion is also present
1424 line which starts with string. The new expansion is also present
1420 with Ctrl-r from the readline library. But this shows, who this
1425 with Ctrl-r from the readline library. But this shows, who this
1421 can be done for other cases.
1426 can be done for other cases.
1422 --Added convention that all shell functions should accept a
1427 --Added convention that all shell functions should accept a
1423 parameter_string This opens the door for different behaviour for
1428 parameter_string This opens the door for different behaviour for
1424 each function. @cd is a good example of this.
1429 each function. @cd is a good example of this.
1425
1430
1426 04.05.99 12:12 porto.ifm.uni-kiel.de
1431 04.05.99 12:12 porto.ifm.uni-kiel.de
1427 --added logfile rotation
1432 --added logfile rotation
1428 --added new mainloop method which freezes first the namespace
1433 --added new mainloop method which freezes first the namespace
1429
1434
1430 07.05.99 21:24 porto.ifm.uni-kiel.de
1435 07.05.99 21:24 porto.ifm.uni-kiel.de
1431 --added the docreader classes. Now there is a help system.
1436 --added the docreader classes. Now there is a help system.
1432 -This is only a first try. Currently it's not easy to put new
1437 -This is only a first try. Currently it's not easy to put new
1433 stuff in the indices. But this is the way to go. Info would be
1438 stuff in the indices. But this is the way to go. Info would be
1434 better, but HTML is every where and not everybody has an info
1439 better, but HTML is every where and not everybody has an info
1435 system installed and it's not so easy to change html-docs to info.
1440 system installed and it's not so easy to change html-docs to info.
1436 --added global logfile option
1441 --added global logfile option
1437 --there is now a hook for object inspection method pinfo needs to
1442 --there is now a hook for object inspection method pinfo needs to
1438 be provided for this. Can be reached by two '??'.
1443 be provided for this. Can be reached by two '??'.
1439
1444
1440 08.05.99 20:51 porto.ifm.uni-kiel.de
1445 08.05.99 20:51 porto.ifm.uni-kiel.de
1441 --added a README
1446 --added a README
1442 --bug in rc file. Something has changed so functions in the rc
1447 --bug in rc file. Something has changed so functions in the rc
1443 file need to reference the shell and not self. Not clear if it's a
1448 file need to reference the shell and not self. Not clear if it's a
1444 bug or feature.
1449 bug or feature.
1445 --changed rc file for new behavior
1450 --changed rc file for new behavior
1446
1451
1447 2004-07-15 Fernando Perez <fperez@colorado.edu>
1452 2004-07-15 Fernando Perez <fperez@colorado.edu>
1448
1453
1449 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1454 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1450 cache was falling out of sync in bizarre manners when multi-line
1455 cache was falling out of sync in bizarre manners when multi-line
1451 input was present. Minor optimizations and cleanup.
1456 input was present. Minor optimizations and cleanup.
1452
1457
1453 (Logger): Remove old Changelog info for cleanup. This is the
1458 (Logger): Remove old Changelog info for cleanup. This is the
1454 information which was there from Janko's original code:
1459 information which was there from Janko's original code:
1455
1460
1456 Changes to Logger: - made the default log filename a parameter
1461 Changes to Logger: - made the default log filename a parameter
1457
1462
1458 - put a check for lines beginning with !@? in log(). Needed
1463 - put a check for lines beginning with !@? in log(). Needed
1459 (even if the handlers properly log their lines) for mid-session
1464 (even if the handlers properly log their lines) for mid-session
1460 logging activation to work properly. Without this, lines logged
1465 logging activation to work properly. Without this, lines logged
1461 in mid session, which get read from the cache, would end up
1466 in mid session, which get read from the cache, would end up
1462 'bare' (with !@? in the open) in the log. Now they are caught
1467 'bare' (with !@? in the open) in the log. Now they are caught
1463 and prepended with a #.
1468 and prepended with a #.
1464
1469
1465 * IPython/iplib.py (InteractiveShell.init_readline): added check
1470 * IPython/iplib.py (InteractiveShell.init_readline): added check
1466 in case MagicCompleter fails to be defined, so we don't crash.
1471 in case MagicCompleter fails to be defined, so we don't crash.
1467
1472
1468 2004-07-13 Fernando Perez <fperez@colorado.edu>
1473 2004-07-13 Fernando Perez <fperez@colorado.edu>
1469
1474
1470 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1475 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1471 of EPS if the requested filename ends in '.eps'.
1476 of EPS if the requested filename ends in '.eps'.
1472
1477
1473 2004-07-04 Fernando Perez <fperez@colorado.edu>
1478 2004-07-04 Fernando Perez <fperez@colorado.edu>
1474
1479
1475 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1480 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1476 escaping of quotes when calling the shell.
1481 escaping of quotes when calling the shell.
1477
1482
1478 2004-07-02 Fernando Perez <fperez@colorado.edu>
1483 2004-07-02 Fernando Perez <fperez@colorado.edu>
1479
1484
1480 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1485 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1481 gettext not working because we were clobbering '_'. Fixes
1486 gettext not working because we were clobbering '_'. Fixes
1482 http://www.scipy.net/roundup/ipython/issue6.
1487 http://www.scipy.net/roundup/ipython/issue6.
1483
1488
1484 2004-07-01 Fernando Perez <fperez@colorado.edu>
1489 2004-07-01 Fernando Perez <fperez@colorado.edu>
1485
1490
1486 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1491 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1487 into @cd. Patch by Ville.
1492 into @cd. Patch by Ville.
1488
1493
1489 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1494 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1490 new function to store things after ipmaker runs. Patch by Ville.
1495 new function to store things after ipmaker runs. Patch by Ville.
1491 Eventually this will go away once ipmaker is removed and the class
1496 Eventually this will go away once ipmaker is removed and the class
1492 gets cleaned up, but for now it's ok. Key functionality here is
1497 gets cleaned up, but for now it's ok. Key functionality here is
1493 the addition of the persistent storage mechanism, a dict for
1498 the addition of the persistent storage mechanism, a dict for
1494 keeping data across sessions (for now just bookmarks, but more can
1499 keeping data across sessions (for now just bookmarks, but more can
1495 be implemented later).
1500 be implemented later).
1496
1501
1497 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1502 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1498 persistent across sections. Patch by Ville, I modified it
1503 persistent across sections. Patch by Ville, I modified it
1499 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1504 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1500 added a '-l' option to list all bookmarks.
1505 added a '-l' option to list all bookmarks.
1501
1506
1502 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1507 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1503 center for cleanup. Registered with atexit.register(). I moved
1508 center for cleanup. Registered with atexit.register(). I moved
1504 here the old exit_cleanup(). After a patch by Ville.
1509 here the old exit_cleanup(). After a patch by Ville.
1505
1510
1506 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1511 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1507 characters in the hacked shlex_split for python 2.2.
1512 characters in the hacked shlex_split for python 2.2.
1508
1513
1509 * IPython/iplib.py (file_matches): more fixes to filenames with
1514 * IPython/iplib.py (file_matches): more fixes to filenames with
1510 whitespace in them. It's not perfect, but limitations in python's
1515 whitespace in them. It's not perfect, but limitations in python's
1511 readline make it impossible to go further.
1516 readline make it impossible to go further.
1512
1517
1513 2004-06-29 Fernando Perez <fperez@colorado.edu>
1518 2004-06-29 Fernando Perez <fperez@colorado.edu>
1514
1519
1515 * IPython/iplib.py (file_matches): escape whitespace correctly in
1520 * IPython/iplib.py (file_matches): escape whitespace correctly in
1516 filename completions. Bug reported by Ville.
1521 filename completions. Bug reported by Ville.
1517
1522
1518 2004-06-28 Fernando Perez <fperez@colorado.edu>
1523 2004-06-28 Fernando Perez <fperez@colorado.edu>
1519
1524
1520 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1525 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1521 the history file will be called 'history-PROFNAME' (or just
1526 the history file will be called 'history-PROFNAME' (or just
1522 'history' if no profile is loaded). I was getting annoyed at
1527 'history' if no profile is loaded). I was getting annoyed at
1523 getting my Numerical work history clobbered by pysh sessions.
1528 getting my Numerical work history clobbered by pysh sessions.
1524
1529
1525 * IPython/iplib.py (InteractiveShell.__init__): Internal
1530 * IPython/iplib.py (InteractiveShell.__init__): Internal
1526 getoutputerror() function so that we can honor the system_verbose
1531 getoutputerror() function so that we can honor the system_verbose
1527 flag for _all_ system calls. I also added escaping of #
1532 flag for _all_ system calls. I also added escaping of #
1528 characters here to avoid confusing Itpl.
1533 characters here to avoid confusing Itpl.
1529
1534
1530 * IPython/Magic.py (shlex_split): removed call to shell in
1535 * IPython/Magic.py (shlex_split): removed call to shell in
1531 parse_options and replaced it with shlex.split(). The annoying
1536 parse_options and replaced it with shlex.split(). The annoying
1532 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1537 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1533 to backport it from 2.3, with several frail hacks (the shlex
1538 to backport it from 2.3, with several frail hacks (the shlex
1534 module is rather limited in 2.2). Thanks to a suggestion by Ville
1539 module is rather limited in 2.2). Thanks to a suggestion by Ville
1535 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1540 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1536 problem.
1541 problem.
1537
1542
1538 (Magic.magic_system_verbose): new toggle to print the actual
1543 (Magic.magic_system_verbose): new toggle to print the actual
1539 system calls made by ipython. Mainly for debugging purposes.
1544 system calls made by ipython. Mainly for debugging purposes.
1540
1545
1541 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1546 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1542 doesn't support persistence. Reported (and fix suggested) by
1547 doesn't support persistence. Reported (and fix suggested) by
1543 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1548 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1544
1549
1545 2004-06-26 Fernando Perez <fperez@colorado.edu>
1550 2004-06-26 Fernando Perez <fperez@colorado.edu>
1546
1551
1547 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1552 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1548 continue prompts.
1553 continue prompts.
1549
1554
1550 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1555 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1551 function (basically a big docstring) and a few more things here to
1556 function (basically a big docstring) and a few more things here to
1552 speedup startup. pysh.py is now very lightweight. We want because
1557 speedup startup. pysh.py is now very lightweight. We want because
1553 it gets execfile'd, while InterpreterExec gets imported, so
1558 it gets execfile'd, while InterpreterExec gets imported, so
1554 byte-compilation saves time.
1559 byte-compilation saves time.
1555
1560
1556 2004-06-25 Fernando Perez <fperez@colorado.edu>
1561 2004-06-25 Fernando Perez <fperez@colorado.edu>
1557
1562
1558 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1563 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1559 -NUM', which was recently broken.
1564 -NUM', which was recently broken.
1560
1565
1561 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1566 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1562 in multi-line input (but not !!, which doesn't make sense there).
1567 in multi-line input (but not !!, which doesn't make sense there).
1563
1568
1564 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1569 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1565 It's just too useful, and people can turn it off in the less
1570 It's just too useful, and people can turn it off in the less
1566 common cases where it's a problem.
1571 common cases where it's a problem.
1567
1572
1568 2004-06-24 Fernando Perez <fperez@colorado.edu>
1573 2004-06-24 Fernando Perez <fperez@colorado.edu>
1569
1574
1570 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1575 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1571 special syntaxes (like alias calling) is now allied in multi-line
1576 special syntaxes (like alias calling) is now allied in multi-line
1572 input. This is still _very_ experimental, but it's necessary for
1577 input. This is still _very_ experimental, but it's necessary for
1573 efficient shell usage combining python looping syntax with system
1578 efficient shell usage combining python looping syntax with system
1574 calls. For now it's restricted to aliases, I don't think it
1579 calls. For now it's restricted to aliases, I don't think it
1575 really even makes sense to have this for magics.
1580 really even makes sense to have this for magics.
1576
1581
1577 2004-06-23 Fernando Perez <fperez@colorado.edu>
1582 2004-06-23 Fernando Perez <fperez@colorado.edu>
1578
1583
1579 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1584 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1580 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1585 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1581
1586
1582 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1587 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1583 extensions under Windows (after code sent by Gary Bishop). The
1588 extensions under Windows (after code sent by Gary Bishop). The
1584 extensions considered 'executable' are stored in IPython's rc
1589 extensions considered 'executable' are stored in IPython's rc
1585 structure as win_exec_ext.
1590 structure as win_exec_ext.
1586
1591
1587 * IPython/genutils.py (shell): new function, like system() but
1592 * IPython/genutils.py (shell): new function, like system() but
1588 without return value. Very useful for interactive shell work.
1593 without return value. Very useful for interactive shell work.
1589
1594
1590 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1595 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1591 delete aliases.
1596 delete aliases.
1592
1597
1593 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1598 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1594 sure that the alias table doesn't contain python keywords.
1599 sure that the alias table doesn't contain python keywords.
1595
1600
1596 2004-06-21 Fernando Perez <fperez@colorado.edu>
1601 2004-06-21 Fernando Perez <fperez@colorado.edu>
1597
1602
1598 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1603 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1599 non-existent items are found in $PATH. Reported by Thorsten.
1604 non-existent items are found in $PATH. Reported by Thorsten.
1600
1605
1601 2004-06-20 Fernando Perez <fperez@colorado.edu>
1606 2004-06-20 Fernando Perez <fperez@colorado.edu>
1602
1607
1603 * IPython/iplib.py (complete): modified the completer so that the
1608 * IPython/iplib.py (complete): modified the completer so that the
1604 order of priorities can be easily changed at runtime.
1609 order of priorities can be easily changed at runtime.
1605
1610
1606 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1611 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1607 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1612 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1608
1613
1609 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1614 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1610 expand Python variables prepended with $ in all system calls. The
1615 expand Python variables prepended with $ in all system calls. The
1611 same was done to InteractiveShell.handle_shell_escape. Now all
1616 same was done to InteractiveShell.handle_shell_escape. Now all
1612 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1617 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1613 expansion of python variables and expressions according to the
1618 expansion of python variables and expressions according to the
1614 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1619 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1615
1620
1616 Though PEP-215 has been rejected, a similar (but simpler) one
1621 Though PEP-215 has been rejected, a similar (but simpler) one
1617 seems like it will go into Python 2.4, PEP-292 -
1622 seems like it will go into Python 2.4, PEP-292 -
1618 http://www.python.org/peps/pep-0292.html.
1623 http://www.python.org/peps/pep-0292.html.
1619
1624
1620 I'll keep the full syntax of PEP-215, since IPython has since the
1625 I'll keep the full syntax of PEP-215, since IPython has since the
1621 start used Ka-Ping Yee's reference implementation discussed there
1626 start used Ka-Ping Yee's reference implementation discussed there
1622 (Itpl), and I actually like the powerful semantics it offers.
1627 (Itpl), and I actually like the powerful semantics it offers.
1623
1628
1624 In order to access normal shell variables, the $ has to be escaped
1629 In order to access normal shell variables, the $ has to be escaped
1625 via an extra $. For example:
1630 via an extra $. For example:
1626
1631
1627 In [7]: PATH='a python variable'
1632 In [7]: PATH='a python variable'
1628
1633
1629 In [8]: !echo $PATH
1634 In [8]: !echo $PATH
1630 a python variable
1635 a python variable
1631
1636
1632 In [9]: !echo $$PATH
1637 In [9]: !echo $$PATH
1633 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1638 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1634
1639
1635 (Magic.parse_options): escape $ so the shell doesn't evaluate
1640 (Magic.parse_options): escape $ so the shell doesn't evaluate
1636 things prematurely.
1641 things prematurely.
1637
1642
1638 * IPython/iplib.py (InteractiveShell.call_alias): added the
1643 * IPython/iplib.py (InteractiveShell.call_alias): added the
1639 ability for aliases to expand python variables via $.
1644 ability for aliases to expand python variables via $.
1640
1645
1641 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1646 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1642 system, now there's a @rehash/@rehashx pair of magics. These work
1647 system, now there's a @rehash/@rehashx pair of magics. These work
1643 like the csh rehash command, and can be invoked at any time. They
1648 like the csh rehash command, and can be invoked at any time. They
1644 build a table of aliases to everything in the user's $PATH
1649 build a table of aliases to everything in the user's $PATH
1645 (@rehash uses everything, @rehashx is slower but only adds
1650 (@rehash uses everything, @rehashx is slower but only adds
1646 executable files). With this, the pysh.py-based shell profile can
1651 executable files). With this, the pysh.py-based shell profile can
1647 now simply call rehash upon startup, and full access to all
1652 now simply call rehash upon startup, and full access to all
1648 programs in the user's path is obtained.
1653 programs in the user's path is obtained.
1649
1654
1650 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1655 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1651 functionality is now fully in place. I removed the old dynamic
1656 functionality is now fully in place. I removed the old dynamic
1652 code generation based approach, in favor of a much lighter one
1657 code generation based approach, in favor of a much lighter one
1653 based on a simple dict. The advantage is that this allows me to
1658 based on a simple dict. The advantage is that this allows me to
1654 now have thousands of aliases with negligible cost (unthinkable
1659 now have thousands of aliases with negligible cost (unthinkable
1655 with the old system).
1660 with the old system).
1656
1661
1657 2004-06-19 Fernando Perez <fperez@colorado.edu>
1662 2004-06-19 Fernando Perez <fperez@colorado.edu>
1658
1663
1659 * IPython/iplib.py (__init__): extended MagicCompleter class to
1664 * IPython/iplib.py (__init__): extended MagicCompleter class to
1660 also complete (last in priority) on user aliases.
1665 also complete (last in priority) on user aliases.
1661
1666
1662 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1667 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1663 call to eval.
1668 call to eval.
1664 (ItplNS.__init__): Added a new class which functions like Itpl,
1669 (ItplNS.__init__): Added a new class which functions like Itpl,
1665 but allows configuring the namespace for the evaluation to occur
1670 but allows configuring the namespace for the evaluation to occur
1666 in.
1671 in.
1667
1672
1668 2004-06-18 Fernando Perez <fperez@colorado.edu>
1673 2004-06-18 Fernando Perez <fperez@colorado.edu>
1669
1674
1670 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1675 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1671 better message when 'exit' or 'quit' are typed (a common newbie
1676 better message when 'exit' or 'quit' are typed (a common newbie
1672 confusion).
1677 confusion).
1673
1678
1674 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1679 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1675 check for Windows users.
1680 check for Windows users.
1676
1681
1677 * IPython/iplib.py (InteractiveShell.user_setup): removed
1682 * IPython/iplib.py (InteractiveShell.user_setup): removed
1678 disabling of colors for Windows. I'll test at runtime and issue a
1683 disabling of colors for Windows. I'll test at runtime and issue a
1679 warning if Gary's readline isn't found, as to nudge users to
1684 warning if Gary's readline isn't found, as to nudge users to
1680 download it.
1685 download it.
1681
1686
1682 2004-06-16 Fernando Perez <fperez@colorado.edu>
1687 2004-06-16 Fernando Perez <fperez@colorado.edu>
1683
1688
1684 * IPython/genutils.py (Stream.__init__): changed to print errors
1689 * IPython/genutils.py (Stream.__init__): changed to print errors
1685 to sys.stderr. I had a circular dependency here. Now it's
1690 to sys.stderr. I had a circular dependency here. Now it's
1686 possible to run ipython as IDLE's shell (consider this pre-alpha,
1691 possible to run ipython as IDLE's shell (consider this pre-alpha,
1687 since true stdout things end up in the starting terminal instead
1692 since true stdout things end up in the starting terminal instead
1688 of IDLE's out).
1693 of IDLE's out).
1689
1694
1690 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1695 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1691 users who haven't # updated their prompt_in2 definitions. Remove
1696 users who haven't # updated their prompt_in2 definitions. Remove
1692 eventually.
1697 eventually.
1693 (multiple_replace): added credit to original ASPN recipe.
1698 (multiple_replace): added credit to original ASPN recipe.
1694
1699
1695 2004-06-15 Fernando Perez <fperez@colorado.edu>
1700 2004-06-15 Fernando Perez <fperez@colorado.edu>
1696
1701
1697 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1702 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1698 list of auto-defined aliases.
1703 list of auto-defined aliases.
1699
1704
1700 2004-06-13 Fernando Perez <fperez@colorado.edu>
1705 2004-06-13 Fernando Perez <fperez@colorado.edu>
1701
1706
1702 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1707 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1703 install was really requested (so setup.py can be used for other
1708 install was really requested (so setup.py can be used for other
1704 things under Windows).
1709 things under Windows).
1705
1710
1706 2004-06-10 Fernando Perez <fperez@colorado.edu>
1711 2004-06-10 Fernando Perez <fperez@colorado.edu>
1707
1712
1708 * IPython/Logger.py (Logger.create_log): Manually remove any old
1713 * IPython/Logger.py (Logger.create_log): Manually remove any old
1709 backup, since os.remove may fail under Windows. Fixes bug
1714 backup, since os.remove may fail under Windows. Fixes bug
1710 reported by Thorsten.
1715 reported by Thorsten.
1711
1716
1712 2004-06-09 Fernando Perez <fperez@colorado.edu>
1717 2004-06-09 Fernando Perez <fperez@colorado.edu>
1713
1718
1714 * examples/example-embed.py: fixed all references to %n (replaced
1719 * examples/example-embed.py: fixed all references to %n (replaced
1715 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1720 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1716 for all examples and the manual as well.
1721 for all examples and the manual as well.
1717
1722
1718 2004-06-08 Fernando Perez <fperez@colorado.edu>
1723 2004-06-08 Fernando Perez <fperez@colorado.edu>
1719
1724
1720 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1725 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1721 alignment and color management. All 3 prompt subsystems now
1726 alignment and color management. All 3 prompt subsystems now
1722 inherit from BasePrompt.
1727 inherit from BasePrompt.
1723
1728
1724 * tools/release: updates for windows installer build and tag rpms
1729 * tools/release: updates for windows installer build and tag rpms
1725 with python version (since paths are fixed).
1730 with python version (since paths are fixed).
1726
1731
1727 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1732 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1728 which will become eventually obsolete. Also fixed the default
1733 which will become eventually obsolete. Also fixed the default
1729 prompt_in2 to use \D, so at least new users start with the correct
1734 prompt_in2 to use \D, so at least new users start with the correct
1730 defaults.
1735 defaults.
1731 WARNING: Users with existing ipythonrc files will need to apply
1736 WARNING: Users with existing ipythonrc files will need to apply
1732 this fix manually!
1737 this fix manually!
1733
1738
1734 * setup.py: make windows installer (.exe). This is finally the
1739 * setup.py: make windows installer (.exe). This is finally the
1735 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1740 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1736 which I hadn't included because it required Python 2.3 (or recent
1741 which I hadn't included because it required Python 2.3 (or recent
1737 distutils).
1742 distutils).
1738
1743
1739 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1744 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1740 usage of new '\D' escape.
1745 usage of new '\D' escape.
1741
1746
1742 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1747 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1743 lacks os.getuid())
1748 lacks os.getuid())
1744 (CachedOutput.set_colors): Added the ability to turn coloring
1749 (CachedOutput.set_colors): Added the ability to turn coloring
1745 on/off with @colors even for manually defined prompt colors. It
1750 on/off with @colors even for manually defined prompt colors. It
1746 uses a nasty global, but it works safely and via the generic color
1751 uses a nasty global, but it works safely and via the generic color
1747 handling mechanism.
1752 handling mechanism.
1748 (Prompt2.__init__): Introduced new escape '\D' for continuation
1753 (Prompt2.__init__): Introduced new escape '\D' for continuation
1749 prompts. It represents the counter ('\#') as dots.
1754 prompts. It represents the counter ('\#') as dots.
1750 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1755 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1751 need to update their ipythonrc files and replace '%n' with '\D' in
1756 need to update their ipythonrc files and replace '%n' with '\D' in
1752 their prompt_in2 settings everywhere. Sorry, but there's
1757 their prompt_in2 settings everywhere. Sorry, but there's
1753 otherwise no clean way to get all prompts to properly align. The
1758 otherwise no clean way to get all prompts to properly align. The
1754 ipythonrc shipped with IPython has been updated.
1759 ipythonrc shipped with IPython has been updated.
1755
1760
1756 2004-06-07 Fernando Perez <fperez@colorado.edu>
1761 2004-06-07 Fernando Perez <fperez@colorado.edu>
1757
1762
1758 * setup.py (isfile): Pass local_icons option to latex2html, so the
1763 * setup.py (isfile): Pass local_icons option to latex2html, so the
1759 resulting HTML file is self-contained. Thanks to
1764 resulting HTML file is self-contained. Thanks to
1760 dryice-AT-liu.com.cn for the tip.
1765 dryice-AT-liu.com.cn for the tip.
1761
1766
1762 * pysh.py: I created a new profile 'shell', which implements a
1767 * pysh.py: I created a new profile 'shell', which implements a
1763 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1768 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1764 system shell, nor will it become one anytime soon. It's mainly
1769 system shell, nor will it become one anytime soon. It's mainly
1765 meant to illustrate the use of the new flexible bash-like prompts.
1770 meant to illustrate the use of the new flexible bash-like prompts.
1766 I guess it could be used by hardy souls for true shell management,
1771 I guess it could be used by hardy souls for true shell management,
1767 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1772 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1768 profile. This uses the InterpreterExec extension provided by
1773 profile. This uses the InterpreterExec extension provided by
1769 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1774 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1770
1775
1771 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1776 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1772 auto-align itself with the length of the previous input prompt
1777 auto-align itself with the length of the previous input prompt
1773 (taking into account the invisible color escapes).
1778 (taking into account the invisible color escapes).
1774 (CachedOutput.__init__): Large restructuring of this class. Now
1779 (CachedOutput.__init__): Large restructuring of this class. Now
1775 all three prompts (primary1, primary2, output) are proper objects,
1780 all three prompts (primary1, primary2, output) are proper objects,
1776 managed by the 'parent' CachedOutput class. The code is still a
1781 managed by the 'parent' CachedOutput class. The code is still a
1777 bit hackish (all prompts share state via a pointer to the cache),
1782 bit hackish (all prompts share state via a pointer to the cache),
1778 but it's overall far cleaner than before.
1783 but it's overall far cleaner than before.
1779
1784
1780 * IPython/genutils.py (getoutputerror): modified to add verbose,
1785 * IPython/genutils.py (getoutputerror): modified to add verbose,
1781 debug and header options. This makes the interface of all getout*
1786 debug and header options. This makes the interface of all getout*
1782 functions uniform.
1787 functions uniform.
1783 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1788 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1784
1789
1785 * IPython/Magic.py (Magic.default_option): added a function to
1790 * IPython/Magic.py (Magic.default_option): added a function to
1786 allow registering default options for any magic command. This
1791 allow registering default options for any magic command. This
1787 makes it easy to have profiles which customize the magics globally
1792 makes it easy to have profiles which customize the magics globally
1788 for a certain use. The values set through this function are
1793 for a certain use. The values set through this function are
1789 picked up by the parse_options() method, which all magics should
1794 picked up by the parse_options() method, which all magics should
1790 use to parse their options.
1795 use to parse their options.
1791
1796
1792 * IPython/genutils.py (warn): modified the warnings framework to
1797 * IPython/genutils.py (warn): modified the warnings framework to
1793 use the Term I/O class. I'm trying to slowly unify all of
1798 use the Term I/O class. I'm trying to slowly unify all of
1794 IPython's I/O operations to pass through Term.
1799 IPython's I/O operations to pass through Term.
1795
1800
1796 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1801 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1797 the secondary prompt to correctly match the length of the primary
1802 the secondary prompt to correctly match the length of the primary
1798 one for any prompt. Now multi-line code will properly line up
1803 one for any prompt. Now multi-line code will properly line up
1799 even for path dependent prompts, such as the new ones available
1804 even for path dependent prompts, such as the new ones available
1800 via the prompt_specials.
1805 via the prompt_specials.
1801
1806
1802 2004-06-06 Fernando Perez <fperez@colorado.edu>
1807 2004-06-06 Fernando Perez <fperez@colorado.edu>
1803
1808
1804 * IPython/Prompts.py (prompt_specials): Added the ability to have
1809 * IPython/Prompts.py (prompt_specials): Added the ability to have
1805 bash-like special sequences in the prompts, which get
1810 bash-like special sequences in the prompts, which get
1806 automatically expanded. Things like hostname, current working
1811 automatically expanded. Things like hostname, current working
1807 directory and username are implemented already, but it's easy to
1812 directory and username are implemented already, but it's easy to
1808 add more in the future. Thanks to a patch by W.J. van der Laan
1813 add more in the future. Thanks to a patch by W.J. van der Laan
1809 <gnufnork-AT-hetdigitalegat.nl>
1814 <gnufnork-AT-hetdigitalegat.nl>
1810 (prompt_specials): Added color support for prompt strings, so
1815 (prompt_specials): Added color support for prompt strings, so
1811 users can define arbitrary color setups for their prompts.
1816 users can define arbitrary color setups for their prompts.
1812
1817
1813 2004-06-05 Fernando Perez <fperez@colorado.edu>
1818 2004-06-05 Fernando Perez <fperez@colorado.edu>
1814
1819
1815 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1820 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1816 code to load Gary Bishop's readline and configure it
1821 code to load Gary Bishop's readline and configure it
1817 automatically. Thanks to Gary for help on this.
1822 automatically. Thanks to Gary for help on this.
1818
1823
1819 2004-06-01 Fernando Perez <fperez@colorado.edu>
1824 2004-06-01 Fernando Perez <fperez@colorado.edu>
1820
1825
1821 * IPython/Logger.py (Logger.create_log): fix bug for logging
1826 * IPython/Logger.py (Logger.create_log): fix bug for logging
1822 with no filename (previous fix was incomplete).
1827 with no filename (previous fix was incomplete).
1823
1828
1824 2004-05-25 Fernando Perez <fperez@colorado.edu>
1829 2004-05-25 Fernando Perez <fperez@colorado.edu>
1825
1830
1826 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1831 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1827 parens would get passed to the shell.
1832 parens would get passed to the shell.
1828
1833
1829 2004-05-20 Fernando Perez <fperez@colorado.edu>
1834 2004-05-20 Fernando Perez <fperez@colorado.edu>
1830
1835
1831 * IPython/Magic.py (Magic.magic_prun): changed default profile
1836 * IPython/Magic.py (Magic.magic_prun): changed default profile
1832 sort order to 'time' (the more common profiling need).
1837 sort order to 'time' (the more common profiling need).
1833
1838
1834 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1839 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1835 so that source code shown is guaranteed in sync with the file on
1840 so that source code shown is guaranteed in sync with the file on
1836 disk (also changed in psource). Similar fix to the one for
1841 disk (also changed in psource). Similar fix to the one for
1837 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1842 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1838 <yann.ledu-AT-noos.fr>.
1843 <yann.ledu-AT-noos.fr>.
1839
1844
1840 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1845 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1841 with a single option would not be correctly parsed. Closes
1846 with a single option would not be correctly parsed. Closes
1842 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1847 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1843 introduced in 0.6.0 (on 2004-05-06).
1848 introduced in 0.6.0 (on 2004-05-06).
1844
1849
1845 2004-05-13 *** Released version 0.6.0
1850 2004-05-13 *** Released version 0.6.0
1846
1851
1847 2004-05-13 Fernando Perez <fperez@colorado.edu>
1852 2004-05-13 Fernando Perez <fperez@colorado.edu>
1848
1853
1849 * debian/: Added debian/ directory to CVS, so that debian support
1854 * debian/: Added debian/ directory to CVS, so that debian support
1850 is publicly accessible. The debian package is maintained by Jack
1855 is publicly accessible. The debian package is maintained by Jack
1851 Moffit <jack-AT-xiph.org>.
1856 Moffit <jack-AT-xiph.org>.
1852
1857
1853 * Documentation: included the notes about an ipython-based system
1858 * Documentation: included the notes about an ipython-based system
1854 shell (the hypothetical 'pysh') into the new_design.pdf document,
1859 shell (the hypothetical 'pysh') into the new_design.pdf document,
1855 so that these ideas get distributed to users along with the
1860 so that these ideas get distributed to users along with the
1856 official documentation.
1861 official documentation.
1857
1862
1858 2004-05-10 Fernando Perez <fperez@colorado.edu>
1863 2004-05-10 Fernando Perez <fperez@colorado.edu>
1859
1864
1860 * IPython/Logger.py (Logger.create_log): fix recently introduced
1865 * IPython/Logger.py (Logger.create_log): fix recently introduced
1861 bug (misindented line) where logstart would fail when not given an
1866 bug (misindented line) where logstart would fail when not given an
1862 explicit filename.
1867 explicit filename.
1863
1868
1864 2004-05-09 Fernando Perez <fperez@colorado.edu>
1869 2004-05-09 Fernando Perez <fperez@colorado.edu>
1865
1870
1866 * IPython/Magic.py (Magic.parse_options): skip system call when
1871 * IPython/Magic.py (Magic.parse_options): skip system call when
1867 there are no options to look for. Faster, cleaner for the common
1872 there are no options to look for. Faster, cleaner for the common
1868 case.
1873 case.
1869
1874
1870 * Documentation: many updates to the manual: describing Windows
1875 * Documentation: many updates to the manual: describing Windows
1871 support better, Gnuplot updates, credits, misc small stuff. Also
1876 support better, Gnuplot updates, credits, misc small stuff. Also
1872 updated the new_design doc a bit.
1877 updated the new_design doc a bit.
1873
1878
1874 2004-05-06 *** Released version 0.6.0.rc1
1879 2004-05-06 *** Released version 0.6.0.rc1
1875
1880
1876 2004-05-06 Fernando Perez <fperez@colorado.edu>
1881 2004-05-06 Fernando Perez <fperez@colorado.edu>
1877
1882
1878 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1883 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1879 operations to use the vastly more efficient list/''.join() method.
1884 operations to use the vastly more efficient list/''.join() method.
1880 (FormattedTB.text): Fix
1885 (FormattedTB.text): Fix
1881 http://www.scipy.net/roundup/ipython/issue12 - exception source
1886 http://www.scipy.net/roundup/ipython/issue12 - exception source
1882 extract not updated after reload. Thanks to Mike Salib
1887 extract not updated after reload. Thanks to Mike Salib
1883 <msalib-AT-mit.edu> for pinning the source of the problem.
1888 <msalib-AT-mit.edu> for pinning the source of the problem.
1884 Fortunately, the solution works inside ipython and doesn't require
1889 Fortunately, the solution works inside ipython and doesn't require
1885 any changes to python proper.
1890 any changes to python proper.
1886
1891
1887 * IPython/Magic.py (Magic.parse_options): Improved to process the
1892 * IPython/Magic.py (Magic.parse_options): Improved to process the
1888 argument list as a true shell would (by actually using the
1893 argument list as a true shell would (by actually using the
1889 underlying system shell). This way, all @magics automatically get
1894 underlying system shell). This way, all @magics automatically get
1890 shell expansion for variables. Thanks to a comment by Alex
1895 shell expansion for variables. Thanks to a comment by Alex
1891 Schmolck.
1896 Schmolck.
1892
1897
1893 2004-04-04 Fernando Perez <fperez@colorado.edu>
1898 2004-04-04 Fernando Perez <fperez@colorado.edu>
1894
1899
1895 * IPython/iplib.py (InteractiveShell.interact): Added a special
1900 * IPython/iplib.py (InteractiveShell.interact): Added a special
1896 trap for a debugger quit exception, which is basically impossible
1901 trap for a debugger quit exception, which is basically impossible
1897 to handle by normal mechanisms, given what pdb does to the stack.
1902 to handle by normal mechanisms, given what pdb does to the stack.
1898 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1903 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1899
1904
1900 2004-04-03 Fernando Perez <fperez@colorado.edu>
1905 2004-04-03 Fernando Perez <fperez@colorado.edu>
1901
1906
1902 * IPython/genutils.py (Term): Standardized the names of the Term
1907 * IPython/genutils.py (Term): Standardized the names of the Term
1903 class streams to cin/cout/cerr, following C++ naming conventions
1908 class streams to cin/cout/cerr, following C++ naming conventions
1904 (I can't use in/out/err because 'in' is not a valid attribute
1909 (I can't use in/out/err because 'in' is not a valid attribute
1905 name).
1910 name).
1906
1911
1907 * IPython/iplib.py (InteractiveShell.interact): don't increment
1912 * IPython/iplib.py (InteractiveShell.interact): don't increment
1908 the prompt if there's no user input. By Daniel 'Dang' Griffith
1913 the prompt if there's no user input. By Daniel 'Dang' Griffith
1909 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1914 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1910 Francois Pinard.
1915 Francois Pinard.
1911
1916
1912 2004-04-02 Fernando Perez <fperez@colorado.edu>
1917 2004-04-02 Fernando Perez <fperez@colorado.edu>
1913
1918
1914 * IPython/genutils.py (Stream.__init__): Modified to survive at
1919 * IPython/genutils.py (Stream.__init__): Modified to survive at
1915 least importing in contexts where stdin/out/err aren't true file
1920 least importing in contexts where stdin/out/err aren't true file
1916 objects, such as PyCrust (they lack fileno() and mode). However,
1921 objects, such as PyCrust (they lack fileno() and mode). However,
1917 the recovery facilities which rely on these things existing will
1922 the recovery facilities which rely on these things existing will
1918 not work.
1923 not work.
1919
1924
1920 2004-04-01 Fernando Perez <fperez@colorado.edu>
1925 2004-04-01 Fernando Perez <fperez@colorado.edu>
1921
1926
1922 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1927 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1923 use the new getoutputerror() function, so it properly
1928 use the new getoutputerror() function, so it properly
1924 distinguishes stdout/err.
1929 distinguishes stdout/err.
1925
1930
1926 * IPython/genutils.py (getoutputerror): added a function to
1931 * IPython/genutils.py (getoutputerror): added a function to
1927 capture separately the standard output and error of a command.
1932 capture separately the standard output and error of a command.
1928 After a comment from dang on the mailing lists. This code is
1933 After a comment from dang on the mailing lists. This code is
1929 basically a modified version of commands.getstatusoutput(), from
1934 basically a modified version of commands.getstatusoutput(), from
1930 the standard library.
1935 the standard library.
1931
1936
1932 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1937 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1933 '!!' as a special syntax (shorthand) to access @sx.
1938 '!!' as a special syntax (shorthand) to access @sx.
1934
1939
1935 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1940 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1936 command and return its output as a list split on '\n'.
1941 command and return its output as a list split on '\n'.
1937
1942
1938 2004-03-31 Fernando Perez <fperez@colorado.edu>
1943 2004-03-31 Fernando Perez <fperez@colorado.edu>
1939
1944
1940 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1945 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1941 method to dictionaries used as FakeModule instances if they lack
1946 method to dictionaries used as FakeModule instances if they lack
1942 it. At least pydoc in python2.3 breaks for runtime-defined
1947 it. At least pydoc in python2.3 breaks for runtime-defined
1943 functions without this hack. At some point I need to _really_
1948 functions without this hack. At some point I need to _really_
1944 understand what FakeModule is doing, because it's a gross hack.
1949 understand what FakeModule is doing, because it's a gross hack.
1945 But it solves Arnd's problem for now...
1950 But it solves Arnd's problem for now...
1946
1951
1947 2004-02-27 Fernando Perez <fperez@colorado.edu>
1952 2004-02-27 Fernando Perez <fperez@colorado.edu>
1948
1953
1949 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1954 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1950 mode would behave erratically. Also increased the number of
1955 mode would behave erratically. Also increased the number of
1951 possible logs in rotate mod to 999. Thanks to Rod Holland
1956 possible logs in rotate mod to 999. Thanks to Rod Holland
1952 <rhh@StructureLABS.com> for the report and fixes.
1957 <rhh@StructureLABS.com> for the report and fixes.
1953
1958
1954 2004-02-26 Fernando Perez <fperez@colorado.edu>
1959 2004-02-26 Fernando Perez <fperez@colorado.edu>
1955
1960
1956 * IPython/genutils.py (page): Check that the curses module really
1961 * IPython/genutils.py (page): Check that the curses module really
1957 has the initscr attribute before trying to use it. For some
1962 has the initscr attribute before trying to use it. For some
1958 reason, the Solaris curses module is missing this. I think this
1963 reason, the Solaris curses module is missing this. I think this
1959 should be considered a Solaris python bug, but I'm not sure.
1964 should be considered a Solaris python bug, but I'm not sure.
1960
1965
1961 2004-01-17 Fernando Perez <fperez@colorado.edu>
1966 2004-01-17 Fernando Perez <fperez@colorado.edu>
1962
1967
1963 * IPython/genutils.py (Stream.__init__): Changes to try to make
1968 * IPython/genutils.py (Stream.__init__): Changes to try to make
1964 ipython robust against stdin/out/err being closed by the user.
1969 ipython robust against stdin/out/err being closed by the user.
1965 This is 'user error' (and blocks a normal python session, at least
1970 This is 'user error' (and blocks a normal python session, at least
1966 the stdout case). However, Ipython should be able to survive such
1971 the stdout case). However, Ipython should be able to survive such
1967 instances of abuse as gracefully as possible. To simplify the
1972 instances of abuse as gracefully as possible. To simplify the
1968 coding and maintain compatibility with Gary Bishop's Term
1973 coding and maintain compatibility with Gary Bishop's Term
1969 contributions, I've made use of classmethods for this. I think
1974 contributions, I've made use of classmethods for this. I think
1970 this introduces a dependency on python 2.2.
1975 this introduces a dependency on python 2.2.
1971
1976
1972 2004-01-13 Fernando Perez <fperez@colorado.edu>
1977 2004-01-13 Fernando Perez <fperez@colorado.edu>
1973
1978
1974 * IPython/numutils.py (exp_safe): simplified the code a bit and
1979 * IPython/numutils.py (exp_safe): simplified the code a bit and
1975 removed the need for importing the kinds module altogether.
1980 removed the need for importing the kinds module altogether.
1976
1981
1977 2004-01-06 Fernando Perez <fperez@colorado.edu>
1982 2004-01-06 Fernando Perez <fperez@colorado.edu>
1978
1983
1979 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1984 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1980 a magic function instead, after some community feedback. No
1985 a magic function instead, after some community feedback. No
1981 special syntax will exist for it, but its name is deliberately
1986 special syntax will exist for it, but its name is deliberately
1982 very short.
1987 very short.
1983
1988
1984 2003-12-20 Fernando Perez <fperez@colorado.edu>
1989 2003-12-20 Fernando Perez <fperez@colorado.edu>
1985
1990
1986 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1991 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1987 new functionality, to automagically assign the result of a shell
1992 new functionality, to automagically assign the result of a shell
1988 command to a variable. I'll solicit some community feedback on
1993 command to a variable. I'll solicit some community feedback on
1989 this before making it permanent.
1994 this before making it permanent.
1990
1995
1991 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1996 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1992 requested about callables for which inspect couldn't obtain a
1997 requested about callables for which inspect couldn't obtain a
1993 proper argspec. Thanks to a crash report sent by Etienne
1998 proper argspec. Thanks to a crash report sent by Etienne
1994 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1999 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1995
2000
1996 2003-12-09 Fernando Perez <fperez@colorado.edu>
2001 2003-12-09 Fernando Perez <fperez@colorado.edu>
1997
2002
1998 * IPython/genutils.py (page): patch for the pager to work across
2003 * IPython/genutils.py (page): patch for the pager to work across
1999 various versions of Windows. By Gary Bishop.
2004 various versions of Windows. By Gary Bishop.
2000
2005
2001 2003-12-04 Fernando Perez <fperez@colorado.edu>
2006 2003-12-04 Fernando Perez <fperez@colorado.edu>
2002
2007
2003 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2008 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2004 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2009 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2005 While I tested this and it looks ok, there may still be corner
2010 While I tested this and it looks ok, there may still be corner
2006 cases I've missed.
2011 cases I've missed.
2007
2012
2008 2003-12-01 Fernando Perez <fperez@colorado.edu>
2013 2003-12-01 Fernando Perez <fperez@colorado.edu>
2009
2014
2010 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2015 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2011 where a line like 'p,q=1,2' would fail because the automagic
2016 where a line like 'p,q=1,2' would fail because the automagic
2012 system would be triggered for @p.
2017 system would be triggered for @p.
2013
2018
2014 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2019 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2015 cleanups, code unmodified.
2020 cleanups, code unmodified.
2016
2021
2017 * IPython/genutils.py (Term): added a class for IPython to handle
2022 * IPython/genutils.py (Term): added a class for IPython to handle
2018 output. In most cases it will just be a proxy for stdout/err, but
2023 output. In most cases it will just be a proxy for stdout/err, but
2019 having this allows modifications to be made for some platforms,
2024 having this allows modifications to be made for some platforms,
2020 such as handling color escapes under Windows. All of this code
2025 such as handling color escapes under Windows. All of this code
2021 was contributed by Gary Bishop, with minor modifications by me.
2026 was contributed by Gary Bishop, with minor modifications by me.
2022 The actual changes affect many files.
2027 The actual changes affect many files.
2023
2028
2024 2003-11-30 Fernando Perez <fperez@colorado.edu>
2029 2003-11-30 Fernando Perez <fperez@colorado.edu>
2025
2030
2026 * IPython/iplib.py (file_matches): new completion code, courtesy
2031 * IPython/iplib.py (file_matches): new completion code, courtesy
2027 of Jeff Collins. This enables filename completion again under
2032 of Jeff Collins. This enables filename completion again under
2028 python 2.3, which disabled it at the C level.
2033 python 2.3, which disabled it at the C level.
2029
2034
2030 2003-11-11 Fernando Perez <fperez@colorado.edu>
2035 2003-11-11 Fernando Perez <fperez@colorado.edu>
2031
2036
2032 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2037 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2033 for Numeric.array(map(...)), but often convenient.
2038 for Numeric.array(map(...)), but often convenient.
2034
2039
2035 2003-11-05 Fernando Perez <fperez@colorado.edu>
2040 2003-11-05 Fernando Perez <fperez@colorado.edu>
2036
2041
2037 * IPython/numutils.py (frange): Changed a call from int() to
2042 * IPython/numutils.py (frange): Changed a call from int() to
2038 int(round()) to prevent a problem reported with arange() in the
2043 int(round()) to prevent a problem reported with arange() in the
2039 numpy list.
2044 numpy list.
2040
2045
2041 2003-10-06 Fernando Perez <fperez@colorado.edu>
2046 2003-10-06 Fernando Perez <fperez@colorado.edu>
2042
2047
2043 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2048 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2044 prevent crashes if sys lacks an argv attribute (it happens with
2049 prevent crashes if sys lacks an argv attribute (it happens with
2045 embedded interpreters which build a bare-bones sys module).
2050 embedded interpreters which build a bare-bones sys module).
2046 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2051 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2047
2052
2048 2003-09-24 Fernando Perez <fperez@colorado.edu>
2053 2003-09-24 Fernando Perez <fperez@colorado.edu>
2049
2054
2050 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2055 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2051 to protect against poorly written user objects where __getattr__
2056 to protect against poorly written user objects where __getattr__
2052 raises exceptions other than AttributeError. Thanks to a bug
2057 raises exceptions other than AttributeError. Thanks to a bug
2053 report by Oliver Sander <osander-AT-gmx.de>.
2058 report by Oliver Sander <osander-AT-gmx.de>.
2054
2059
2055 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2060 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2056 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2061 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2057
2062
2058 2003-09-09 Fernando Perez <fperez@colorado.edu>
2063 2003-09-09 Fernando Perez <fperez@colorado.edu>
2059
2064
2060 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2065 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2061 unpacking a list whith a callable as first element would
2066 unpacking a list whith a callable as first element would
2062 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2067 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2063 Collins.
2068 Collins.
2064
2069
2065 2003-08-25 *** Released version 0.5.0
2070 2003-08-25 *** Released version 0.5.0
2066
2071
2067 2003-08-22 Fernando Perez <fperez@colorado.edu>
2072 2003-08-22 Fernando Perez <fperez@colorado.edu>
2068
2073
2069 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2074 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2070 improperly defined user exceptions. Thanks to feedback from Mark
2075 improperly defined user exceptions. Thanks to feedback from Mark
2071 Russell <mrussell-AT-verio.net>.
2076 Russell <mrussell-AT-verio.net>.
2072
2077
2073 2003-08-20 Fernando Perez <fperez@colorado.edu>
2078 2003-08-20 Fernando Perez <fperez@colorado.edu>
2074
2079
2075 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2080 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2076 printing so that it would print multi-line string forms starting
2081 printing so that it would print multi-line string forms starting
2077 with a new line. This way the formatting is better respected for
2082 with a new line. This way the formatting is better respected for
2078 objects which work hard to make nice string forms.
2083 objects which work hard to make nice string forms.
2079
2084
2080 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2085 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2081 autocall would overtake data access for objects with both
2086 autocall would overtake data access for objects with both
2082 __getitem__ and __call__.
2087 __getitem__ and __call__.
2083
2088
2084 2003-08-19 *** Released version 0.5.0-rc1
2089 2003-08-19 *** Released version 0.5.0-rc1
2085
2090
2086 2003-08-19 Fernando Perez <fperez@colorado.edu>
2091 2003-08-19 Fernando Perez <fperez@colorado.edu>
2087
2092
2088 * IPython/deep_reload.py (load_tail): single tiny change here
2093 * IPython/deep_reload.py (load_tail): single tiny change here
2089 seems to fix the long-standing bug of dreload() failing to work
2094 seems to fix the long-standing bug of dreload() failing to work
2090 for dotted names. But this module is pretty tricky, so I may have
2095 for dotted names. But this module is pretty tricky, so I may have
2091 missed some subtlety. Needs more testing!.
2096 missed some subtlety. Needs more testing!.
2092
2097
2093 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2098 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2094 exceptions which have badly implemented __str__ methods.
2099 exceptions which have badly implemented __str__ methods.
2095 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2100 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2096 which I've been getting reports about from Python 2.3 users. I
2101 which I've been getting reports about from Python 2.3 users. I
2097 wish I had a simple test case to reproduce the problem, so I could
2102 wish I had a simple test case to reproduce the problem, so I could
2098 either write a cleaner workaround or file a bug report if
2103 either write a cleaner workaround or file a bug report if
2099 necessary.
2104 necessary.
2100
2105
2101 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2106 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2102 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2107 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2103 a bug report by Tjabo Kloppenburg.
2108 a bug report by Tjabo Kloppenburg.
2104
2109
2105 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2110 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2106 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2111 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2107 seems rather unstable. Thanks to a bug report by Tjabo
2112 seems rather unstable. Thanks to a bug report by Tjabo
2108 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2113 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2109
2114
2110 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2115 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2111 this out soon because of the critical fixes in the inner loop for
2116 this out soon because of the critical fixes in the inner loop for
2112 generators.
2117 generators.
2113
2118
2114 * IPython/Magic.py (Magic.getargspec): removed. This (and
2119 * IPython/Magic.py (Magic.getargspec): removed. This (and
2115 _get_def) have been obsoleted by OInspect for a long time, I
2120 _get_def) have been obsoleted by OInspect for a long time, I
2116 hadn't noticed that they were dead code.
2121 hadn't noticed that they were dead code.
2117 (Magic._ofind): restored _ofind functionality for a few literals
2122 (Magic._ofind): restored _ofind functionality for a few literals
2118 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2123 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2119 for things like "hello".capitalize?, since that would require a
2124 for things like "hello".capitalize?, since that would require a
2120 potentially dangerous eval() again.
2125 potentially dangerous eval() again.
2121
2126
2122 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2127 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2123 logic a bit more to clean up the escapes handling and minimize the
2128 logic a bit more to clean up the escapes handling and minimize the
2124 use of _ofind to only necessary cases. The interactive 'feel' of
2129 use of _ofind to only necessary cases. The interactive 'feel' of
2125 IPython should have improved quite a bit with the changes in
2130 IPython should have improved quite a bit with the changes in
2126 _prefilter and _ofind (besides being far safer than before).
2131 _prefilter and _ofind (besides being far safer than before).
2127
2132
2128 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2133 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2129 obscure, never reported). Edit would fail to find the object to
2134 obscure, never reported). Edit would fail to find the object to
2130 edit under some circumstances.
2135 edit under some circumstances.
2131 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2136 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2132 which were causing double-calling of generators. Those eval calls
2137 which were causing double-calling of generators. Those eval calls
2133 were _very_ dangerous, since code with side effects could be
2138 were _very_ dangerous, since code with side effects could be
2134 triggered. As they say, 'eval is evil'... These were the
2139 triggered. As they say, 'eval is evil'... These were the
2135 nastiest evals in IPython. Besides, _ofind is now far simpler,
2140 nastiest evals in IPython. Besides, _ofind is now far simpler,
2136 and it should also be quite a bit faster. Its use of inspect is
2141 and it should also be quite a bit faster. Its use of inspect is
2137 also safer, so perhaps some of the inspect-related crashes I've
2142 also safer, so perhaps some of the inspect-related crashes I've
2138 seen lately with Python 2.3 might be taken care of. That will
2143 seen lately with Python 2.3 might be taken care of. That will
2139 need more testing.
2144 need more testing.
2140
2145
2141 2003-08-17 Fernando Perez <fperez@colorado.edu>
2146 2003-08-17 Fernando Perez <fperez@colorado.edu>
2142
2147
2143 * IPython/iplib.py (InteractiveShell._prefilter): significant
2148 * IPython/iplib.py (InteractiveShell._prefilter): significant
2144 simplifications to the logic for handling user escapes. Faster
2149 simplifications to the logic for handling user escapes. Faster
2145 and simpler code.
2150 and simpler code.
2146
2151
2147 2003-08-14 Fernando Perez <fperez@colorado.edu>
2152 2003-08-14 Fernando Perez <fperez@colorado.edu>
2148
2153
2149 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2154 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2150 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2155 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2151 but it should be quite a bit faster. And the recursive version
2156 but it should be quite a bit faster. And the recursive version
2152 generated O(log N) intermediate storage for all rank>1 arrays,
2157 generated O(log N) intermediate storage for all rank>1 arrays,
2153 even if they were contiguous.
2158 even if they were contiguous.
2154 (l1norm): Added this function.
2159 (l1norm): Added this function.
2155 (norm): Added this function for arbitrary norms (including
2160 (norm): Added this function for arbitrary norms (including
2156 l-infinity). l1 and l2 are still special cases for convenience
2161 l-infinity). l1 and l2 are still special cases for convenience
2157 and speed.
2162 and speed.
2158
2163
2159 2003-08-03 Fernando Perez <fperez@colorado.edu>
2164 2003-08-03 Fernando Perez <fperez@colorado.edu>
2160
2165
2161 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2166 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2162 exceptions, which now raise PendingDeprecationWarnings in Python
2167 exceptions, which now raise PendingDeprecationWarnings in Python
2163 2.3. There were some in Magic and some in Gnuplot2.
2168 2.3. There were some in Magic and some in Gnuplot2.
2164
2169
2165 2003-06-30 Fernando Perez <fperez@colorado.edu>
2170 2003-06-30 Fernando Perez <fperez@colorado.edu>
2166
2171
2167 * IPython/genutils.py (page): modified to call curses only for
2172 * IPython/genutils.py (page): modified to call curses only for
2168 terminals where TERM=='xterm'. After problems under many other
2173 terminals where TERM=='xterm'. After problems under many other
2169 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2174 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2170
2175
2171 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2176 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2172 would be triggered when readline was absent. This was just an old
2177 would be triggered when readline was absent. This was just an old
2173 debugging statement I'd forgotten to take out.
2178 debugging statement I'd forgotten to take out.
2174
2179
2175 2003-06-20 Fernando Perez <fperez@colorado.edu>
2180 2003-06-20 Fernando Perez <fperez@colorado.edu>
2176
2181
2177 * IPython/genutils.py (clock): modified to return only user time
2182 * IPython/genutils.py (clock): modified to return only user time
2178 (not counting system time), after a discussion on scipy. While
2183 (not counting system time), after a discussion on scipy. While
2179 system time may be a useful quantity occasionally, it may much
2184 system time may be a useful quantity occasionally, it may much
2180 more easily be skewed by occasional swapping or other similar
2185 more easily be skewed by occasional swapping or other similar
2181 activity.
2186 activity.
2182
2187
2183 2003-06-05 Fernando Perez <fperez@colorado.edu>
2188 2003-06-05 Fernando Perez <fperez@colorado.edu>
2184
2189
2185 * IPython/numutils.py (identity): new function, for building
2190 * IPython/numutils.py (identity): new function, for building
2186 arbitrary rank Kronecker deltas (mostly backwards compatible with
2191 arbitrary rank Kronecker deltas (mostly backwards compatible with
2187 Numeric.identity)
2192 Numeric.identity)
2188
2193
2189 2003-06-03 Fernando Perez <fperez@colorado.edu>
2194 2003-06-03 Fernando Perez <fperez@colorado.edu>
2190
2195
2191 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2196 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2192 arguments passed to magics with spaces, to allow trailing '\' to
2197 arguments passed to magics with spaces, to allow trailing '\' to
2193 work normally (mainly for Windows users).
2198 work normally (mainly for Windows users).
2194
2199
2195 2003-05-29 Fernando Perez <fperez@colorado.edu>
2200 2003-05-29 Fernando Perez <fperez@colorado.edu>
2196
2201
2197 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2202 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2198 instead of pydoc.help. This fixes a bizarre behavior where
2203 instead of pydoc.help. This fixes a bizarre behavior where
2199 printing '%s' % locals() would trigger the help system. Now
2204 printing '%s' % locals() would trigger the help system. Now
2200 ipython behaves like normal python does.
2205 ipython behaves like normal python does.
2201
2206
2202 Note that if one does 'from pydoc import help', the bizarre
2207 Note that if one does 'from pydoc import help', the bizarre
2203 behavior returns, but this will also happen in normal python, so
2208 behavior returns, but this will also happen in normal python, so
2204 it's not an ipython bug anymore (it has to do with how pydoc.help
2209 it's not an ipython bug anymore (it has to do with how pydoc.help
2205 is implemented).
2210 is implemented).
2206
2211
2207 2003-05-22 Fernando Perez <fperez@colorado.edu>
2212 2003-05-22 Fernando Perez <fperez@colorado.edu>
2208
2213
2209 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2214 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2210 return [] instead of None when nothing matches, also match to end
2215 return [] instead of None when nothing matches, also match to end
2211 of line. Patch by Gary Bishop.
2216 of line. Patch by Gary Bishop.
2212
2217
2213 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2218 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2214 protection as before, for files passed on the command line. This
2219 protection as before, for files passed on the command line. This
2215 prevents the CrashHandler from kicking in if user files call into
2220 prevents the CrashHandler from kicking in if user files call into
2216 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2221 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2217 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2222 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2218
2223
2219 2003-05-20 *** Released version 0.4.0
2224 2003-05-20 *** Released version 0.4.0
2220
2225
2221 2003-05-20 Fernando Perez <fperez@colorado.edu>
2226 2003-05-20 Fernando Perez <fperez@colorado.edu>
2222
2227
2223 * setup.py: added support for manpages. It's a bit hackish b/c of
2228 * setup.py: added support for manpages. It's a bit hackish b/c of
2224 a bug in the way the bdist_rpm distutils target handles gzipped
2229 a bug in the way the bdist_rpm distutils target handles gzipped
2225 manpages, but it works. After a patch by Jack.
2230 manpages, but it works. After a patch by Jack.
2226
2231
2227 2003-05-19 Fernando Perez <fperez@colorado.edu>
2232 2003-05-19 Fernando Perez <fperez@colorado.edu>
2228
2233
2229 * IPython/numutils.py: added a mockup of the kinds module, since
2234 * IPython/numutils.py: added a mockup of the kinds module, since
2230 it was recently removed from Numeric. This way, numutils will
2235 it was recently removed from Numeric. This way, numutils will
2231 work for all users even if they are missing kinds.
2236 work for all users even if they are missing kinds.
2232
2237
2233 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2238 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2234 failure, which can occur with SWIG-wrapped extensions. After a
2239 failure, which can occur with SWIG-wrapped extensions. After a
2235 crash report from Prabhu.
2240 crash report from Prabhu.
2236
2241
2237 2003-05-16 Fernando Perez <fperez@colorado.edu>
2242 2003-05-16 Fernando Perez <fperez@colorado.edu>
2238
2243
2239 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2244 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2240 protect ipython from user code which may call directly
2245 protect ipython from user code which may call directly
2241 sys.excepthook (this looks like an ipython crash to the user, even
2246 sys.excepthook (this looks like an ipython crash to the user, even
2242 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2247 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2243 This is especially important to help users of WxWindows, but may
2248 This is especially important to help users of WxWindows, but may
2244 also be useful in other cases.
2249 also be useful in other cases.
2245
2250
2246 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2251 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2247 an optional tb_offset to be specified, and to preserve exception
2252 an optional tb_offset to be specified, and to preserve exception
2248 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2253 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2249
2254
2250 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2255 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2251
2256
2252 2003-05-15 Fernando Perez <fperez@colorado.edu>
2257 2003-05-15 Fernando Perez <fperez@colorado.edu>
2253
2258
2254 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2259 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2255 installing for a new user under Windows.
2260 installing for a new user under Windows.
2256
2261
2257 2003-05-12 Fernando Perez <fperez@colorado.edu>
2262 2003-05-12 Fernando Perez <fperez@colorado.edu>
2258
2263
2259 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2264 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2260 handler for Emacs comint-based lines. Currently it doesn't do
2265 handler for Emacs comint-based lines. Currently it doesn't do
2261 much (but importantly, it doesn't update the history cache). In
2266 much (but importantly, it doesn't update the history cache). In
2262 the future it may be expanded if Alex needs more functionality
2267 the future it may be expanded if Alex needs more functionality
2263 there.
2268 there.
2264
2269
2265 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2270 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2266 info to crash reports.
2271 info to crash reports.
2267
2272
2268 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2273 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2269 just like Python's -c. Also fixed crash with invalid -color
2274 just like Python's -c. Also fixed crash with invalid -color
2270 option value at startup. Thanks to Will French
2275 option value at startup. Thanks to Will French
2271 <wfrench-AT-bestweb.net> for the bug report.
2276 <wfrench-AT-bestweb.net> for the bug report.
2272
2277
2273 2003-05-09 Fernando Perez <fperez@colorado.edu>
2278 2003-05-09 Fernando Perez <fperez@colorado.edu>
2274
2279
2275 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2280 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2276 to EvalDict (it's a mapping, after all) and simplified its code
2281 to EvalDict (it's a mapping, after all) and simplified its code
2277 quite a bit, after a nice discussion on c.l.py where Gustavo
2282 quite a bit, after a nice discussion on c.l.py where Gustavo
2278 Córdova <gcordova-AT-sismex.com> suggested the new version.
2283 Córdova <gcordova-AT-sismex.com> suggested the new version.
2279
2284
2280 2003-04-30 Fernando Perez <fperez@colorado.edu>
2285 2003-04-30 Fernando Perez <fperez@colorado.edu>
2281
2286
2282 * IPython/genutils.py (timings_out): modified it to reduce its
2287 * IPython/genutils.py (timings_out): modified it to reduce its
2283 overhead in the common reps==1 case.
2288 overhead in the common reps==1 case.
2284
2289
2285 2003-04-29 Fernando Perez <fperez@colorado.edu>
2290 2003-04-29 Fernando Perez <fperez@colorado.edu>
2286
2291
2287 * IPython/genutils.py (timings_out): Modified to use the resource
2292 * IPython/genutils.py (timings_out): Modified to use the resource
2288 module, which avoids the wraparound problems of time.clock().
2293 module, which avoids the wraparound problems of time.clock().
2289
2294
2290 2003-04-17 *** Released version 0.2.15pre4
2295 2003-04-17 *** Released version 0.2.15pre4
2291
2296
2292 2003-04-17 Fernando Perez <fperez@colorado.edu>
2297 2003-04-17 Fernando Perez <fperez@colorado.edu>
2293
2298
2294 * setup.py (scriptfiles): Split windows-specific stuff over to a
2299 * setup.py (scriptfiles): Split windows-specific stuff over to a
2295 separate file, in an attempt to have a Windows GUI installer.
2300 separate file, in an attempt to have a Windows GUI installer.
2296 That didn't work, but part of the groundwork is done.
2301 That didn't work, but part of the groundwork is done.
2297
2302
2298 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2303 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2299 indent/unindent with 4 spaces. Particularly useful in combination
2304 indent/unindent with 4 spaces. Particularly useful in combination
2300 with the new auto-indent option.
2305 with the new auto-indent option.
2301
2306
2302 2003-04-16 Fernando Perez <fperez@colorado.edu>
2307 2003-04-16 Fernando Perez <fperez@colorado.edu>
2303
2308
2304 * IPython/Magic.py: various replacements of self.rc for
2309 * IPython/Magic.py: various replacements of self.rc for
2305 self.shell.rc. A lot more remains to be done to fully disentangle
2310 self.shell.rc. A lot more remains to be done to fully disentangle
2306 this class from the main Shell class.
2311 this class from the main Shell class.
2307
2312
2308 * IPython/GnuplotRuntime.py: added checks for mouse support so
2313 * IPython/GnuplotRuntime.py: added checks for mouse support so
2309 that we don't try to enable it if the current gnuplot doesn't
2314 that we don't try to enable it if the current gnuplot doesn't
2310 really support it. Also added checks so that we don't try to
2315 really support it. Also added checks so that we don't try to
2311 enable persist under Windows (where Gnuplot doesn't recognize the
2316 enable persist under Windows (where Gnuplot doesn't recognize the
2312 option).
2317 option).
2313
2318
2314 * IPython/iplib.py (InteractiveShell.interact): Added optional
2319 * IPython/iplib.py (InteractiveShell.interact): Added optional
2315 auto-indenting code, after a patch by King C. Shu
2320 auto-indenting code, after a patch by King C. Shu
2316 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2321 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2317 get along well with pasting indented code. If I ever figure out
2322 get along well with pasting indented code. If I ever figure out
2318 how to make that part go well, it will become on by default.
2323 how to make that part go well, it will become on by default.
2319
2324
2320 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2325 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2321 crash ipython if there was an unmatched '%' in the user's prompt
2326 crash ipython if there was an unmatched '%' in the user's prompt
2322 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2327 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2323
2328
2324 * IPython/iplib.py (InteractiveShell.interact): removed the
2329 * IPython/iplib.py (InteractiveShell.interact): removed the
2325 ability to ask the user whether he wants to crash or not at the
2330 ability to ask the user whether he wants to crash or not at the
2326 'last line' exception handler. Calling functions at that point
2331 'last line' exception handler. Calling functions at that point
2327 changes the stack, and the error reports would have incorrect
2332 changes the stack, and the error reports would have incorrect
2328 tracebacks.
2333 tracebacks.
2329
2334
2330 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2335 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2331 pass through a peger a pretty-printed form of any object. After a
2336 pass through a peger a pretty-printed form of any object. After a
2332 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2337 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2333
2338
2334 2003-04-14 Fernando Perez <fperez@colorado.edu>
2339 2003-04-14 Fernando Perez <fperez@colorado.edu>
2335
2340
2336 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2341 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2337 all files in ~ would be modified at first install (instead of
2342 all files in ~ would be modified at first install (instead of
2338 ~/.ipython). This could be potentially disastrous, as the
2343 ~/.ipython). This could be potentially disastrous, as the
2339 modification (make line-endings native) could damage binary files.
2344 modification (make line-endings native) could damage binary files.
2340
2345
2341 2003-04-10 Fernando Perez <fperez@colorado.edu>
2346 2003-04-10 Fernando Perez <fperez@colorado.edu>
2342
2347
2343 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2348 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2344 handle only lines which are invalid python. This now means that
2349 handle only lines which are invalid python. This now means that
2345 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2350 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2346 for the bug report.
2351 for the bug report.
2347
2352
2348 2003-04-01 Fernando Perez <fperez@colorado.edu>
2353 2003-04-01 Fernando Perez <fperez@colorado.edu>
2349
2354
2350 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2355 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2351 where failing to set sys.last_traceback would crash pdb.pm().
2356 where failing to set sys.last_traceback would crash pdb.pm().
2352 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2357 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2353 report.
2358 report.
2354
2359
2355 2003-03-25 Fernando Perez <fperez@colorado.edu>
2360 2003-03-25 Fernando Perez <fperez@colorado.edu>
2356
2361
2357 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2362 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2358 before printing it (it had a lot of spurious blank lines at the
2363 before printing it (it had a lot of spurious blank lines at the
2359 end).
2364 end).
2360
2365
2361 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2366 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2362 output would be sent 21 times! Obviously people don't use this
2367 output would be sent 21 times! Obviously people don't use this
2363 too often, or I would have heard about it.
2368 too often, or I would have heard about it.
2364
2369
2365 2003-03-24 Fernando Perez <fperez@colorado.edu>
2370 2003-03-24 Fernando Perez <fperez@colorado.edu>
2366
2371
2367 * setup.py (scriptfiles): renamed the data_files parameter from
2372 * setup.py (scriptfiles): renamed the data_files parameter from
2368 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2373 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2369 for the patch.
2374 for the patch.
2370
2375
2371 2003-03-20 Fernando Perez <fperez@colorado.edu>
2376 2003-03-20 Fernando Perez <fperez@colorado.edu>
2372
2377
2373 * IPython/genutils.py (error): added error() and fatal()
2378 * IPython/genutils.py (error): added error() and fatal()
2374 functions.
2379 functions.
2375
2380
2376 2003-03-18 *** Released version 0.2.15pre3
2381 2003-03-18 *** Released version 0.2.15pre3
2377
2382
2378 2003-03-18 Fernando Perez <fperez@colorado.edu>
2383 2003-03-18 Fernando Perez <fperez@colorado.edu>
2379
2384
2380 * setupext/install_data_ext.py
2385 * setupext/install_data_ext.py
2381 (install_data_ext.initialize_options): Class contributed by Jack
2386 (install_data_ext.initialize_options): Class contributed by Jack
2382 Moffit for fixing the old distutils hack. He is sending this to
2387 Moffit for fixing the old distutils hack. He is sending this to
2383 the distutils folks so in the future we may not need it as a
2388 the distutils folks so in the future we may not need it as a
2384 private fix.
2389 private fix.
2385
2390
2386 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2391 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2387 changes for Debian packaging. See his patch for full details.
2392 changes for Debian packaging. See his patch for full details.
2388 The old distutils hack of making the ipythonrc* files carry a
2393 The old distutils hack of making the ipythonrc* files carry a
2389 bogus .py extension is gone, at last. Examples were moved to a
2394 bogus .py extension is gone, at last. Examples were moved to a
2390 separate subdir under doc/, and the separate executable scripts
2395 separate subdir under doc/, and the separate executable scripts
2391 now live in their own directory. Overall a great cleanup. The
2396 now live in their own directory. Overall a great cleanup. The
2392 manual was updated to use the new files, and setup.py has been
2397 manual was updated to use the new files, and setup.py has been
2393 fixed for this setup.
2398 fixed for this setup.
2394
2399
2395 * IPython/PyColorize.py (Parser.usage): made non-executable and
2400 * IPython/PyColorize.py (Parser.usage): made non-executable and
2396 created a pycolor wrapper around it to be included as a script.
2401 created a pycolor wrapper around it to be included as a script.
2397
2402
2398 2003-03-12 *** Released version 0.2.15pre2
2403 2003-03-12 *** Released version 0.2.15pre2
2399
2404
2400 2003-03-12 Fernando Perez <fperez@colorado.edu>
2405 2003-03-12 Fernando Perez <fperez@colorado.edu>
2401
2406
2402 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2407 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2403 long-standing problem with garbage characters in some terminals.
2408 long-standing problem with garbage characters in some terminals.
2404 The issue was really that the \001 and \002 escapes must _only_ be
2409 The issue was really that the \001 and \002 escapes must _only_ be
2405 passed to input prompts (which call readline), but _never_ to
2410 passed to input prompts (which call readline), but _never_ to
2406 normal text to be printed on screen. I changed ColorANSI to have
2411 normal text to be printed on screen. I changed ColorANSI to have
2407 two classes: TermColors and InputTermColors, each with the
2412 two classes: TermColors and InputTermColors, each with the
2408 appropriate escapes for input prompts or normal text. The code in
2413 appropriate escapes for input prompts or normal text. The code in
2409 Prompts.py got slightly more complicated, but this very old and
2414 Prompts.py got slightly more complicated, but this very old and
2410 annoying bug is finally fixed.
2415 annoying bug is finally fixed.
2411
2416
2412 All the credit for nailing down the real origin of this problem
2417 All the credit for nailing down the real origin of this problem
2413 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2418 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2414 *Many* thanks to him for spending quite a bit of effort on this.
2419 *Many* thanks to him for spending quite a bit of effort on this.
2415
2420
2416 2003-03-05 *** Released version 0.2.15pre1
2421 2003-03-05 *** Released version 0.2.15pre1
2417
2422
2418 2003-03-03 Fernando Perez <fperez@colorado.edu>
2423 2003-03-03 Fernando Perez <fperez@colorado.edu>
2419
2424
2420 * IPython/FakeModule.py: Moved the former _FakeModule to a
2425 * IPython/FakeModule.py: Moved the former _FakeModule to a
2421 separate file, because it's also needed by Magic (to fix a similar
2426 separate file, because it's also needed by Magic (to fix a similar
2422 pickle-related issue in @run).
2427 pickle-related issue in @run).
2423
2428
2424 2003-03-02 Fernando Perez <fperez@colorado.edu>
2429 2003-03-02 Fernando Perez <fperez@colorado.edu>
2425
2430
2426 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2431 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2427 the autocall option at runtime.
2432 the autocall option at runtime.
2428 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2433 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2429 across Magic.py to start separating Magic from InteractiveShell.
2434 across Magic.py to start separating Magic from InteractiveShell.
2430 (Magic._ofind): Fixed to return proper namespace for dotted
2435 (Magic._ofind): Fixed to return proper namespace for dotted
2431 names. Before, a dotted name would always return 'not currently
2436 names. Before, a dotted name would always return 'not currently
2432 defined', because it would find the 'parent'. s.x would be found,
2437 defined', because it would find the 'parent'. s.x would be found,
2433 but since 'x' isn't defined by itself, it would get confused.
2438 but since 'x' isn't defined by itself, it would get confused.
2434 (Magic.magic_run): Fixed pickling problems reported by Ralf
2439 (Magic.magic_run): Fixed pickling problems reported by Ralf
2435 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2440 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2436 that I'd used when Mike Heeter reported similar issues at the
2441 that I'd used when Mike Heeter reported similar issues at the
2437 top-level, but now for @run. It boils down to injecting the
2442 top-level, but now for @run. It boils down to injecting the
2438 namespace where code is being executed with something that looks
2443 namespace where code is being executed with something that looks
2439 enough like a module to fool pickle.dump(). Since a pickle stores
2444 enough like a module to fool pickle.dump(). Since a pickle stores
2440 a named reference to the importing module, we need this for
2445 a named reference to the importing module, we need this for
2441 pickles to save something sensible.
2446 pickles to save something sensible.
2442
2447
2443 * IPython/ipmaker.py (make_IPython): added an autocall option.
2448 * IPython/ipmaker.py (make_IPython): added an autocall option.
2444
2449
2445 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2450 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2446 the auto-eval code. Now autocalling is an option, and the code is
2451 the auto-eval code. Now autocalling is an option, and the code is
2447 also vastly safer. There is no more eval() involved at all.
2452 also vastly safer. There is no more eval() involved at all.
2448
2453
2449 2003-03-01 Fernando Perez <fperez@colorado.edu>
2454 2003-03-01 Fernando Perez <fperez@colorado.edu>
2450
2455
2451 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2456 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2452 dict with named keys instead of a tuple.
2457 dict with named keys instead of a tuple.
2453
2458
2454 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2459 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2455
2460
2456 * setup.py (make_shortcut): Fixed message about directories
2461 * setup.py (make_shortcut): Fixed message about directories
2457 created during Windows installation (the directories were ok, just
2462 created during Windows installation (the directories were ok, just
2458 the printed message was misleading). Thanks to Chris Liechti
2463 the printed message was misleading). Thanks to Chris Liechti
2459 <cliechti-AT-gmx.net> for the heads up.
2464 <cliechti-AT-gmx.net> for the heads up.
2460
2465
2461 2003-02-21 Fernando Perez <fperez@colorado.edu>
2466 2003-02-21 Fernando Perez <fperez@colorado.edu>
2462
2467
2463 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2468 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2464 of ValueError exception when checking for auto-execution. This
2469 of ValueError exception when checking for auto-execution. This
2465 one is raised by things like Numeric arrays arr.flat when the
2470 one is raised by things like Numeric arrays arr.flat when the
2466 array is non-contiguous.
2471 array is non-contiguous.
2467
2472
2468 2003-01-31 Fernando Perez <fperez@colorado.edu>
2473 2003-01-31 Fernando Perez <fperez@colorado.edu>
2469
2474
2470 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2475 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2471 not return any value at all (even though the command would get
2476 not return any value at all (even though the command would get
2472 executed).
2477 executed).
2473 (xsys): Flush stdout right after printing the command to ensure
2478 (xsys): Flush stdout right after printing the command to ensure
2474 proper ordering of commands and command output in the total
2479 proper ordering of commands and command output in the total
2475 output.
2480 output.
2476 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2481 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2477 system/getoutput as defaults. The old ones are kept for
2482 system/getoutput as defaults. The old ones are kept for
2478 compatibility reasons, so no code which uses this library needs
2483 compatibility reasons, so no code which uses this library needs
2479 changing.
2484 changing.
2480
2485
2481 2003-01-27 *** Released version 0.2.14
2486 2003-01-27 *** Released version 0.2.14
2482
2487
2483 2003-01-25 Fernando Perez <fperez@colorado.edu>
2488 2003-01-25 Fernando Perez <fperez@colorado.edu>
2484
2489
2485 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2490 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2486 functions defined in previous edit sessions could not be re-edited
2491 functions defined in previous edit sessions could not be re-edited
2487 (because the temp files were immediately removed). Now temp files
2492 (because the temp files were immediately removed). Now temp files
2488 are removed only at IPython's exit.
2493 are removed only at IPython's exit.
2489 (Magic.magic_run): Improved @run to perform shell-like expansions
2494 (Magic.magic_run): Improved @run to perform shell-like expansions
2490 on its arguments (~users and $VARS). With this, @run becomes more
2495 on its arguments (~users and $VARS). With this, @run becomes more
2491 like a normal command-line.
2496 like a normal command-line.
2492
2497
2493 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2498 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2494 bugs related to embedding and cleaned up that code. A fairly
2499 bugs related to embedding and cleaned up that code. A fairly
2495 important one was the impossibility to access the global namespace
2500 important one was the impossibility to access the global namespace
2496 through the embedded IPython (only local variables were visible).
2501 through the embedded IPython (only local variables were visible).
2497
2502
2498 2003-01-14 Fernando Perez <fperez@colorado.edu>
2503 2003-01-14 Fernando Perez <fperez@colorado.edu>
2499
2504
2500 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2505 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2501 auto-calling to be a bit more conservative. Now it doesn't get
2506 auto-calling to be a bit more conservative. Now it doesn't get
2502 triggered if any of '!=()<>' are in the rest of the input line, to
2507 triggered if any of '!=()<>' are in the rest of the input line, to
2503 allow comparing callables. Thanks to Alex for the heads up.
2508 allow comparing callables. Thanks to Alex for the heads up.
2504
2509
2505 2003-01-07 Fernando Perez <fperez@colorado.edu>
2510 2003-01-07 Fernando Perez <fperez@colorado.edu>
2506
2511
2507 * IPython/genutils.py (page): fixed estimation of the number of
2512 * IPython/genutils.py (page): fixed estimation of the number of
2508 lines in a string to be paged to simply count newlines. This
2513 lines in a string to be paged to simply count newlines. This
2509 prevents over-guessing due to embedded escape sequences. A better
2514 prevents over-guessing due to embedded escape sequences. A better
2510 long-term solution would involve stripping out the control chars
2515 long-term solution would involve stripping out the control chars
2511 for the count, but it's potentially so expensive I just don't
2516 for the count, but it's potentially so expensive I just don't
2512 think it's worth doing.
2517 think it's worth doing.
2513
2518
2514 2002-12-19 *** Released version 0.2.14pre50
2519 2002-12-19 *** Released version 0.2.14pre50
2515
2520
2516 2002-12-19 Fernando Perez <fperez@colorado.edu>
2521 2002-12-19 Fernando Perez <fperez@colorado.edu>
2517
2522
2518 * tools/release (version): Changed release scripts to inform
2523 * tools/release (version): Changed release scripts to inform
2519 Andrea and build a NEWS file with a list of recent changes.
2524 Andrea and build a NEWS file with a list of recent changes.
2520
2525
2521 * IPython/ColorANSI.py (__all__): changed terminal detection
2526 * IPython/ColorANSI.py (__all__): changed terminal detection
2522 code. Seems to work better for xterms without breaking
2527 code. Seems to work better for xterms without breaking
2523 konsole. Will need more testing to determine if WinXP and Mac OSX
2528 konsole. Will need more testing to determine if WinXP and Mac OSX
2524 also work ok.
2529 also work ok.
2525
2530
2526 2002-12-18 *** Released version 0.2.14pre49
2531 2002-12-18 *** Released version 0.2.14pre49
2527
2532
2528 2002-12-18 Fernando Perez <fperez@colorado.edu>
2533 2002-12-18 Fernando Perez <fperez@colorado.edu>
2529
2534
2530 * Docs: added new info about Mac OSX, from Andrea.
2535 * Docs: added new info about Mac OSX, from Andrea.
2531
2536
2532 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2537 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2533 allow direct plotting of python strings whose format is the same
2538 allow direct plotting of python strings whose format is the same
2534 of gnuplot data files.
2539 of gnuplot data files.
2535
2540
2536 2002-12-16 Fernando Perez <fperez@colorado.edu>
2541 2002-12-16 Fernando Perez <fperez@colorado.edu>
2537
2542
2538 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2543 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2539 value of exit question to be acknowledged.
2544 value of exit question to be acknowledged.
2540
2545
2541 2002-12-03 Fernando Perez <fperez@colorado.edu>
2546 2002-12-03 Fernando Perez <fperez@colorado.edu>
2542
2547
2543 * IPython/ipmaker.py: removed generators, which had been added
2548 * IPython/ipmaker.py: removed generators, which had been added
2544 by mistake in an earlier debugging run. This was causing trouble
2549 by mistake in an earlier debugging run. This was causing trouble
2545 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2550 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2546 for pointing this out.
2551 for pointing this out.
2547
2552
2548 2002-11-17 Fernando Perez <fperez@colorado.edu>
2553 2002-11-17 Fernando Perez <fperez@colorado.edu>
2549
2554
2550 * Manual: updated the Gnuplot section.
2555 * Manual: updated the Gnuplot section.
2551
2556
2552 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2557 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2553 a much better split of what goes in Runtime and what goes in
2558 a much better split of what goes in Runtime and what goes in
2554 Interactive.
2559 Interactive.
2555
2560
2556 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2561 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2557 being imported from iplib.
2562 being imported from iplib.
2558
2563
2559 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2564 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2560 for command-passing. Now the global Gnuplot instance is called
2565 for command-passing. Now the global Gnuplot instance is called
2561 'gp' instead of 'g', which was really a far too fragile and
2566 'gp' instead of 'g', which was really a far too fragile and
2562 common name.
2567 common name.
2563
2568
2564 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2569 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2565 bounding boxes generated by Gnuplot for square plots.
2570 bounding boxes generated by Gnuplot for square plots.
2566
2571
2567 * IPython/genutils.py (popkey): new function added. I should
2572 * IPython/genutils.py (popkey): new function added. I should
2568 suggest this on c.l.py as a dict method, it seems useful.
2573 suggest this on c.l.py as a dict method, it seems useful.
2569
2574
2570 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2575 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2571 to transparently handle PostScript generation. MUCH better than
2576 to transparently handle PostScript generation. MUCH better than
2572 the previous plot_eps/replot_eps (which I removed now). The code
2577 the previous plot_eps/replot_eps (which I removed now). The code
2573 is also fairly clean and well documented now (including
2578 is also fairly clean and well documented now (including
2574 docstrings).
2579 docstrings).
2575
2580
2576 2002-11-13 Fernando Perez <fperez@colorado.edu>
2581 2002-11-13 Fernando Perez <fperez@colorado.edu>
2577
2582
2578 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2583 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2579 (inconsistent with options).
2584 (inconsistent with options).
2580
2585
2581 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2586 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2582 manually disabled, I don't know why. Fixed it.
2587 manually disabled, I don't know why. Fixed it.
2583 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2588 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2584 eps output.
2589 eps output.
2585
2590
2586 2002-11-12 Fernando Perez <fperez@colorado.edu>
2591 2002-11-12 Fernando Perez <fperez@colorado.edu>
2587
2592
2588 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2593 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2589 don't propagate up to caller. Fixes crash reported by François
2594 don't propagate up to caller. Fixes crash reported by François
2590 Pinard.
2595 Pinard.
2591
2596
2592 2002-11-09 Fernando Perez <fperez@colorado.edu>
2597 2002-11-09 Fernando Perez <fperez@colorado.edu>
2593
2598
2594 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2599 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2595 history file for new users.
2600 history file for new users.
2596 (make_IPython): fixed bug where initial install would leave the
2601 (make_IPython): fixed bug where initial install would leave the
2597 user running in the .ipython dir.
2602 user running in the .ipython dir.
2598 (make_IPython): fixed bug where config dir .ipython would be
2603 (make_IPython): fixed bug where config dir .ipython would be
2599 created regardless of the given -ipythondir option. Thanks to Cory
2604 created regardless of the given -ipythondir option. Thanks to Cory
2600 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2605 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2601
2606
2602 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2607 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2603 type confirmations. Will need to use it in all of IPython's code
2608 type confirmations. Will need to use it in all of IPython's code
2604 consistently.
2609 consistently.
2605
2610
2606 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2611 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2607 context to print 31 lines instead of the default 5. This will make
2612 context to print 31 lines instead of the default 5. This will make
2608 the crash reports extremely detailed in case the problem is in
2613 the crash reports extremely detailed in case the problem is in
2609 libraries I don't have access to.
2614 libraries I don't have access to.
2610
2615
2611 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2616 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2612 line of defense' code to still crash, but giving users fair
2617 line of defense' code to still crash, but giving users fair
2613 warning. I don't want internal errors to go unreported: if there's
2618 warning. I don't want internal errors to go unreported: if there's
2614 an internal problem, IPython should crash and generate a full
2619 an internal problem, IPython should crash and generate a full
2615 report.
2620 report.
2616
2621
2617 2002-11-08 Fernando Perez <fperez@colorado.edu>
2622 2002-11-08 Fernando Perez <fperez@colorado.edu>
2618
2623
2619 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2624 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2620 otherwise uncaught exceptions which can appear if people set
2625 otherwise uncaught exceptions which can appear if people set
2621 sys.stdout to something badly broken. Thanks to a crash report
2626 sys.stdout to something badly broken. Thanks to a crash report
2622 from henni-AT-mail.brainbot.com.
2627 from henni-AT-mail.brainbot.com.
2623
2628
2624 2002-11-04 Fernando Perez <fperez@colorado.edu>
2629 2002-11-04 Fernando Perez <fperez@colorado.edu>
2625
2630
2626 * IPython/iplib.py (InteractiveShell.interact): added
2631 * IPython/iplib.py (InteractiveShell.interact): added
2627 __IPYTHON__active to the builtins. It's a flag which goes on when
2632 __IPYTHON__active to the builtins. It's a flag which goes on when
2628 the interaction starts and goes off again when it stops. This
2633 the interaction starts and goes off again when it stops. This
2629 allows embedding code to detect being inside IPython. Before this
2634 allows embedding code to detect being inside IPython. Before this
2630 was done via __IPYTHON__, but that only shows that an IPython
2635 was done via __IPYTHON__, but that only shows that an IPython
2631 instance has been created.
2636 instance has been created.
2632
2637
2633 * IPython/Magic.py (Magic.magic_env): I realized that in a
2638 * IPython/Magic.py (Magic.magic_env): I realized that in a
2634 UserDict, instance.data holds the data as a normal dict. So I
2639 UserDict, instance.data holds the data as a normal dict. So I
2635 modified @env to return os.environ.data instead of rebuilding a
2640 modified @env to return os.environ.data instead of rebuilding a
2636 dict by hand.
2641 dict by hand.
2637
2642
2638 2002-11-02 Fernando Perez <fperez@colorado.edu>
2643 2002-11-02 Fernando Perez <fperez@colorado.edu>
2639
2644
2640 * IPython/genutils.py (warn): changed so that level 1 prints no
2645 * IPython/genutils.py (warn): changed so that level 1 prints no
2641 header. Level 2 is now the default (with 'WARNING' header, as
2646 header. Level 2 is now the default (with 'WARNING' header, as
2642 before). I think I tracked all places where changes were needed in
2647 before). I think I tracked all places where changes were needed in
2643 IPython, but outside code using the old level numbering may have
2648 IPython, but outside code using the old level numbering may have
2644 broken.
2649 broken.
2645
2650
2646 * IPython/iplib.py (InteractiveShell.runcode): added this to
2651 * IPython/iplib.py (InteractiveShell.runcode): added this to
2647 handle the tracebacks in SystemExit traps correctly. The previous
2652 handle the tracebacks in SystemExit traps correctly. The previous
2648 code (through interact) was printing more of the stack than
2653 code (through interact) was printing more of the stack than
2649 necessary, showing IPython internal code to the user.
2654 necessary, showing IPython internal code to the user.
2650
2655
2651 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2656 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2652 default. Now that the default at the confirmation prompt is yes,
2657 default. Now that the default at the confirmation prompt is yes,
2653 it's not so intrusive. François' argument that ipython sessions
2658 it's not so intrusive. François' argument that ipython sessions
2654 tend to be complex enough not to lose them from an accidental C-d,
2659 tend to be complex enough not to lose them from an accidental C-d,
2655 is a valid one.
2660 is a valid one.
2656
2661
2657 * IPython/iplib.py (InteractiveShell.interact): added a
2662 * IPython/iplib.py (InteractiveShell.interact): added a
2658 showtraceback() call to the SystemExit trap, and modified the exit
2663 showtraceback() call to the SystemExit trap, and modified the exit
2659 confirmation to have yes as the default.
2664 confirmation to have yes as the default.
2660
2665
2661 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2666 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2662 this file. It's been gone from the code for a long time, this was
2667 this file. It's been gone from the code for a long time, this was
2663 simply leftover junk.
2668 simply leftover junk.
2664
2669
2665 2002-11-01 Fernando Perez <fperez@colorado.edu>
2670 2002-11-01 Fernando Perez <fperez@colorado.edu>
2666
2671
2667 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2672 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2668 added. If set, IPython now traps EOF and asks for
2673 added. If set, IPython now traps EOF and asks for
2669 confirmation. After a request by François Pinard.
2674 confirmation. After a request by François Pinard.
2670
2675
2671 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2676 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2672 of @abort, and with a new (better) mechanism for handling the
2677 of @abort, and with a new (better) mechanism for handling the
2673 exceptions.
2678 exceptions.
2674
2679
2675 2002-10-27 Fernando Perez <fperez@colorado.edu>
2680 2002-10-27 Fernando Perez <fperez@colorado.edu>
2676
2681
2677 * IPython/usage.py (__doc__): updated the --help information and
2682 * IPython/usage.py (__doc__): updated the --help information and
2678 the ipythonrc file to indicate that -log generates
2683 the ipythonrc file to indicate that -log generates
2679 ./ipython.log. Also fixed the corresponding info in @logstart.
2684 ./ipython.log. Also fixed the corresponding info in @logstart.
2680 This and several other fixes in the manuals thanks to reports by
2685 This and several other fixes in the manuals thanks to reports by
2681 François Pinard <pinard-AT-iro.umontreal.ca>.
2686 François Pinard <pinard-AT-iro.umontreal.ca>.
2682
2687
2683 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2688 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2684 refer to @logstart (instead of @log, which doesn't exist).
2689 refer to @logstart (instead of @log, which doesn't exist).
2685
2690
2686 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2691 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2687 AttributeError crash. Thanks to Christopher Armstrong
2692 AttributeError crash. Thanks to Christopher Armstrong
2688 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2693 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2689 introduced recently (in 0.2.14pre37) with the fix to the eval
2694 introduced recently (in 0.2.14pre37) with the fix to the eval
2690 problem mentioned below.
2695 problem mentioned below.
2691
2696
2692 2002-10-17 Fernando Perez <fperez@colorado.edu>
2697 2002-10-17 Fernando Perez <fperez@colorado.edu>
2693
2698
2694 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2699 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2695 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2700 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2696
2701
2697 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2702 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2698 this function to fix a problem reported by Alex Schmolck. He saw
2703 this function to fix a problem reported by Alex Schmolck. He saw
2699 it with list comprehensions and generators, which were getting
2704 it with list comprehensions and generators, which were getting
2700 called twice. The real problem was an 'eval' call in testing for
2705 called twice. The real problem was an 'eval' call in testing for
2701 automagic which was evaluating the input line silently.
2706 automagic which was evaluating the input line silently.
2702
2707
2703 This is a potentially very nasty bug, if the input has side
2708 This is a potentially very nasty bug, if the input has side
2704 effects which must not be repeated. The code is much cleaner now,
2709 effects which must not be repeated. The code is much cleaner now,
2705 without any blanket 'except' left and with a regexp test for
2710 without any blanket 'except' left and with a regexp test for
2706 actual function names.
2711 actual function names.
2707
2712
2708 But an eval remains, which I'm not fully comfortable with. I just
2713 But an eval remains, which I'm not fully comfortable with. I just
2709 don't know how to find out if an expression could be a callable in
2714 don't know how to find out if an expression could be a callable in
2710 the user's namespace without doing an eval on the string. However
2715 the user's namespace without doing an eval on the string. However
2711 that string is now much more strictly checked so that no code
2716 that string is now much more strictly checked so that no code
2712 slips by, so the eval should only happen for things that can
2717 slips by, so the eval should only happen for things that can
2713 really be only function/method names.
2718 really be only function/method names.
2714
2719
2715 2002-10-15 Fernando Perez <fperez@colorado.edu>
2720 2002-10-15 Fernando Perez <fperez@colorado.edu>
2716
2721
2717 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2722 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2718 OSX information to main manual, removed README_Mac_OSX file from
2723 OSX information to main manual, removed README_Mac_OSX file from
2719 distribution. Also updated credits for recent additions.
2724 distribution. Also updated credits for recent additions.
2720
2725
2721 2002-10-10 Fernando Perez <fperez@colorado.edu>
2726 2002-10-10 Fernando Perez <fperez@colorado.edu>
2722
2727
2723 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2728 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2724 terminal-related issues. Many thanks to Andrea Riciputi
2729 terminal-related issues. Many thanks to Andrea Riciputi
2725 <andrea.riciputi-AT-libero.it> for writing it.
2730 <andrea.riciputi-AT-libero.it> for writing it.
2726
2731
2727 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2732 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2728 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2733 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2729
2734
2730 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2735 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2731 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2736 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2732 <syver-en-AT-online.no> who both submitted patches for this problem.
2737 <syver-en-AT-online.no> who both submitted patches for this problem.
2733
2738
2734 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2739 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2735 global embedding to make sure that things don't overwrite user
2740 global embedding to make sure that things don't overwrite user
2736 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2741 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2737
2742
2738 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2743 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2739 compatibility. Thanks to Hayden Callow
2744 compatibility. Thanks to Hayden Callow
2740 <h.callow-AT-elec.canterbury.ac.nz>
2745 <h.callow-AT-elec.canterbury.ac.nz>
2741
2746
2742 2002-10-04 Fernando Perez <fperez@colorado.edu>
2747 2002-10-04 Fernando Perez <fperez@colorado.edu>
2743
2748
2744 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2749 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2745 Gnuplot.File objects.
2750 Gnuplot.File objects.
2746
2751
2747 2002-07-23 Fernando Perez <fperez@colorado.edu>
2752 2002-07-23 Fernando Perez <fperez@colorado.edu>
2748
2753
2749 * IPython/genutils.py (timing): Added timings() and timing() for
2754 * IPython/genutils.py (timing): Added timings() and timing() for
2750 quick access to the most commonly needed data, the execution
2755 quick access to the most commonly needed data, the execution
2751 times. Old timing() renamed to timings_out().
2756 times. Old timing() renamed to timings_out().
2752
2757
2753 2002-07-18 Fernando Perez <fperez@colorado.edu>
2758 2002-07-18 Fernando Perez <fperez@colorado.edu>
2754
2759
2755 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2760 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2756 bug with nested instances disrupting the parent's tab completion.
2761 bug with nested instances disrupting the parent's tab completion.
2757
2762
2758 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2763 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2759 all_completions code to begin the emacs integration.
2764 all_completions code to begin the emacs integration.
2760
2765
2761 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2766 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2762 argument to allow titling individual arrays when plotting.
2767 argument to allow titling individual arrays when plotting.
2763
2768
2764 2002-07-15 Fernando Perez <fperez@colorado.edu>
2769 2002-07-15 Fernando Perez <fperez@colorado.edu>
2765
2770
2766 * setup.py (make_shortcut): changed to retrieve the value of
2771 * setup.py (make_shortcut): changed to retrieve the value of
2767 'Program Files' directory from the registry (this value changes in
2772 'Program Files' directory from the registry (this value changes in
2768 non-english versions of Windows). Thanks to Thomas Fanslau
2773 non-english versions of Windows). Thanks to Thomas Fanslau
2769 <tfanslau-AT-gmx.de> for the report.
2774 <tfanslau-AT-gmx.de> for the report.
2770
2775
2771 2002-07-10 Fernando Perez <fperez@colorado.edu>
2776 2002-07-10 Fernando Perez <fperez@colorado.edu>
2772
2777
2773 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2778 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2774 a bug in pdb, which crashes if a line with only whitespace is
2779 a bug in pdb, which crashes if a line with only whitespace is
2775 entered. Bug report submitted to sourceforge.
2780 entered. Bug report submitted to sourceforge.
2776
2781
2777 2002-07-09 Fernando Perez <fperez@colorado.edu>
2782 2002-07-09 Fernando Perez <fperez@colorado.edu>
2778
2783
2779 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2784 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2780 reporting exceptions (it's a bug in inspect.py, I just set a
2785 reporting exceptions (it's a bug in inspect.py, I just set a
2781 workaround).
2786 workaround).
2782
2787
2783 2002-07-08 Fernando Perez <fperez@colorado.edu>
2788 2002-07-08 Fernando Perez <fperez@colorado.edu>
2784
2789
2785 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2790 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2786 __IPYTHON__ in __builtins__ to show up in user_ns.
2791 __IPYTHON__ in __builtins__ to show up in user_ns.
2787
2792
2788 2002-07-03 Fernando Perez <fperez@colorado.edu>
2793 2002-07-03 Fernando Perez <fperez@colorado.edu>
2789
2794
2790 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2795 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2791 name from @gp_set_instance to @gp_set_default.
2796 name from @gp_set_instance to @gp_set_default.
2792
2797
2793 * IPython/ipmaker.py (make_IPython): default editor value set to
2798 * IPython/ipmaker.py (make_IPython): default editor value set to
2794 '0' (a string), to match the rc file. Otherwise will crash when
2799 '0' (a string), to match the rc file. Otherwise will crash when
2795 .strip() is called on it.
2800 .strip() is called on it.
2796
2801
2797
2802
2798 2002-06-28 Fernando Perez <fperez@colorado.edu>
2803 2002-06-28 Fernando Perez <fperez@colorado.edu>
2799
2804
2800 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2805 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2801 of files in current directory when a file is executed via
2806 of files in current directory when a file is executed via
2802 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2807 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2803
2808
2804 * setup.py (manfiles): fix for rpm builds, submitted by RA
2809 * setup.py (manfiles): fix for rpm builds, submitted by RA
2805 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2810 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2806
2811
2807 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2812 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2808 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2813 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2809 string!). A. Schmolck caught this one.
2814 string!). A. Schmolck caught this one.
2810
2815
2811 2002-06-27 Fernando Perez <fperez@colorado.edu>
2816 2002-06-27 Fernando Perez <fperez@colorado.edu>
2812
2817
2813 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2818 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2814 defined files at the cmd line. __name__ wasn't being set to
2819 defined files at the cmd line. __name__ wasn't being set to
2815 __main__.
2820 __main__.
2816
2821
2817 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2822 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2818 regular lists and tuples besides Numeric arrays.
2823 regular lists and tuples besides Numeric arrays.
2819
2824
2820 * IPython/Prompts.py (CachedOutput.__call__): Added output
2825 * IPython/Prompts.py (CachedOutput.__call__): Added output
2821 supression for input ending with ';'. Similar to Mathematica and
2826 supression for input ending with ';'. Similar to Mathematica and
2822 Matlab. The _* vars and Out[] list are still updated, just like
2827 Matlab. The _* vars and Out[] list are still updated, just like
2823 Mathematica behaves.
2828 Mathematica behaves.
2824
2829
2825 2002-06-25 Fernando Perez <fperez@colorado.edu>
2830 2002-06-25 Fernando Perez <fperez@colorado.edu>
2826
2831
2827 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2832 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2828 .ini extensions for profiels under Windows.
2833 .ini extensions for profiels under Windows.
2829
2834
2830 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2835 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2831 string form. Fix contributed by Alexander Schmolck
2836 string form. Fix contributed by Alexander Schmolck
2832 <a.schmolck-AT-gmx.net>
2837 <a.schmolck-AT-gmx.net>
2833
2838
2834 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2839 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2835 pre-configured Gnuplot instance.
2840 pre-configured Gnuplot instance.
2836
2841
2837 2002-06-21 Fernando Perez <fperez@colorado.edu>
2842 2002-06-21 Fernando Perez <fperez@colorado.edu>
2838
2843
2839 * IPython/numutils.py (exp_safe): new function, works around the
2844 * IPython/numutils.py (exp_safe): new function, works around the
2840 underflow problems in Numeric.
2845 underflow problems in Numeric.
2841 (log2): New fn. Safe log in base 2: returns exact integer answer
2846 (log2): New fn. Safe log in base 2: returns exact integer answer
2842 for exact integer powers of 2.
2847 for exact integer powers of 2.
2843
2848
2844 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2849 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2845 properly.
2850 properly.
2846
2851
2847 2002-06-20 Fernando Perez <fperez@colorado.edu>
2852 2002-06-20 Fernando Perez <fperez@colorado.edu>
2848
2853
2849 * IPython/genutils.py (timing): new function like
2854 * IPython/genutils.py (timing): new function like
2850 Mathematica's. Similar to time_test, but returns more info.
2855 Mathematica's. Similar to time_test, but returns more info.
2851
2856
2852 2002-06-18 Fernando Perez <fperez@colorado.edu>
2857 2002-06-18 Fernando Perez <fperez@colorado.edu>
2853
2858
2854 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2859 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2855 according to Mike Heeter's suggestions.
2860 according to Mike Heeter's suggestions.
2856
2861
2857 2002-06-16 Fernando Perez <fperez@colorado.edu>
2862 2002-06-16 Fernando Perez <fperez@colorado.edu>
2858
2863
2859 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2864 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2860 system. GnuplotMagic is gone as a user-directory option. New files
2865 system. GnuplotMagic is gone as a user-directory option. New files
2861 make it easier to use all the gnuplot stuff both from external
2866 make it easier to use all the gnuplot stuff both from external
2862 programs as well as from IPython. Had to rewrite part of
2867 programs as well as from IPython. Had to rewrite part of
2863 hardcopy() b/c of a strange bug: often the ps files simply don't
2868 hardcopy() b/c of a strange bug: often the ps files simply don't
2864 get created, and require a repeat of the command (often several
2869 get created, and require a repeat of the command (often several
2865 times).
2870 times).
2866
2871
2867 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2872 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2868 resolve output channel at call time, so that if sys.stderr has
2873 resolve output channel at call time, so that if sys.stderr has
2869 been redirected by user this gets honored.
2874 been redirected by user this gets honored.
2870
2875
2871 2002-06-13 Fernando Perez <fperez@colorado.edu>
2876 2002-06-13 Fernando Perez <fperez@colorado.edu>
2872
2877
2873 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2878 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2874 IPShell. Kept a copy with the old names to avoid breaking people's
2879 IPShell. Kept a copy with the old names to avoid breaking people's
2875 embedded code.
2880 embedded code.
2876
2881
2877 * IPython/ipython: simplified it to the bare minimum after
2882 * IPython/ipython: simplified it to the bare minimum after
2878 Holger's suggestions. Added info about how to use it in
2883 Holger's suggestions. Added info about how to use it in
2879 PYTHONSTARTUP.
2884 PYTHONSTARTUP.
2880
2885
2881 * IPython/Shell.py (IPythonShell): changed the options passing
2886 * IPython/Shell.py (IPythonShell): changed the options passing
2882 from a string with funky %s replacements to a straight list. Maybe
2887 from a string with funky %s replacements to a straight list. Maybe
2883 a bit more typing, but it follows sys.argv conventions, so there's
2888 a bit more typing, but it follows sys.argv conventions, so there's
2884 less special-casing to remember.
2889 less special-casing to remember.
2885
2890
2886 2002-06-12 Fernando Perez <fperez@colorado.edu>
2891 2002-06-12 Fernando Perez <fperez@colorado.edu>
2887
2892
2888 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2893 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2889 command. Thanks to a suggestion by Mike Heeter.
2894 command. Thanks to a suggestion by Mike Heeter.
2890 (Magic.magic_pfile): added behavior to look at filenames if given
2895 (Magic.magic_pfile): added behavior to look at filenames if given
2891 arg is not a defined object.
2896 arg is not a defined object.
2892 (Magic.magic_save): New @save function to save code snippets. Also
2897 (Magic.magic_save): New @save function to save code snippets. Also
2893 a Mike Heeter idea.
2898 a Mike Heeter idea.
2894
2899
2895 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2900 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2896 plot() and replot(). Much more convenient now, especially for
2901 plot() and replot(). Much more convenient now, especially for
2897 interactive use.
2902 interactive use.
2898
2903
2899 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2904 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2900 filenames.
2905 filenames.
2901
2906
2902 2002-06-02 Fernando Perez <fperez@colorado.edu>
2907 2002-06-02 Fernando Perez <fperez@colorado.edu>
2903
2908
2904 * IPython/Struct.py (Struct.__init__): modified to admit
2909 * IPython/Struct.py (Struct.__init__): modified to admit
2905 initialization via another struct.
2910 initialization via another struct.
2906
2911
2907 * IPython/genutils.py (SystemExec.__init__): New stateful
2912 * IPython/genutils.py (SystemExec.__init__): New stateful
2908 interface to xsys and bq. Useful for writing system scripts.
2913 interface to xsys and bq. Useful for writing system scripts.
2909
2914
2910 2002-05-30 Fernando Perez <fperez@colorado.edu>
2915 2002-05-30 Fernando Perez <fperez@colorado.edu>
2911
2916
2912 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2917 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2913 documents. This will make the user download smaller (it's getting
2918 documents. This will make the user download smaller (it's getting
2914 too big).
2919 too big).
2915
2920
2916 2002-05-29 Fernando Perez <fperez@colorado.edu>
2921 2002-05-29 Fernando Perez <fperez@colorado.edu>
2917
2922
2918 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2923 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2919 fix problems with shelve and pickle. Seems to work, but I don't
2924 fix problems with shelve and pickle. Seems to work, but I don't
2920 know if corner cases break it. Thanks to Mike Heeter
2925 know if corner cases break it. Thanks to Mike Heeter
2921 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2926 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2922
2927
2923 2002-05-24 Fernando Perez <fperez@colorado.edu>
2928 2002-05-24 Fernando Perez <fperez@colorado.edu>
2924
2929
2925 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2930 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2926 macros having broken.
2931 macros having broken.
2927
2932
2928 2002-05-21 Fernando Perez <fperez@colorado.edu>
2933 2002-05-21 Fernando Perez <fperez@colorado.edu>
2929
2934
2930 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2935 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2931 introduced logging bug: all history before logging started was
2936 introduced logging bug: all history before logging started was
2932 being written one character per line! This came from the redesign
2937 being written one character per line! This came from the redesign
2933 of the input history as a special list which slices to strings,
2938 of the input history as a special list which slices to strings,
2934 not to lists.
2939 not to lists.
2935
2940
2936 2002-05-20 Fernando Perez <fperez@colorado.edu>
2941 2002-05-20 Fernando Perez <fperez@colorado.edu>
2937
2942
2938 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2943 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2939 be an attribute of all classes in this module. The design of these
2944 be an attribute of all classes in this module. The design of these
2940 classes needs some serious overhauling.
2945 classes needs some serious overhauling.
2941
2946
2942 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2947 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2943 which was ignoring '_' in option names.
2948 which was ignoring '_' in option names.
2944
2949
2945 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2950 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2946 'Verbose_novars' to 'Context' and made it the new default. It's a
2951 'Verbose_novars' to 'Context' and made it the new default. It's a
2947 bit more readable and also safer than verbose.
2952 bit more readable and also safer than verbose.
2948
2953
2949 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2954 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2950 triple-quoted strings.
2955 triple-quoted strings.
2951
2956
2952 * IPython/OInspect.py (__all__): new module exposing the object
2957 * IPython/OInspect.py (__all__): new module exposing the object
2953 introspection facilities. Now the corresponding magics are dummy
2958 introspection facilities. Now the corresponding magics are dummy
2954 wrappers around this. Having this module will make it much easier
2959 wrappers around this. Having this module will make it much easier
2955 to put these functions into our modified pdb.
2960 to put these functions into our modified pdb.
2956 This new object inspector system uses the new colorizing module,
2961 This new object inspector system uses the new colorizing module,
2957 so source code and other things are nicely syntax highlighted.
2962 so source code and other things are nicely syntax highlighted.
2958
2963
2959 2002-05-18 Fernando Perez <fperez@colorado.edu>
2964 2002-05-18 Fernando Perez <fperez@colorado.edu>
2960
2965
2961 * IPython/ColorANSI.py: Split the coloring tools into a separate
2966 * IPython/ColorANSI.py: Split the coloring tools into a separate
2962 module so I can use them in other code easier (they were part of
2967 module so I can use them in other code easier (they were part of
2963 ultraTB).
2968 ultraTB).
2964
2969
2965 2002-05-17 Fernando Perez <fperez@colorado.edu>
2970 2002-05-17 Fernando Perez <fperez@colorado.edu>
2966
2971
2967 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2972 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2968 fixed it to set the global 'g' also to the called instance, as
2973 fixed it to set the global 'g' also to the called instance, as
2969 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2974 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2970 user's 'g' variables).
2975 user's 'g' variables).
2971
2976
2972 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2977 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2973 global variables (aliases to _ih,_oh) so that users which expect
2978 global variables (aliases to _ih,_oh) so that users which expect
2974 In[5] or Out[7] to work aren't unpleasantly surprised.
2979 In[5] or Out[7] to work aren't unpleasantly surprised.
2975 (InputList.__getslice__): new class to allow executing slices of
2980 (InputList.__getslice__): new class to allow executing slices of
2976 input history directly. Very simple class, complements the use of
2981 input history directly. Very simple class, complements the use of
2977 macros.
2982 macros.
2978
2983
2979 2002-05-16 Fernando Perez <fperez@colorado.edu>
2984 2002-05-16 Fernando Perez <fperez@colorado.edu>
2980
2985
2981 * setup.py (docdirbase): make doc directory be just doc/IPython
2986 * setup.py (docdirbase): make doc directory be just doc/IPython
2982 without version numbers, it will reduce clutter for users.
2987 without version numbers, it will reduce clutter for users.
2983
2988
2984 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2989 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2985 execfile call to prevent possible memory leak. See for details:
2990 execfile call to prevent possible memory leak. See for details:
2986 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2991 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2987
2992
2988 2002-05-15 Fernando Perez <fperez@colorado.edu>
2993 2002-05-15 Fernando Perez <fperez@colorado.edu>
2989
2994
2990 * IPython/Magic.py (Magic.magic_psource): made the object
2995 * IPython/Magic.py (Magic.magic_psource): made the object
2991 introspection names be more standard: pdoc, pdef, pfile and
2996 introspection names be more standard: pdoc, pdef, pfile and
2992 psource. They all print/page their output, and it makes
2997 psource. They all print/page their output, and it makes
2993 remembering them easier. Kept old names for compatibility as
2998 remembering them easier. Kept old names for compatibility as
2994 aliases.
2999 aliases.
2995
3000
2996 2002-05-14 Fernando Perez <fperez@colorado.edu>
3001 2002-05-14 Fernando Perez <fperez@colorado.edu>
2997
3002
2998 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3003 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
2999 what the mouse problem was. The trick is to use gnuplot with temp
3004 what the mouse problem was. The trick is to use gnuplot with temp
3000 files and NOT with pipes (for data communication), because having
3005 files and NOT with pipes (for data communication), because having
3001 both pipes and the mouse on is bad news.
3006 both pipes and the mouse on is bad news.
3002
3007
3003 2002-05-13 Fernando Perez <fperez@colorado.edu>
3008 2002-05-13 Fernando Perez <fperez@colorado.edu>
3004
3009
3005 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3010 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3006 bug. Information would be reported about builtins even when
3011 bug. Information would be reported about builtins even when
3007 user-defined functions overrode them.
3012 user-defined functions overrode them.
3008
3013
3009 2002-05-11 Fernando Perez <fperez@colorado.edu>
3014 2002-05-11 Fernando Perez <fperez@colorado.edu>
3010
3015
3011 * IPython/__init__.py (__all__): removed FlexCompleter from
3016 * IPython/__init__.py (__all__): removed FlexCompleter from
3012 __all__ so that things don't fail in platforms without readline.
3017 __all__ so that things don't fail in platforms without readline.
3013
3018
3014 2002-05-10 Fernando Perez <fperez@colorado.edu>
3019 2002-05-10 Fernando Perez <fperez@colorado.edu>
3015
3020
3016 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3021 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3017 it requires Numeric, effectively making Numeric a dependency for
3022 it requires Numeric, effectively making Numeric a dependency for
3018 IPython.
3023 IPython.
3019
3024
3020 * Released 0.2.13
3025 * Released 0.2.13
3021
3026
3022 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3027 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3023 profiler interface. Now all the major options from the profiler
3028 profiler interface. Now all the major options from the profiler
3024 module are directly supported in IPython, both for single
3029 module are directly supported in IPython, both for single
3025 expressions (@prun) and for full programs (@run -p).
3030 expressions (@prun) and for full programs (@run -p).
3026
3031
3027 2002-05-09 Fernando Perez <fperez@colorado.edu>
3032 2002-05-09 Fernando Perez <fperez@colorado.edu>
3028
3033
3029 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3034 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3030 magic properly formatted for screen.
3035 magic properly formatted for screen.
3031
3036
3032 * setup.py (make_shortcut): Changed things to put pdf version in
3037 * setup.py (make_shortcut): Changed things to put pdf version in
3033 doc/ instead of doc/manual (had to change lyxport a bit).
3038 doc/ instead of doc/manual (had to change lyxport a bit).
3034
3039
3035 * IPython/Magic.py (Profile.string_stats): made profile runs go
3040 * IPython/Magic.py (Profile.string_stats): made profile runs go
3036 through pager (they are long and a pager allows searching, saving,
3041 through pager (they are long and a pager allows searching, saving,
3037 etc.)
3042 etc.)
3038
3043
3039 2002-05-08 Fernando Perez <fperez@colorado.edu>
3044 2002-05-08 Fernando Perez <fperez@colorado.edu>
3040
3045
3041 * Released 0.2.12
3046 * Released 0.2.12
3042
3047
3043 2002-05-06 Fernando Perez <fperez@colorado.edu>
3048 2002-05-06 Fernando Perez <fperez@colorado.edu>
3044
3049
3045 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3050 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3046 introduced); 'hist n1 n2' was broken.
3051 introduced); 'hist n1 n2' was broken.
3047 (Magic.magic_pdb): added optional on/off arguments to @pdb
3052 (Magic.magic_pdb): added optional on/off arguments to @pdb
3048 (Magic.magic_run): added option -i to @run, which executes code in
3053 (Magic.magic_run): added option -i to @run, which executes code in
3049 the IPython namespace instead of a clean one. Also added @irun as
3054 the IPython namespace instead of a clean one. Also added @irun as
3050 an alias to @run -i.
3055 an alias to @run -i.
3051
3056
3052 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3057 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3053 fixed (it didn't really do anything, the namespaces were wrong).
3058 fixed (it didn't really do anything, the namespaces were wrong).
3054
3059
3055 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3060 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3056
3061
3057 * IPython/__init__.py (__all__): Fixed package namespace, now
3062 * IPython/__init__.py (__all__): Fixed package namespace, now
3058 'import IPython' does give access to IPython.<all> as
3063 'import IPython' does give access to IPython.<all> as
3059 expected. Also renamed __release__ to Release.
3064 expected. Also renamed __release__ to Release.
3060
3065
3061 * IPython/Debugger.py (__license__): created new Pdb class which
3066 * IPython/Debugger.py (__license__): created new Pdb class which
3062 functions like a drop-in for the normal pdb.Pdb but does NOT
3067 functions like a drop-in for the normal pdb.Pdb but does NOT
3063 import readline by default. This way it doesn't muck up IPython's
3068 import readline by default. This way it doesn't muck up IPython's
3064 readline handling, and now tab-completion finally works in the
3069 readline handling, and now tab-completion finally works in the
3065 debugger -- sort of. It completes things globally visible, but the
3070 debugger -- sort of. It completes things globally visible, but the
3066 completer doesn't track the stack as pdb walks it. That's a bit
3071 completer doesn't track the stack as pdb walks it. That's a bit
3067 tricky, and I'll have to implement it later.
3072 tricky, and I'll have to implement it later.
3068
3073
3069 2002-05-05 Fernando Perez <fperez@colorado.edu>
3074 2002-05-05 Fernando Perez <fperez@colorado.edu>
3070
3075
3071 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3076 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3072 magic docstrings when printed via ? (explicit \'s were being
3077 magic docstrings when printed via ? (explicit \'s were being
3073 printed).
3078 printed).
3074
3079
3075 * IPython/ipmaker.py (make_IPython): fixed namespace
3080 * IPython/ipmaker.py (make_IPython): fixed namespace
3076 identification bug. Now variables loaded via logs or command-line
3081 identification bug. Now variables loaded via logs or command-line
3077 files are recognized in the interactive namespace by @who.
3082 files are recognized in the interactive namespace by @who.
3078
3083
3079 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3084 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3080 log replay system stemming from the string form of Structs.
3085 log replay system stemming from the string form of Structs.
3081
3086
3082 * IPython/Magic.py (Macro.__init__): improved macros to properly
3087 * IPython/Magic.py (Macro.__init__): improved macros to properly
3083 handle magic commands in them.
3088 handle magic commands in them.
3084 (Magic.magic_logstart): usernames are now expanded so 'logstart
3089 (Magic.magic_logstart): usernames are now expanded so 'logstart
3085 ~/mylog' now works.
3090 ~/mylog' now works.
3086
3091
3087 * IPython/iplib.py (complete): fixed bug where paths starting with
3092 * IPython/iplib.py (complete): fixed bug where paths starting with
3088 '/' would be completed as magic names.
3093 '/' would be completed as magic names.
3089
3094
3090 2002-05-04 Fernando Perez <fperez@colorado.edu>
3095 2002-05-04 Fernando Perez <fperez@colorado.edu>
3091
3096
3092 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3097 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3093 allow running full programs under the profiler's control.
3098 allow running full programs under the profiler's control.
3094
3099
3095 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3100 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3096 mode to report exceptions verbosely but without formatting
3101 mode to report exceptions verbosely but without formatting
3097 variables. This addresses the issue of ipython 'freezing' (it's
3102 variables. This addresses the issue of ipython 'freezing' (it's
3098 not frozen, but caught in an expensive formatting loop) when huge
3103 not frozen, but caught in an expensive formatting loop) when huge
3099 variables are in the context of an exception.
3104 variables are in the context of an exception.
3100 (VerboseTB.text): Added '--->' markers at line where exception was
3105 (VerboseTB.text): Added '--->' markers at line where exception was
3101 triggered. Much clearer to read, especially in NoColor modes.
3106 triggered. Much clearer to read, especially in NoColor modes.
3102
3107
3103 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3108 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3104 implemented in reverse when changing to the new parse_options().
3109 implemented in reverse when changing to the new parse_options().
3105
3110
3106 2002-05-03 Fernando Perez <fperez@colorado.edu>
3111 2002-05-03 Fernando Perez <fperez@colorado.edu>
3107
3112
3108 * IPython/Magic.py (Magic.parse_options): new function so that
3113 * IPython/Magic.py (Magic.parse_options): new function so that
3109 magics can parse options easier.
3114 magics can parse options easier.
3110 (Magic.magic_prun): new function similar to profile.run(),
3115 (Magic.magic_prun): new function similar to profile.run(),
3111 suggested by Chris Hart.
3116 suggested by Chris Hart.
3112 (Magic.magic_cd): fixed behavior so that it only changes if
3117 (Magic.magic_cd): fixed behavior so that it only changes if
3113 directory actually is in history.
3118 directory actually is in history.
3114
3119
3115 * IPython/usage.py (__doc__): added information about potential
3120 * IPython/usage.py (__doc__): added information about potential
3116 slowness of Verbose exception mode when there are huge data
3121 slowness of Verbose exception mode when there are huge data
3117 structures to be formatted (thanks to Archie Paulson).
3122 structures to be formatted (thanks to Archie Paulson).
3118
3123
3119 * IPython/ipmaker.py (make_IPython): Changed default logging
3124 * IPython/ipmaker.py (make_IPython): Changed default logging
3120 (when simply called with -log) to use curr_dir/ipython.log in
3125 (when simply called with -log) to use curr_dir/ipython.log in
3121 rotate mode. Fixed crash which was occuring with -log before
3126 rotate mode. Fixed crash which was occuring with -log before
3122 (thanks to Jim Boyle).
3127 (thanks to Jim Boyle).
3123
3128
3124 2002-05-01 Fernando Perez <fperez@colorado.edu>
3129 2002-05-01 Fernando Perez <fperez@colorado.edu>
3125
3130
3126 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3131 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3127 was nasty -- though somewhat of a corner case).
3132 was nasty -- though somewhat of a corner case).
3128
3133
3129 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3134 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3130 text (was a bug).
3135 text (was a bug).
3131
3136
3132 2002-04-30 Fernando Perez <fperez@colorado.edu>
3137 2002-04-30 Fernando Perez <fperez@colorado.edu>
3133
3138
3134 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3139 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3135 a print after ^D or ^C from the user so that the In[] prompt
3140 a print after ^D or ^C from the user so that the In[] prompt
3136 doesn't over-run the gnuplot one.
3141 doesn't over-run the gnuplot one.
3137
3142
3138 2002-04-29 Fernando Perez <fperez@colorado.edu>
3143 2002-04-29 Fernando Perez <fperez@colorado.edu>
3139
3144
3140 * Released 0.2.10
3145 * Released 0.2.10
3141
3146
3142 * IPython/__release__.py (version): get date dynamically.
3147 * IPython/__release__.py (version): get date dynamically.
3143
3148
3144 * Misc. documentation updates thanks to Arnd's comments. Also ran
3149 * Misc. documentation updates thanks to Arnd's comments. Also ran
3145 a full spellcheck on the manual (hadn't been done in a while).
3150 a full spellcheck on the manual (hadn't been done in a while).
3146
3151
3147 2002-04-27 Fernando Perez <fperez@colorado.edu>
3152 2002-04-27 Fernando Perez <fperez@colorado.edu>
3148
3153
3149 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3154 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3150 starting a log in mid-session would reset the input history list.
3155 starting a log in mid-session would reset the input history list.
3151
3156
3152 2002-04-26 Fernando Perez <fperez@colorado.edu>
3157 2002-04-26 Fernando Perez <fperez@colorado.edu>
3153
3158
3154 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3159 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3155 all files were being included in an update. Now anything in
3160 all files were being included in an update. Now anything in
3156 UserConfig that matches [A-Za-z]*.py will go (this excludes
3161 UserConfig that matches [A-Za-z]*.py will go (this excludes
3157 __init__.py)
3162 __init__.py)
3158
3163
3159 2002-04-25 Fernando Perez <fperez@colorado.edu>
3164 2002-04-25 Fernando Perez <fperez@colorado.edu>
3160
3165
3161 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3166 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3162 to __builtins__ so that any form of embedded or imported code can
3167 to __builtins__ so that any form of embedded or imported code can
3163 test for being inside IPython.
3168 test for being inside IPython.
3164
3169
3165 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3170 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3166 changed to GnuplotMagic because it's now an importable module,
3171 changed to GnuplotMagic because it's now an importable module,
3167 this makes the name follow that of the standard Gnuplot module.
3172 this makes the name follow that of the standard Gnuplot module.
3168 GnuplotMagic can now be loaded at any time in mid-session.
3173 GnuplotMagic can now be loaded at any time in mid-session.
3169
3174
3170 2002-04-24 Fernando Perez <fperez@colorado.edu>
3175 2002-04-24 Fernando Perez <fperez@colorado.edu>
3171
3176
3172 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3177 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3173 the globals (IPython has its own namespace) and the
3178 the globals (IPython has its own namespace) and the
3174 PhysicalQuantity stuff is much better anyway.
3179 PhysicalQuantity stuff is much better anyway.
3175
3180
3176 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3181 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3177 embedding example to standard user directory for
3182 embedding example to standard user directory for
3178 distribution. Also put it in the manual.
3183 distribution. Also put it in the manual.
3179
3184
3180 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3185 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3181 instance as first argument (so it doesn't rely on some obscure
3186 instance as first argument (so it doesn't rely on some obscure
3182 hidden global).
3187 hidden global).
3183
3188
3184 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3189 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3185 delimiters. While it prevents ().TAB from working, it allows
3190 delimiters. While it prevents ().TAB from working, it allows
3186 completions in open (... expressions. This is by far a more common
3191 completions in open (... expressions. This is by far a more common
3187 case.
3192 case.
3188
3193
3189 2002-04-23 Fernando Perez <fperez@colorado.edu>
3194 2002-04-23 Fernando Perez <fperez@colorado.edu>
3190
3195
3191 * IPython/Extensions/InterpreterPasteInput.py: new
3196 * IPython/Extensions/InterpreterPasteInput.py: new
3192 syntax-processing module for pasting lines with >>> or ... at the
3197 syntax-processing module for pasting lines with >>> or ... at the
3193 start.
3198 start.
3194
3199
3195 * IPython/Extensions/PhysicalQ_Interactive.py
3200 * IPython/Extensions/PhysicalQ_Interactive.py
3196 (PhysicalQuantityInteractive.__int__): fixed to work with either
3201 (PhysicalQuantityInteractive.__int__): fixed to work with either
3197 Numeric or math.
3202 Numeric or math.
3198
3203
3199 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3204 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3200 provided profiles. Now we have:
3205 provided profiles. Now we have:
3201 -math -> math module as * and cmath with its own namespace.
3206 -math -> math module as * and cmath with its own namespace.
3202 -numeric -> Numeric as *, plus gnuplot & grace
3207 -numeric -> Numeric as *, plus gnuplot & grace
3203 -physics -> same as before
3208 -physics -> same as before
3204
3209
3205 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3210 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3206 user-defined magics wouldn't be found by @magic if they were
3211 user-defined magics wouldn't be found by @magic if they were
3207 defined as class methods. Also cleaned up the namespace search
3212 defined as class methods. Also cleaned up the namespace search
3208 logic and the string building (to use %s instead of many repeated
3213 logic and the string building (to use %s instead of many repeated
3209 string adds).
3214 string adds).
3210
3215
3211 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3216 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3212 of user-defined magics to operate with class methods (cleaner, in
3217 of user-defined magics to operate with class methods (cleaner, in
3213 line with the gnuplot code).
3218 line with the gnuplot code).
3214
3219
3215 2002-04-22 Fernando Perez <fperez@colorado.edu>
3220 2002-04-22 Fernando Perez <fperez@colorado.edu>
3216
3221
3217 * setup.py: updated dependency list so that manual is updated when
3222 * setup.py: updated dependency list so that manual is updated when
3218 all included files change.
3223 all included files change.
3219
3224
3220 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3225 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3221 the delimiter removal option (the fix is ugly right now).
3226 the delimiter removal option (the fix is ugly right now).
3222
3227
3223 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3228 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3224 all of the math profile (quicker loading, no conflict between
3229 all of the math profile (quicker loading, no conflict between
3225 g-9.8 and g-gnuplot).
3230 g-9.8 and g-gnuplot).
3226
3231
3227 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3232 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3228 name of post-mortem files to IPython_crash_report.txt.
3233 name of post-mortem files to IPython_crash_report.txt.
3229
3234
3230 * Cleanup/update of the docs. Added all the new readline info and
3235 * Cleanup/update of the docs. Added all the new readline info and
3231 formatted all lists as 'real lists'.
3236 formatted all lists as 'real lists'.
3232
3237
3233 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3238 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3234 tab-completion options, since the full readline parse_and_bind is
3239 tab-completion options, since the full readline parse_and_bind is
3235 now accessible.
3240 now accessible.
3236
3241
3237 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3242 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3238 handling of readline options. Now users can specify any string to
3243 handling of readline options. Now users can specify any string to
3239 be passed to parse_and_bind(), as well as the delimiters to be
3244 be passed to parse_and_bind(), as well as the delimiters to be
3240 removed.
3245 removed.
3241 (InteractiveShell.__init__): Added __name__ to the global
3246 (InteractiveShell.__init__): Added __name__ to the global
3242 namespace so that things like Itpl which rely on its existence
3247 namespace so that things like Itpl which rely on its existence
3243 don't crash.
3248 don't crash.
3244 (InteractiveShell._prefilter): Defined the default with a _ so
3249 (InteractiveShell._prefilter): Defined the default with a _ so
3245 that prefilter() is easier to override, while the default one
3250 that prefilter() is easier to override, while the default one
3246 remains available.
3251 remains available.
3247
3252
3248 2002-04-18 Fernando Perez <fperez@colorado.edu>
3253 2002-04-18 Fernando Perez <fperez@colorado.edu>
3249
3254
3250 * Added information about pdb in the docs.
3255 * Added information about pdb in the docs.
3251
3256
3252 2002-04-17 Fernando Perez <fperez@colorado.edu>
3257 2002-04-17 Fernando Perez <fperez@colorado.edu>
3253
3258
3254 * IPython/ipmaker.py (make_IPython): added rc_override option to
3259 * IPython/ipmaker.py (make_IPython): added rc_override option to
3255 allow passing config options at creation time which may override
3260 allow passing config options at creation time which may override
3256 anything set in the config files or command line. This is
3261 anything set in the config files or command line. This is
3257 particularly useful for configuring embedded instances.
3262 particularly useful for configuring embedded instances.
3258
3263
3259 2002-04-15 Fernando Perez <fperez@colorado.edu>
3264 2002-04-15 Fernando Perez <fperez@colorado.edu>
3260
3265
3261 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3266 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3262 crash embedded instances because of the input cache falling out of
3267 crash embedded instances because of the input cache falling out of
3263 sync with the output counter.
3268 sync with the output counter.
3264
3269
3265 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3270 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3266 mode which calls pdb after an uncaught exception in IPython itself.
3271 mode which calls pdb after an uncaught exception in IPython itself.
3267
3272
3268 2002-04-14 Fernando Perez <fperez@colorado.edu>
3273 2002-04-14 Fernando Perez <fperez@colorado.edu>
3269
3274
3270 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3275 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3271 readline, fix it back after each call.
3276 readline, fix it back after each call.
3272
3277
3273 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3278 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3274 method to force all access via __call__(), which guarantees that
3279 method to force all access via __call__(), which guarantees that
3275 traceback references are properly deleted.
3280 traceback references are properly deleted.
3276
3281
3277 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3282 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3278 improve printing when pprint is in use.
3283 improve printing when pprint is in use.
3279
3284
3280 2002-04-13 Fernando Perez <fperez@colorado.edu>
3285 2002-04-13 Fernando Perez <fperez@colorado.edu>
3281
3286
3282 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3287 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3283 exceptions aren't caught anymore. If the user triggers one, he
3288 exceptions aren't caught anymore. If the user triggers one, he
3284 should know why he's doing it and it should go all the way up,
3289 should know why he's doing it and it should go all the way up,
3285 just like any other exception. So now @abort will fully kill the
3290 just like any other exception. So now @abort will fully kill the
3286 embedded interpreter and the embedding code (unless that happens
3291 embedded interpreter and the embedding code (unless that happens
3287 to catch SystemExit).
3292 to catch SystemExit).
3288
3293
3289 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3294 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3290 and a debugger() method to invoke the interactive pdb debugger
3295 and a debugger() method to invoke the interactive pdb debugger
3291 after printing exception information. Also added the corresponding
3296 after printing exception information. Also added the corresponding
3292 -pdb option and @pdb magic to control this feature, and updated
3297 -pdb option and @pdb magic to control this feature, and updated
3293 the docs. After a suggestion from Christopher Hart
3298 the docs. After a suggestion from Christopher Hart
3294 (hart-AT-caltech.edu).
3299 (hart-AT-caltech.edu).
3295
3300
3296 2002-04-12 Fernando Perez <fperez@colorado.edu>
3301 2002-04-12 Fernando Perez <fperez@colorado.edu>
3297
3302
3298 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3303 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3299 the exception handlers defined by the user (not the CrashHandler)
3304 the exception handlers defined by the user (not the CrashHandler)
3300 so that user exceptions don't trigger an ipython bug report.
3305 so that user exceptions don't trigger an ipython bug report.
3301
3306
3302 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3307 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3303 configurable (it should have always been so).
3308 configurable (it should have always been so).
3304
3309
3305 2002-03-26 Fernando Perez <fperez@colorado.edu>
3310 2002-03-26 Fernando Perez <fperez@colorado.edu>
3306
3311
3307 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3312 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3308 and there to fix embedding namespace issues. This should all be
3313 and there to fix embedding namespace issues. This should all be
3309 done in a more elegant way.
3314 done in a more elegant way.
3310
3315
3311 2002-03-25 Fernando Perez <fperez@colorado.edu>
3316 2002-03-25 Fernando Perez <fperez@colorado.edu>
3312
3317
3313 * IPython/genutils.py (get_home_dir): Try to make it work under
3318 * IPython/genutils.py (get_home_dir): Try to make it work under
3314 win9x also.
3319 win9x also.
3315
3320
3316 2002-03-20 Fernando Perez <fperez@colorado.edu>
3321 2002-03-20 Fernando Perez <fperez@colorado.edu>
3317
3322
3318 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3323 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3319 sys.displayhook untouched upon __init__.
3324 sys.displayhook untouched upon __init__.
3320
3325
3321 2002-03-19 Fernando Perez <fperez@colorado.edu>
3326 2002-03-19 Fernando Perez <fperez@colorado.edu>
3322
3327
3323 * Released 0.2.9 (for embedding bug, basically).
3328 * Released 0.2.9 (for embedding bug, basically).
3324
3329
3325 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3330 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3326 exceptions so that enclosing shell's state can be restored.
3331 exceptions so that enclosing shell's state can be restored.
3327
3332
3328 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3333 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3329 naming conventions in the .ipython/ dir.
3334 naming conventions in the .ipython/ dir.
3330
3335
3331 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3336 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3332 from delimiters list so filenames with - in them get expanded.
3337 from delimiters list so filenames with - in them get expanded.
3333
3338
3334 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3339 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3335 sys.displayhook not being properly restored after an embedded call.
3340 sys.displayhook not being properly restored after an embedded call.
3336
3341
3337 2002-03-18 Fernando Perez <fperez@colorado.edu>
3342 2002-03-18 Fernando Perez <fperez@colorado.edu>
3338
3343
3339 * Released 0.2.8
3344 * Released 0.2.8
3340
3345
3341 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3346 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3342 some files weren't being included in a -upgrade.
3347 some files weren't being included in a -upgrade.
3343 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3348 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3344 on' so that the first tab completes.
3349 on' so that the first tab completes.
3345 (InteractiveShell.handle_magic): fixed bug with spaces around
3350 (InteractiveShell.handle_magic): fixed bug with spaces around
3346 quotes breaking many magic commands.
3351 quotes breaking many magic commands.
3347
3352
3348 * setup.py: added note about ignoring the syntax error messages at
3353 * setup.py: added note about ignoring the syntax error messages at
3349 installation.
3354 installation.
3350
3355
3351 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3356 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3352 streamlining the gnuplot interface, now there's only one magic @gp.
3357 streamlining the gnuplot interface, now there's only one magic @gp.
3353
3358
3354 2002-03-17 Fernando Perez <fperez@colorado.edu>
3359 2002-03-17 Fernando Perez <fperez@colorado.edu>
3355
3360
3356 * IPython/UserConfig/magic_gnuplot.py: new name for the
3361 * IPython/UserConfig/magic_gnuplot.py: new name for the
3357 example-magic_pm.py file. Much enhanced system, now with a shell
3362 example-magic_pm.py file. Much enhanced system, now with a shell
3358 for communicating directly with gnuplot, one command at a time.
3363 for communicating directly with gnuplot, one command at a time.
3359
3364
3360 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3365 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3361 setting __name__=='__main__'.
3366 setting __name__=='__main__'.
3362
3367
3363 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3368 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3364 mini-shell for accessing gnuplot from inside ipython. Should
3369 mini-shell for accessing gnuplot from inside ipython. Should
3365 extend it later for grace access too. Inspired by Arnd's
3370 extend it later for grace access too. Inspired by Arnd's
3366 suggestion.
3371 suggestion.
3367
3372
3368 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3373 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3369 calling magic functions with () in their arguments. Thanks to Arnd
3374 calling magic functions with () in their arguments. Thanks to Arnd
3370 Baecker for pointing this to me.
3375 Baecker for pointing this to me.
3371
3376
3372 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3377 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3373 infinitely for integer or complex arrays (only worked with floats).
3378 infinitely for integer or complex arrays (only worked with floats).
3374
3379
3375 2002-03-16 Fernando Perez <fperez@colorado.edu>
3380 2002-03-16 Fernando Perez <fperez@colorado.edu>
3376
3381
3377 * setup.py: Merged setup and setup_windows into a single script
3382 * setup.py: Merged setup and setup_windows into a single script
3378 which properly handles things for windows users.
3383 which properly handles things for windows users.
3379
3384
3380 2002-03-15 Fernando Perez <fperez@colorado.edu>
3385 2002-03-15 Fernando Perez <fperez@colorado.edu>
3381
3386
3382 * Big change to the manual: now the magics are all automatically
3387 * Big change to the manual: now the magics are all automatically
3383 documented. This information is generated from their docstrings
3388 documented. This information is generated from their docstrings
3384 and put in a latex file included by the manual lyx file. This way
3389 and put in a latex file included by the manual lyx file. This way
3385 we get always up to date information for the magics. The manual
3390 we get always up to date information for the magics. The manual
3386 now also has proper version information, also auto-synced.
3391 now also has proper version information, also auto-synced.
3387
3392
3388 For this to work, an undocumented --magic_docstrings option was added.
3393 For this to work, an undocumented --magic_docstrings option was added.
3389
3394
3390 2002-03-13 Fernando Perez <fperez@colorado.edu>
3395 2002-03-13 Fernando Perez <fperez@colorado.edu>
3391
3396
3392 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3397 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3393 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3398 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3394
3399
3395 2002-03-12 Fernando Perez <fperez@colorado.edu>
3400 2002-03-12 Fernando Perez <fperez@colorado.edu>
3396
3401
3397 * IPython/ultraTB.py (TermColors): changed color escapes again to
3402 * IPython/ultraTB.py (TermColors): changed color escapes again to
3398 fix the (old, reintroduced) line-wrapping bug. Basically, if
3403 fix the (old, reintroduced) line-wrapping bug. Basically, if
3399 \001..\002 aren't given in the color escapes, lines get wrapped
3404 \001..\002 aren't given in the color escapes, lines get wrapped
3400 weirdly. But giving those screws up old xterms and emacs terms. So
3405 weirdly. But giving those screws up old xterms and emacs terms. So
3401 I added some logic for emacs terms to be ok, but I can't identify old
3406 I added some logic for emacs terms to be ok, but I can't identify old
3402 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3407 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3403
3408
3404 2002-03-10 Fernando Perez <fperez@colorado.edu>
3409 2002-03-10 Fernando Perez <fperez@colorado.edu>
3405
3410
3406 * IPython/usage.py (__doc__): Various documentation cleanups and
3411 * IPython/usage.py (__doc__): Various documentation cleanups and
3407 updates, both in usage docstrings and in the manual.
3412 updates, both in usage docstrings and in the manual.
3408
3413
3409 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3414 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3410 handling of caching. Set minimum acceptabe value for having a
3415 handling of caching. Set minimum acceptabe value for having a
3411 cache at 20 values.
3416 cache at 20 values.
3412
3417
3413 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3418 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3414 install_first_time function to a method, renamed it and added an
3419 install_first_time function to a method, renamed it and added an
3415 'upgrade' mode. Now people can update their config directory with
3420 'upgrade' mode. Now people can update their config directory with
3416 a simple command line switch (-upgrade, also new).
3421 a simple command line switch (-upgrade, also new).
3417
3422
3418 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3423 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3419 @file (convenient for automagic users under Python >= 2.2).
3424 @file (convenient for automagic users under Python >= 2.2).
3420 Removed @files (it seemed more like a plural than an abbrev. of
3425 Removed @files (it seemed more like a plural than an abbrev. of
3421 'file show').
3426 'file show').
3422
3427
3423 * IPython/iplib.py (install_first_time): Fixed crash if there were
3428 * IPython/iplib.py (install_first_time): Fixed crash if there were
3424 backup files ('~') in .ipython/ install directory.
3429 backup files ('~') in .ipython/ install directory.
3425
3430
3426 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3431 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3427 system. Things look fine, but these changes are fairly
3432 system. Things look fine, but these changes are fairly
3428 intrusive. Test them for a few days.
3433 intrusive. Test them for a few days.
3429
3434
3430 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3435 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3431 the prompts system. Now all in/out prompt strings are user
3436 the prompts system. Now all in/out prompt strings are user
3432 controllable. This is particularly useful for embedding, as one
3437 controllable. This is particularly useful for embedding, as one
3433 can tag embedded instances with particular prompts.
3438 can tag embedded instances with particular prompts.
3434
3439
3435 Also removed global use of sys.ps1/2, which now allows nested
3440 Also removed global use of sys.ps1/2, which now allows nested
3436 embeddings without any problems. Added command-line options for
3441 embeddings without any problems. Added command-line options for
3437 the prompt strings.
3442 the prompt strings.
3438
3443
3439 2002-03-08 Fernando Perez <fperez@colorado.edu>
3444 2002-03-08 Fernando Perez <fperez@colorado.edu>
3440
3445
3441 * IPython/UserConfig/example-embed-short.py (ipshell): added
3446 * IPython/UserConfig/example-embed-short.py (ipshell): added
3442 example file with the bare minimum code for embedding.
3447 example file with the bare minimum code for embedding.
3443
3448
3444 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3449 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3445 functionality for the embeddable shell to be activated/deactivated
3450 functionality for the embeddable shell to be activated/deactivated
3446 either globally or at each call.
3451 either globally or at each call.
3447
3452
3448 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3453 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3449 rewriting the prompt with '--->' for auto-inputs with proper
3454 rewriting the prompt with '--->' for auto-inputs with proper
3450 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3455 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3451 this is handled by the prompts class itself, as it should.
3456 this is handled by the prompts class itself, as it should.
3452
3457
3453 2002-03-05 Fernando Perez <fperez@colorado.edu>
3458 2002-03-05 Fernando Perez <fperez@colorado.edu>
3454
3459
3455 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3460 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3456 @logstart to avoid name clashes with the math log function.
3461 @logstart to avoid name clashes with the math log function.
3457
3462
3458 * Big updates to X/Emacs section of the manual.
3463 * Big updates to X/Emacs section of the manual.
3459
3464
3460 * Removed ipython_emacs. Milan explained to me how to pass
3465 * Removed ipython_emacs. Milan explained to me how to pass
3461 arguments to ipython through Emacs. Some day I'm going to end up
3466 arguments to ipython through Emacs. Some day I'm going to end up
3462 learning some lisp...
3467 learning some lisp...
3463
3468
3464 2002-03-04 Fernando Perez <fperez@colorado.edu>
3469 2002-03-04 Fernando Perez <fperez@colorado.edu>
3465
3470
3466 * IPython/ipython_emacs: Created script to be used as the
3471 * IPython/ipython_emacs: Created script to be used as the
3467 py-python-command Emacs variable so we can pass IPython
3472 py-python-command Emacs variable so we can pass IPython
3468 parameters. I can't figure out how to tell Emacs directly to pass
3473 parameters. I can't figure out how to tell Emacs directly to pass
3469 parameters to IPython, so a dummy shell script will do it.
3474 parameters to IPython, so a dummy shell script will do it.
3470
3475
3471 Other enhancements made for things to work better under Emacs'
3476 Other enhancements made for things to work better under Emacs'
3472 various types of terminals. Many thanks to Milan Zamazal
3477 various types of terminals. Many thanks to Milan Zamazal
3473 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3478 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3474
3479
3475 2002-03-01 Fernando Perez <fperez@colorado.edu>
3480 2002-03-01 Fernando Perez <fperez@colorado.edu>
3476
3481
3477 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3482 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3478 that loading of readline is now optional. This gives better
3483 that loading of readline is now optional. This gives better
3479 control to emacs users.
3484 control to emacs users.
3480
3485
3481 * IPython/ultraTB.py (__date__): Modified color escape sequences
3486 * IPython/ultraTB.py (__date__): Modified color escape sequences
3482 and now things work fine under xterm and in Emacs' term buffers
3487 and now things work fine under xterm and in Emacs' term buffers
3483 (though not shell ones). Well, in emacs you get colors, but all
3488 (though not shell ones). Well, in emacs you get colors, but all
3484 seem to be 'light' colors (no difference between dark and light
3489 seem to be 'light' colors (no difference between dark and light
3485 ones). But the garbage chars are gone, and also in xterms. It
3490 ones). But the garbage chars are gone, and also in xterms. It
3486 seems that now I'm using 'cleaner' ansi sequences.
3491 seems that now I'm using 'cleaner' ansi sequences.
3487
3492
3488 2002-02-21 Fernando Perez <fperez@colorado.edu>
3493 2002-02-21 Fernando Perez <fperez@colorado.edu>
3489
3494
3490 * Released 0.2.7 (mainly to publish the scoping fix).
3495 * Released 0.2.7 (mainly to publish the scoping fix).
3491
3496
3492 * IPython/Logger.py (Logger.logstate): added. A corresponding
3497 * IPython/Logger.py (Logger.logstate): added. A corresponding
3493 @logstate magic was created.
3498 @logstate magic was created.
3494
3499
3495 * IPython/Magic.py: fixed nested scoping problem under Python
3500 * IPython/Magic.py: fixed nested scoping problem under Python
3496 2.1.x (automagic wasn't working).
3501 2.1.x (automagic wasn't working).
3497
3502
3498 2002-02-20 Fernando Perez <fperez@colorado.edu>
3503 2002-02-20 Fernando Perez <fperez@colorado.edu>
3499
3504
3500 * Released 0.2.6.
3505 * Released 0.2.6.
3501
3506
3502 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3507 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3503 option so that logs can come out without any headers at all.
3508 option so that logs can come out without any headers at all.
3504
3509
3505 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3510 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3506 SciPy.
3511 SciPy.
3507
3512
3508 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3513 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3509 that embedded IPython calls don't require vars() to be explicitly
3514 that embedded IPython calls don't require vars() to be explicitly
3510 passed. Now they are extracted from the caller's frame (code
3515 passed. Now they are extracted from the caller's frame (code
3511 snatched from Eric Jones' weave). Added better documentation to
3516 snatched from Eric Jones' weave). Added better documentation to
3512 the section on embedding and the example file.
3517 the section on embedding and the example file.
3513
3518
3514 * IPython/genutils.py (page): Changed so that under emacs, it just
3519 * IPython/genutils.py (page): Changed so that under emacs, it just
3515 prints the string. You can then page up and down in the emacs
3520 prints the string. You can then page up and down in the emacs
3516 buffer itself. This is how the builtin help() works.
3521 buffer itself. This is how the builtin help() works.
3517
3522
3518 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3523 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3519 macro scoping: macros need to be executed in the user's namespace
3524 macro scoping: macros need to be executed in the user's namespace
3520 to work as if they had been typed by the user.
3525 to work as if they had been typed by the user.
3521
3526
3522 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3527 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3523 execute automatically (no need to type 'exec...'). They then
3528 execute automatically (no need to type 'exec...'). They then
3524 behave like 'true macros'. The printing system was also modified
3529 behave like 'true macros'. The printing system was also modified
3525 for this to work.
3530 for this to work.
3526
3531
3527 2002-02-19 Fernando Perez <fperez@colorado.edu>
3532 2002-02-19 Fernando Perez <fperez@colorado.edu>
3528
3533
3529 * IPython/genutils.py (page_file): new function for paging files
3534 * IPython/genutils.py (page_file): new function for paging files
3530 in an OS-independent way. Also necessary for file viewing to work
3535 in an OS-independent way. Also necessary for file viewing to work
3531 well inside Emacs buffers.
3536 well inside Emacs buffers.
3532 (page): Added checks for being in an emacs buffer.
3537 (page): Added checks for being in an emacs buffer.
3533 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3538 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3534 same bug in iplib.
3539 same bug in iplib.
3535
3540
3536 2002-02-18 Fernando Perez <fperez@colorado.edu>
3541 2002-02-18 Fernando Perez <fperez@colorado.edu>
3537
3542
3538 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3543 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3539 of readline so that IPython can work inside an Emacs buffer.
3544 of readline so that IPython can work inside an Emacs buffer.
3540
3545
3541 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3546 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3542 method signatures (they weren't really bugs, but it looks cleaner
3547 method signatures (they weren't really bugs, but it looks cleaner
3543 and keeps PyChecker happy).
3548 and keeps PyChecker happy).
3544
3549
3545 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3550 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3546 for implementing various user-defined hooks. Currently only
3551 for implementing various user-defined hooks. Currently only
3547 display is done.
3552 display is done.
3548
3553
3549 * IPython/Prompts.py (CachedOutput._display): changed display
3554 * IPython/Prompts.py (CachedOutput._display): changed display
3550 functions so that they can be dynamically changed by users easily.
3555 functions so that they can be dynamically changed by users easily.
3551
3556
3552 * IPython/Extensions/numeric_formats.py (num_display): added an
3557 * IPython/Extensions/numeric_formats.py (num_display): added an
3553 extension for printing NumPy arrays in flexible manners. It
3558 extension for printing NumPy arrays in flexible manners. It
3554 doesn't do anything yet, but all the structure is in
3559 doesn't do anything yet, but all the structure is in
3555 place. Ultimately the plan is to implement output format control
3560 place. Ultimately the plan is to implement output format control
3556 like in Octave.
3561 like in Octave.
3557
3562
3558 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3563 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3559 methods are found at run-time by all the automatic machinery.
3564 methods are found at run-time by all the automatic machinery.
3560
3565
3561 2002-02-17 Fernando Perez <fperez@colorado.edu>
3566 2002-02-17 Fernando Perez <fperez@colorado.edu>
3562
3567
3563 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3568 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3564 whole file a little.
3569 whole file a little.
3565
3570
3566 * ToDo: closed this document. Now there's a new_design.lyx
3571 * ToDo: closed this document. Now there's a new_design.lyx
3567 document for all new ideas. Added making a pdf of it for the
3572 document for all new ideas. Added making a pdf of it for the
3568 end-user distro.
3573 end-user distro.
3569
3574
3570 * IPython/Logger.py (Logger.switch_log): Created this to replace
3575 * IPython/Logger.py (Logger.switch_log): Created this to replace
3571 logon() and logoff(). It also fixes a nasty crash reported by
3576 logon() and logoff(). It also fixes a nasty crash reported by
3572 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3577 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3573
3578
3574 * IPython/iplib.py (complete): got auto-completion to work with
3579 * IPython/iplib.py (complete): got auto-completion to work with
3575 automagic (I had wanted this for a long time).
3580 automagic (I had wanted this for a long time).
3576
3581
3577 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3582 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3578 to @file, since file() is now a builtin and clashes with automagic
3583 to @file, since file() is now a builtin and clashes with automagic
3579 for @file.
3584 for @file.
3580
3585
3581 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3586 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3582 of this was previously in iplib, which had grown to more than 2000
3587 of this was previously in iplib, which had grown to more than 2000
3583 lines, way too long. No new functionality, but it makes managing
3588 lines, way too long. No new functionality, but it makes managing
3584 the code a bit easier.
3589 the code a bit easier.
3585
3590
3586 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3591 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3587 information to crash reports.
3592 information to crash reports.
3588
3593
3589 2002-02-12 Fernando Perez <fperez@colorado.edu>
3594 2002-02-12 Fernando Perez <fperez@colorado.edu>
3590
3595
3591 * Released 0.2.5.
3596 * Released 0.2.5.
3592
3597
3593 2002-02-11 Fernando Perez <fperez@colorado.edu>
3598 2002-02-11 Fernando Perez <fperez@colorado.edu>
3594
3599
3595 * Wrote a relatively complete Windows installer. It puts
3600 * Wrote a relatively complete Windows installer. It puts
3596 everything in place, creates Start Menu entries and fixes the
3601 everything in place, creates Start Menu entries and fixes the
3597 color issues. Nothing fancy, but it works.
3602 color issues. Nothing fancy, but it works.
3598
3603
3599 2002-02-10 Fernando Perez <fperez@colorado.edu>
3604 2002-02-10 Fernando Perez <fperez@colorado.edu>
3600
3605
3601 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3606 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3602 os.path.expanduser() call so that we can type @run ~/myfile.py and
3607 os.path.expanduser() call so that we can type @run ~/myfile.py and
3603 have thigs work as expected.
3608 have thigs work as expected.
3604
3609
3605 * IPython/genutils.py (page): fixed exception handling so things
3610 * IPython/genutils.py (page): fixed exception handling so things
3606 work both in Unix and Windows correctly. Quitting a pager triggers
3611 work both in Unix and Windows correctly. Quitting a pager triggers
3607 an IOError/broken pipe in Unix, and in windows not finding a pager
3612 an IOError/broken pipe in Unix, and in windows not finding a pager
3608 is also an IOError, so I had to actually look at the return value
3613 is also an IOError, so I had to actually look at the return value
3609 of the exception, not just the exception itself. Should be ok now.
3614 of the exception, not just the exception itself. Should be ok now.
3610
3615
3611 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3616 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3612 modified to allow case-insensitive color scheme changes.
3617 modified to allow case-insensitive color scheme changes.
3613
3618
3614 2002-02-09 Fernando Perez <fperez@colorado.edu>
3619 2002-02-09 Fernando Perez <fperez@colorado.edu>
3615
3620
3616 * IPython/genutils.py (native_line_ends): new function to leave
3621 * IPython/genutils.py (native_line_ends): new function to leave
3617 user config files with os-native line-endings.
3622 user config files with os-native line-endings.
3618
3623
3619 * README and manual updates.
3624 * README and manual updates.
3620
3625
3621 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3626 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3622 instead of StringType to catch Unicode strings.
3627 instead of StringType to catch Unicode strings.
3623
3628
3624 * IPython/genutils.py (filefind): fixed bug for paths with
3629 * IPython/genutils.py (filefind): fixed bug for paths with
3625 embedded spaces (very common in Windows).
3630 embedded spaces (very common in Windows).
3626
3631
3627 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3632 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3628 files under Windows, so that they get automatically associated
3633 files under Windows, so that they get automatically associated
3629 with a text editor. Windows makes it a pain to handle
3634 with a text editor. Windows makes it a pain to handle
3630 extension-less files.
3635 extension-less files.
3631
3636
3632 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3637 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3633 warning about readline only occur for Posix. In Windows there's no
3638 warning about readline only occur for Posix. In Windows there's no
3634 way to get readline, so why bother with the warning.
3639 way to get readline, so why bother with the warning.
3635
3640
3636 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3641 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3637 for __str__ instead of dir(self), since dir() changed in 2.2.
3642 for __str__ instead of dir(self), since dir() changed in 2.2.
3638
3643
3639 * Ported to Windows! Tested on XP, I suspect it should work fine
3644 * Ported to Windows! Tested on XP, I suspect it should work fine
3640 on NT/2000, but I don't think it will work on 98 et al. That
3645 on NT/2000, but I don't think it will work on 98 et al. That
3641 series of Windows is such a piece of junk anyway that I won't try
3646 series of Windows is such a piece of junk anyway that I won't try
3642 porting it there. The XP port was straightforward, showed a few
3647 porting it there. The XP port was straightforward, showed a few
3643 bugs here and there (fixed all), in particular some string
3648 bugs here and there (fixed all), in particular some string
3644 handling stuff which required considering Unicode strings (which
3649 handling stuff which required considering Unicode strings (which
3645 Windows uses). This is good, but hasn't been too tested :) No
3650 Windows uses). This is good, but hasn't been too tested :) No
3646 fancy installer yet, I'll put a note in the manual so people at
3651 fancy installer yet, I'll put a note in the manual so people at
3647 least make manually a shortcut.
3652 least make manually a shortcut.
3648
3653
3649 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3654 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3650 into a single one, "colors". This now controls both prompt and
3655 into a single one, "colors". This now controls both prompt and
3651 exception color schemes, and can be changed both at startup
3656 exception color schemes, and can be changed both at startup
3652 (either via command-line switches or via ipythonrc files) and at
3657 (either via command-line switches or via ipythonrc files) and at
3653 runtime, with @colors.
3658 runtime, with @colors.
3654 (Magic.magic_run): renamed @prun to @run and removed the old
3659 (Magic.magic_run): renamed @prun to @run and removed the old
3655 @run. The two were too similar to warrant keeping both.
3660 @run. The two were too similar to warrant keeping both.
3656
3661
3657 2002-02-03 Fernando Perez <fperez@colorado.edu>
3662 2002-02-03 Fernando Perez <fperez@colorado.edu>
3658
3663
3659 * IPython/iplib.py (install_first_time): Added comment on how to
3664 * IPython/iplib.py (install_first_time): Added comment on how to
3660 configure the color options for first-time users. Put a <return>
3665 configure the color options for first-time users. Put a <return>
3661 request at the end so that small-terminal users get a chance to
3666 request at the end so that small-terminal users get a chance to
3662 read the startup info.
3667 read the startup info.
3663
3668
3664 2002-01-23 Fernando Perez <fperez@colorado.edu>
3669 2002-01-23 Fernando Perez <fperez@colorado.edu>
3665
3670
3666 * IPython/iplib.py (CachedOutput.update): Changed output memory
3671 * IPython/iplib.py (CachedOutput.update): Changed output memory
3667 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3672 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3668 input history we still use _i. Did this b/c these variable are
3673 input history we still use _i. Did this b/c these variable are
3669 very commonly used in interactive work, so the less we need to
3674 very commonly used in interactive work, so the less we need to
3670 type the better off we are.
3675 type the better off we are.
3671 (Magic.magic_prun): updated @prun to better handle the namespaces
3676 (Magic.magic_prun): updated @prun to better handle the namespaces
3672 the file will run in, including a fix for __name__ not being set
3677 the file will run in, including a fix for __name__ not being set
3673 before.
3678 before.
3674
3679
3675 2002-01-20 Fernando Perez <fperez@colorado.edu>
3680 2002-01-20 Fernando Perez <fperez@colorado.edu>
3676
3681
3677 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3682 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3678 extra garbage for Python 2.2. Need to look more carefully into
3683 extra garbage for Python 2.2. Need to look more carefully into
3679 this later.
3684 this later.
3680
3685
3681 2002-01-19 Fernando Perez <fperez@colorado.edu>
3686 2002-01-19 Fernando Perez <fperez@colorado.edu>
3682
3687
3683 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3688 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3684 display SyntaxError exceptions properly formatted when they occur
3689 display SyntaxError exceptions properly formatted when they occur
3685 (they can be triggered by imported code).
3690 (they can be triggered by imported code).
3686
3691
3687 2002-01-18 Fernando Perez <fperez@colorado.edu>
3692 2002-01-18 Fernando Perez <fperez@colorado.edu>
3688
3693
3689 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3694 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3690 SyntaxError exceptions are reported nicely formatted, instead of
3695 SyntaxError exceptions are reported nicely formatted, instead of
3691 spitting out only offset information as before.
3696 spitting out only offset information as before.
3692 (Magic.magic_prun): Added the @prun function for executing
3697 (Magic.magic_prun): Added the @prun function for executing
3693 programs with command line args inside IPython.
3698 programs with command line args inside IPython.
3694
3699
3695 2002-01-16 Fernando Perez <fperez@colorado.edu>
3700 2002-01-16 Fernando Perez <fperez@colorado.edu>
3696
3701
3697 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3702 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3698 to *not* include the last item given in a range. This brings their
3703 to *not* include the last item given in a range. This brings their
3699 behavior in line with Python's slicing:
3704 behavior in line with Python's slicing:
3700 a[n1:n2] -> a[n1]...a[n2-1]
3705 a[n1:n2] -> a[n1]...a[n2-1]
3701 It may be a bit less convenient, but I prefer to stick to Python's
3706 It may be a bit less convenient, but I prefer to stick to Python's
3702 conventions *everywhere*, so users never have to wonder.
3707 conventions *everywhere*, so users never have to wonder.
3703 (Magic.magic_macro): Added @macro function to ease the creation of
3708 (Magic.magic_macro): Added @macro function to ease the creation of
3704 macros.
3709 macros.
3705
3710
3706 2002-01-05 Fernando Perez <fperez@colorado.edu>
3711 2002-01-05 Fernando Perez <fperez@colorado.edu>
3707
3712
3708 * Released 0.2.4.
3713 * Released 0.2.4.
3709
3714
3710 * IPython/iplib.py (Magic.magic_pdef):
3715 * IPython/iplib.py (Magic.magic_pdef):
3711 (InteractiveShell.safe_execfile): report magic lines and error
3716 (InteractiveShell.safe_execfile): report magic lines and error
3712 lines without line numbers so one can easily copy/paste them for
3717 lines without line numbers so one can easily copy/paste them for
3713 re-execution.
3718 re-execution.
3714
3719
3715 * Updated manual with recent changes.
3720 * Updated manual with recent changes.
3716
3721
3717 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3722 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3718 docstring printing when class? is called. Very handy for knowing
3723 docstring printing when class? is called. Very handy for knowing
3719 how to create class instances (as long as __init__ is well
3724 how to create class instances (as long as __init__ is well
3720 documented, of course :)
3725 documented, of course :)
3721 (Magic.magic_doc): print both class and constructor docstrings.
3726 (Magic.magic_doc): print both class and constructor docstrings.
3722 (Magic.magic_pdef): give constructor info if passed a class and
3727 (Magic.magic_pdef): give constructor info if passed a class and
3723 __call__ info for callable object instances.
3728 __call__ info for callable object instances.
3724
3729
3725 2002-01-04 Fernando Perez <fperez@colorado.edu>
3730 2002-01-04 Fernando Perez <fperez@colorado.edu>
3726
3731
3727 * Made deep_reload() off by default. It doesn't always work
3732 * Made deep_reload() off by default. It doesn't always work
3728 exactly as intended, so it's probably safer to have it off. It's
3733 exactly as intended, so it's probably safer to have it off. It's
3729 still available as dreload() anyway, so nothing is lost.
3734 still available as dreload() anyway, so nothing is lost.
3730
3735
3731 2002-01-02 Fernando Perez <fperez@colorado.edu>
3736 2002-01-02 Fernando Perez <fperez@colorado.edu>
3732
3737
3733 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3738 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3734 so I wanted an updated release).
3739 so I wanted an updated release).
3735
3740
3736 2001-12-27 Fernando Perez <fperez@colorado.edu>
3741 2001-12-27 Fernando Perez <fperez@colorado.edu>
3737
3742
3738 * IPython/iplib.py (InteractiveShell.interact): Added the original
3743 * IPython/iplib.py (InteractiveShell.interact): Added the original
3739 code from 'code.py' for this module in order to change the
3744 code from 'code.py' for this module in order to change the
3740 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3745 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3741 the history cache would break when the user hit Ctrl-C, and
3746 the history cache would break when the user hit Ctrl-C, and
3742 interact() offers no way to add any hooks to it.
3747 interact() offers no way to add any hooks to it.
3743
3748
3744 2001-12-23 Fernando Perez <fperez@colorado.edu>
3749 2001-12-23 Fernando Perez <fperez@colorado.edu>
3745
3750
3746 * setup.py: added check for 'MANIFEST' before trying to remove
3751 * setup.py: added check for 'MANIFEST' before trying to remove
3747 it. Thanks to Sean Reifschneider.
3752 it. Thanks to Sean Reifschneider.
3748
3753
3749 2001-12-22 Fernando Perez <fperez@colorado.edu>
3754 2001-12-22 Fernando Perez <fperez@colorado.edu>
3750
3755
3751 * Released 0.2.2.
3756 * Released 0.2.2.
3752
3757
3753 * Finished (reasonably) writing the manual. Later will add the
3758 * Finished (reasonably) writing the manual. Later will add the
3754 python-standard navigation stylesheets, but for the time being
3759 python-standard navigation stylesheets, but for the time being
3755 it's fairly complete. Distribution will include html and pdf
3760 it's fairly complete. Distribution will include html and pdf
3756 versions.
3761 versions.
3757
3762
3758 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3763 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3759 (MayaVi author).
3764 (MayaVi author).
3760
3765
3761 2001-12-21 Fernando Perez <fperez@colorado.edu>
3766 2001-12-21 Fernando Perez <fperez@colorado.edu>
3762
3767
3763 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3768 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3764 good public release, I think (with the manual and the distutils
3769 good public release, I think (with the manual and the distutils
3765 installer). The manual can use some work, but that can go
3770 installer). The manual can use some work, but that can go
3766 slowly. Otherwise I think it's quite nice for end users. Next
3771 slowly. Otherwise I think it's quite nice for end users. Next
3767 summer, rewrite the guts of it...
3772 summer, rewrite the guts of it...
3768
3773
3769 * Changed format of ipythonrc files to use whitespace as the
3774 * Changed format of ipythonrc files to use whitespace as the
3770 separator instead of an explicit '='. Cleaner.
3775 separator instead of an explicit '='. Cleaner.
3771
3776
3772 2001-12-20 Fernando Perez <fperez@colorado.edu>
3777 2001-12-20 Fernando Perez <fperez@colorado.edu>
3773
3778
3774 * Started a manual in LyX. For now it's just a quick merge of the
3779 * Started a manual in LyX. For now it's just a quick merge of the
3775 various internal docstrings and READMEs. Later it may grow into a
3780 various internal docstrings and READMEs. Later it may grow into a
3776 nice, full-blown manual.
3781 nice, full-blown manual.
3777
3782
3778 * Set up a distutils based installer. Installation should now be
3783 * Set up a distutils based installer. Installation should now be
3779 trivially simple for end-users.
3784 trivially simple for end-users.
3780
3785
3781 2001-12-11 Fernando Perez <fperez@colorado.edu>
3786 2001-12-11 Fernando Perez <fperez@colorado.edu>
3782
3787
3783 * Released 0.2.0. First public release, announced it at
3788 * Released 0.2.0. First public release, announced it at
3784 comp.lang.python. From now on, just bugfixes...
3789 comp.lang.python. From now on, just bugfixes...
3785
3790
3786 * Went through all the files, set copyright/license notices and
3791 * Went through all the files, set copyright/license notices and
3787 cleaned up things. Ready for release.
3792 cleaned up things. Ready for release.
3788
3793
3789 2001-12-10 Fernando Perez <fperez@colorado.edu>
3794 2001-12-10 Fernando Perez <fperez@colorado.edu>
3790
3795
3791 * Changed the first-time installer not to use tarfiles. It's more
3796 * Changed the first-time installer not to use tarfiles. It's more
3792 robust now and less unix-dependent. Also makes it easier for
3797 robust now and less unix-dependent. Also makes it easier for
3793 people to later upgrade versions.
3798 people to later upgrade versions.
3794
3799
3795 * Changed @exit to @abort to reflect the fact that it's pretty
3800 * Changed @exit to @abort to reflect the fact that it's pretty
3796 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3801 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3797 becomes significant only when IPyhton is embedded: in that case,
3802 becomes significant only when IPyhton is embedded: in that case,
3798 C-D closes IPython only, but @abort kills the enclosing program
3803 C-D closes IPython only, but @abort kills the enclosing program
3799 too (unless it had called IPython inside a try catching
3804 too (unless it had called IPython inside a try catching
3800 SystemExit).
3805 SystemExit).
3801
3806
3802 * Created Shell module which exposes the actuall IPython Shell
3807 * Created Shell module which exposes the actuall IPython Shell
3803 classes, currently the normal and the embeddable one. This at
3808 classes, currently the normal and the embeddable one. This at
3804 least offers a stable interface we won't need to change when
3809 least offers a stable interface we won't need to change when
3805 (later) the internals are rewritten. That rewrite will be confined
3810 (later) the internals are rewritten. That rewrite will be confined
3806 to iplib and ipmaker, but the Shell interface should remain as is.
3811 to iplib and ipmaker, but the Shell interface should remain as is.
3807
3812
3808 * Added embed module which offers an embeddable IPShell object,
3813 * Added embed module which offers an embeddable IPShell object,
3809 useful to fire up IPython *inside* a running program. Great for
3814 useful to fire up IPython *inside* a running program. Great for
3810 debugging or dynamical data analysis.
3815 debugging or dynamical data analysis.
3811
3816
3812 2001-12-08 Fernando Perez <fperez@colorado.edu>
3817 2001-12-08 Fernando Perez <fperez@colorado.edu>
3813
3818
3814 * Fixed small bug preventing seeing info from methods of defined
3819 * Fixed small bug preventing seeing info from methods of defined
3815 objects (incorrect namespace in _ofind()).
3820 objects (incorrect namespace in _ofind()).
3816
3821
3817 * Documentation cleanup. Moved the main usage docstrings to a
3822 * Documentation cleanup. Moved the main usage docstrings to a
3818 separate file, usage.py (cleaner to maintain, and hopefully in the
3823 separate file, usage.py (cleaner to maintain, and hopefully in the
3819 future some perlpod-like way of producing interactive, man and
3824 future some perlpod-like way of producing interactive, man and
3820 html docs out of it will be found).
3825 html docs out of it will be found).
3821
3826
3822 * Added @profile to see your profile at any time.
3827 * Added @profile to see your profile at any time.
3823
3828
3824 * Added @p as an alias for 'print'. It's especially convenient if
3829 * Added @p as an alias for 'print'. It's especially convenient if
3825 using automagic ('p x' prints x).
3830 using automagic ('p x' prints x).
3826
3831
3827 * Small cleanups and fixes after a pychecker run.
3832 * Small cleanups and fixes after a pychecker run.
3828
3833
3829 * Changed the @cd command to handle @cd - and @cd -<n> for
3834 * Changed the @cd command to handle @cd - and @cd -<n> for
3830 visiting any directory in _dh.
3835 visiting any directory in _dh.
3831
3836
3832 * Introduced _dh, a history of visited directories. @dhist prints
3837 * Introduced _dh, a history of visited directories. @dhist prints
3833 it out with numbers.
3838 it out with numbers.
3834
3839
3835 2001-12-07 Fernando Perez <fperez@colorado.edu>
3840 2001-12-07 Fernando Perez <fperez@colorado.edu>
3836
3841
3837 * Released 0.1.22
3842 * Released 0.1.22
3838
3843
3839 * Made initialization a bit more robust against invalid color
3844 * Made initialization a bit more robust against invalid color
3840 options in user input (exit, not traceback-crash).
3845 options in user input (exit, not traceback-crash).
3841
3846
3842 * Changed the bug crash reporter to write the report only in the
3847 * Changed the bug crash reporter to write the report only in the
3843 user's .ipython directory. That way IPython won't litter people's
3848 user's .ipython directory. That way IPython won't litter people's
3844 hard disks with crash files all over the place. Also print on
3849 hard disks with crash files all over the place. Also print on
3845 screen the necessary mail command.
3850 screen the necessary mail command.
3846
3851
3847 * With the new ultraTB, implemented LightBG color scheme for light
3852 * With the new ultraTB, implemented LightBG color scheme for light
3848 background terminals. A lot of people like white backgrounds, so I
3853 background terminals. A lot of people like white backgrounds, so I
3849 guess we should at least give them something readable.
3854 guess we should at least give them something readable.
3850
3855
3851 2001-12-06 Fernando Perez <fperez@colorado.edu>
3856 2001-12-06 Fernando Perez <fperez@colorado.edu>
3852
3857
3853 * Modified the structure of ultraTB. Now there's a proper class
3858 * Modified the structure of ultraTB. Now there's a proper class
3854 for tables of color schemes which allow adding schemes easily and
3859 for tables of color schemes which allow adding schemes easily and
3855 switching the active scheme without creating a new instance every
3860 switching the active scheme without creating a new instance every
3856 time (which was ridiculous). The syntax for creating new schemes
3861 time (which was ridiculous). The syntax for creating new schemes
3857 is also cleaner. I think ultraTB is finally done, with a clean
3862 is also cleaner. I think ultraTB is finally done, with a clean
3858 class structure. Names are also much cleaner (now there's proper
3863 class structure. Names are also much cleaner (now there's proper
3859 color tables, no need for every variable to also have 'color' in
3864 color tables, no need for every variable to also have 'color' in
3860 its name).
3865 its name).
3861
3866
3862 * Broke down genutils into separate files. Now genutils only
3867 * Broke down genutils into separate files. Now genutils only
3863 contains utility functions, and classes have been moved to their
3868 contains utility functions, and classes have been moved to their
3864 own files (they had enough independent functionality to warrant
3869 own files (they had enough independent functionality to warrant
3865 it): ConfigLoader, OutputTrap, Struct.
3870 it): ConfigLoader, OutputTrap, Struct.
3866
3871
3867 2001-12-05 Fernando Perez <fperez@colorado.edu>
3872 2001-12-05 Fernando Perez <fperez@colorado.edu>
3868
3873
3869 * IPython turns 21! Released version 0.1.21, as a candidate for
3874 * IPython turns 21! Released version 0.1.21, as a candidate for
3870 public consumption. If all goes well, release in a few days.
3875 public consumption. If all goes well, release in a few days.
3871
3876
3872 * Fixed path bug (files in Extensions/ directory wouldn't be found
3877 * Fixed path bug (files in Extensions/ directory wouldn't be found
3873 unless IPython/ was explicitly in sys.path).
3878 unless IPython/ was explicitly in sys.path).
3874
3879
3875 * Extended the FlexCompleter class as MagicCompleter to allow
3880 * Extended the FlexCompleter class as MagicCompleter to allow
3876 completion of @-starting lines.
3881 completion of @-starting lines.
3877
3882
3878 * Created __release__.py file as a central repository for release
3883 * Created __release__.py file as a central repository for release
3879 info that other files can read from.
3884 info that other files can read from.
3880
3885
3881 * Fixed small bug in logging: when logging was turned on in
3886 * Fixed small bug in logging: when logging was turned on in
3882 mid-session, old lines with special meanings (!@?) were being
3887 mid-session, old lines with special meanings (!@?) were being
3883 logged without the prepended comment, which is necessary since
3888 logged without the prepended comment, which is necessary since
3884 they are not truly valid python syntax. This should make session
3889 they are not truly valid python syntax. This should make session
3885 restores produce less errors.
3890 restores produce less errors.
3886
3891
3887 * The namespace cleanup forced me to make a FlexCompleter class
3892 * The namespace cleanup forced me to make a FlexCompleter class
3888 which is nothing but a ripoff of rlcompleter, but with selectable
3893 which is nothing but a ripoff of rlcompleter, but with selectable
3889 namespace (rlcompleter only works in __main__.__dict__). I'll try
3894 namespace (rlcompleter only works in __main__.__dict__). I'll try
3890 to submit a note to the authors to see if this change can be
3895 to submit a note to the authors to see if this change can be
3891 incorporated in future rlcompleter releases (Dec.6: done)
3896 incorporated in future rlcompleter releases (Dec.6: done)
3892
3897
3893 * More fixes to namespace handling. It was a mess! Now all
3898 * More fixes to namespace handling. It was a mess! Now all
3894 explicit references to __main__.__dict__ are gone (except when
3899 explicit references to __main__.__dict__ are gone (except when
3895 really needed) and everything is handled through the namespace
3900 really needed) and everything is handled through the namespace
3896 dicts in the IPython instance. We seem to be getting somewhere
3901 dicts in the IPython instance. We seem to be getting somewhere
3897 with this, finally...
3902 with this, finally...
3898
3903
3899 * Small documentation updates.
3904 * Small documentation updates.
3900
3905
3901 * Created the Extensions directory under IPython (with an
3906 * Created the Extensions directory under IPython (with an
3902 __init__.py). Put the PhysicalQ stuff there. This directory should
3907 __init__.py). Put the PhysicalQ stuff there. This directory should
3903 be used for all special-purpose extensions.
3908 be used for all special-purpose extensions.
3904
3909
3905 * File renaming:
3910 * File renaming:
3906 ipythonlib --> ipmaker
3911 ipythonlib --> ipmaker
3907 ipplib --> iplib
3912 ipplib --> iplib
3908 This makes a bit more sense in terms of what these files actually do.
3913 This makes a bit more sense in terms of what these files actually do.
3909
3914
3910 * Moved all the classes and functions in ipythonlib to ipplib, so
3915 * Moved all the classes and functions in ipythonlib to ipplib, so
3911 now ipythonlib only has make_IPython(). This will ease up its
3916 now ipythonlib only has make_IPython(). This will ease up its
3912 splitting in smaller functional chunks later.
3917 splitting in smaller functional chunks later.
3913
3918
3914 * Cleaned up (done, I think) output of @whos. Better column
3919 * Cleaned up (done, I think) output of @whos. Better column
3915 formatting, and now shows str(var) for as much as it can, which is
3920 formatting, and now shows str(var) for as much as it can, which is
3916 typically what one gets with a 'print var'.
3921 typically what one gets with a 'print var'.
3917
3922
3918 2001-12-04 Fernando Perez <fperez@colorado.edu>
3923 2001-12-04 Fernando Perez <fperez@colorado.edu>
3919
3924
3920 * Fixed namespace problems. Now builtin/IPyhton/user names get
3925 * Fixed namespace problems. Now builtin/IPyhton/user names get
3921 properly reported in their namespace. Internal namespace handling
3926 properly reported in their namespace. Internal namespace handling
3922 is finally getting decent (not perfect yet, but much better than
3927 is finally getting decent (not perfect yet, but much better than
3923 the ad-hoc mess we had).
3928 the ad-hoc mess we had).
3924
3929
3925 * Removed -exit option. If people just want to run a python
3930 * Removed -exit option. If people just want to run a python
3926 script, that's what the normal interpreter is for. Less
3931 script, that's what the normal interpreter is for. Less
3927 unnecessary options, less chances for bugs.
3932 unnecessary options, less chances for bugs.
3928
3933
3929 * Added a crash handler which generates a complete post-mortem if
3934 * Added a crash handler which generates a complete post-mortem if
3930 IPython crashes. This will help a lot in tracking bugs down the
3935 IPython crashes. This will help a lot in tracking bugs down the
3931 road.
3936 road.
3932
3937
3933 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3938 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3934 which were boud to functions being reassigned would bypass the
3939 which were boud to functions being reassigned would bypass the
3935 logger, breaking the sync of _il with the prompt counter. This
3940 logger, breaking the sync of _il with the prompt counter. This
3936 would then crash IPython later when a new line was logged.
3941 would then crash IPython later when a new line was logged.
3937
3942
3938 2001-12-02 Fernando Perez <fperez@colorado.edu>
3943 2001-12-02 Fernando Perez <fperez@colorado.edu>
3939
3944
3940 * Made IPython a package. This means people don't have to clutter
3945 * Made IPython a package. This means people don't have to clutter
3941 their sys.path with yet another directory. Changed the INSTALL
3946 their sys.path with yet another directory. Changed the INSTALL
3942 file accordingly.
3947 file accordingly.
3943
3948
3944 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3949 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3945 sorts its output (so @who shows it sorted) and @whos formats the
3950 sorts its output (so @who shows it sorted) and @whos formats the
3946 table according to the width of the first column. Nicer, easier to
3951 table according to the width of the first column. Nicer, easier to
3947 read. Todo: write a generic table_format() which takes a list of
3952 read. Todo: write a generic table_format() which takes a list of
3948 lists and prints it nicely formatted, with optional row/column
3953 lists and prints it nicely formatted, with optional row/column
3949 separators and proper padding and justification.
3954 separators and proper padding and justification.
3950
3955
3951 * Released 0.1.20
3956 * Released 0.1.20
3952
3957
3953 * Fixed bug in @log which would reverse the inputcache list (a
3958 * Fixed bug in @log which would reverse the inputcache list (a
3954 copy operation was missing).
3959 copy operation was missing).
3955
3960
3956 * Code cleanup. @config was changed to use page(). Better, since
3961 * Code cleanup. @config was changed to use page(). Better, since
3957 its output is always quite long.
3962 its output is always quite long.
3958
3963
3959 * Itpl is back as a dependency. I was having too many problems
3964 * Itpl is back as a dependency. I was having too many problems
3960 getting the parametric aliases to work reliably, and it's just
3965 getting the parametric aliases to work reliably, and it's just
3961 easier to code weird string operations with it than playing %()s
3966 easier to code weird string operations with it than playing %()s
3962 games. It's only ~6k, so I don't think it's too big a deal.
3967 games. It's only ~6k, so I don't think it's too big a deal.
3963
3968
3964 * Found (and fixed) a very nasty bug with history. !lines weren't
3969 * Found (and fixed) a very nasty bug with history. !lines weren't
3965 getting cached, and the out of sync caches would crash
3970 getting cached, and the out of sync caches would crash
3966 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3971 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3967 division of labor a bit better. Bug fixed, cleaner structure.
3972 division of labor a bit better. Bug fixed, cleaner structure.
3968
3973
3969 2001-12-01 Fernando Perez <fperez@colorado.edu>
3974 2001-12-01 Fernando Perez <fperez@colorado.edu>
3970
3975
3971 * Released 0.1.19
3976 * Released 0.1.19
3972
3977
3973 * Added option -n to @hist to prevent line number printing. Much
3978 * Added option -n to @hist to prevent line number printing. Much
3974 easier to copy/paste code this way.
3979 easier to copy/paste code this way.
3975
3980
3976 * Created global _il to hold the input list. Allows easy
3981 * Created global _il to hold the input list. Allows easy
3977 re-execution of blocks of code by slicing it (inspired by Janko's
3982 re-execution of blocks of code by slicing it (inspired by Janko's
3978 comment on 'macros').
3983 comment on 'macros').
3979
3984
3980 * Small fixes and doc updates.
3985 * Small fixes and doc updates.
3981
3986
3982 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3987 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3983 much too fragile with automagic. Handles properly multi-line
3988 much too fragile with automagic. Handles properly multi-line
3984 statements and takes parameters.
3989 statements and takes parameters.
3985
3990
3986 2001-11-30 Fernando Perez <fperez@colorado.edu>
3991 2001-11-30 Fernando Perez <fperez@colorado.edu>
3987
3992
3988 * Version 0.1.18 released.
3993 * Version 0.1.18 released.
3989
3994
3990 * Fixed nasty namespace bug in initial module imports.
3995 * Fixed nasty namespace bug in initial module imports.
3991
3996
3992 * Added copyright/license notes to all code files (except
3997 * Added copyright/license notes to all code files (except
3993 DPyGetOpt). For the time being, LGPL. That could change.
3998 DPyGetOpt). For the time being, LGPL. That could change.
3994
3999
3995 * Rewrote a much nicer README, updated INSTALL, cleaned up
4000 * Rewrote a much nicer README, updated INSTALL, cleaned up
3996 ipythonrc-* samples.
4001 ipythonrc-* samples.
3997
4002
3998 * Overall code/documentation cleanup. Basically ready for
4003 * Overall code/documentation cleanup. Basically ready for
3999 release. Only remaining thing: licence decision (LGPL?).
4004 release. Only remaining thing: licence decision (LGPL?).
4000
4005
4001 * Converted load_config to a class, ConfigLoader. Now recursion
4006 * Converted load_config to a class, ConfigLoader. Now recursion
4002 control is better organized. Doesn't include the same file twice.
4007 control is better organized. Doesn't include the same file twice.
4003
4008
4004 2001-11-29 Fernando Perez <fperez@colorado.edu>
4009 2001-11-29 Fernando Perez <fperez@colorado.edu>
4005
4010
4006 * Got input history working. Changed output history variables from
4011 * Got input history working. Changed output history variables from
4007 _p to _o so that _i is for input and _o for output. Just cleaner
4012 _p to _o so that _i is for input and _o for output. Just cleaner
4008 convention.
4013 convention.
4009
4014
4010 * Implemented parametric aliases. This pretty much allows the
4015 * Implemented parametric aliases. This pretty much allows the
4011 alias system to offer full-blown shell convenience, I think.
4016 alias system to offer full-blown shell convenience, I think.
4012
4017
4013 * Version 0.1.17 released, 0.1.18 opened.
4018 * Version 0.1.17 released, 0.1.18 opened.
4014
4019
4015 * dot_ipython/ipythonrc (alias): added documentation.
4020 * dot_ipython/ipythonrc (alias): added documentation.
4016 (xcolor): Fixed small bug (xcolors -> xcolor)
4021 (xcolor): Fixed small bug (xcolors -> xcolor)
4017
4022
4018 * Changed the alias system. Now alias is a magic command to define
4023 * Changed the alias system. Now alias is a magic command to define
4019 aliases just like the shell. Rationale: the builtin magics should
4024 aliases just like the shell. Rationale: the builtin magics should
4020 be there for things deeply connected to IPython's
4025 be there for things deeply connected to IPython's
4021 architecture. And this is a much lighter system for what I think
4026 architecture. And this is a much lighter system for what I think
4022 is the really important feature: allowing users to define quickly
4027 is the really important feature: allowing users to define quickly
4023 magics that will do shell things for them, so they can customize
4028 magics that will do shell things for them, so they can customize
4024 IPython easily to match their work habits. If someone is really
4029 IPython easily to match their work habits. If someone is really
4025 desperate to have another name for a builtin alias, they can
4030 desperate to have another name for a builtin alias, they can
4026 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4031 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4027 works.
4032 works.
4028
4033
4029 2001-11-28 Fernando Perez <fperez@colorado.edu>
4034 2001-11-28 Fernando Perez <fperez@colorado.edu>
4030
4035
4031 * Changed @file so that it opens the source file at the proper
4036 * Changed @file so that it opens the source file at the proper
4032 line. Since it uses less, if your EDITOR environment is
4037 line. Since it uses less, if your EDITOR environment is
4033 configured, typing v will immediately open your editor of choice
4038 configured, typing v will immediately open your editor of choice
4034 right at the line where the object is defined. Not as quick as
4039 right at the line where the object is defined. Not as quick as
4035 having a direct @edit command, but for all intents and purposes it
4040 having a direct @edit command, but for all intents and purposes it
4036 works. And I don't have to worry about writing @edit to deal with
4041 works. And I don't have to worry about writing @edit to deal with
4037 all the editors, less does that.
4042 all the editors, less does that.
4038
4043
4039 * Version 0.1.16 released, 0.1.17 opened.
4044 * Version 0.1.16 released, 0.1.17 opened.
4040
4045
4041 * Fixed some nasty bugs in the page/page_dumb combo that could
4046 * Fixed some nasty bugs in the page/page_dumb combo that could
4042 crash IPython.
4047 crash IPython.
4043
4048
4044 2001-11-27 Fernando Perez <fperez@colorado.edu>
4049 2001-11-27 Fernando Perez <fperez@colorado.edu>
4045
4050
4046 * Version 0.1.15 released, 0.1.16 opened.
4051 * Version 0.1.15 released, 0.1.16 opened.
4047
4052
4048 * Finally got ? and ?? to work for undefined things: now it's
4053 * Finally got ? and ?? to work for undefined things: now it's
4049 possible to type {}.get? and get information about the get method
4054 possible to type {}.get? and get information about the get method
4050 of dicts, or os.path? even if only os is defined (so technically
4055 of dicts, or os.path? even if only os is defined (so technically
4051 os.path isn't). Works at any level. For example, after import os,
4056 os.path isn't). Works at any level. For example, after import os,
4052 os?, os.path?, os.path.abspath? all work. This is great, took some
4057 os?, os.path?, os.path.abspath? all work. This is great, took some
4053 work in _ofind.
4058 work in _ofind.
4054
4059
4055 * Fixed more bugs with logging. The sanest way to do it was to add
4060 * Fixed more bugs with logging. The sanest way to do it was to add
4056 to @log a 'mode' parameter. Killed two in one shot (this mode
4061 to @log a 'mode' parameter. Killed two in one shot (this mode
4057 option was a request of Janko's). I think it's finally clean
4062 option was a request of Janko's). I think it's finally clean
4058 (famous last words).
4063 (famous last words).
4059
4064
4060 * Added a page_dumb() pager which does a decent job of paging on
4065 * Added a page_dumb() pager which does a decent job of paging on
4061 screen, if better things (like less) aren't available. One less
4066 screen, if better things (like less) aren't available. One less
4062 unix dependency (someday maybe somebody will port this to
4067 unix dependency (someday maybe somebody will port this to
4063 windows).
4068 windows).
4064
4069
4065 * Fixed problem in magic_log: would lock of logging out if log
4070 * Fixed problem in magic_log: would lock of logging out if log
4066 creation failed (because it would still think it had succeeded).
4071 creation failed (because it would still think it had succeeded).
4067
4072
4068 * Improved the page() function using curses to auto-detect screen
4073 * Improved the page() function using curses to auto-detect screen
4069 size. Now it can make a much better decision on whether to print
4074 size. Now it can make a much better decision on whether to print
4070 or page a string. Option screen_length was modified: a value 0
4075 or page a string. Option screen_length was modified: a value 0
4071 means auto-detect, and that's the default now.
4076 means auto-detect, and that's the default now.
4072
4077
4073 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4078 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4074 go out. I'll test it for a few days, then talk to Janko about
4079 go out. I'll test it for a few days, then talk to Janko about
4075 licences and announce it.
4080 licences and announce it.
4076
4081
4077 * Fixed the length of the auto-generated ---> prompt which appears
4082 * Fixed the length of the auto-generated ---> prompt which appears
4078 for auto-parens and auto-quotes. Getting this right isn't trivial,
4083 for auto-parens and auto-quotes. Getting this right isn't trivial,
4079 with all the color escapes, different prompt types and optional
4084 with all the color escapes, different prompt types and optional
4080 separators. But it seems to be working in all the combinations.
4085 separators. But it seems to be working in all the combinations.
4081
4086
4082 2001-11-26 Fernando Perez <fperez@colorado.edu>
4087 2001-11-26 Fernando Perez <fperez@colorado.edu>
4083
4088
4084 * Wrote a regexp filter to get option types from the option names
4089 * Wrote a regexp filter to get option types from the option names
4085 string. This eliminates the need to manually keep two duplicate
4090 string. This eliminates the need to manually keep two duplicate
4086 lists.
4091 lists.
4087
4092
4088 * Removed the unneeded check_option_names. Now options are handled
4093 * Removed the unneeded check_option_names. Now options are handled
4089 in a much saner manner and it's easy to visually check that things
4094 in a much saner manner and it's easy to visually check that things
4090 are ok.
4095 are ok.
4091
4096
4092 * Updated version numbers on all files I modified to carry a
4097 * Updated version numbers on all files I modified to carry a
4093 notice so Janko and Nathan have clear version markers.
4098 notice so Janko and Nathan have clear version markers.
4094
4099
4095 * Updated docstring for ultraTB with my changes. I should send
4100 * Updated docstring for ultraTB with my changes. I should send
4096 this to Nathan.
4101 this to Nathan.
4097
4102
4098 * Lots of small fixes. Ran everything through pychecker again.
4103 * Lots of small fixes. Ran everything through pychecker again.
4099
4104
4100 * Made loading of deep_reload an cmd line option. If it's not too
4105 * Made loading of deep_reload an cmd line option. If it's not too
4101 kosher, now people can just disable it. With -nodeep_reload it's
4106 kosher, now people can just disable it. With -nodeep_reload it's
4102 still available as dreload(), it just won't overwrite reload().
4107 still available as dreload(), it just won't overwrite reload().
4103
4108
4104 * Moved many options to the no| form (-opt and -noopt
4109 * Moved many options to the no| form (-opt and -noopt
4105 accepted). Cleaner.
4110 accepted). Cleaner.
4106
4111
4107 * Changed magic_log so that if called with no parameters, it uses
4112 * Changed magic_log so that if called with no parameters, it uses
4108 'rotate' mode. That way auto-generated logs aren't automatically
4113 'rotate' mode. That way auto-generated logs aren't automatically
4109 over-written. For normal logs, now a backup is made if it exists
4114 over-written. For normal logs, now a backup is made if it exists
4110 (only 1 level of backups). A new 'backup' mode was added to the
4115 (only 1 level of backups). A new 'backup' mode was added to the
4111 Logger class to support this. This was a request by Janko.
4116 Logger class to support this. This was a request by Janko.
4112
4117
4113 * Added @logoff/@logon to stop/restart an active log.
4118 * Added @logoff/@logon to stop/restart an active log.
4114
4119
4115 * Fixed a lot of bugs in log saving/replay. It was pretty
4120 * Fixed a lot of bugs in log saving/replay. It was pretty
4116 broken. Now special lines (!@,/) appear properly in the command
4121 broken. Now special lines (!@,/) appear properly in the command
4117 history after a log replay.
4122 history after a log replay.
4118
4123
4119 * Tried and failed to implement full session saving via pickle. My
4124 * Tried and failed to implement full session saving via pickle. My
4120 idea was to pickle __main__.__dict__, but modules can't be
4125 idea was to pickle __main__.__dict__, but modules can't be
4121 pickled. This would be a better alternative to replaying logs, but
4126 pickled. This would be a better alternative to replaying logs, but
4122 seems quite tricky to get to work. Changed -session to be called
4127 seems quite tricky to get to work. Changed -session to be called
4123 -logplay, which more accurately reflects what it does. And if we
4128 -logplay, which more accurately reflects what it does. And if we
4124 ever get real session saving working, -session is now available.
4129 ever get real session saving working, -session is now available.
4125
4130
4126 * Implemented color schemes for prompts also. As for tracebacks,
4131 * Implemented color schemes for prompts also. As for tracebacks,
4127 currently only NoColor and Linux are supported. But now the
4132 currently only NoColor and Linux are supported. But now the
4128 infrastructure is in place, based on a generic ColorScheme
4133 infrastructure is in place, based on a generic ColorScheme
4129 class. So writing and activating new schemes both for the prompts
4134 class. So writing and activating new schemes both for the prompts
4130 and the tracebacks should be straightforward.
4135 and the tracebacks should be straightforward.
4131
4136
4132 * Version 0.1.13 released, 0.1.14 opened.
4137 * Version 0.1.13 released, 0.1.14 opened.
4133
4138
4134 * Changed handling of options for output cache. Now counter is
4139 * Changed handling of options for output cache. Now counter is
4135 hardwired starting at 1 and one specifies the maximum number of
4140 hardwired starting at 1 and one specifies the maximum number of
4136 entries *in the outcache* (not the max prompt counter). This is
4141 entries *in the outcache* (not the max prompt counter). This is
4137 much better, since many statements won't increase the cache
4142 much better, since many statements won't increase the cache
4138 count. It also eliminated some confusing options, now there's only
4143 count. It also eliminated some confusing options, now there's only
4139 one: cache_size.
4144 one: cache_size.
4140
4145
4141 * Added 'alias' magic function and magic_alias option in the
4146 * Added 'alias' magic function and magic_alias option in the
4142 ipythonrc file. Now the user can easily define whatever names he
4147 ipythonrc file. Now the user can easily define whatever names he
4143 wants for the magic functions without having to play weird
4148 wants for the magic functions without having to play weird
4144 namespace games. This gives IPython a real shell-like feel.
4149 namespace games. This gives IPython a real shell-like feel.
4145
4150
4146 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4151 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4147 @ or not).
4152 @ or not).
4148
4153
4149 This was one of the last remaining 'visible' bugs (that I know
4154 This was one of the last remaining 'visible' bugs (that I know
4150 of). I think if I can clean up the session loading so it works
4155 of). I think if I can clean up the session loading so it works
4151 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4156 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4152 about licensing).
4157 about licensing).
4153
4158
4154 2001-11-25 Fernando Perez <fperez@colorado.edu>
4159 2001-11-25 Fernando Perez <fperez@colorado.edu>
4155
4160
4156 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4161 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4157 there's a cleaner distinction between what ? and ?? show.
4162 there's a cleaner distinction between what ? and ?? show.
4158
4163
4159 * Added screen_length option. Now the user can define his own
4164 * Added screen_length option. Now the user can define his own
4160 screen size for page() operations.
4165 screen size for page() operations.
4161
4166
4162 * Implemented magic shell-like functions with automatic code
4167 * Implemented magic shell-like functions with automatic code
4163 generation. Now adding another function is just a matter of adding
4168 generation. Now adding another function is just a matter of adding
4164 an entry to a dict, and the function is dynamically generated at
4169 an entry to a dict, and the function is dynamically generated at
4165 run-time. Python has some really cool features!
4170 run-time. Python has some really cool features!
4166
4171
4167 * Renamed many options to cleanup conventions a little. Now all
4172 * Renamed many options to cleanup conventions a little. Now all
4168 are lowercase, and only underscores where needed. Also in the code
4173 are lowercase, and only underscores where needed. Also in the code
4169 option name tables are clearer.
4174 option name tables are clearer.
4170
4175
4171 * Changed prompts a little. Now input is 'In [n]:' instead of
4176 * Changed prompts a little. Now input is 'In [n]:' instead of
4172 'In[n]:='. This allows it the numbers to be aligned with the
4177 'In[n]:='. This allows it the numbers to be aligned with the
4173 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4178 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4174 Python (it was a Mathematica thing). The '...' continuation prompt
4179 Python (it was a Mathematica thing). The '...' continuation prompt
4175 was also changed a little to align better.
4180 was also changed a little to align better.
4176
4181
4177 * Fixed bug when flushing output cache. Not all _p<n> variables
4182 * Fixed bug when flushing output cache. Not all _p<n> variables
4178 exist, so their deletion needs to be wrapped in a try:
4183 exist, so their deletion needs to be wrapped in a try:
4179
4184
4180 * Figured out how to properly use inspect.formatargspec() (it
4185 * Figured out how to properly use inspect.formatargspec() (it
4181 requires the args preceded by *). So I removed all the code from
4186 requires the args preceded by *). So I removed all the code from
4182 _get_pdef in Magic, which was just replicating that.
4187 _get_pdef in Magic, which was just replicating that.
4183
4188
4184 * Added test to prefilter to allow redefining magic function names
4189 * Added test to prefilter to allow redefining magic function names
4185 as variables. This is ok, since the @ form is always available,
4190 as variables. This is ok, since the @ form is always available,
4186 but whe should allow the user to define a variable called 'ls' if
4191 but whe should allow the user to define a variable called 'ls' if
4187 he needs it.
4192 he needs it.
4188
4193
4189 * Moved the ToDo information from README into a separate ToDo.
4194 * Moved the ToDo information from README into a separate ToDo.
4190
4195
4191 * General code cleanup and small bugfixes. I think it's close to a
4196 * General code cleanup and small bugfixes. I think it's close to a
4192 state where it can be released, obviously with a big 'beta'
4197 state where it can be released, obviously with a big 'beta'
4193 warning on it.
4198 warning on it.
4194
4199
4195 * Got the magic function split to work. Now all magics are defined
4200 * Got the magic function split to work. Now all magics are defined
4196 in a separate class. It just organizes things a bit, and now
4201 in a separate class. It just organizes things a bit, and now
4197 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4202 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4198 was too long).
4203 was too long).
4199
4204
4200 * Changed @clear to @reset to avoid potential confusions with
4205 * Changed @clear to @reset to avoid potential confusions with
4201 the shell command clear. Also renamed @cl to @clear, which does
4206 the shell command clear. Also renamed @cl to @clear, which does
4202 exactly what people expect it to from their shell experience.
4207 exactly what people expect it to from their shell experience.
4203
4208
4204 Added a check to the @reset command (since it's so
4209 Added a check to the @reset command (since it's so
4205 destructive, it's probably a good idea to ask for confirmation).
4210 destructive, it's probably a good idea to ask for confirmation).
4206 But now reset only works for full namespace resetting. Since the
4211 But now reset only works for full namespace resetting. Since the
4207 del keyword is already there for deleting a few specific
4212 del keyword is already there for deleting a few specific
4208 variables, I don't see the point of having a redundant magic
4213 variables, I don't see the point of having a redundant magic
4209 function for the same task.
4214 function for the same task.
4210
4215
4211 2001-11-24 Fernando Perez <fperez@colorado.edu>
4216 2001-11-24 Fernando Perez <fperez@colorado.edu>
4212
4217
4213 * Updated the builtin docs (esp. the ? ones).
4218 * Updated the builtin docs (esp. the ? ones).
4214
4219
4215 * Ran all the code through pychecker. Not terribly impressed with
4220 * Ran all the code through pychecker. Not terribly impressed with
4216 it: lots of spurious warnings and didn't really find anything of
4221 it: lots of spurious warnings and didn't really find anything of
4217 substance (just a few modules being imported and not used).
4222 substance (just a few modules being imported and not used).
4218
4223
4219 * Implemented the new ultraTB functionality into IPython. New
4224 * Implemented the new ultraTB functionality into IPython. New
4220 option: xcolors. This chooses color scheme. xmode now only selects
4225 option: xcolors. This chooses color scheme. xmode now only selects
4221 between Plain and Verbose. Better orthogonality.
4226 between Plain and Verbose. Better orthogonality.
4222
4227
4223 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4228 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4224 mode and color scheme for the exception handlers. Now it's
4229 mode and color scheme for the exception handlers. Now it's
4225 possible to have the verbose traceback with no coloring.
4230 possible to have the verbose traceback with no coloring.
4226
4231
4227 2001-11-23 Fernando Perez <fperez@colorado.edu>
4232 2001-11-23 Fernando Perez <fperez@colorado.edu>
4228
4233
4229 * Version 0.1.12 released, 0.1.13 opened.
4234 * Version 0.1.12 released, 0.1.13 opened.
4230
4235
4231 * Removed option to set auto-quote and auto-paren escapes by
4236 * Removed option to set auto-quote and auto-paren escapes by
4232 user. The chances of breaking valid syntax are just too high. If
4237 user. The chances of breaking valid syntax are just too high. If
4233 someone *really* wants, they can always dig into the code.
4238 someone *really* wants, they can always dig into the code.
4234
4239
4235 * Made prompt separators configurable.
4240 * Made prompt separators configurable.
4236
4241
4237 2001-11-22 Fernando Perez <fperez@colorado.edu>
4242 2001-11-22 Fernando Perez <fperez@colorado.edu>
4238
4243
4239 * Small bugfixes in many places.
4244 * Small bugfixes in many places.
4240
4245
4241 * Removed the MyCompleter class from ipplib. It seemed redundant
4246 * Removed the MyCompleter class from ipplib. It seemed redundant
4242 with the C-p,C-n history search functionality. Less code to
4247 with the C-p,C-n history search functionality. Less code to
4243 maintain.
4248 maintain.
4244
4249
4245 * Moved all the original ipython.py code into ipythonlib.py. Right
4250 * Moved all the original ipython.py code into ipythonlib.py. Right
4246 now it's just one big dump into a function called make_IPython, so
4251 now it's just one big dump into a function called make_IPython, so
4247 no real modularity has been gained. But at least it makes the
4252 no real modularity has been gained. But at least it makes the
4248 wrapper script tiny, and since ipythonlib is a module, it gets
4253 wrapper script tiny, and since ipythonlib is a module, it gets
4249 compiled and startup is much faster.
4254 compiled and startup is much faster.
4250
4255
4251 This is a reasobably 'deep' change, so we should test it for a
4256 This is a reasobably 'deep' change, so we should test it for a
4252 while without messing too much more with the code.
4257 while without messing too much more with the code.
4253
4258
4254 2001-11-21 Fernando Perez <fperez@colorado.edu>
4259 2001-11-21 Fernando Perez <fperez@colorado.edu>
4255
4260
4256 * Version 0.1.11 released, 0.1.12 opened for further work.
4261 * Version 0.1.11 released, 0.1.12 opened for further work.
4257
4262
4258 * Removed dependency on Itpl. It was only needed in one place. It
4263 * Removed dependency on Itpl. It was only needed in one place. It
4259 would be nice if this became part of python, though. It makes life
4264 would be nice if this became part of python, though. It makes life
4260 *a lot* easier in some cases.
4265 *a lot* easier in some cases.
4261
4266
4262 * Simplified the prefilter code a bit. Now all handlers are
4267 * Simplified the prefilter code a bit. Now all handlers are
4263 expected to explicitly return a value (at least a blank string).
4268 expected to explicitly return a value (at least a blank string).
4264
4269
4265 * Heavy edits in ipplib. Removed the help system altogether. Now
4270 * Heavy edits in ipplib. Removed the help system altogether. Now
4266 obj?/?? is used for inspecting objects, a magic @doc prints
4271 obj?/?? is used for inspecting objects, a magic @doc prints
4267 docstrings, and full-blown Python help is accessed via the 'help'
4272 docstrings, and full-blown Python help is accessed via the 'help'
4268 keyword. This cleans up a lot of code (less to maintain) and does
4273 keyword. This cleans up a lot of code (less to maintain) and does
4269 the job. Since 'help' is now a standard Python component, might as
4274 the job. Since 'help' is now a standard Python component, might as
4270 well use it and remove duplicate functionality.
4275 well use it and remove duplicate functionality.
4271
4276
4272 Also removed the option to use ipplib as a standalone program. By
4277 Also removed the option to use ipplib as a standalone program. By
4273 now it's too dependent on other parts of IPython to function alone.
4278 now it's too dependent on other parts of IPython to function alone.
4274
4279
4275 * Fixed bug in genutils.pager. It would crash if the pager was
4280 * Fixed bug in genutils.pager. It would crash if the pager was
4276 exited immediately after opening (broken pipe).
4281 exited immediately after opening (broken pipe).
4277
4282
4278 * Trimmed down the VerboseTB reporting a little. The header is
4283 * Trimmed down the VerboseTB reporting a little. The header is
4279 much shorter now and the repeated exception arguments at the end
4284 much shorter now and the repeated exception arguments at the end
4280 have been removed. For interactive use the old header seemed a bit
4285 have been removed. For interactive use the old header seemed a bit
4281 excessive.
4286 excessive.
4282
4287
4283 * Fixed small bug in output of @whos for variables with multi-word
4288 * Fixed small bug in output of @whos for variables with multi-word
4284 types (only first word was displayed).
4289 types (only first word was displayed).
4285
4290
4286 2001-11-17 Fernando Perez <fperez@colorado.edu>
4291 2001-11-17 Fernando Perez <fperez@colorado.edu>
4287
4292
4288 * Version 0.1.10 released, 0.1.11 opened for further work.
4293 * Version 0.1.10 released, 0.1.11 opened for further work.
4289
4294
4290 * Modified dirs and friends. dirs now *returns* the stack (not
4295 * Modified dirs and friends. dirs now *returns* the stack (not
4291 prints), so one can manipulate it as a variable. Convenient to
4296 prints), so one can manipulate it as a variable. Convenient to
4292 travel along many directories.
4297 travel along many directories.
4293
4298
4294 * Fixed bug in magic_pdef: would only work with functions with
4299 * Fixed bug in magic_pdef: would only work with functions with
4295 arguments with default values.
4300 arguments with default values.
4296
4301
4297 2001-11-14 Fernando Perez <fperez@colorado.edu>
4302 2001-11-14 Fernando Perez <fperez@colorado.edu>
4298
4303
4299 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4304 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4300 example with IPython. Various other minor fixes and cleanups.
4305 example with IPython. Various other minor fixes and cleanups.
4301
4306
4302 * Version 0.1.9 released, 0.1.10 opened for further work.
4307 * Version 0.1.9 released, 0.1.10 opened for further work.
4303
4308
4304 * Added sys.path to the list of directories searched in the
4309 * Added sys.path to the list of directories searched in the
4305 execfile= option. It used to be the current directory and the
4310 execfile= option. It used to be the current directory and the
4306 user's IPYTHONDIR only.
4311 user's IPYTHONDIR only.
4307
4312
4308 2001-11-13 Fernando Perez <fperez@colorado.edu>
4313 2001-11-13 Fernando Perez <fperez@colorado.edu>
4309
4314
4310 * Reinstated the raw_input/prefilter separation that Janko had
4315 * Reinstated the raw_input/prefilter separation that Janko had
4311 initially. This gives a more convenient setup for extending the
4316 initially. This gives a more convenient setup for extending the
4312 pre-processor from the outside: raw_input always gets a string,
4317 pre-processor from the outside: raw_input always gets a string,
4313 and prefilter has to process it. We can then redefine prefilter
4318 and prefilter has to process it. We can then redefine prefilter
4314 from the outside and implement extensions for special
4319 from the outside and implement extensions for special
4315 purposes.
4320 purposes.
4316
4321
4317 Today I got one for inputting PhysicalQuantity objects
4322 Today I got one for inputting PhysicalQuantity objects
4318 (from Scientific) without needing any function calls at
4323 (from Scientific) without needing any function calls at
4319 all. Extremely convenient, and it's all done as a user-level
4324 all. Extremely convenient, and it's all done as a user-level
4320 extension (no IPython code was touched). Now instead of:
4325 extension (no IPython code was touched). Now instead of:
4321 a = PhysicalQuantity(4.2,'m/s**2')
4326 a = PhysicalQuantity(4.2,'m/s**2')
4322 one can simply say
4327 one can simply say
4323 a = 4.2 m/s**2
4328 a = 4.2 m/s**2
4324 or even
4329 or even
4325 a = 4.2 m/s^2
4330 a = 4.2 m/s^2
4326
4331
4327 I use this, but it's also a proof of concept: IPython really is
4332 I use this, but it's also a proof of concept: IPython really is
4328 fully user-extensible, even at the level of the parsing of the
4333 fully user-extensible, even at the level of the parsing of the
4329 command line. It's not trivial, but it's perfectly doable.
4334 command line. It's not trivial, but it's perfectly doable.
4330
4335
4331 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4336 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4332 the problem of modules being loaded in the inverse order in which
4337 the problem of modules being loaded in the inverse order in which
4333 they were defined in
4338 they were defined in
4334
4339
4335 * Version 0.1.8 released, 0.1.9 opened for further work.
4340 * Version 0.1.8 released, 0.1.9 opened for further work.
4336
4341
4337 * Added magics pdef, source and file. They respectively show the
4342 * Added magics pdef, source and file. They respectively show the
4338 definition line ('prototype' in C), source code and full python
4343 definition line ('prototype' in C), source code and full python
4339 file for any callable object. The object inspector oinfo uses
4344 file for any callable object. The object inspector oinfo uses
4340 these to show the same information.
4345 these to show the same information.
4341
4346
4342 * Version 0.1.7 released, 0.1.8 opened for further work.
4347 * Version 0.1.7 released, 0.1.8 opened for further work.
4343
4348
4344 * Separated all the magic functions into a class called Magic. The
4349 * Separated all the magic functions into a class called Magic. The
4345 InteractiveShell class was becoming too big for Xemacs to handle
4350 InteractiveShell class was becoming too big for Xemacs to handle
4346 (de-indenting a line would lock it up for 10 seconds while it
4351 (de-indenting a line would lock it up for 10 seconds while it
4347 backtracked on the whole class!)
4352 backtracked on the whole class!)
4348
4353
4349 FIXME: didn't work. It can be done, but right now namespaces are
4354 FIXME: didn't work. It can be done, but right now namespaces are
4350 all messed up. Do it later (reverted it for now, so at least
4355 all messed up. Do it later (reverted it for now, so at least
4351 everything works as before).
4356 everything works as before).
4352
4357
4353 * Got the object introspection system (magic_oinfo) working! I
4358 * Got the object introspection system (magic_oinfo) working! I
4354 think this is pretty much ready for release to Janko, so he can
4359 think this is pretty much ready for release to Janko, so he can
4355 test it for a while and then announce it. Pretty much 100% of what
4360 test it for a while and then announce it. Pretty much 100% of what
4356 I wanted for the 'phase 1' release is ready. Happy, tired.
4361 I wanted for the 'phase 1' release is ready. Happy, tired.
4357
4362
4358 2001-11-12 Fernando Perez <fperez@colorado.edu>
4363 2001-11-12 Fernando Perez <fperez@colorado.edu>
4359
4364
4360 * Version 0.1.6 released, 0.1.7 opened for further work.
4365 * Version 0.1.6 released, 0.1.7 opened for further work.
4361
4366
4362 * Fixed bug in printing: it used to test for truth before
4367 * Fixed bug in printing: it used to test for truth before
4363 printing, so 0 wouldn't print. Now checks for None.
4368 printing, so 0 wouldn't print. Now checks for None.
4364
4369
4365 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4370 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4366 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4371 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4367 reaches by hand into the outputcache. Think of a better way to do
4372 reaches by hand into the outputcache. Think of a better way to do
4368 this later.
4373 this later.
4369
4374
4370 * Various small fixes thanks to Nathan's comments.
4375 * Various small fixes thanks to Nathan's comments.
4371
4376
4372 * Changed magic_pprint to magic_Pprint. This way it doesn't
4377 * Changed magic_pprint to magic_Pprint. This way it doesn't
4373 collide with pprint() and the name is consistent with the command
4378 collide with pprint() and the name is consistent with the command
4374 line option.
4379 line option.
4375
4380
4376 * Changed prompt counter behavior to be fully like
4381 * Changed prompt counter behavior to be fully like
4377 Mathematica's. That is, even input that doesn't return a result
4382 Mathematica's. That is, even input that doesn't return a result
4378 raises the prompt counter. The old behavior was kind of confusing
4383 raises the prompt counter. The old behavior was kind of confusing
4379 (getting the same prompt number several times if the operation
4384 (getting the same prompt number several times if the operation
4380 didn't return a result).
4385 didn't return a result).
4381
4386
4382 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4387 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4383
4388
4384 * Fixed -Classic mode (wasn't working anymore).
4389 * Fixed -Classic mode (wasn't working anymore).
4385
4390
4386 * Added colored prompts using Nathan's new code. Colors are
4391 * Added colored prompts using Nathan's new code. Colors are
4387 currently hardwired, they can be user-configurable. For
4392 currently hardwired, they can be user-configurable. For
4388 developers, they can be chosen in file ipythonlib.py, at the
4393 developers, they can be chosen in file ipythonlib.py, at the
4389 beginning of the CachedOutput class def.
4394 beginning of the CachedOutput class def.
4390
4395
4391 2001-11-11 Fernando Perez <fperez@colorado.edu>
4396 2001-11-11 Fernando Perez <fperez@colorado.edu>
4392
4397
4393 * Version 0.1.5 released, 0.1.6 opened for further work.
4398 * Version 0.1.5 released, 0.1.6 opened for further work.
4394
4399
4395 * Changed magic_env to *return* the environment as a dict (not to
4400 * Changed magic_env to *return* the environment as a dict (not to
4396 print it). This way it prints, but it can also be processed.
4401 print it). This way it prints, but it can also be processed.
4397
4402
4398 * Added Verbose exception reporting to interactive
4403 * Added Verbose exception reporting to interactive
4399 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4404 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4400 traceback. Had to make some changes to the ultraTB file. This is
4405 traceback. Had to make some changes to the ultraTB file. This is
4401 probably the last 'big' thing in my mental todo list. This ties
4406 probably the last 'big' thing in my mental todo list. This ties
4402 in with the next entry:
4407 in with the next entry:
4403
4408
4404 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4409 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4405 has to specify is Plain, Color or Verbose for all exception
4410 has to specify is Plain, Color or Verbose for all exception
4406 handling.
4411 handling.
4407
4412
4408 * Removed ShellServices option. All this can really be done via
4413 * Removed ShellServices option. All this can really be done via
4409 the magic system. It's easier to extend, cleaner and has automatic
4414 the magic system. It's easier to extend, cleaner and has automatic
4410 namespace protection and documentation.
4415 namespace protection and documentation.
4411
4416
4412 2001-11-09 Fernando Perez <fperez@colorado.edu>
4417 2001-11-09 Fernando Perez <fperez@colorado.edu>
4413
4418
4414 * Fixed bug in output cache flushing (missing parameter to
4419 * Fixed bug in output cache flushing (missing parameter to
4415 __init__). Other small bugs fixed (found using pychecker).
4420 __init__). Other small bugs fixed (found using pychecker).
4416
4421
4417 * Version 0.1.4 opened for bugfixing.
4422 * Version 0.1.4 opened for bugfixing.
4418
4423
4419 2001-11-07 Fernando Perez <fperez@colorado.edu>
4424 2001-11-07 Fernando Perez <fperez@colorado.edu>
4420
4425
4421 * Version 0.1.3 released, mainly because of the raw_input bug.
4426 * Version 0.1.3 released, mainly because of the raw_input bug.
4422
4427
4423 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4428 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4424 and when testing for whether things were callable, a call could
4429 and when testing for whether things were callable, a call could
4425 actually be made to certain functions. They would get called again
4430 actually be made to certain functions. They would get called again
4426 once 'really' executed, with a resulting double call. A disaster
4431 once 'really' executed, with a resulting double call. A disaster
4427 in many cases (list.reverse() would never work!).
4432 in many cases (list.reverse() would never work!).
4428
4433
4429 * Removed prefilter() function, moved its code to raw_input (which
4434 * Removed prefilter() function, moved its code to raw_input (which
4430 after all was just a near-empty caller for prefilter). This saves
4435 after all was just a near-empty caller for prefilter). This saves
4431 a function call on every prompt, and simplifies the class a tiny bit.
4436 a function call on every prompt, and simplifies the class a tiny bit.
4432
4437
4433 * Fix _ip to __ip name in magic example file.
4438 * Fix _ip to __ip name in magic example file.
4434
4439
4435 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4440 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4436 work with non-gnu versions of tar.
4441 work with non-gnu versions of tar.
4437
4442
4438 2001-11-06 Fernando Perez <fperez@colorado.edu>
4443 2001-11-06 Fernando Perez <fperez@colorado.edu>
4439
4444
4440 * Version 0.1.2. Just to keep track of the recent changes.
4445 * Version 0.1.2. Just to keep track of the recent changes.
4441
4446
4442 * Fixed nasty bug in output prompt routine. It used to check 'if
4447 * Fixed nasty bug in output prompt routine. It used to check 'if
4443 arg != None...'. Problem is, this fails if arg implements a
4448 arg != None...'. Problem is, this fails if arg implements a
4444 special comparison (__cmp__) which disallows comparing to
4449 special comparison (__cmp__) which disallows comparing to
4445 None. Found it when trying to use the PhysicalQuantity module from
4450 None. Found it when trying to use the PhysicalQuantity module from
4446 ScientificPython.
4451 ScientificPython.
4447
4452
4448 2001-11-05 Fernando Perez <fperez@colorado.edu>
4453 2001-11-05 Fernando Perez <fperez@colorado.edu>
4449
4454
4450 * Also added dirs. Now the pushd/popd/dirs family functions
4455 * Also added dirs. Now the pushd/popd/dirs family functions
4451 basically like the shell, with the added convenience of going home
4456 basically like the shell, with the added convenience of going home
4452 when called with no args.
4457 when called with no args.
4453
4458
4454 * pushd/popd slightly modified to mimic shell behavior more
4459 * pushd/popd slightly modified to mimic shell behavior more
4455 closely.
4460 closely.
4456
4461
4457 * Added env,pushd,popd from ShellServices as magic functions. I
4462 * Added env,pushd,popd from ShellServices as magic functions. I
4458 think the cleanest will be to port all desired functions from
4463 think the cleanest will be to port all desired functions from
4459 ShellServices as magics and remove ShellServices altogether. This
4464 ShellServices as magics and remove ShellServices altogether. This
4460 will provide a single, clean way of adding functionality
4465 will provide a single, clean way of adding functionality
4461 (shell-type or otherwise) to IP.
4466 (shell-type or otherwise) to IP.
4462
4467
4463 2001-11-04 Fernando Perez <fperez@colorado.edu>
4468 2001-11-04 Fernando Perez <fperez@colorado.edu>
4464
4469
4465 * Added .ipython/ directory to sys.path. This way users can keep
4470 * Added .ipython/ directory to sys.path. This way users can keep
4466 customizations there and access them via import.
4471 customizations there and access them via import.
4467
4472
4468 2001-11-03 Fernando Perez <fperez@colorado.edu>
4473 2001-11-03 Fernando Perez <fperez@colorado.edu>
4469
4474
4470 * Opened version 0.1.1 for new changes.
4475 * Opened version 0.1.1 for new changes.
4471
4476
4472 * Changed version number to 0.1.0: first 'public' release, sent to
4477 * Changed version number to 0.1.0: first 'public' release, sent to
4473 Nathan and Janko.
4478 Nathan and Janko.
4474
4479
4475 * Lots of small fixes and tweaks.
4480 * Lots of small fixes and tweaks.
4476
4481
4477 * Minor changes to whos format. Now strings are shown, snipped if
4482 * Minor changes to whos format. Now strings are shown, snipped if
4478 too long.
4483 too long.
4479
4484
4480 * Changed ShellServices to work on __main__ so they show up in @who
4485 * Changed ShellServices to work on __main__ so they show up in @who
4481
4486
4482 * Help also works with ? at the end of a line:
4487 * Help also works with ? at the end of a line:
4483 ?sin and sin?
4488 ?sin and sin?
4484 both produce the same effect. This is nice, as often I use the
4489 both produce the same effect. This is nice, as often I use the
4485 tab-complete to find the name of a method, but I used to then have
4490 tab-complete to find the name of a method, but I used to then have
4486 to go to the beginning of the line to put a ? if I wanted more
4491 to go to the beginning of the line to put a ? if I wanted more
4487 info. Now I can just add the ? and hit return. Convenient.
4492 info. Now I can just add the ? and hit return. Convenient.
4488
4493
4489 2001-11-02 Fernando Perez <fperez@colorado.edu>
4494 2001-11-02 Fernando Perez <fperez@colorado.edu>
4490
4495
4491 * Python version check (>=2.1) added.
4496 * Python version check (>=2.1) added.
4492
4497
4493 * Added LazyPython documentation. At this point the docs are quite
4498 * Added LazyPython documentation. At this point the docs are quite
4494 a mess. A cleanup is in order.
4499 a mess. A cleanup is in order.
4495
4500
4496 * Auto-installer created. For some bizarre reason, the zipfiles
4501 * Auto-installer created. For some bizarre reason, the zipfiles
4497 module isn't working on my system. So I made a tar version
4502 module isn't working on my system. So I made a tar version
4498 (hopefully the command line options in various systems won't kill
4503 (hopefully the command line options in various systems won't kill
4499 me).
4504 me).
4500
4505
4501 * Fixes to Struct in genutils. Now all dictionary-like methods are
4506 * Fixes to Struct in genutils. Now all dictionary-like methods are
4502 protected (reasonably).
4507 protected (reasonably).
4503
4508
4504 * Added pager function to genutils and changed ? to print usage
4509 * Added pager function to genutils and changed ? to print usage
4505 note through it (it was too long).
4510 note through it (it was too long).
4506
4511
4507 * Added the LazyPython functionality. Works great! I changed the
4512 * Added the LazyPython functionality. Works great! I changed the
4508 auto-quote escape to ';', it's on home row and next to '. But
4513 auto-quote escape to ';', it's on home row and next to '. But
4509 both auto-quote and auto-paren (still /) escapes are command-line
4514 both auto-quote and auto-paren (still /) escapes are command-line
4510 parameters.
4515 parameters.
4511
4516
4512
4517
4513 2001-11-01 Fernando Perez <fperez@colorado.edu>
4518 2001-11-01 Fernando Perez <fperez@colorado.edu>
4514
4519
4515 * Version changed to 0.0.7. Fairly large change: configuration now
4520 * Version changed to 0.0.7. Fairly large change: configuration now
4516 is all stored in a directory, by default .ipython. There, all
4521 is all stored in a directory, by default .ipython. There, all
4517 config files have normal looking names (not .names)
4522 config files have normal looking names (not .names)
4518
4523
4519 * Version 0.0.6 Released first to Lucas and Archie as a test
4524 * Version 0.0.6 Released first to Lucas and Archie as a test
4520 run. Since it's the first 'semi-public' release, change version to
4525 run. Since it's the first 'semi-public' release, change version to
4521 > 0.0.6 for any changes now.
4526 > 0.0.6 for any changes now.
4522
4527
4523 * Stuff I had put in the ipplib.py changelog:
4528 * Stuff I had put in the ipplib.py changelog:
4524
4529
4525 Changes to InteractiveShell:
4530 Changes to InteractiveShell:
4526
4531
4527 - Made the usage message a parameter.
4532 - Made the usage message a parameter.
4528
4533
4529 - Require the name of the shell variable to be given. It's a bit
4534 - Require the name of the shell variable to be given. It's a bit
4530 of a hack, but allows the name 'shell' not to be hardwire in the
4535 of a hack, but allows the name 'shell' not to be hardwire in the
4531 magic (@) handler, which is problematic b/c it requires
4536 magic (@) handler, which is problematic b/c it requires
4532 polluting the global namespace with 'shell'. This in turn is
4537 polluting the global namespace with 'shell'. This in turn is
4533 fragile: if a user redefines a variable called shell, things
4538 fragile: if a user redefines a variable called shell, things
4534 break.
4539 break.
4535
4540
4536 - magic @: all functions available through @ need to be defined
4541 - magic @: all functions available through @ need to be defined
4537 as magic_<name>, even though they can be called simply as
4542 as magic_<name>, even though they can be called simply as
4538 @<name>. This allows the special command @magic to gather
4543 @<name>. This allows the special command @magic to gather
4539 information automatically about all existing magic functions,
4544 information automatically about all existing magic functions,
4540 even if they are run-time user extensions, by parsing the shell
4545 even if they are run-time user extensions, by parsing the shell
4541 instance __dict__ looking for special magic_ names.
4546 instance __dict__ looking for special magic_ names.
4542
4547
4543 - mainloop: added *two* local namespace parameters. This allows
4548 - mainloop: added *two* local namespace parameters. This allows
4544 the class to differentiate between parameters which were there
4549 the class to differentiate between parameters which were there
4545 before and after command line initialization was processed. This
4550 before and after command line initialization was processed. This
4546 way, later @who can show things loaded at startup by the
4551 way, later @who can show things loaded at startup by the
4547 user. This trick was necessary to make session saving/reloading
4552 user. This trick was necessary to make session saving/reloading
4548 really work: ideally after saving/exiting/reloading a session,
4553 really work: ideally after saving/exiting/reloading a session,
4549 *everythin* should look the same, including the output of @who. I
4554 *everythin* should look the same, including the output of @who. I
4550 was only able to make this work with this double namespace
4555 was only able to make this work with this double namespace
4551 trick.
4556 trick.
4552
4557
4553 - added a header to the logfile which allows (almost) full
4558 - added a header to the logfile which allows (almost) full
4554 session restoring.
4559 session restoring.
4555
4560
4556 - prepend lines beginning with @ or !, with a and log
4561 - prepend lines beginning with @ or !, with a and log
4557 them. Why? !lines: may be useful to know what you did @lines:
4562 them. Why? !lines: may be useful to know what you did @lines:
4558 they may affect session state. So when restoring a session, at
4563 they may affect session state. So when restoring a session, at
4559 least inform the user of their presence. I couldn't quite get
4564 least inform the user of their presence. I couldn't quite get
4560 them to properly re-execute, but at least the user is warned.
4565 them to properly re-execute, but at least the user is warned.
4561
4566
4562 * Started ChangeLog.
4567 * Started ChangeLog.
@@ -1,392 +1,391 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 \-[no]autocall
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 'str(43)' automatically.
121 .TP
121 .TP
122 .B \-[no]autoindent
122 .B \-[no]autoindent
123 Turn automatic indentation on/off.
123 Turn automatic indentation on/off.
124 .TP
124 .TP
125 .B \-[no]automagic
125 .B \-[no]automagic
126 Make magic commands automatic (without needing their first character
126 Make magic commands automatic (without needing their first character
127 to be @). Type @magic at the IPython prompt for more information.
127 to be %). Type %magic at the IPython prompt for more information.
128 .TP
128 .TP
129 .B \-[no]autoparens
129 .B \-[no]autoedit_syntax
130 Make IPython automatically call any callable object even if you didn't
130 When a syntax error occurs after editing a file, automatically open the file
131 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
131 to the trouble causing line for convenient fixing.
132 automatically.
133 .TP
132 .TP
134 .B \-[no]banner
133 .B \-[no]banner
135 Print the intial information banner (default on).
134 Print the intial information banner (default on).
136 .TP
135 .TP
137 .B \-c <command>
136 .B \-c <command>
138 Execute the given command string, and set sys.argv to ['c']. This is similar
137 Execute the given command string, and set sys.argv to ['c']. This is similar
139 to the \-c option in the normal Python interpreter.
138 to the \-c option in the normal Python interpreter.
140 .TP
139 .TP
141 .B \-cache_size|cs <n>
140 .B \-cache_size|cs <n>
142 Size of the output cache (maximum number of entries to hold in
141 Size of the output cache (maximum number of entries to hold in
143 memory). The default is 1000, you can change it permanently in your
142 memory). The default is 1000, you can change it permanently in your
144 config file. Setting it to 0 completely disables the caching system,
143 config file. Setting it to 0 completely disables the caching system,
145 and the minimum value accepted is 20 (if you provide a value less than
144 and the minimum value accepted is 20 (if you provide a value less than
146 20, it is reset to 0 and a warning is issued). This limit is defined
145 20, it is reset to 0 and a warning is issued). This limit is defined
147 because otherwise you'll spend more time re-flushing a too small cache
146 because otherwise you'll spend more time re-flushing a too small cache
148 than working.
147 than working.
149 .TP
148 .TP
150 .B \-classic|cl
149 .B \-classic|cl
151 Gives IPython a similar feel to the classic Python prompt.
150 Gives IPython a similar feel to the classic Python prompt.
152 .TP
151 .TP
153 .B \-colors <scheme>
152 .B \-colors <scheme>
154 Color scheme for prompts and exception reporting. Currently
153 Color scheme for prompts and exception reporting. Currently
155 implemented: NoColor, Linux, and LightBG.
154 implemented: NoColor, Linux, and LightBG.
156 .TP
155 .TP
157 .B \-[no]color_info
156 .B \-[no]color_info
158 IPython can display information about objects via a set of functions,
157 IPython can display information about objects via a set of functions,
159 and optionally can use colors for this, syntax highlighting source
158 and optionally can use colors for this, syntax highlighting source
160 code and various other elements. However, because this information is
159 code and various other elements. However, because this information is
161 passed through a pager (like 'less') and many pagers get confused with
160 passed through a pager (like 'less') and many pagers get confused with
162 color codes, this option is off by default. You can test it and turn
161 color codes, this option is off by default. You can test it and turn
163 it on permanently in your ipythonrc file if it works for you. As a
162 it on permanently in your ipythonrc file if it works for you. As a
164 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
163 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
165 that in RedHat 7.2 doesn't.
164 that in RedHat 7.2 doesn't.
166 .br
165 .br
167 .sp 1
166 .sp 1
168 Test it and turn it on permanently if it works with your system. The
167 Test it and turn it on permanently if it works with your system. The
169 magic function @color_info allows you to toggle this interactively for
168 magic function @color_info allows you to toggle this interactively for
170 testing.
169 testing.
171 .TP
170 .TP
172 .B \-[no]confirm_exit
171 .B \-[no]confirm_exit
173 Set to confirm when you try to exit IPython with an EOF (Control-D in
172 Set to confirm when you try to exit IPython with an EOF (Control-D in
174 Unix, Control-Z/Enter in Windows). Note that using the magic functions
173 Unix, Control-Z/Enter in Windows). Note that using the magic functions
175 @Exit or @Quit you can force a direct exit, bypassing any
174 @Exit or @Quit you can force a direct exit, bypassing any
176 confirmation.
175 confirmation.
177 .TP
176 .TP
178 .B \-[no]debug
177 .B \-[no]debug
179 Show information about the loading process. Very useful to pin down
178 Show information about the loading process. Very useful to pin down
180 problems with your configuration files or to get details about session
179 problems with your configuration files or to get details about session
181 restores.
180 restores.
182 .TP
181 .TP
183 .B \-[no]deep_reload
182 .B \-[no]deep_reload
184 IPython can use the deep_reload module which reloads changes in
183 IPython can use the deep_reload module which reloads changes in
185 modules recursively (it replaces the reload() function, so you don't
184 modules recursively (it replaces the reload() function, so you don't
186 need to change anything to use it). deep_reload() forces a full reload
185 need to change anything to use it). deep_reload() forces a full reload
187 of modules whose code may have changed, which the default reload()
186 of modules whose code may have changed, which the default reload()
188 function does not.
187 function does not.
189 .br
188 .br
190 .sp 1
189 .sp 1
191 When deep_reload is off, IPython will use the normal reload(), but
190 When deep_reload is off, IPython will use the normal reload(), but
192 deep_reload will still be available as dreload(). This feature is off
191 deep_reload will still be available as dreload(). This feature is off
193 by default [which means that you have both normal reload() and
192 by default [which means that you have both normal reload() and
194 dreload()].
193 dreload()].
195 .TP
194 .TP
196 .B \-editor <name>
195 .B \-editor <name>
197 Which editor to use with the @edit command. By default, IPython will
196 Which editor to use with the @edit command. By default, IPython will
198 honor your EDITOR environment variable (if not set, vi is the Unix
197 honor your EDITOR environment variable (if not set, vi is the Unix
199 default and notepad the Windows one). Since this editor is invoked on
198 default and notepad the Windows one). Since this editor is invoked on
200 the fly by IPython and is meant for editing small code snippets, you
199 the fly by IPython and is meant for editing small code snippets, you
201 may want to use a small, lightweight editor here (in case your default
200 may want to use a small, lightweight editor here (in case your default
202 EDITOR is something like Emacs).
201 EDITOR is something like Emacs).
203 .TP
202 .TP
204 .B \-ipythondir <name>
203 .B \-ipythondir <name>
205 The name of your IPython configuration directory IPYTHONDIR. This can
204 The name of your IPython configuration directory IPYTHONDIR. This can
206 also be specified through the environment variable IPYTHONDIR.
205 also be specified through the environment variable IPYTHONDIR.
207 .TP
206 .TP
208 .B \-log|l
207 .B \-log|l
209 Generate a log file of all input. The file is named ipython.log in
208 Generate a log file of all input. The file is named ipython.log in
210 your current directory (which prevents logs from multiple IPython
209 your current directory (which prevents logs from multiple IPython
211 sessions from trampling each other). You can use this to later restore
210 sessions from trampling each other). You can use this to later restore
212 a session by loading your logfile as a file to be executed with option
211 a session by loading your logfile as a file to be executed with option
213 -logplay (see below).
212 -logplay (see below).
214 .TP
213 .TP
215 .B \-logfile|lf
214 .B \-logfile|lf
216 Specifu the name of your logfile.
215 Specifu the name of your logfile.
217 .TP
216 .TP
218 .B \-logplay|lp
217 .B \-logplay|lp
219 Replay a previous log. For restoring a session as close as possible to
218 Replay a previous log. For restoring a session as close as possible to
220 the state you left it in, use this option (don't just run the
219 the state you left it in, use this option (don't just run the
221 logfile). With \-logplay, IPython will try to reconstruct the previous
220 logfile). With \-logplay, IPython will try to reconstruct the previous
222 working environment in full, not just execute the commands in the
221 working environment in full, not just execute the commands in the
223 logfile.
222 logfile.
224 .br
223 .br
225 .sh 1
224 .sh 1
226 When a session is restored, logging is automatically turned on again
225 When a session is restored, logging is automatically turned on again
227 with the name of the logfile it was invoked with (it is read from the
226 with the name of the logfile it was invoked with (it is read from the
228 log header). So once you've turned logging on for a session, you can
227 log header). So once you've turned logging on for a session, you can
229 quit IPython and reload it as many times as you want and it will
228 quit IPython and reload it as many times as you want and it will
230 continue to log its history and restore from the beginning every time.
229 continue to log its history and restore from the beginning every time.
231 .br
230 .br
232 .sp 1
231 .sp 1
233 Caveats: there are limitations in this option. The history variables
232 Caveats: there are limitations in this option. The history variables
234 _i*,_* and _dh don't get restored properly. In the future we will try
233 _i*,_* and _dh don't get restored properly. In the future we will try
235 to implement full session saving by writing and retrieving a
234 to implement full session saving by writing and retrieving a
236 'snapshot' of the memory state of IPython. But our first attempts
235 'snapshot' of the memory state of IPython. But our first attempts
237 failed because of inherent limitations of Python's Pickle module, so
236 failed because of inherent limitations of Python's Pickle module, so
238 this may have to wait.
237 this may have to wait.
239 .TP
238 .TP
240 .B \-[no]messages
239 .B \-[no]messages
241 Print messages which IPython collects about its startup process
240 Print messages which IPython collects about its startup process
242 (default on).
241 (default on).
243 .TP
242 .TP
244 .B \-[no]pdb
243 .B \-[no]pdb
245 Automatically call the pdb debugger after every uncaught exception. If
244 Automatically call the pdb debugger after every uncaught exception. If
246 you are used to debugging using pdb, this puts you automatically
245 you are used to debugging using pdb, this puts you automatically
247 inside of it after any call (either in IPython or in code called by
246 inside of it after any call (either in IPython or in code called by
248 it) which triggers an exception which goes uncaught.
247 it) which triggers an exception which goes uncaught.
249 .TP
248 .TP
250 .B \-[no]pprint
249 .B \-[no]pprint
251 IPython can optionally use the pprint (pretty printer) module for
250 IPython can optionally use the pprint (pretty printer) module for
252 displaying results. pprint tends to give a nicer display of nested
251 displaying results. pprint tends to give a nicer display of nested
253 data structures. If you like it, you can turn it on permanently in
252 data structures. If you like it, you can turn it on permanently in
254 your config file (default off).
253 your config file (default off).
255 .TP
254 .TP
256 .B \-profile|p <name>
255 .B \-profile|p <name>
257 Assume that your config file is ipythonrc-<name> (looks in current dir
256 Assume that your config file is ipythonrc-<name> (looks in current dir
258 first, then in IPYTHONDIR). This is a quick way to keep and load
257 first, then in IPYTHONDIR). This is a quick way to keep and load
259 multiple config files for different tasks, especially if you use the
258 multiple config files for different tasks, especially if you use the
260 include option of config files. You can keep a basic
259 include option of config files. You can keep a basic
261 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
260 IPYTHONDIR/ipythonrc file and then have other 'profiles' which include
262 this one and load extra things for particular tasks. For example:
261 this one and load extra things for particular tasks. For example:
263 .br
262 .br
264 .sp 1
263 .sp 1
265 1) $HOME/.ipython/ipythonrc : load basic things you always want.
264 1) $HOME/.ipython/ipythonrc : load basic things you always want.
266 .br
265 .br
267 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
266 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-related
268 modules.
267 modules.
269 .br
268 .br
270 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
269 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
271 plotting modules.
270 plotting modules.
272 .br
271 .br
273 .sp 1
272 .sp 1
274 Since it is possible to create an endless loop by having circular file
273 Since it is possible to create an endless loop by having circular file
275 inclusions, IPython will stop if it reaches 15 recursive inclusions.
274 inclusions, IPython will stop if it reaches 15 recursive inclusions.
276 .TP
275 .TP
277 .B \-prompt_in1|pi1 <string>
276 .B \-prompt_in1|pi1 <string>
278 Specify the string used for input prompts. Note that if you are using
277 Specify the string used for input prompts. Note that if you are using
279 numbered prompts, the number is represented with a '\\#' in the
278 numbered prompts, the number is represented with a '\\#' in the
280 string. Don't forget to quote strings with spaces embedded in
279 string. Don't forget to quote strings with spaces embedded in
281 them. Default: 'In [\\#]:'.
280 them. Default: 'In [\\#]:'.
282 .br
281 .br
283 .sp 1
282 .sp 1
284 Most bash-like escapes can be used to customize IPython's prompts, as well as
283 Most bash-like escapes can be used to customize IPython's prompts, as well as
285 a few additional ones which are IPython-specific. All valid prompt escapes
284 a few additional ones which are IPython-specific. All valid prompt escapes
286 are described in detail in the Customization section of the IPython HTML/PDF
285 are described in detail in the Customization section of the IPython HTML/PDF
287 manual.
286 manual.
288 .TP
287 .TP
289 .B \-prompt_in2|pi2 <string>
288 .B \-prompt_in2|pi2 <string>
290 Similar to the previous option, but used for the continuation prompts. The
289 Similar to the previous option, but used for the continuation prompts. The
291 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
290 special sequence '\\D' is similar to '\\#', but with all digits replaced dots
292 (so you can have your continuation prompt aligned with your input
291 (so you can have your continuation prompt aligned with your input
293 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
292 prompt). Default: ' .\\D.:' (note three spaces at the start for alignment
294 with 'In [\\#]').
293 with 'In [\\#]').
295 .TP
294 .TP
296 .B \-prompt_out|po <string>
295 .B \-prompt_out|po <string>
297 String used for output prompts, also uses numbers like prompt_in1.
296 String used for output prompts, also uses numbers like prompt_in1.
298 Default: 'Out[\\#]:'.
297 Default: 'Out[\\#]:'.
299 .TP
298 .TP
300 .B \-quick
299 .B \-quick
301 Start in bare bones mode (no config file loaded).
300 Start in bare bones mode (no config file loaded).
302 .TP
301 .TP
303 .B \-rcfile <name>
302 .B \-rcfile <name>
304 Name of your IPython resource configuration file. normally IPython
303 Name of your IPython resource configuration file. normally IPython
305 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
304 loads ipythonrc (from current directory) or IPYTHONDIR/ipythonrc. If
306 the loading of your config file fails, IPython starts with a bare
305 the loading of your config file fails, IPython starts with a bare
307 bones configuration (no modules loaded at all).
306 bones configuration (no modules loaded at all).
308 .TP
307 .TP
309 .B \-[no]readline
308 .B \-[no]readline
310 Use the readline library, which is needed to support name completion
309 Use the readline library, which is needed to support name completion
311 and command history, among other things. It is enabled by default, but
310 and command history, among other things. It is enabled by default, but
312 may cause problems for users of X/Emacs in Python comint or shell
311 may cause problems for users of X/Emacs in Python comint or shell
313 buffers.
312 buffers.
314 .br
313 .br
315 .sp 1
314 .sp 1
316 Note that emacs 'eterm' buffers (opened with M-x term) support
315 Note that emacs 'eterm' buffers (opened with M-x term) support
317 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
316 IPython's readline and syntax coloring fine, only 'emacs' (M-x shell
318 and C-c !) buffers do not.
317 and C-c !) buffers do not.
319 .TP
318 .TP
320 .B \-screen_length|sl <n>
319 .B \-screen_length|sl <n>
321 Number of lines of your screen. This is used to control printing of
320 Number of lines of your screen. This is used to control printing of
322 very long strings. Strings longer than this number of lines will be
321 very long strings. Strings longer than this number of lines will be
323 sent through a pager instead of directly printed.
322 sent through a pager instead of directly printed.
324 .br
323 .br
325 .sp 1
324 .sp 1
326 The default value for this is 0, which means IPython will auto-detect
325 The default value for this is 0, which means IPython will auto-detect
327 your screen size every time it needs to print certain potentially long
326 your screen size every time it needs to print certain potentially long
328 strings (this doesn't change the behavior of the 'print' keyword, it's
327 strings (this doesn't change the behavior of the 'print' keyword, it's
329 only triggered internally). If for some reason this isn't working well
328 only triggered internally). If for some reason this isn't working well
330 (it needs curses support), specify it yourself. Otherwise don't change
329 (it needs curses support), specify it yourself. Otherwise don't change
331 the default.
330 the default.
332 .TP
331 .TP
333 .B \-separate_in|si <string>
332 .B \-separate_in|si <string>
334 Separator before input prompts. Default '\n'.
333 Separator before input prompts. Default '\n'.
335 .TP
334 .TP
336 .B \-separate_out|so <string>
335 .B \-separate_out|so <string>
337 Separator before output prompts. Default: 0 (nothing).
336 Separator before output prompts. Default: 0 (nothing).
338 .TP
337 .TP
339 .B \-separate_out2|so2 <string>
338 .B \-separate_out2|so2 <string>
340 Separator after output prompts. Default: 0 (nothing).
339 Separator after output prompts. Default: 0 (nothing).
341 .TP
340 .TP
342 .B \-nosep
341 .B \-nosep
343 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
342 Shorthand for '\-separate_in 0 \-separate_out 0 \-separate_out2 0'.
344 Simply removes all input/output separators.
343 Simply removes all input/output separators.
345 .TP
344 .TP
346 .B \-upgrade
345 .B \-upgrade
347 Allows you to upgrade your IPYTHONDIR configuration when you install a
346 Allows you to upgrade your IPYTHONDIR configuration when you install a
348 new version of IPython. Since new versions may include new command
347 new version of IPython. Since new versions may include new command
349 lines options or example files, this copies updated ipythonrc-type
348 lines options or example files, this copies updated ipythonrc-type
350 files. However, it backs up (with a .old extension) all files which
349 files. However, it backs up (with a .old extension) all files which
351 it overwrites so that you can merge back any custimizations you might
350 it overwrites so that you can merge back any custimizations you might
352 have in your personal files.
351 have in your personal files.
353 .TP
352 .TP
354 .B \-Version
353 .B \-Version
355 Print version information and exit.
354 Print version information and exit.
356 .TP
355 .TP
357 .B \-xmode <modename>
356 .B \-xmode <modename>
358 Mode for exception reporting. The valid modes are Plain, Context, and
357 Mode for exception reporting. The valid modes are Plain, Context, and
359 Verbose.
358 Verbose.
360 .br
359 .br
361 .sp 1
360 .sp 1
362 \- Plain: similar to python's normal traceback printing.
361 \- Plain: similar to python's normal traceback printing.
363 .br
362 .br
364 .sp 1
363 .sp 1
365 \- Context: prints 5 lines of context source code around each line in the
364 \- Context: prints 5 lines of context source code around each line in the
366 traceback.
365 traceback.
367 .br
366 .br
368 .sp 1
367 .sp 1
369 \- Verbose: similar to Context, but additionally prints the variables
368 \- Verbose: similar to Context, but additionally prints the variables
370 currently visible where the exception happened (shortening their strings if
369 currently visible where the exception happened (shortening their strings if
371 too long). This can potentially be very slow, if you happen to have a huge
370 too long). This can potentially be very slow, if you happen to have a huge
372 data structure whose string representation is complex to compute. Your
371 data structure whose string representation is complex to compute. Your
373 computer may appear to freeze for a while with cpu usage at 100%. If this
372 computer may appear to freeze for a while with cpu usage at 100%. If this
374 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
373 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than
375 once).
374 once).
376 .
375 .
377 .SH EMBEDDING
376 .SH EMBEDDING
378 It is possible to start an IPython instance inside your own Python
377 It is possible to start an IPython instance inside your own Python
379 programs. In the documentation example files there are some
378 programs. In the documentation example files there are some
380 illustrations on how to do this.
379 illustrations on how to do this.
381 .br
380 .br
382 .sp 1
381 .sp 1
383 This feature allows you to evalutate dynamically the state of your
382 This feature allows you to evalutate dynamically the state of your
384 code, operate with your variables, analyze them, etc. Note however
383 code, operate with your variables, analyze them, etc. Note however
385 that any changes you make to values while in the shell do NOT
384 that any changes you make to values while in the shell do NOT
386 propagate back to the running code, so it is safe to modify your
385 propagate back to the running code, so it is safe to modify your
387 values because you won't break your code in bizarre ways by doing so.
386 values because you won't break your code in bizarre ways by doing so.
388 .SH AUTHOR
387 .SH AUTHOR
389 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
388 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
390 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
389 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
391 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
390 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
392 <jack@xiph.org>, for the Debian project (but may be used by others).
391 <jack@xiph.org>, for the Debian project (but may be used by others).
@@ -1,9124 +1,9168 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 While you can use IPython under Windows with only a stock Python installation,
938 While you can use IPython under Windows with only a stock Python installation,
939 there is one extension,
939 there is one extension,
940 \family typewriter
940 \family typewriter
941 readline
941 readline
942 \family default
942 \family default
943 , which will make the whole experience a lot more pleasant.
943 , which will make the whole experience a lot more pleasant.
944 It is almost a requirement, since IPython will complain in its absence
944 It is almost a requirement, since IPython will complain in its absence
945 (though it will function).
945 (though it will function).
946
946
947 \layout Standard
947 \layout Standard
948
948
949 The
949 The
950 \family typewriter
950 \family typewriter
951 readline
951 readline
952 \family default
952 \family default
953 extension needs two other libraries to work, so in all you need:
953 extension needs two other libraries to work, so in all you need:
954 \layout Enumerate
954 \layout Enumerate
955
955
956
956
957 \family typewriter
957 \family typewriter
958 PyWin32
958 PyWin32
959 \family default
959 \family default
960 from
960 from
961 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
961 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
962
962
963 \end_inset
963 \end_inset
964
964
965 .
965 .
966 \layout Enumerate
966 \layout Enumerate
967
967
968
968
969 \family typewriter
969 \family typewriter
970 CTypes
970 CTypes
971 \family default
971 \family default
972 from
972 from
973 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
973 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
974
974
975 \end_inset
975 \end_inset
976
976
977 (you
977 (you
978 \emph on
978 \emph on
979 must
979 must
980 \emph default
980 \emph default
981 use version 0.9.1 or newer).
981 use version 0.9.1 or newer).
982 \layout Enumerate
982 \layout Enumerate
983
983
984
984
985 \family typewriter
985 \family typewriter
986 Readline
986 Readline
987 \family default
987 \family default
988 for Windows from
988 for Windows from
989 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
989 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
990
990
991 \end_inset
991 \end_inset
992
992
993 .
993 .
994 \layout Standard
994 \layout Standard
995
995
996
996
997 \series bold
997 \series bold
998 Warning about a broken readline-like library:
998 Warning about a broken readline-like library:
999 \series default
999 \series default
1000 several users have reported problems stemming from using the pseudo-readline
1000 several users have reported problems stemming from using the pseudo-readline
1001 library at
1001 library at
1002 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1002 \begin_inset LatexCommand \htmlurl{http://newcenturycomputers.net/projects/readline.html}
1003
1003
1004 \end_inset
1004 \end_inset
1005
1005
1006 .
1006 .
1007 This is a broken library which, while called readline, only implements
1007 This is a broken library which, while called readline, only implements
1008 an incomplete subset of the readline API.
1008 an incomplete subset of the readline API.
1009 Since it is still called readline, it fools IPython's detection mechanisms
1009 Since it is still called readline, it fools IPython's detection mechanisms
1010 and causes unpredictable crashes later.
1010 and causes unpredictable crashes later.
1011 If you wish to use IPython under Windows, you must NOT use this library,
1011 If you wish to use IPython under Windows, you must NOT use this library,
1012 which for all purposes is (at least as of version 1.6) terminally broken.
1012 which for all purposes is (at least as of version 1.6) terminally broken.
1013 \layout Subsubsection
1013 \layout Subsubsection
1014
1014
1015 Gary Bishop's readline and color support for Windows
1015 Gary Bishop's readline and color support for Windows
1016 \layout Standard
1016 \layout Standard
1017
1017
1018 Some of IPython's very useful features are:
1018 Some of IPython's very useful features are:
1019 \layout Itemize
1019 \layout Itemize
1020
1020
1021 Integrated readline support (Tab-based file, object and attribute completion,
1021 Integrated readline support (Tab-based file, object and attribute completion,
1022 input history across sessions, editable command line, etc.)
1022 input history across sessions, editable command line, etc.)
1023 \layout Itemize
1023 \layout Itemize
1024
1024
1025 Coloring of prompts, code and tracebacks.
1025 Coloring of prompts, code and tracebacks.
1026 \layout Standard
1026 \layout Standard
1027
1027
1028 These, by default, are only available under Unix-like operating systems.
1028 These, by default, are only available under Unix-like operating systems.
1029 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
1029 However, thanks to Gary Bishop's work, Windows XP/2k users can also benefit
1030 from them.
1030 from them.
1031 His readline library implements both GNU readline functionality and color
1031 His readline library implements both GNU readline functionality and color
1032 support, so that IPython under Windows XP/2k can be as friendly and powerful
1032 support, so that IPython under Windows XP/2k can be as friendly and powerful
1033 as under Unix-like environments.
1033 as under Unix-like environments.
1034 \layout Standard
1034 \layout Standard
1035
1035
1036 You can find Gary's tools at
1036 You can find Gary's tools at
1037 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
1037 \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/uncpythontools}
1038
1038
1039 \end_inset
1039 \end_inset
1040
1040
1041 ; Gary's
1041 ; Gary's
1042 \family typewriter
1042 \family typewriter
1043 readline
1043 readline
1044 \family default
1044 \family default
1045 requires in turn the
1045 requires in turn the
1046 \family typewriter
1046 \family typewriter
1047 ctypes
1047 ctypes
1048 \family default
1048 \family default
1049 library by Thomas Heller, available at
1049 library by Thomas Heller, available at
1050 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
1050 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/theller/ctypes}
1051
1051
1052 \end_inset
1052 \end_inset
1053
1053
1054 , and Mark Hammond's
1054 , and Mark Hammond's
1055 \family typewriter
1055 \family typewriter
1056 PyWin32
1056 PyWin32
1057 \family default
1057 \family default
1058 from
1058 from
1059 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
1059 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond}
1060
1060
1061 \end_inset
1061 \end_inset
1062
1062
1063 (
1063 (
1064 \family typewriter
1064 \family typewriter
1065 PyWin32
1065 PyWin32
1066 \family default
1066 \family default
1067 is great for anything Windows-related anyway, so you might as well get
1067 is great for anything Windows-related anyway, so you might as well get
1068 it).
1068 it).
1069 \layout Standard
1069 \layout Standard
1070
1070
1071 Under MS\SpecialChar ~
1071 Under MS\SpecialChar ~
1072 Windows, IPython will complain if it can not find this
1072 Windows, IPython will complain if it can not find this
1073 \family typewriter
1073 \family typewriter
1074 readline
1074 readline
1075 \family default
1075 \family default
1076 library at startup and any time the
1076 library at startup and any time the
1077 \family typewriter
1077 \family typewriter
1078 %colors
1078 %colors
1079 \family default
1079 \family default
1080 command is issued, so you can consider it to be a quasi-requirement.
1080 command is issued, so you can consider it to be a quasi-requirement.
1081 \layout Subsubsection
1081 \layout Subsubsection
1082
1082
1083 Installation procedure
1083 Installation procedure
1084 \layout Standard
1084 \layout Standard
1085
1085
1086 Once you have the above installed, from the IPython download directory grab
1086 Once you have the above installed, from the IPython download directory grab
1087 the
1087 the
1088 \family typewriter
1088 \family typewriter
1089 ipython-XXX.win32.exe
1089 ipython-XXX.win32.exe
1090 \family default
1090 \family default
1091 file, where
1091 file, where
1092 \family typewriter
1092 \family typewriter
1093 XXX
1093 XXX
1094 \family default
1094 \family default
1095 represents the version number.
1095 represents the version number.
1096 This is a regular windows executable installer, which you can simply double-cli
1096 This is a regular windows executable installer, which you can simply double-cli
1097 ck to install.
1097 ck to install.
1098 It will add an entry for IPython to your Start Menu, as well as registering
1098 It will add an entry for IPython to your Start Menu, as well as registering
1099 IPython in the Windows list of applications, so you can later uninstall
1099 IPython in the Windows list of applications, so you can later uninstall
1100 it from the Control Panel.
1100 it from the Control Panel.
1101
1101
1102 \layout Standard
1102 \layout Standard
1103
1103
1104 IPython tries to install the configuration information in a directory named
1104 IPython tries to install the configuration information in a directory named
1105
1105
1106 \family typewriter
1106 \family typewriter
1107 .ipython
1107 .ipython
1108 \family default
1108 \family default
1109 (
1109 (
1110 \family typewriter
1110 \family typewriter
1111 _ipython
1111 _ipython
1112 \family default
1112 \family default
1113 under Windows) located in your `home' directory.
1113 under Windows) located in your `home' directory.
1114 IPython sets this directory by looking for a
1114 IPython sets this directory by looking for a
1115 \family typewriter
1115 \family typewriter
1116 HOME
1116 HOME
1117 \family default
1117 \family default
1118 environment variable; if such a variable does not exist, it uses
1118 environment variable; if such a variable does not exist, it uses
1119 \family typewriter
1119 \family typewriter
1120 HOMEDRIVE
1120 HOMEDRIVE
1121 \backslash
1121 \backslash
1122 HOMEPATH
1122 HOMEPATH
1123 \family default
1123 \family default
1124 (these are always defined by Windows).
1124 (these are always defined by Windows).
1125 This typically gives something like
1125 This typically gives something like
1126 \family typewriter
1126 \family typewriter
1127 C:
1127 C:
1128 \backslash
1128 \backslash
1129 Documents and Settings
1129 Documents and Settings
1130 \backslash
1130 \backslash
1131 YourUserName
1131 YourUserName
1132 \family default
1132 \family default
1133 , but your local details may vary.
1133 , but your local details may vary.
1134 In this directory you will find all the files that configure IPython's
1134 In this directory you will find all the files that configure IPython's
1135 defaults, and you can put there your profiles and extensions.
1135 defaults, and you can put there your profiles and extensions.
1136 This directory is automatically added by IPython to
1136 This directory is automatically added by IPython to
1137 \family typewriter
1137 \family typewriter
1138 sys.path
1138 sys.path
1139 \family default
1139 \family default
1140 , so anything you place there can be found by
1140 , so anything you place there can be found by
1141 \family typewriter
1141 \family typewriter
1142 import
1142 import
1143 \family default
1143 \family default
1144 statements.
1144 statements.
1145 \layout Paragraph
1145 \layout Paragraph
1146
1146
1147 Upgrading
1147 Upgrading
1148 \layout Standard
1148 \layout Standard
1149
1149
1150 For an IPython upgrade, you should first uninstall the previous version.
1150 For an IPython upgrade, you should first uninstall the previous version.
1151 This will ensure that all files and directories (such as the documentation)
1151 This will ensure that all files and directories (such as the documentation)
1152 which carry embedded version strings in their names are properly removed.
1152 which carry embedded version strings in their names are properly removed.
1153 \layout Paragraph
1153 \layout Paragraph
1154
1154
1155 Manual installation under Win32
1155 Manual installation under Win32
1156 \layout Standard
1156 \layout Standard
1157
1157
1158 In case the automatic installer does not work for some reason, you can download
1158 In case the automatic installer does not work for some reason, you can download
1159 the
1159 the
1160 \family typewriter
1160 \family typewriter
1161 ipython-XXX.tar.gz
1161 ipython-XXX.tar.gz
1162 \family default
1162 \family default
1163 file, which contains the full IPython source distribution (the popular
1163 file, which contains the full IPython source distribution (the popular
1164 WinZip can read
1164 WinZip can read
1165 \family typewriter
1165 \family typewriter
1166 .tar.gz
1166 .tar.gz
1167 \family default
1167 \family default
1168 files).
1168 files).
1169 After uncompressing the archive, you can install it at a command terminal
1169 After uncompressing the archive, you can install it at a command terminal
1170 just like any other Python module, by using
1170 just like any other Python module, by using
1171 \family typewriter
1171 \family typewriter
1172 `python setup.py install'
1172 `python setup.py install'
1173 \family default
1173 \family default
1174 .
1174 .
1175
1175
1176 \layout Standard
1176 \layout Standard
1177
1177
1178 After the installation, run the supplied
1178 After the installation, run the supplied
1179 \family typewriter
1179 \family typewriter
1180 win32_manual_post_install.py
1180 win32_manual_post_install.py
1181 \family default
1181 \family default
1182 script, which creates the necessary Start Menu shortcuts for you.
1182 script, which creates the necessary Start Menu shortcuts for you.
1183 \layout Subsection
1183 \layout Subsection
1184
1184
1185
1185
1186 \begin_inset LatexCommand \label{sec:upgrade}
1186 \begin_inset LatexCommand \label{sec:upgrade}
1187
1187
1188 \end_inset
1188 \end_inset
1189
1189
1190 Upgrading from a previous version
1190 Upgrading from a previous version
1191 \layout Standard
1191 \layout Standard
1192
1192
1193 If you are upgrading from a previous version of IPython, after doing the
1193 If you are upgrading from a previous version of IPython, after doing the
1194 routine installation described above, you should call IPython with the
1194 routine installation described above, you should call IPython with the
1195
1195
1196 \family typewriter
1196 \family typewriter
1197 -upgrade
1197 -upgrade
1198 \family default
1198 \family default
1199 option the first time you run your new copy.
1199 option the first time you run your new copy.
1200 This will automatically update your configuration directory while preserving
1200 This will automatically update your configuration directory while preserving
1201 copies of your old files.
1201 copies of your old files.
1202 You can then later merge back any personal customizations you may have
1202 You can then later merge back any personal customizations you may have
1203 made into the new files.
1203 made into the new files.
1204 It is a good idea to do this as there may be new options available in the
1204 It is a good idea to do this as there may be new options available in the
1205 new configuration files which you will not have.
1205 new configuration files which you will not have.
1206 \layout Standard
1206 \layout Standard
1207
1207
1208 Under Windows, if you don't know how to call python scripts with arguments
1208 Under Windows, if you don't know how to call python scripts with arguments
1209 from a command line, simply delete the old config directory and IPython
1209 from a command line, simply delete the old config directory and IPython
1210 will make a new one.
1210 will make a new one.
1211 Win2k and WinXP users will find it in
1211 Win2k and WinXP users will find it in
1212 \family typewriter
1212 \family typewriter
1213 C:
1213 C:
1214 \backslash
1214 \backslash
1215 Documents and Settings
1215 Documents and Settings
1216 \backslash
1216 \backslash
1217 YourUserName
1217 YourUserName
1218 \backslash
1218 \backslash
1219 _ipython
1219 _ipython
1220 \family default
1220 \family default
1221 , and Win 9x users under
1221 , and Win 9x users under
1222 \family typewriter
1222 \family typewriter
1223 C:
1223 C:
1224 \backslash
1224 \backslash
1225 Program Files
1225 Program Files
1226 \backslash
1226 \backslash
1227 IPython
1227 IPython
1228 \backslash
1228 \backslash
1229 _ipython.
1229 _ipython.
1230 \layout Section
1230 \layout Section
1231
1231
1232
1232
1233 \begin_inset LatexCommand \label{sec:good_config}
1233 \begin_inset LatexCommand \label{sec:good_config}
1234
1234
1235 \end_inset
1235 \end_inset
1236
1236
1237
1237
1238 \begin_inset OptArg
1238 \begin_inset OptArg
1239 collapsed true
1239 collapsed true
1240
1240
1241 \layout Standard
1241 \layout Standard
1242
1242
1243 Initial configuration
1243 Initial configuration
1244 \begin_inset ERT
1244 \begin_inset ERT
1245 status Collapsed
1245 status Collapsed
1246
1246
1247 \layout Standard
1247 \layout Standard
1248
1248
1249 \backslash
1249 \backslash
1250 ldots
1250 ldots
1251 \end_inset
1251 \end_inset
1252
1252
1253
1253
1254 \end_inset
1254 \end_inset
1255
1255
1256 Initial configuration of your environment
1256 Initial configuration of your environment
1257 \layout Standard
1257 \layout Standard
1258
1258
1259 This section will help you set various things in your environment for your
1259 This section will help you set various things in your environment for your
1260 IPython sessions to be as efficient as possible.
1260 IPython sessions to be as efficient as possible.
1261 All of IPython's configuration information, along with several example
1261 All of IPython's configuration information, along with several example
1262 files, is stored in a directory named by default
1262 files, is stored in a directory named by default
1263 \family typewriter
1263 \family typewriter
1264 $HOME/.ipython
1264 $HOME/.ipython
1265 \family default
1265 \family default
1266 .
1266 .
1267 You can change this by defining the environment variable
1267 You can change this by defining the environment variable
1268 \family typewriter
1268 \family typewriter
1269 IPYTHONDIR
1269 IPYTHONDIR
1270 \family default
1270 \family default
1271 , or at runtime with the command line option
1271 , or at runtime with the command line option
1272 \family typewriter
1272 \family typewriter
1273 -ipythondir
1273 -ipythondir
1274 \family default
1274 \family default
1275 .
1275 .
1276 \layout Standard
1276 \layout Standard
1277
1277
1278 If all goes well, the first time you run IPython it should automatically
1278 If all goes well, the first time you run IPython it should automatically
1279 create a user copy of the config directory for you, based on its builtin
1279 create a user copy of the config directory for you, based on its builtin
1280 defaults.
1280 defaults.
1281 You can look at the files it creates to learn more about configuring the
1281 You can look at the files it creates to learn more about configuring the
1282 system.
1282 system.
1283 The main file you will modify to configure IPython's behavior is called
1283 The main file you will modify to configure IPython's behavior is called
1284
1284
1285 \family typewriter
1285 \family typewriter
1286 ipythonrc
1286 ipythonrc
1287 \family default
1287 \family default
1288 (with a
1288 (with a
1289 \family typewriter
1289 \family typewriter
1290 .ini
1290 .ini
1291 \family default
1291 \family default
1292 extension under Windows), included for reference in Sec.
1292 extension under Windows), included for reference in Sec.
1293
1293
1294 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1294 \begin_inset LatexCommand \ref{sec:ipytonrc-sample}
1295
1295
1296 \end_inset
1296 \end_inset
1297
1297
1298 .
1298 .
1299 This file is very commented and has many variables you can change to suit
1299 This file is very commented and has many variables you can change to suit
1300 your taste, you can find more details in Sec.
1300 your taste, you can find more details in Sec.
1301
1301
1302 \begin_inset LatexCommand \ref{sec:customization}
1302 \begin_inset LatexCommand \ref{sec:customization}
1303
1303
1304 \end_inset
1304 \end_inset
1305
1305
1306 .
1306 .
1307 Here we discuss the basic things you will want to make sure things are
1307 Here we discuss the basic things you will want to make sure things are
1308 working properly from the beginning.
1308 working properly from the beginning.
1309 \layout Subsection
1309 \layout Subsection
1310
1310
1311
1311
1312 \begin_inset LatexCommand \label{sec:help-access}
1312 \begin_inset LatexCommand \label{sec:help-access}
1313
1313
1314 \end_inset
1314 \end_inset
1315
1315
1316 Access to the Python help system
1316 Access to the Python help system
1317 \layout Standard
1317 \layout Standard
1318
1318
1319 This is true for Python in general (not just for IPython): you should have
1319 This is true for Python in general (not just for IPython): you should have
1320 an environment variable called
1320 an environment variable called
1321 \family typewriter
1321 \family typewriter
1322 PYTHONDOCS
1322 PYTHONDOCS
1323 \family default
1323 \family default
1324 pointing to the directory where your HTML Python documentation lives.
1324 pointing to the directory where your HTML Python documentation lives.
1325 In my system it's
1325 In my system it's
1326 \family typewriter
1326 \family typewriter
1327 /usr/share/doc/python-docs-2.3.4/html
1327 /usr/share/doc/python-docs-2.3.4/html
1328 \family default
1328 \family default
1329 , check your local details or ask your systems administrator.
1329 , check your local details or ask your systems administrator.
1330
1330
1331 \layout Standard
1331 \layout Standard
1332
1332
1333 This is the directory which holds the HTML version of the Python manuals.
1333 This is the directory which holds the HTML version of the Python manuals.
1334 Unfortunately it seems that different Linux distributions package these
1334 Unfortunately it seems that different Linux distributions package these
1335 files differently, so you may have to look around a bit.
1335 files differently, so you may have to look around a bit.
1336 Below I show the contents of this directory on my system for reference:
1336 Below I show the contents of this directory on my system for reference:
1337 \layout Standard
1337 \layout Standard
1338
1338
1339
1339
1340 \family typewriter
1340 \family typewriter
1341 [html]> ls
1341 [html]> ls
1342 \newline
1342 \newline
1343 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1343 about.dat acks.html dist/ ext/ index.html lib/ modindex.html stdabout.dat tut/
1344 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1344 about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
1345 \layout Standard
1345 \layout Standard
1346
1346
1347 You should really make sure this variable is correctly set so that Python's
1347 You should really make sure this variable is correctly set so that Python's
1348 pydoc-based help system works.
1348 pydoc-based help system works.
1349 It is a powerful and convenient system with full access to the Python manuals
1349 It is a powerful and convenient system with full access to the Python manuals
1350 and all modules accessible to you.
1350 and all modules accessible to you.
1351 \layout Standard
1351 \layout Standard
1352
1352
1353 Under Windows it seems that pydoc finds the documentation automatically,
1353 Under Windows it seems that pydoc finds the documentation automatically,
1354 so no extra setup appears necessary.
1354 so no extra setup appears necessary.
1355 \layout Subsection
1355 \layout Subsection
1356
1356
1357 Editor
1357 Editor
1358 \layout Standard
1358 \layout Standard
1359
1359
1360 The
1360 The
1361 \family typewriter
1361 \family typewriter
1362 %edit
1362 %edit
1363 \family default
1363 \family default
1364 command (and its alias
1364 command (and its alias
1365 \family typewriter
1365 \family typewriter
1366 %ed
1366 %ed
1367 \family default
1367 \family default
1368 ) will invoke the editor set in your environment as
1368 ) will invoke the editor set in your environment as
1369 \family typewriter
1369 \family typewriter
1370 EDITOR
1370 EDITOR
1371 \family default
1371 \family default
1372 .
1372 .
1373 If this variable is not set, it will default to
1373 If this variable is not set, it will default to
1374 \family typewriter
1374 \family typewriter
1375 vi
1375 vi
1376 \family default
1376 \family default
1377 under Linux/Unix and to
1377 under Linux/Unix and to
1378 \family typewriter
1378 \family typewriter
1379 notepad
1379 notepad
1380 \family default
1380 \family default
1381 under Windows.
1381 under Windows.
1382 You may want to set this variable properly and to a lightweight editor
1382 You may want to set this variable properly and to a lightweight editor
1383 which doesn't take too long to start (that is, something other than a new
1383 which doesn't take too long to start (that is, something other than a new
1384 instance of
1384 instance of
1385 \family typewriter
1385 \family typewriter
1386 Emacs
1386 Emacs
1387 \family default
1387 \family default
1388 ).
1388 ).
1389 This way you can edit multi-line code quickly and with the power of a real
1389 This way you can edit multi-line code quickly and with the power of a real
1390 editor right inside IPython.
1390 editor right inside IPython.
1391
1391
1392 \layout Standard
1392 \layout Standard
1393
1393
1394 If you are a dedicated
1394 If you are a dedicated
1395 \family typewriter
1395 \family typewriter
1396 Emacs
1396 Emacs
1397 \family default
1397 \family default
1398 user, you should set up the
1398 user, you should set up the
1399 \family typewriter
1399 \family typewriter
1400 Emacs
1400 Emacs
1401 \family default
1401 \family default
1402 server so that new requests are handled by the original process.
1402 server so that new requests are handled by the original process.
1403 This means that almost no time is spent in handling the request (assuming
1403 This means that almost no time is spent in handling the request (assuming
1404 an
1404 an
1405 \family typewriter
1405 \family typewriter
1406 Emacs
1406 Emacs
1407 \family default
1407 \family default
1408 process is already running).
1408 process is already running).
1409 For this to work, you need to set your
1409 For this to work, you need to set your
1410 \family typewriter
1410 \family typewriter
1411 EDITOR
1411 EDITOR
1412 \family default
1412 \family default
1413 environment variable to
1413 environment variable to
1414 \family typewriter
1414 \family typewriter
1415 'emacsclient'
1415 'emacsclient'
1416 \family default
1416 \family default
1417 .
1417 .
1418
1418
1419 \family typewriter
1419 \family typewriter
1420
1420
1421 \family default
1421 \family default
1422 The code below, supplied by Francois Pinard, can then be used in your
1422 The code below, supplied by Francois Pinard, can then be used in your
1423 \family typewriter
1423 \family typewriter
1424 .emacs
1424 .emacs
1425 \family default
1425 \family default
1426 file to enable the server:
1426 file to enable the server:
1427 \layout Standard
1427 \layout Standard
1428
1428
1429
1429
1430 \family typewriter
1430 \family typewriter
1431 (defvar server-buffer-clients)
1431 (defvar server-buffer-clients)
1432 \newline
1432 \newline
1433 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1433 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
1434 \newline
1434 \newline
1435
1435
1436 \begin_inset ERT
1436 \begin_inset ERT
1437 status Collapsed
1437 status Collapsed
1438
1438
1439 \layout Standard
1439 \layout Standard
1440
1440
1441 \backslash
1441 \backslash
1442 hspace*{0mm}
1442 hspace*{0mm}
1443 \end_inset
1443 \end_inset
1444
1444
1445 \SpecialChar ~
1445 \SpecialChar ~
1446 \SpecialChar ~
1446 \SpecialChar ~
1447 (server-start)
1447 (server-start)
1448 \newline
1448 \newline
1449
1449
1450 \begin_inset ERT
1450 \begin_inset ERT
1451 status Collapsed
1451 status Collapsed
1452
1452
1453 \layout Standard
1453 \layout Standard
1454
1454
1455 \backslash
1455 \backslash
1456 hspace*{0mm}
1456 hspace*{0mm}
1457 \end_inset
1457 \end_inset
1458
1458
1459 \SpecialChar ~
1459 \SpecialChar ~
1460 \SpecialChar ~
1460 \SpecialChar ~
1461 (defun fp-kill-server-with-buffer-routine ()
1461 (defun fp-kill-server-with-buffer-routine ()
1462 \newline
1462 \newline
1463
1463
1464 \begin_inset ERT
1464 \begin_inset ERT
1465 status Collapsed
1465 status Collapsed
1466
1466
1467 \layout Standard
1467 \layout Standard
1468
1468
1469 \backslash
1469 \backslash
1470 hspace*{0mm}
1470 hspace*{0mm}
1471 \end_inset
1471 \end_inset
1472
1472
1473 \SpecialChar ~
1473 \SpecialChar ~
1474 \SpecialChar ~
1474 \SpecialChar ~
1475 \SpecialChar ~
1475 \SpecialChar ~
1476 \SpecialChar ~
1476 \SpecialChar ~
1477 (and server-buffer-clients (server-done)))
1477 (and server-buffer-clients (server-done)))
1478 \newline
1478 \newline
1479
1479
1480 \begin_inset ERT
1480 \begin_inset ERT
1481 status Collapsed
1481 status Collapsed
1482
1482
1483 \layout Standard
1483 \layout Standard
1484
1484
1485 \backslash
1485 \backslash
1486 hspace*{0mm}
1486 hspace*{0mm}
1487 \end_inset
1487 \end_inset
1488
1488
1489 \SpecialChar ~
1489 \SpecialChar ~
1490 \SpecialChar ~
1490 \SpecialChar ~
1491 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1491 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
1492 \layout Standard
1492 \layout Standard
1493
1493
1494 You can also set the value of this editor via the commmand-line option '-
1494 You can also set the value of this editor via the commmand-line option '-
1495 \family typewriter
1495 \family typewriter
1496 editor'
1496 editor'
1497 \family default
1497 \family default
1498 or in your
1498 or in your
1499 \family typewriter
1499 \family typewriter
1500 ipythonrc
1500 ipythonrc
1501 \family default
1501 \family default
1502 file.
1502 file.
1503 This is useful if you wish to use specifically for IPython an editor different
1503 This is useful if you wish to use specifically for IPython an editor different
1504 from your typical default (and for Windows users who tend to use fewer
1504 from your typical default (and for Windows users who tend to use fewer
1505 environment variables).
1505 environment variables).
1506 \layout Subsection
1506 \layout Subsection
1507
1507
1508 Color
1508 Color
1509 \layout Standard
1509 \layout Standard
1510
1510
1511 The default IPython configuration has most bells and whistles turned on
1511 The default IPython configuration has most bells and whistles turned on
1512 (they're pretty safe).
1512 (they're pretty safe).
1513 But there's one that
1513 But there's one that
1514 \emph on
1514 \emph on
1515 may
1515 may
1516 \emph default
1516 \emph default
1517 cause problems on some systems: the use of color on screen for displaying
1517 cause problems on some systems: the use of color on screen for displaying
1518 information.
1518 information.
1519 This is very useful, since IPython can show prompts and exception tracebacks
1519 This is very useful, since IPython can show prompts and exception tracebacks
1520 with various colors, display syntax-highlighted source code, and in general
1520 with various colors, display syntax-highlighted source code, and in general
1521 make it easier to visually parse information.
1521 make it easier to visually parse information.
1522 \layout Standard
1522 \layout Standard
1523
1523
1524 The following terminals seem to handle the color sequences fine:
1524 The following terminals seem to handle the color sequences fine:
1525 \layout Itemize
1525 \layout Itemize
1526
1526
1527 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1527 Linux main text console, KDE Konsole, Gnome Terminal, E-term, rxvt, xterm.
1528 \layout Itemize
1528 \layout Itemize
1529
1529
1530 CDE terminal (tested under Solaris).
1530 CDE terminal (tested under Solaris).
1531 This one boldfaces light colors.
1531 This one boldfaces light colors.
1532 \layout Itemize
1532 \layout Itemize
1533
1533
1534 (X)Emacs buffers.
1534 (X)Emacs buffers.
1535 See sec.
1535 See sec.
1536 \begin_inset LatexCommand \ref{sec:emacs}
1536 \begin_inset LatexCommand \ref{sec:emacs}
1537
1537
1538 \end_inset
1538 \end_inset
1539
1539
1540 for more details on using IPython with (X)Emacs.
1540 for more details on using IPython with (X)Emacs.
1541 \layout Itemize
1541 \layout Itemize
1542
1542
1543 A Windows (XP/2k) command prompt
1543 A Windows (XP/2k) command prompt
1544 \emph on
1544 \emph on
1545 with Gary Bishop's support extensions
1545 with Gary Bishop's support extensions
1546 \emph default
1546 \emph default
1547 .
1547 .
1548 Gary's extensions are discussed in Sec.\SpecialChar ~
1548 Gary's extensions are discussed in Sec.\SpecialChar ~
1549
1549
1550 \begin_inset LatexCommand \ref{sub:Under-Windows}
1550 \begin_inset LatexCommand \ref{sub:Under-Windows}
1551
1551
1552 \end_inset
1552 \end_inset
1553
1553
1554 .
1554 .
1555 \layout Itemize
1555 \layout Itemize
1556
1556
1557 A Windows (XP/2k) CygWin shell.
1557 A Windows (XP/2k) CygWin shell.
1558 Although some users have reported problems; it is not clear whether there
1558 Although some users have reported problems; it is not clear whether there
1559 is an issue for everyone or only under specific configurations.
1559 is an issue for everyone or only under specific configurations.
1560 If you have full color support under cygwin, please post to the IPython
1560 If you have full color support under cygwin, please post to the IPython
1561 mailing list so this issue can be resolved for all users.
1561 mailing list so this issue can be resolved for all users.
1562 \layout Standard
1562 \layout Standard
1563
1563
1564 These have shown problems:
1564 These have shown problems:
1565 \layout Itemize
1565 \layout Itemize
1566
1566
1567 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1567 Windows command prompt in WinXP/2k logged into a Linux machine via telnet
1568 or ssh.
1568 or ssh.
1569 \layout Itemize
1569 \layout Itemize
1570
1570
1571 Windows native command prompt in WinXP/2k,
1571 Windows native command prompt in WinXP/2k,
1572 \emph on
1572 \emph on
1573 without
1573 without
1574 \emph default
1574 \emph default
1575 Gary Bishop's extensions.
1575 Gary Bishop's extensions.
1576 Once Gary's readline library is installed, the normal WinXP/2k command
1576 Once Gary's readline library is installed, the normal WinXP/2k command
1577 prompt works perfectly.
1577 prompt works perfectly.
1578 \layout Standard
1578 \layout Standard
1579
1579
1580 Currently the following color schemes are available:
1580 Currently the following color schemes are available:
1581 \layout Itemize
1581 \layout Itemize
1582
1582
1583
1583
1584 \family typewriter
1584 \family typewriter
1585 NoColor
1585 NoColor
1586 \family default
1586 \family default
1587 : uses no color escapes at all (all escapes are empty
1587 : uses no color escapes at all (all escapes are empty
1588 \begin_inset Quotes eld
1588 \begin_inset Quotes eld
1589 \end_inset
1589 \end_inset
1590
1590
1591
1591
1592 \begin_inset Quotes eld
1592 \begin_inset Quotes eld
1593 \end_inset
1593 \end_inset
1594
1594
1595 strings).
1595 strings).
1596 This 'scheme' is thus fully safe to use in any terminal.
1596 This 'scheme' is thus fully safe to use in any terminal.
1597 \layout Itemize
1597 \layout Itemize
1598
1598
1599
1599
1600 \family typewriter
1600 \family typewriter
1601 Linux
1601 Linux
1602 \family default
1602 \family default
1603 : works well in Linux console type environments: dark background with light
1603 : works well in Linux console type environments: dark background with light
1604 fonts.
1604 fonts.
1605 It uses bright colors for information, so it is difficult to read if you
1605 It uses bright colors for information, so it is difficult to read if you
1606 have a light colored background.
1606 have a light colored background.
1607 \layout Itemize
1607 \layout Itemize
1608
1608
1609
1609
1610 \family typewriter
1610 \family typewriter
1611 LightBG
1611 LightBG
1612 \family default
1612 \family default
1613 : the basic colors are similar to those in the
1613 : the basic colors are similar to those in the
1614 \family typewriter
1614 \family typewriter
1615 Linux
1615 Linux
1616 \family default
1616 \family default
1617 scheme but darker.
1617 scheme but darker.
1618 It is easy to read in terminals with light backgrounds.
1618 It is easy to read in terminals with light backgrounds.
1619 \layout Standard
1619 \layout Standard
1620
1620
1621 IPython uses colors for two main groups of things: prompts and tracebacks
1621 IPython uses colors for two main groups of things: prompts and tracebacks
1622 which are directly printed to the terminal, and the object introspection
1622 which are directly printed to the terminal, and the object introspection
1623 system which passes large sets of data through a pager.
1623 system which passes large sets of data through a pager.
1624 \layout Subsubsection
1624 \layout Subsubsection
1625
1625
1626 Input/Output prompts and exception tracebacks
1626 Input/Output prompts and exception tracebacks
1627 \layout Standard
1627 \layout Standard
1628
1628
1629 You can test whether the colored prompts and tracebacks work on your system
1629 You can test whether the colored prompts and tracebacks work on your system
1630 interactively by typing
1630 interactively by typing
1631 \family typewriter
1631 \family typewriter
1632 '%colors Linux'
1632 '%colors Linux'
1633 \family default
1633 \family default
1634 at the prompt (use '
1634 at the prompt (use '
1635 \family typewriter
1635 \family typewriter
1636 %colors LightBG'
1636 %colors LightBG'
1637 \family default
1637 \family default
1638 if your terminal has a light background).
1638 if your terminal has a light background).
1639 If the input prompt shows garbage like:
1639 If the input prompt shows garbage like:
1640 \newline
1640 \newline
1641
1641
1642 \family typewriter
1642 \family typewriter
1643 [0;32mIn [[1;32m1[0;32m]: [0;00m
1643 [0;32mIn [[1;32m1[0;32m]: [0;00m
1644 \family default
1644 \family default
1645
1645
1646 \newline
1646 \newline
1647 instead of (in color) something like:
1647 instead of (in color) something like:
1648 \newline
1648 \newline
1649
1649
1650 \family typewriter
1650 \family typewriter
1651 In [1]:
1651 In [1]:
1652 \family default
1652 \family default
1653
1653
1654 \newline
1654 \newline
1655 this means that your terminal doesn't properly handle color escape sequences.
1655 this means that your terminal doesn't properly handle color escape sequences.
1656 You can go to a 'no color' mode by typing '
1656 You can go to a 'no color' mode by typing '
1657 \family typewriter
1657 \family typewriter
1658 %colors NoColor
1658 %colors NoColor
1659 \family default
1659 \family default
1660 '.
1660 '.
1661
1661
1662 \layout Standard
1662 \layout Standard
1663
1663
1664 You can try using a different terminal emulator program.
1664 You can try using a different terminal emulator program.
1665 To permanently set your color preferences, edit the file
1665 To permanently set your color preferences, edit the file
1666 \family typewriter
1666 \family typewriter
1667 $HOME/.ipython/ipythonrc
1667 $HOME/.ipython/ipythonrc
1668 \family default
1668 \family default
1669 and set the
1669 and set the
1670 \family typewriter
1670 \family typewriter
1671 colors
1671 colors
1672 \family default
1672 \family default
1673 option to the desired value.
1673 option to the desired value.
1674 \layout Subsubsection
1674 \layout Subsubsection
1675
1675
1676 Object details (types, docstrings, source code, etc.)
1676 Object details (types, docstrings, source code, etc.)
1677 \layout Standard
1677 \layout Standard
1678
1678
1679 IPython has a set of special functions for studying the objects you are
1679 IPython has a set of special functions for studying the objects you are
1680 working with, discussed in detail in Sec.
1680 working with, discussed in detail in Sec.
1681
1681
1682 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1682 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1683
1683
1684 \end_inset
1684 \end_inset
1685
1685
1686 .
1686 .
1687 But this system relies on passing information which is longer than your
1687 But this system relies on passing information which is longer than your
1688 screen through a data pager, such as the common Unix
1688 screen through a data pager, such as the common Unix
1689 \family typewriter
1689 \family typewriter
1690 less
1690 less
1691 \family default
1691 \family default
1692 and
1692 and
1693 \family typewriter
1693 \family typewriter
1694 more
1694 more
1695 \family default
1695 \family default
1696 programs.
1696 programs.
1697 In order to be able to see this information in color, your pager needs
1697 In order to be able to see this information in color, your pager needs
1698 to be properly configured.
1698 to be properly configured.
1699 I strongly recommend using
1699 I strongly recommend using
1700 \family typewriter
1700 \family typewriter
1701 less
1701 less
1702 \family default
1702 \family default
1703 instead of
1703 instead of
1704 \family typewriter
1704 \family typewriter
1705 more
1705 more
1706 \family default
1706 \family default
1707 , as it seems that
1707 , as it seems that
1708 \family typewriter
1708 \family typewriter
1709 more
1709 more
1710 \family default
1710 \family default
1711 simply can not understand colored text correctly.
1711 simply can not understand colored text correctly.
1712 \layout Standard
1712 \layout Standard
1713
1713
1714 In order to configure
1714 In order to configure
1715 \family typewriter
1715 \family typewriter
1716 less
1716 less
1717 \family default
1717 \family default
1718 as your default pager, do the following:
1718 as your default pager, do the following:
1719 \layout Enumerate
1719 \layout Enumerate
1720
1720
1721 Set the environment
1721 Set the environment
1722 \family typewriter
1722 \family typewriter
1723 PAGER
1723 PAGER
1724 \family default
1724 \family default
1725 variable to
1725 variable to
1726 \family typewriter
1726 \family typewriter
1727 less
1727 less
1728 \family default
1728 \family default
1729 .
1729 .
1730 \layout Enumerate
1730 \layout Enumerate
1731
1731
1732 Set the environment
1732 Set the environment
1733 \family typewriter
1733 \family typewriter
1734 LESS
1734 LESS
1735 \family default
1735 \family default
1736 variable to
1736 variable to
1737 \family typewriter
1737 \family typewriter
1738 -r
1738 -r
1739 \family default
1739 \family default
1740 (plus any other options you always want to pass to
1740 (plus any other options you always want to pass to
1741 \family typewriter
1741 \family typewriter
1742 less
1742 less
1743 \family default
1743 \family default
1744 by default).
1744 by default).
1745 This tells
1745 This tells
1746 \family typewriter
1746 \family typewriter
1747 less
1747 less
1748 \family default
1748 \family default
1749 to properly interpret control sequences, which is how color information
1749 to properly interpret control sequences, which is how color information
1750 is given to your terminal.
1750 is given to your terminal.
1751 \layout Standard
1751 \layout Standard
1752
1752
1753 For the
1753 For the
1754 \family typewriter
1754 \family typewriter
1755 csh
1755 csh
1756 \family default
1756 \family default
1757 or
1757 or
1758 \family typewriter
1758 \family typewriter
1759 tcsh
1759 tcsh
1760 \family default
1760 \family default
1761 shells, add to your
1761 shells, add to your
1762 \family typewriter
1762 \family typewriter
1763 ~/.cshrc
1763 ~/.cshrc
1764 \family default
1764 \family default
1765 file the lines:
1765 file the lines:
1766 \layout Standard
1766 \layout Standard
1767
1767
1768
1768
1769 \family typewriter
1769 \family typewriter
1770 setenv PAGER less
1770 setenv PAGER less
1771 \newline
1771 \newline
1772 setenv LESS -r
1772 setenv LESS -r
1773 \layout Standard
1773 \layout Standard
1774
1774
1775 There is similar syntax for other Unix shells, look at your system documentation
1775 There is similar syntax for other Unix shells, look at your system documentation
1776 for details.
1776 for details.
1777 \layout Standard
1777 \layout Standard
1778
1778
1779 If you are on a system which lacks proper data pagers (such as Windows),
1779 If you are on a system which lacks proper data pagers (such as Windows),
1780 IPython will use a very limited builtin pager.
1780 IPython will use a very limited builtin pager.
1781 \layout Subsection
1781 \layout Subsection
1782
1782
1783
1783
1784 \begin_inset LatexCommand \label{sec:emacs}
1784 \begin_inset LatexCommand \label{sec:emacs}
1785
1785
1786 \end_inset
1786 \end_inset
1787
1787
1788 (X)Emacs configuration
1788 (X)Emacs configuration
1789 \layout Standard
1789 \layout Standard
1790
1790
1791 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1791 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, currently
1792 (X)Emacs and IPython get along very well.
1792 (X)Emacs and IPython get along very well.
1793
1793
1794 \layout Standard
1794 \layout Standard
1795
1795
1796
1796
1797 \series bold
1797 \series bold
1798 Important note:
1798 Important note:
1799 \series default
1799 \series default
1800 You will need to use a recent enough version of
1800 You will need to use a recent enough version of
1801 \family typewriter
1801 \family typewriter
1802 python-mode.el
1802 python-mode.el
1803 \family default
1803 \family default
1804 , along with the file
1804 , along with the file
1805 \family typewriter
1805 \family typewriter
1806 ipython.el
1806 ipython.el
1807 \family default
1807 \family default
1808 .
1808 .
1809 You can check that the version you have of
1809 You can check that the version you have of
1810 \family typewriter
1810 \family typewriter
1811 python-mode.el
1811 python-mode.el
1812 \family default
1812 \family default
1813 is new enough by either looking at the revision number in the file itself,
1813 is new enough by either looking at the revision number in the file itself,
1814 or asking for it in (X)Emacs via
1814 or asking for it in (X)Emacs via
1815 \family typewriter
1815 \family typewriter
1816 M-x py-version
1816 M-x py-version
1817 \family default
1817 \family default
1818 .
1818 .
1819 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1819 Versions 4.68 and newer contain the necessary fixes for proper IPython support.
1820 \layout Standard
1820 \layout Standard
1821
1821
1822 The file
1822 The file
1823 \family typewriter
1823 \family typewriter
1824 ipython.el
1824 ipython.el
1825 \family default
1825 \family default
1826 is included with the IPython distribution, in the documentation directory
1826 is included with the IPython distribution, in the documentation directory
1827 (where this manual resides in PDF and HTML formats).
1827 (where this manual resides in PDF and HTML formats).
1828 \layout Standard
1828 \layout Standard
1829
1829
1830 Once you put these files in your Emacs path, all you need in your
1830 Once you put these files in your Emacs path, all you need in your
1831 \family typewriter
1831 \family typewriter
1832 .emacs
1832 .emacs
1833 \family default
1833 \family default
1834 file is:
1834 file is:
1835 \layout Standard
1835 \layout Standard
1836
1836
1837
1837
1838 \family typewriter
1838 \family typewriter
1839 (require 'ipython)
1839 (require 'ipython)
1840 \layout Standard
1840 \layout Standard
1841
1841
1842 This should give you full support for executing code snippets via IPython,
1842 This should give you full support for executing code snippets via IPython,
1843 opening IPython as your Python shell via
1843 opening IPython as your Python shell via
1844 \family typewriter
1844 \family typewriter
1845 C-c\SpecialChar ~
1845 C-c\SpecialChar ~
1846 !
1846 !
1847 \family default
1847 \family default
1848 , etc.
1848 , etc.
1849
1849
1850 \layout Subsubsection*
1850 \layout Subsubsection*
1851
1851
1852 Notes
1852 Notes
1853 \layout Itemize
1853 \layout Itemize
1854
1854
1855 There is one caveat you should be aware of: you must start the IPython shell
1855 There is one caveat you should be aware of: you must start the IPython shell
1856
1856
1857 \emph on
1857 \emph on
1858 before
1858 before
1859 \emph default
1859 \emph default
1860 attempting to execute any code regions via
1860 attempting to execute any code regions via
1861 \family typewriter
1861 \family typewriter
1862 C-c\SpecialChar ~
1862 C-c\SpecialChar ~
1863 |
1863 |
1864 \family default
1864 \family default
1865 .
1865 .
1866 Simply type
1866 Simply type
1867 \family typewriter
1867 \family typewriter
1868 C-c\SpecialChar ~
1868 C-c\SpecialChar ~
1869 !
1869 !
1870 \family default
1870 \family default
1871 to start IPython before passing any code regions to the interpreter, and
1871 to start IPython before passing any code regions to the interpreter, and
1872 you shouldn't experience any problems.
1872 you shouldn't experience any problems.
1873 \newline
1873 \newline
1874 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1874 This is due to a bug in Python itself, which has been fixed for Python 2.3,
1875 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1875 but exists as of Python 2.2.2 (reported as SF bug [ 737947 ]).
1876 \layout Itemize
1876 \layout Itemize
1877
1877
1878 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1878 The (X)Emacs support is maintained by Alexander Schmolck, so all comments/reques
1879 ts should be directed to him through the IPython mailing lists.
1879 ts should be directed to him through the IPython mailing lists.
1880
1880
1881 \layout Itemize
1881 \layout Itemize
1882
1882
1883 This code is still somewhat experimental so it's a bit rough around the
1883 This code is still somewhat experimental so it's a bit rough around the
1884 edges (although in practice, it works quite well).
1884 edges (although in practice, it works quite well).
1885 \layout Itemize
1885 \layout Itemize
1886
1886
1887 Be aware that if you customize
1887 Be aware that if you customize
1888 \family typewriter
1888 \family typewriter
1889 py-python-command
1889 py-python-command
1890 \family default
1890 \family default
1891 previously, this value will override what
1891 previously, this value will override what
1892 \family typewriter
1892 \family typewriter
1893 ipython.el
1893 ipython.el
1894 \family default
1894 \family default
1895 does (because loading the customization variables comes later).
1895 does (because loading the customization variables comes later).
1896 \layout Section
1896 \layout Section
1897
1897
1898
1898
1899 \begin_inset LatexCommand \label{sec:quick_tips}
1899 \begin_inset LatexCommand \label{sec:quick_tips}
1900
1900
1901 \end_inset
1901 \end_inset
1902
1902
1903 Quick tips
1903 Quick tips
1904 \layout Standard
1904 \layout Standard
1905
1905
1906 IPython can be used as an improved replacement for the Python prompt, and
1906 IPython can be used as an improved replacement for the Python prompt, and
1907 for that you don't really need to read any more of this manual.
1907 for that you don't really need to read any more of this manual.
1908 But in this section we'll try to summarize a few tips on how to make the
1908 But in this section we'll try to summarize a few tips on how to make the
1909 most effective use of it for everyday Python development, highlighting
1909 most effective use of it for everyday Python development, highlighting
1910 things you might miss in the rest of the manual (which is getting long).
1910 things you might miss in the rest of the manual (which is getting long).
1911 We'll give references to parts in the manual which provide more detail
1911 We'll give references to parts in the manual which provide more detail
1912 when appropriate.
1912 when appropriate.
1913 \layout Standard
1913 \layout Standard
1914
1914
1915 The following article by Jeremy Jones provides an introductory tutorial
1915 The following article by Jeremy Jones provides an introductory tutorial
1916 about IPython:
1916 about IPython:
1917 \newline
1917 \newline
1918
1918
1919 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1919 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html}
1920
1920
1921 \end_inset
1921 \end_inset
1922
1922
1923
1923
1924 \layout Itemize
1924 \layout Itemize
1925
1925
1926 The TAB key.
1926 The TAB key.
1927 TAB-completion, especially for attributes, is a convenient way to explore
1927 TAB-completion, especially for attributes, is a convenient way to explore
1928 the structure of any object you're dealing with.
1928 the structure of any object you're dealing with.
1929 Simply type
1929 Simply type
1930 \family typewriter
1930 \family typewriter
1931 object_name.<TAB>
1931 object_name.<TAB>
1932 \family default
1932 \family default
1933 and a list of the object's attributes will be printed (see sec.
1933 and a list of the object's attributes will be printed (see sec.
1934
1934
1935 \begin_inset LatexCommand \ref{sec:readline}
1935 \begin_inset LatexCommand \ref{sec:readline}
1936
1936
1937 \end_inset
1937 \end_inset
1938
1938
1939 for more).
1939 for more).
1940 Tab completion also works on file and directory names, which combined with
1940 Tab completion also works on file and directory names, which combined with
1941 IPython's alias system allows you to do from within IPython many of the
1941 IPython's alias system allows you to do from within IPython many of the
1942 things you normally would need the system shell for.
1942 things you normally would need the system shell for.
1943
1943
1944 \layout Itemize
1944 \layout Itemize
1945
1945
1946 Explore your objects.
1946 Explore your objects.
1947 Typing
1947 Typing
1948 \family typewriter
1948 \family typewriter
1949 object_name?
1949 object_name?
1950 \family default
1950 \family default
1951 will print all sorts of details about any object, including docstrings,
1951 will print all sorts of details about any object, including docstrings,
1952 function definition lines (for call arguments) and constructor details
1952 function definition lines (for call arguments) and constructor details
1953 for classes.
1953 for classes.
1954 The magic commands
1954 The magic commands
1955 \family typewriter
1955 \family typewriter
1956 %pdoc
1956 %pdoc
1957 \family default
1957 \family default
1958 ,
1958 ,
1959 \family typewriter
1959 \family typewriter
1960 %pdef
1960 %pdef
1961 \family default
1961 \family default
1962 ,
1962 ,
1963 \family typewriter
1963 \family typewriter
1964 %psource
1964 %psource
1965 \family default
1965 \family default
1966 and
1966 and
1967 \family typewriter
1967 \family typewriter
1968 %pfile
1968 %pfile
1969 \family default
1969 \family default
1970 will respectively print the docstring, function definition line, full source
1970 will respectively print the docstring, function definition line, full source
1971 code and the complete file for any object (when they can be found).
1971 code and the complete file for any object (when they can be found).
1972 If automagic is on (it is by default), you don't need to type the '
1972 If automagic is on (it is by default), you don't need to type the '
1973 \family typewriter
1973 \family typewriter
1974 %
1974 %
1975 \family default
1975 \family default
1976 ' explicitly.
1976 ' explicitly.
1977 See sec.
1977 See sec.
1978
1978
1979 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1979 \begin_inset LatexCommand \ref{sec:dyn-object-info}
1980
1980
1981 \end_inset
1981 \end_inset
1982
1982
1983 for more.
1983 for more.
1984 \layout Itemize
1984 \layout Itemize
1985
1985
1986 The
1986 The
1987 \family typewriter
1987 \family typewriter
1988 %run
1988 %run
1989 \family default
1989 \family default
1990 magic command allows you to run any python script and load all of its data
1990 magic command allows you to run any python script and load all of its data
1991 directly into the interactive namespace.
1991 directly into the interactive namespace.
1992 Since the file is re-read from disk each time, changes you make to it are
1992 Since the file is re-read from disk each time, changes you make to it are
1993 reflected immediately (in contrast to the behavior of
1993 reflected immediately (in contrast to the behavior of
1994 \family typewriter
1994 \family typewriter
1995 import
1995 import
1996 \family default
1996 \family default
1997 ).
1997 ).
1998 I rarely use
1998 I rarely use
1999 \family typewriter
1999 \family typewriter
2000 import
2000 import
2001 \family default
2001 \family default
2002 for code I am testing, relying on
2002 for code I am testing, relying on
2003 \family typewriter
2003 \family typewriter
2004 %run
2004 %run
2005 \family default
2005 \family default
2006 instead.
2006 instead.
2007 See sec.
2007 See sec.
2008
2008
2009 \begin_inset LatexCommand \ref{sec:magic}
2009 \begin_inset LatexCommand \ref{sec:magic}
2010
2010
2011 \end_inset
2011 \end_inset
2012
2012
2013 for more on this and other magic commands, or type the name of any magic
2013 for more on this and other magic commands, or type the name of any magic
2014 command and ? to get details on it.
2014 command and ? to get details on it.
2015 See also sec.
2015 See also sec.
2016
2016
2017 \begin_inset LatexCommand \ref{sec:dreload}
2017 \begin_inset LatexCommand \ref{sec:dreload}
2018
2018
2019 \end_inset
2019 \end_inset
2020
2020
2021 for a recursive reload command.
2021 for a recursive reload command.
2022 \newline
2022 \newline
2023
2023
2024 \family typewriter
2024 \family typewriter
2025 %run
2025 %run
2026 \family default
2026 \family default
2027 also has special flags for timing the execution of your scripts (
2027 also has special flags for timing the execution of your scripts (
2028 \family typewriter
2028 \family typewriter
2029 -t
2029 -t
2030 \family default
2030 \family default
2031 ) and for executing them under the control of either Python's
2031 ) and for executing them under the control of either Python's
2032 \family typewriter
2032 \family typewriter
2033 pdb
2033 pdb
2034 \family default
2034 \family default
2035 debugger (
2035 debugger (
2036 \family typewriter
2036 \family typewriter
2037 -d
2037 -d
2038 \family default
2038 \family default
2039 ) or profiler (
2039 ) or profiler (
2040 \family typewriter
2040 \family typewriter
2041 -p
2041 -p
2042 \family default
2042 \family default
2043 ).
2043 ).
2044 With all of these,
2044 With all of these,
2045 \family typewriter
2045 \family typewriter
2046 %run
2046 %run
2047 \family default
2047 \family default
2048 can be used as the main tool for efficient interactive development of code
2048 can be used as the main tool for efficient interactive development of code
2049 which you write in your editor of choice.
2049 which you write in your editor of choice.
2050 \layout Itemize
2050 \layout Itemize
2051
2051
2052 Use the Python debugger,
2052 Use the Python debugger,
2053 \family typewriter
2053 \family typewriter
2054 pdb
2054 pdb
2055 \family default
2055 \family default
2056
2056
2057 \begin_inset Foot
2057 \begin_inset Foot
2058 collapsed true
2058 collapsed true
2059
2059
2060 \layout Standard
2060 \layout Standard
2061
2061
2062 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2062 Thanks to Christian Hart and Matthew Arnison for the suggestions leading
2063 to IPython's improved debugger and profiler support.
2063 to IPython's improved debugger and profiler support.
2064 \end_inset
2064 \end_inset
2065
2065
2066 .
2066 .
2067 The
2067 The
2068 \family typewriter
2068 \family typewriter
2069 %pdb
2069 %pdb
2070 \family default
2070 \family default
2071 command allows you to toggle on and off the automatic invocation of an
2071 command allows you to toggle on and off the automatic invocation of an
2072 IPython-enhanced
2072 IPython-enhanced
2073 \family typewriter
2073 \family typewriter
2074 pdb
2074 pdb
2075 \family default
2075 \family default
2076 debugger (with coloring, tab completion and more) at any uncaught exception.
2076 debugger (with coloring, tab completion and more) at any uncaught exception.
2077 The advantage of this is that
2077 The advantage of this is that
2078 \family typewriter
2078 \family typewriter
2079 pdb
2079 pdb
2080 \family default
2080 \family default
2081 starts
2081 starts
2082 \emph on
2082 \emph on
2083 inside
2083 inside
2084 \emph default
2084 \emph default
2085 the function where the exception occurred, with all data still available.
2085 the function where the exception occurred, with all data still available.
2086 You can print variables, see code, execute statements and even walk up
2086 You can print variables, see code, execute statements and even walk up
2087 and down the call stack to track down the true source of the problem (which
2087 and down the call stack to track down the true source of the problem (which
2088 often is many layers in the stack above where the exception gets triggered).
2088 often is many layers in the stack above where the exception gets triggered).
2089 \newline
2089 \newline
2090 Running programs with
2090 Running programs with
2091 \family typewriter
2091 \family typewriter
2092 %run
2092 %run
2093 \family default
2093 \family default
2094 and pdb active can be an efficient to develop and debug code, in many cases
2094 and pdb active can be an efficient to develop and debug code, in many cases
2095 eliminating the need for
2095 eliminating the need for
2096 \family typewriter
2096 \family typewriter
2097 print
2097 print
2098 \family default
2098 \family default
2099 statements or external debugging tools.
2099 statements or external debugging tools.
2100 I often simply put a
2100 I often simply put a
2101 \family typewriter
2101 \family typewriter
2102 1/0
2102 1/0
2103 \family default
2103 \family default
2104 in a place where I want to take a look so that pdb gets called, quickly
2104 in a place where I want to take a look so that pdb gets called, quickly
2105 view whatever variables I need to or test various pieces of code and then
2105 view whatever variables I need to or test various pieces of code and then
2106 remove the
2106 remove the
2107 \family typewriter
2107 \family typewriter
2108 1/0
2108 1/0
2109 \family default
2109 \family default
2110 .
2110 .
2111 \newline
2111 \newline
2112 Note also that `
2112 Note also that `
2113 \family typewriter
2113 \family typewriter
2114 %run -d
2114 %run -d
2115 \family default
2115 \family default
2116 ' activates
2116 ' activates
2117 \family typewriter
2117 \family typewriter
2118 pdb
2118 pdb
2119 \family default
2119 \family default
2120 and automatically sets initial breakpoints for you to step through your
2120 and automatically sets initial breakpoints for you to step through your
2121 code, watch variables, etc.
2121 code, watch variables, etc.
2122 See Sec.\SpecialChar ~
2122 See Sec.\SpecialChar ~
2123
2123
2124 \begin_inset LatexCommand \ref{sec:cache_output}
2124 \begin_inset LatexCommand \ref{sec:cache_output}
2125
2125
2126 \end_inset
2126 \end_inset
2127
2127
2128 for details.
2128 for details.
2129 \layout Itemize
2129 \layout Itemize
2130
2130
2131 Use the output cache.
2131 Use the output cache.
2132 All output results are automatically stored in a global dictionary named
2132 All output results are automatically stored in a global dictionary named
2133
2133
2134 \family typewriter
2134 \family typewriter
2135 Out
2135 Out
2136 \family default
2136 \family default
2137 and variables named
2137 and variables named
2138 \family typewriter
2138 \family typewriter
2139 _1
2139 _1
2140 \family default
2140 \family default
2141 ,
2141 ,
2142 \family typewriter
2142 \family typewriter
2143 _2
2143 _2
2144 \family default
2144 \family default
2145 , etc.
2145 , etc.
2146 alias them.
2146 alias them.
2147 For example, the result of input line 4 is available either as
2147 For example, the result of input line 4 is available either as
2148 \family typewriter
2148 \family typewriter
2149 Out[4]
2149 Out[4]
2150 \family default
2150 \family default
2151 or as
2151 or as
2152 \family typewriter
2152 \family typewriter
2153 _4
2153 _4
2154 \family default
2154 \family default
2155 .
2155 .
2156 Additionally, three variables named
2156 Additionally, three variables named
2157 \family typewriter
2157 \family typewriter
2158 _
2158 _
2159 \family default
2159 \family default
2160 ,
2160 ,
2161 \family typewriter
2161 \family typewriter
2162 __
2162 __
2163 \family default
2163 \family default
2164 and
2164 and
2165 \family typewriter
2165 \family typewriter
2166 ___
2166 ___
2167 \family default
2167 \family default
2168 are always kept updated with the for the last three results.
2168 are always kept updated with the for the last three results.
2169 This allows you to recall any previous result and further use it for new
2169 This allows you to recall any previous result and further use it for new
2170 calculations.
2170 calculations.
2171 See Sec.\SpecialChar ~
2171 See Sec.\SpecialChar ~
2172
2172
2173 \begin_inset LatexCommand \ref{sec:cache_output}
2173 \begin_inset LatexCommand \ref{sec:cache_output}
2174
2174
2175 \end_inset
2175 \end_inset
2176
2176
2177 for more.
2177 for more.
2178 \layout Itemize
2178 \layout Itemize
2179
2179
2180 Put a '
2180 Put a '
2181 \family typewriter
2181 \family typewriter
2182 ;
2182 ;
2183 \family default
2183 \family default
2184 ' at the end of a line to supress the printing of output.
2184 ' at the end of a line to supress the printing of output.
2185 This is useful when doing calculations which generate long output you are
2185 This is useful when doing calculations which generate long output you are
2186 not interested in seeing.
2186 not interested in seeing.
2187 The
2187 The
2188 \family typewriter
2188 \family typewriter
2189 _*
2189 _*
2190 \family default
2190 \family default
2191 variables and the
2191 variables and the
2192 \family typewriter
2192 \family typewriter
2193 Out[]
2193 Out[]
2194 \family default
2194 \family default
2195 list do get updated with the contents of the output, even if it is not
2195 list do get updated with the contents of the output, even if it is not
2196 printed.
2196 printed.
2197 You can thus still access the generated results this way for further processing.
2197 You can thus still access the generated results this way for further processing.
2198 \layout Itemize
2198 \layout Itemize
2199
2199
2200 A similar system exists for caching input.
2200 A similar system exists for caching input.
2201 All input is stored in a global list called
2201 All input is stored in a global list called
2202 \family typewriter
2202 \family typewriter
2203 In
2203 In
2204 \family default
2204 \family default
2205 , so you can re-execute lines 22 through 28 plus line 34 by typing
2205 , so you can re-execute lines 22 through 28 plus line 34 by typing
2206 \family typewriter
2206 \family typewriter
2207 'exec In[22:29]+In[34]'
2207 'exec In[22:29]+In[34]'
2208 \family default
2208 \family default
2209 (using Python slicing notation).
2209 (using Python slicing notation).
2210 If you need to execute the same set of lines often, you can assign them
2210 If you need to execute the same set of lines often, you can assign them
2211 to a macro with the
2211 to a macro with the
2212 \family typewriter
2212 \family typewriter
2213 %macro
2213 %macro
2214 \family default
2214 \family default
2215
2215
2216 \family typewriter
2216 \family typewriter
2217 function.
2217 function.
2218
2218
2219 \family default
2219 \family default
2220 See sec.
2220 See sec.
2221
2221
2222 \begin_inset LatexCommand \ref{sec:cache_input}
2222 \begin_inset LatexCommand \ref{sec:cache_input}
2223
2223
2224 \end_inset
2224 \end_inset
2225
2225
2226 for more.
2226 for more.
2227 \layout Itemize
2227 \layout Itemize
2228
2228
2229 Use your input history.
2229 Use your input history.
2230 The
2230 The
2231 \family typewriter
2231 \family typewriter
2232 %hist
2232 %hist
2233 \family default
2233 \family default
2234 command can show you all previous input, without line numbers if desired
2234 command can show you all previous input, without line numbers if desired
2235 (option
2235 (option
2236 \family typewriter
2236 \family typewriter
2237 -n
2237 -n
2238 \family default
2238 \family default
2239 ) so you can directly copy and paste code either back in IPython or in a
2239 ) so you can directly copy and paste code either back in IPython or in a
2240 text editor.
2240 text editor.
2241 You can also save all your history by turning on logging via
2241 You can also save all your history by turning on logging via
2242 \family typewriter
2242 \family typewriter
2243 %logstart
2243 %logstart
2244 \family default
2244 \family default
2245 ; these logs can later be either reloaded as IPython sessions or used as
2245 ; these logs can later be either reloaded as IPython sessions or used as
2246 code for your programs.
2246 code for your programs.
2247 \layout Itemize
2247 \layout Itemize
2248
2248
2249 Define your own macros with
2249 Define your own macros with
2250 \family typewriter
2250 \family typewriter
2251 %macro
2251 %macro
2252 \family default
2252 \family default
2253 .
2253 .
2254 This can be useful for automating sequences of expressions when working
2254 This can be useful for automating sequences of expressions when working
2255 interactively.
2255 interactively.
2256 \layout Itemize
2256 \layout Itemize
2257
2257
2258 Define your own system aliases.
2258 Define your own system aliases.
2259 Even though IPython gives you access to your system shell via the
2259 Even though IPython gives you access to your system shell via the
2260 \family typewriter
2260 \family typewriter
2261 !
2261 !
2262 \family default
2262 \family default
2263 prefix, it is convenient to have aliases to the system commands you use
2263 prefix, it is convenient to have aliases to the system commands you use
2264 most often.
2264 most often.
2265 This allows you to work seamlessly from inside IPython with the same commands
2265 This allows you to work seamlessly from inside IPython with the same commands
2266 you are used to in your system shell.
2266 you are used to in your system shell.
2267 \newline
2267 \newline
2268 IPython comes with some pre-defined aliases and a complete system for changing
2268 IPython comes with some pre-defined aliases and a complete system for changing
2269 directories, both via a stack (see
2269 directories, both via a stack (see
2270 \family typewriter
2270 \family typewriter
2271 %pushd
2271 %pushd
2272 \family default
2272 \family default
2273 ,
2273 ,
2274 \family typewriter
2274 \family typewriter
2275 %popd
2275 %popd
2276 \family default
2276 \family default
2277 and
2277 and
2278 \family typewriter
2278 \family typewriter
2279 %ds
2279 %ds
2280 \family default
2280 \family default
2281 ) and via direct
2281 ) and via direct
2282 \family typewriter
2282 \family typewriter
2283 %cd
2283 %cd
2284 \family default
2284 \family default
2285 .
2285 .
2286 The latter keeps a history of visited directories and allows you to go
2286 The latter keeps a history of visited directories and allows you to go
2287 to any previously visited one.
2287 to any previously visited one.
2288 \layout Itemize
2288 \layout Itemize
2289
2289
2290 Use Python to manipulate the results of system commands.
2290 Use Python to manipulate the results of system commands.
2291 The `
2291 The `
2292 \family typewriter
2292 \family typewriter
2293 !!
2293 !!
2294 \family default
2294 \family default
2295 ' special syntax, and the
2295 ' special syntax, and the
2296 \family typewriter
2296 \family typewriter
2297 %sc
2297 %sc
2298 \family default
2298 \family default
2299 and
2299 and
2300 \family typewriter
2300 \family typewriter
2301 %sx
2301 %sx
2302 \family default
2302 \family default
2303 magic commands allow you to capture system output into Python variables.
2303 magic commands allow you to capture system output into Python variables.
2304 \layout Itemize
2304 \layout Itemize
2305
2305
2306 Expand python variables when calling the shell (either via
2306 Expand python variables when calling the shell (either via
2307 \family typewriter
2307 \family typewriter
2308 `!'
2308 `!'
2309 \family default
2309 \family default
2310 and
2310 and
2311 \family typewriter
2311 \family typewriter
2312 `!!'
2312 `!!'
2313 \family default
2313 \family default
2314 or via aliases) by prepending a
2314 or via aliases) by prepending a
2315 \family typewriter
2315 \family typewriter
2316 $
2316 $
2317 \family default
2317 \family default
2318 in front of them.
2318 in front of them.
2319 You can also expand complete python expressions.
2319 You can also expand complete python expressions.
2320 See sec.\SpecialChar ~
2320 See sec.\SpecialChar ~
2321
2321
2322 \begin_inset LatexCommand \ref{sub:System-shell-access}
2322 \begin_inset LatexCommand \ref{sub:System-shell-access}
2323
2323
2324 \end_inset
2324 \end_inset
2325
2325
2326 for more.
2326 for more.
2327 \layout Itemize
2327 \layout Itemize
2328
2328
2329 Use profiles to maintain different configurations (modules to load, function
2329 Use profiles to maintain different configurations (modules to load, function
2330 definitions, option settings) for particular tasks.
2330 definitions, option settings) for particular tasks.
2331 You can then have customized versions of IPython for specific purposes.
2331 You can then have customized versions of IPython for specific purposes.
2332 See sec.\SpecialChar ~
2332 See sec.\SpecialChar ~
2333
2333
2334 \begin_inset LatexCommand \ref{sec:profiles}
2334 \begin_inset LatexCommand \ref{sec:profiles}
2335
2335
2336 \end_inset
2336 \end_inset
2337
2337
2338 for more.
2338 for more.
2339 \layout Itemize
2339 \layout Itemize
2340
2340
2341 Embed IPython in your programs.
2341 Embed IPython in your programs.
2342 A few lines of code are enough to load a complete IPython inside your own
2342 A few lines of code are enough to load a complete IPython inside your own
2343 programs, giving you the ability to work with your data interactively after
2343 programs, giving you the ability to work with your data interactively after
2344 automatic processing has been completed.
2344 automatic processing has been completed.
2345 See sec.\SpecialChar ~
2345 See sec.\SpecialChar ~
2346
2346
2347 \begin_inset LatexCommand \ref{sec:embed}
2347 \begin_inset LatexCommand \ref{sec:embed}
2348
2348
2349 \end_inset
2349 \end_inset
2350
2350
2351 for more.
2351 for more.
2352 \layout Itemize
2352 \layout Itemize
2353
2353
2354 Use the Python profiler.
2354 Use the Python profiler.
2355 When dealing with performance issues, the
2355 When dealing with performance issues, the
2356 \family typewriter
2356 \family typewriter
2357 %run
2357 %run
2358 \family default
2358 \family default
2359 command with a
2359 command with a
2360 \family typewriter
2360 \family typewriter
2361 -p
2361 -p
2362 \family default
2362 \family default
2363 option allows you to run complete programs under the control of the Python
2363 option allows you to run complete programs under the control of the Python
2364 profiler.
2364 profiler.
2365 The
2365 The
2366 \family typewriter
2366 \family typewriter
2367 %prun
2367 %prun
2368 \family default
2368 \family default
2369 command does a similar job for single Python expressions (like function
2369 command does a similar job for single Python expressions (like function
2370 calls).
2370 calls).
2371 \layout Itemize
2371 \layout Itemize
2372
2372
2373 Use
2373 Use
2374 \family typewriter
2374 \family typewriter
2375 %edit
2375 %edit
2376 \family default
2376 \family default
2377 to have almost multiline editing.
2377 to have almost multiline editing.
2378 While IPython doesn't support true multiline editing, this command allows
2378 While IPython doesn't support true multiline editing, this command allows
2379 you to call an editor on the spot, and IPython will execute the code you
2379 you to call an editor on the spot, and IPython will execute the code you
2380 type in there as if it were typed interactively.
2380 type in there as if it were typed interactively.
2381 \layout Itemize
2381 \layout Itemize
2382
2382
2383 Use the IPython.demo.Demo class to load any Python script as an interactive
2383 Use the IPython.demo.Demo class to load any Python script as an interactive
2384 demo.
2384 demo.
2385 With a minimal amount of simple markup, you can control the execution of
2385 With a minimal amount of simple markup, you can control the execution of
2386 the script, stopping as needed.
2386 the script, stopping as needed.
2387 See sec.\SpecialChar ~
2387 See sec.\SpecialChar ~
2388
2388
2389 \begin_inset LatexCommand \ref{sec:interactive-demos}
2389 \begin_inset LatexCommand \ref{sec:interactive-demos}
2390
2390
2391 \end_inset
2391 \end_inset
2392
2392
2393 for more.
2393 for more.
2394 \layout Standard
2394 \layout Standard
2395
2395
2396 If you have your own favorite tip on using IPython efficiently for a certain
2396 If you have your own favorite tip on using IPython efficiently for a certain
2397 task (especially things which can't be done in the normal Python interpreter),
2397 task (especially things which can't be done in the normal Python interpreter),
2398 don't hesitate to send it!
2398 don't hesitate to send it!
2399 \layout Section
2399 \layout Section
2400
2400
2401 Command-line use
2401 Command-line use
2402 \layout Standard
2402 \layout Standard
2403
2403
2404 You start IPython with the command:
2404 You start IPython with the command:
2405 \layout Standard
2405 \layout Standard
2406
2406
2407
2407
2408 \family typewriter
2408 \family typewriter
2409 $ ipython [options] files
2409 $ ipython [options] files
2410 \layout Standard
2410 \layout Standard
2411
2411
2412 If invoked with no options, it executes all the files listed in sequence
2412 If invoked with no options, it executes all the files listed in sequence
2413 and drops you into the interpreter while still acknowledging any options
2413 and drops you into the interpreter while still acknowledging any options
2414 you may have set in your ipythonrc file.
2414 you may have set in your ipythonrc file.
2415 This behavior is different from standard Python, which when called as
2415 This behavior is different from standard Python, which when called as
2416 \family typewriter
2416 \family typewriter
2417 python -i
2417 python -i
2418 \family default
2418 \family default
2419 will only execute one file and ignore your configuration setup.
2419 will only execute one file and ignore your configuration setup.
2420 \layout Standard
2420 \layout Standard
2421
2421
2422 Please note that some of the configuration options are not available at
2422 Please note that some of the configuration options are not available at
2423 the command line, simply because they are not practical here.
2423 the command line, simply because they are not practical here.
2424 Look into your ipythonrc configuration file for details on those.
2424 Look into your ipythonrc configuration file for details on those.
2425 This file typically installed in the
2425 This file typically installed in the
2426 \family typewriter
2426 \family typewriter
2427 $HOME/.ipython
2427 $HOME/.ipython
2428 \family default
2428 \family default
2429 directory.
2429 directory.
2430 For Windows users,
2430 For Windows users,
2431 \family typewriter
2431 \family typewriter
2432 $HOME
2432 $HOME
2433 \family default
2433 \family default
2434 resolves to
2434 resolves to
2435 \family typewriter
2435 \family typewriter
2436 C:
2436 C:
2437 \backslash
2437 \backslash
2438
2438
2439 \backslash
2439 \backslash
2440 Documents and Settings
2440 Documents and Settings
2441 \backslash
2441 \backslash
2442
2442
2443 \backslash
2443 \backslash
2444 YourUserName
2444 YourUserName
2445 \family default
2445 \family default
2446 in most instances.
2446 in most instances.
2447 In the rest of this text, we will refer to this directory as
2447 In the rest of this text, we will refer to this directory as
2448 \family typewriter
2448 \family typewriter
2449 IPYTHONDIR
2449 IPYTHONDIR
2450 \family default
2450 \family default
2451 .
2451 .
2452 \layout Subsection
2452 \layout Subsection
2453
2453
2454
2454
2455 \begin_inset LatexCommand \label{sec:threading-opts}
2455 \begin_inset LatexCommand \label{sec:threading-opts}
2456
2456
2457 \end_inset
2457 \end_inset
2458
2458
2459 Special Threading Options
2459 Special Threading Options
2460 \layout Standard
2460 \layout Standard
2461
2461
2462 The following special options are ONLY valid at the beginning of the command
2462 The following special options are ONLY valid at the beginning of the command
2463 line, and not later.
2463 line, and not later.
2464 This is because they control the initial- ization of ipython itself, before
2464 This is because they control the initial- ization of ipython itself, before
2465 the normal option-handling mechanism is active.
2465 the normal option-handling mechanism is active.
2466 \layout List
2466 \layout List
2467 \labelwidthstring 00.00.0000
2467 \labelwidthstring 00.00.0000
2468
2468
2469
2469
2470 \family typewriter
2470 \family typewriter
2471 \series bold
2471 \series bold
2472 -gthread,\SpecialChar ~
2472 -gthread,\SpecialChar ~
2473 -qthread,\SpecialChar ~
2473 -qthread,\SpecialChar ~
2474 -wthread,\SpecialChar ~
2474 -wthread,\SpecialChar ~
2475 -pylab:
2475 -pylab:
2476 \family default
2476 \family default
2477 \series default
2477 \series default
2478 Only
2478 Only
2479 \emph on
2479 \emph on
2480 one
2480 one
2481 \emph default
2481 \emph default
2482 of these can be given, and it can only be given as the first option passed
2482 of these can be given, and it can only be given as the first option passed
2483 to IPython (it will have no effect in any other position).
2483 to IPython (it will have no effect in any other position).
2484 They provide threading support for the GTK Qt and WXPython toolkits, and
2484 They provide threading support for the GTK Qt and WXPython toolkits, and
2485 for the matplotlib library.
2485 for the matplotlib library.
2486 \layout List
2486 \layout List
2487 \labelwidthstring 00.00.0000
2487 \labelwidthstring 00.00.0000
2488
2488
2489 \SpecialChar ~
2489 \SpecialChar ~
2490 With any of the first three options, IPython starts running a separate
2490 With any of the first three options, IPython starts running a separate
2491 thread for the graphical toolkit's operation, so that you can open and
2491 thread for the graphical toolkit's operation, so that you can open and
2492 control graphical elements from within an IPython command line, without
2492 control graphical elements from within an IPython command line, without
2493 blocking.
2493 blocking.
2494 All three provide essentially the same functionality, respectively for
2494 All three provide essentially the same functionality, respectively for
2495 GTK, QT and WXWidgets (via their Python interfaces).
2495 GTK, QT and WXWidgets (via their Python interfaces).
2496 \layout List
2496 \layout List
2497 \labelwidthstring 00.00.0000
2497 \labelwidthstring 00.00.0000
2498
2498
2499 \SpecialChar ~
2499 \SpecialChar ~
2500 If
2500 If
2501 \family typewriter
2501 \family typewriter
2502 -pylab
2502 -pylab
2503 \family default
2503 \family default
2504 is given, IPython loads special support for the mat plotlib library (
2504 is given, IPython loads special support for the mat plotlib library (
2505 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2505 \begin_inset LatexCommand \htmlurl{http://matplotlib.sourceforge.net}
2506
2506
2507 \end_inset
2507 \end_inset
2508
2508
2509 ), allowing interactive usage of any of its backends as defined in the user's
2509 ), allowing interactive usage of any of its backends as defined in the user's
2510
2510
2511 \family typewriter
2511 \family typewriter
2512 ~/.matplotlib/matplotlibrc
2512 ~/.matplotlib/matplotlibrc
2513 \family default
2513 \family default
2514 file.
2514 file.
2515 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2515 It automatically activates GTK, Qt or WX threading for IPyhton if the choice
2516 of matplotlib backend requires it.
2516 of matplotlib backend requires it.
2517 It also modifies the
2517 It also modifies the
2518 \family typewriter
2518 \family typewriter
2519 %run
2519 %run
2520 \family default
2520 \family default
2521 command to correctly execute (without blocking) any matplotlib-based script
2521 command to correctly execute (without blocking) any matplotlib-based script
2522 which calls
2522 which calls
2523 \family typewriter
2523 \family typewriter
2524 show()
2524 show()
2525 \family default
2525 \family default
2526 at the end.
2526 at the end.
2527
2527
2528 \layout List
2528 \layout List
2529 \labelwidthstring 00.00.0000
2529 \labelwidthstring 00.00.0000
2530
2530
2531
2531
2532 \family typewriter
2532 \family typewriter
2533 \series bold
2533 \series bold
2534 -tk
2534 -tk
2535 \family default
2535 \family default
2536 \series default
2536 \series default
2537 The
2537 The
2538 \family typewriter
2538 \family typewriter
2539 -g/q/wthread
2539 -g/q/wthread
2540 \family default
2540 \family default
2541 options, and
2541 options, and
2542 \family typewriter
2542 \family typewriter
2543 -pylab
2543 -pylab
2544 \family default
2544 \family default
2545 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2545 (if matplotlib is configured to use GTK, Qt or WX), will normally block
2546 Tk graphical interfaces.
2546 Tk graphical interfaces.
2547 This means that when either GTK, Qt or WX threading is active, any attempt
2547 This means that when either GTK, Qt or WX threading is active, any attempt
2548 to open a Tk GUI will result in a dead window, and possibly cause the Python
2548 to open a Tk GUI will result in a dead window, and possibly cause the Python
2549 interpreter to crash.
2549 interpreter to crash.
2550 An extra option,
2550 An extra option,
2551 \family typewriter
2551 \family typewriter
2552 -tk
2552 -tk
2553 \family default
2553 \family default
2554 , is available to address this issue.
2554 , is available to address this issue.
2555 It can
2555 It can
2556 \emph on
2556 \emph on
2557 only
2557 only
2558 \emph default
2558 \emph default
2559 be given as a
2559 be given as a
2560 \emph on
2560 \emph on
2561 second
2561 second
2562 \emph default
2562 \emph default
2563 option after any of the above (
2563 option after any of the above (
2564 \family typewriter
2564 \family typewriter
2565 -gthread
2565 -gthread
2566 \family default
2566 \family default
2567 ,
2567 ,
2568 \family typewriter
2568 \family typewriter
2569 -wthread
2569 -wthread
2570 \family default
2570 \family default
2571 or
2571 or
2572 \family typewriter
2572 \family typewriter
2573 -pylab
2573 -pylab
2574 \family default
2574 \family default
2575 ).
2575 ).
2576 \layout List
2576 \layout List
2577 \labelwidthstring 00.00.0000
2577 \labelwidthstring 00.00.0000
2578
2578
2579 \SpecialChar ~
2579 \SpecialChar ~
2580 If
2580 If
2581 \family typewriter
2581 \family typewriter
2582 -tk
2582 -tk
2583 \family default
2583 \family default
2584 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2584 is given, IPython will try to coordinate Tk threading with GTK, Qt or WX.
2585 This is however potentially unreliable, and you will have to test on your
2585 This is however potentially unreliable, and you will have to test on your
2586 platform and Python configuration to determine whether it works for you.
2586 platform and Python configuration to determine whether it works for you.
2587 Debian users have reported success, apparently due to the fact that Debian
2587 Debian users have reported success, apparently due to the fact that Debian
2588 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2588 builds all of Tcl, Tk, Tkinter and Python with pthreads support.
2589 Under other Linux environments (such as Fedora Core 2/3), this option has
2589 Under other Linux environments (such as Fedora Core 2/3), this option has
2590 caused random crashes and lockups of the Python interpreter.
2590 caused random crashes and lockups of the Python interpreter.
2591 Under other operating systems (Mac OSX and Windows), you'll need to try
2591 Under other operating systems (Mac OSX and Windows), you'll need to try
2592 it to find out, since currently no user reports are available.
2592 it to find out, since currently no user reports are available.
2593 \layout List
2593 \layout List
2594 \labelwidthstring 00.00.0000
2594 \labelwidthstring 00.00.0000
2595
2595
2596 \SpecialChar ~
2596 \SpecialChar ~
2597 There is unfortunately no way for IPython to determine at run time whether
2597 There is unfortunately no way for IPython to determine at run time whether
2598
2598
2599 \family typewriter
2599 \family typewriter
2600 -tk
2600 -tk
2601 \family default
2601 \family default
2602 will work reliably or not, so you will need to do some experiments before
2602 will work reliably or not, so you will need to do some experiments before
2603 relying on it for regular work.
2603 relying on it for regular work.
2604
2604
2605 \layout Subsection
2605 \layout Subsection
2606
2606
2607
2607
2608 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2608 \begin_inset LatexCommand \label{sec:cmd-line-opts}
2609
2609
2610 \end_inset
2610 \end_inset
2611
2611
2612 Regular Options
2612 Regular Options
2613 \layout Standard
2613 \layout Standard
2614
2614
2615 After the above threading options have been given, regular options can follow
2615 After the above threading options have been given, regular options can follow
2616 in any order.
2616 in any order.
2617 All options can be abbreviated to their shortest non-ambiguous form and
2617 All options can be abbreviated to their shortest non-ambiguous form and
2618 are case-sensitive.
2618 are case-sensitive.
2619 One or two dashes can be used.
2619 One or two dashes can be used.
2620 Some options have an alternate short form, indicated after a
2620 Some options have an alternate short form, indicated after a
2621 \family typewriter
2621 \family typewriter
2622 |
2622 |
2623 \family default
2623 \family default
2624 .
2624 .
2625 \layout Standard
2625 \layout Standard
2626
2626
2627 Most options can also be set from your ipythonrc configuration file.
2627 Most options can also be set from your ipythonrc configuration file.
2628 See the provided example for more details on what the options do.
2628 See the provided example for more details on what the options do.
2629 Options given at the command line override the values set in the ipythonrc
2629 Options given at the command line override the values set in the ipythonrc
2630 file.
2630 file.
2631 \layout Standard
2631 \layout Standard
2632
2632
2633 All options with a
2633 All options with a
2634 \family typewriter
2634 \family typewriter
2635 [no]
2635 [no]
2636 \family default
2636 \family default
2637 prepended can be specified in negated form (
2637 prepended can be specified in negated form (
2638 \family typewriter
2638 \family typewriter
2639 -nooption
2639 -nooption
2640 \family default
2640 \family default
2641 instead of
2641 instead of
2642 \family typewriter
2642 \family typewriter
2643 -option
2643 -option
2644 \family default
2644 \family default
2645 ) to turn the feature off.
2645 ) to turn the feature off.
2646 \layout List
2646 \layout List
2647 \labelwidthstring 00.00.0000
2647 \labelwidthstring 00.00.0000
2648
2648
2649
2649
2650 \family typewriter
2650 \family typewriter
2651 \series bold
2651 \series bold
2652 -help
2652 -help
2653 \family default
2653 \family default
2654 \series default
2654 \series default
2655 : print a help message and exit.
2655 : print a help message and exit.
2656 \layout List
2656 \layout List
2657 \labelwidthstring 00.00.0000
2657 \labelwidthstring 00.00.0000
2658
2658
2659
2659
2660 \family typewriter
2660 \family typewriter
2661 \series bold
2661 \series bold
2662 -pylab:
2662 -pylab:
2663 \family default
2663 \family default
2664 \series default
2664 \series default
2665 this can
2665 this can
2666 \emph on
2666 \emph on
2667 only
2667 only
2668 \emph default
2668 \emph default
2669 be given as the
2669 be given as the
2670 \emph on
2670 \emph on
2671 first
2671 first
2672 \emph default
2672 \emph default
2673 option passed to IPython (it will have no effect in any other position).
2673 option passed to IPython (it will have no effect in any other position).
2674 It adds special support for the matplotlib library (
2674 It adds special support for the matplotlib library (
2675 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2675 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
2676
2676
2677 \end_inset
2677 \end_inset
2678
2678
2679 ), allowing interactive usage of any of its backends as defined in the user's
2679 ), allowing interactive usage of any of its backends as defined in the user's
2680
2680
2681 \family typewriter
2681 \family typewriter
2682 .matplotlibrc
2682 .matplotlibrc
2683 \family default
2683 \family default
2684 file.
2684 file.
2685 It automatically activates GTK or WX threading for IPyhton if the choice
2685 It automatically activates GTK or WX threading for IPyhton if the choice
2686 of matplotlib backend requires it.
2686 of matplotlib backend requires it.
2687 It also modifies the
2687 It also modifies the
2688 \family typewriter
2688 \family typewriter
2689 %run
2689 %run
2690 \family default
2690 \family default
2691 command to correctly execute (without blocking) any matplotlib-based script
2691 command to correctly execute (without blocking) any matplotlib-based script
2692 which calls
2692 which calls
2693 \family typewriter
2693 \family typewriter
2694 show()
2694 show()
2695 \family default
2695 \family default
2696 at the end.
2696 at the end.
2697 See Sec.\SpecialChar ~
2697 See Sec.\SpecialChar ~
2698
2698
2699 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2699 \begin_inset LatexCommand \ref{sec:matplotlib-support}
2700
2700
2701 \end_inset
2701 \end_inset
2702
2702
2703 for more details.
2703 for more details.
2704 \layout List
2704 \layout List
2705 \labelwidthstring 00.00.0000
2705 \labelwidthstring 00.00.0000
2706
2706
2707
2707
2708 \family typewriter
2708 \family typewriter
2709 \series bold
2709 \series bold
2710 -[no]autocall:
2711 \family default
2712 \series default
2713 Make IPython automatically call any callable object even if you didn't
2714 type explicit parentheses.
2715 For example, `str 43' becomes `str(43)' automatically.
2716 \layout List
2717 \labelwidthstring 00.00.0000
2718
2719
2720 \family typewriter
2721 \series bold
2722 -[no]autoindent:
2723 \family default
2724 \series default
2725 Turn automatic indentation on/off.
2726 \layout List
2727 \labelwidthstring 00.00.0000
2728
2729
2730 \family typewriter
2731 \series bold
2710 -[no]automagic
2732 -[no]automagic
2711 \series default
2733 \series default
2712 :
2734 :
2713 \family default
2735 \family default
2714 make magic commands automatic (without needing their first character to
2736 make magic commands automatic (without needing their first character to
2715 be
2737 be
2716 \family typewriter
2738 \family typewriter
2717 %
2739 %
2718 \family default
2740 \family default
2719 ).
2741 ).
2720 Type
2742 Type
2721 \family typewriter
2743 \family typewriter
2722 %magic
2744 %magic
2723 \family default
2745 \family default
2724 at the IPython prompt for more information.
2746 at the IPython prompt for more information.
2725 \layout List
2747 \layout List
2726 \labelwidthstring 00.00.0000
2748 \labelwidthstring 00.00.0000
2727
2749
2728
2750
2729 \family typewriter
2751 \family typewriter
2730 \series bold
2752 \series bold
2753 -[no]autoedit_syntax:
2754 \family default
2755 \series default
2756 When a syntax error occurs after editing a file, automatically open the
2757 file to the trouble causing line for convenient fixing.
2758
2759 \layout List
2760 \labelwidthstring 00.00.0000
2761
2762
2763 \family typewriter
2764 \series bold
2731 -[no]banner
2765 -[no]banner
2732 \series default
2766 \series default
2733 :
2767 :
2734 \family default
2768 \family default
2735 Print the initial information banner (default on).
2769 Print the initial information banner (default on).
2736 \layout List
2770 \layout List
2737 \labelwidthstring 00.00.0000
2771 \labelwidthstring 00.00.0000
2738
2772
2739
2773
2740 \family typewriter
2774 \family typewriter
2741 \series bold
2775 \series bold
2742 -c\SpecialChar ~
2776 -c\SpecialChar ~
2743 <command>:
2777 <command>:
2744 \family default
2778 \family default
2745 \series default
2779 \series default
2746 execute the given command string, and set sys.argv to
2780 execute the given command string, and set sys.argv to
2747 \family typewriter
2781 \family typewriter
2748 ['c']
2782 ['c']
2749 \family default
2783 \family default
2750 .
2784 .
2751 This is similar to the
2785 This is similar to the
2752 \family typewriter
2786 \family typewriter
2753 -c
2787 -c
2754 \family default
2788 \family default
2755 option in the normal Python interpreter.
2789 option in the normal Python interpreter.
2756
2790
2757 \layout List
2791 \layout List
2758 \labelwidthstring 00.00.0000
2792 \labelwidthstring 00.00.0000
2759
2793
2760
2794
2761 \family typewriter
2795 \family typewriter
2762 \series bold
2796 \series bold
2763 -cache_size|cs\SpecialChar ~
2797 -cache_size|cs\SpecialChar ~
2764 <n>
2798 <n>
2765 \series default
2799 \series default
2766 :
2800 :
2767 \family default
2801 \family default
2768 size of the output cache (maximum number of entries to hold in memory).
2802 size of the output cache (maximum number of entries to hold in memory).
2769 The default is 1000, you can change it permanently in your config file.
2803 The default is 1000, you can change it permanently in your config file.
2770 Setting it to 0 completely disables the caching system, and the minimum
2804 Setting it to 0 completely disables the caching system, and the minimum
2771 value accepted is 20 (if you provide a value less than 20, it is reset
2805 value accepted is 20 (if you provide a value less than 20, it is reset
2772 to 0 and a warning is issued) This limit is defined because otherwise you'll
2806 to 0 and a warning is issued) This limit is defined because otherwise you'll
2773 spend more time re-flushing a too small cache than working.
2807 spend more time re-flushing a too small cache than working.
2774 \layout List
2808 \layout List
2775 \labelwidthstring 00.00.0000
2809 \labelwidthstring 00.00.0000
2776
2810
2777
2811
2778 \family typewriter
2812 \family typewriter
2779 \series bold
2813 \series bold
2780 -classic|cl
2814 -classic|cl
2781 \series default
2815 \series default
2782 :
2816 :
2783 \family default
2817 \family default
2784 Gives IPython a similar feel to the classic Python prompt.
2818 Gives IPython a similar feel to the classic Python prompt.
2785 \layout List
2819 \layout List
2786 \labelwidthstring 00.00.0000
2820 \labelwidthstring 00.00.0000
2787
2821
2788
2822
2789 \family typewriter
2823 \family typewriter
2790 \series bold
2824 \series bold
2791 -colors\SpecialChar ~
2825 -colors\SpecialChar ~
2792 <scheme>:
2826 <scheme>:
2793 \family default
2827 \family default
2794 \series default
2828 \series default
2795 Color scheme for prompts and exception reporting.
2829 Color scheme for prompts and exception reporting.
2796 Currently implemented: NoColor, Linux and LightBG.
2830 Currently implemented: NoColor, Linux and LightBG.
2797 \layout List
2831 \layout List
2798 \labelwidthstring 00.00.0000
2832 \labelwidthstring 00.00.0000
2799
2833
2800
2834
2801 \family typewriter
2835 \family typewriter
2802 \series bold
2836 \series bold
2803 -[no]color_info:
2837 -[no]color_info:
2804 \family default
2838 \family default
2805 \series default
2839 \series default
2806 IPython can display information about objects via a set of functions, and
2840 IPython can display information about objects via a set of functions, and
2807 optionally can use colors for this, syntax highlighting source code and
2841 optionally can use colors for this, syntax highlighting source code and
2808 various other elements.
2842 various other elements.
2809 However, because this information is passed through a pager (like 'less')
2843 However, because this information is passed through a pager (like 'less')
2810 and many pagers get confused with color codes, this option is off by default.
2844 and many pagers get confused with color codes, this option is off by default.
2811 You can test it and turn it on permanently in your ipythonrc file if it
2845 You can test it and turn it on permanently in your ipythonrc file if it
2812 works for you.
2846 works for you.
2813 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
2847 As a reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
2814 that in RedHat 7.2 doesn't.
2848 that in RedHat 7.2 doesn't.
2815 \layout List
2849 \layout List
2816 \labelwidthstring 00.00.0000
2850 \labelwidthstring 00.00.0000
2817
2851
2818 \SpecialChar ~
2852 \SpecialChar ~
2819 Test it and turn it on permanently if it works with your system.
2853 Test it and turn it on permanently if it works with your system.
2820 The magic function
2854 The magic function
2821 \family typewriter
2855 \family typewriter
2822 %color_info
2856 %color_info
2823 \family default
2857 \family default
2824 allows you to toggle this interactively for testing.
2858 allows you to toggle this interactively for testing.
2825 \layout List
2859 \layout List
2826 \labelwidthstring 00.00.0000
2860 \labelwidthstring 00.00.0000
2827
2861
2828
2862
2829 \family typewriter
2863 \family typewriter
2830 \series bold
2864 \series bold
2831 -[no]debug
2865 -[no]debug
2832 \family default
2866 \family default
2833 \series default
2867 \series default
2834 : Show information about the loading process.
2868 : Show information about the loading process.
2835 Very useful to pin down problems with your configuration files or to get
2869 Very useful to pin down problems with your configuration files or to get
2836 details about session restores.
2870 details about session restores.
2837 \layout List
2871 \layout List
2838 \labelwidthstring 00.00.0000
2872 \labelwidthstring 00.00.0000
2839
2873
2840
2874
2841 \family typewriter
2875 \family typewriter
2842 \series bold
2876 \series bold
2843 -[no]deep_reload
2877 -[no]deep_reload
2844 \series default
2878 \series default
2845 :
2879 :
2846 \family default
2880 \family default
2847 IPython can use the
2881 IPython can use the
2848 \family typewriter
2882 \family typewriter
2849 deep_reload
2883 deep_reload
2850 \family default
2884 \family default
2851 module which reloads changes in modules recursively (it replaces the
2885 module which reloads changes in modules recursively (it replaces the
2852 \family typewriter
2886 \family typewriter
2853 reload()
2887 reload()
2854 \family default
2888 \family default
2855 function, so you don't need to change anything to use it).
2889 function, so you don't need to change anything to use it).
2856
2890
2857 \family typewriter
2891 \family typewriter
2858 deep_reload()
2892 deep_reload()
2859 \family default
2893 \family default
2860 forces a full reload of modules whose code may have changed, which the
2894 forces a full reload of modules whose code may have changed, which the
2861 default
2895 default
2862 \family typewriter
2896 \family typewriter
2863 reload()
2897 reload()
2864 \family default
2898 \family default
2865 function does not.
2899 function does not.
2866 \layout List
2900 \layout List
2867 \labelwidthstring 00.00.0000
2901 \labelwidthstring 00.00.0000
2868
2902
2869 \SpecialChar ~
2903 \SpecialChar ~
2870 When deep_reload is off, IPython will use the normal
2904 When deep_reload is off, IPython will use the normal
2871 \family typewriter
2905 \family typewriter
2872 reload()
2906 reload()
2873 \family default
2907 \family default
2874 , but deep_reload will still be available as
2908 , but deep_reload will still be available as
2875 \family typewriter
2909 \family typewriter
2876 dreload()
2910 dreload()
2877 \family default
2911 \family default
2878 .
2912 .
2879 This feature is off by default [which means that you have both normal
2913 This feature is off by default [which means that you have both normal
2880 \family typewriter
2914 \family typewriter
2881 reload()
2915 reload()
2882 \family default
2916 \family default
2883 and
2917 and
2884 \family typewriter
2918 \family typewriter
2885 dreload()
2919 dreload()
2886 \family default
2920 \family default
2887 ].
2921 ].
2888 \layout List
2922 \layout List
2889 \labelwidthstring 00.00.0000
2923 \labelwidthstring 00.00.0000
2890
2924
2891
2925
2892 \family typewriter
2926 \family typewriter
2893 \series bold
2927 \series bold
2894 -editor\SpecialChar ~
2928 -editor\SpecialChar ~
2895 <name>
2929 <name>
2896 \family default
2930 \family default
2897 \series default
2931 \series default
2898 : Which editor to use with the
2932 : Which editor to use with the
2899 \family typewriter
2933 \family typewriter
2900 %edit
2934 %edit
2901 \family default
2935 \family default
2902 command.
2936 command.
2903 By default, IPython will honor your
2937 By default, IPython will honor your
2904 \family typewriter
2938 \family typewriter
2905 EDITOR
2939 EDITOR
2906 \family default
2940 \family default
2907 environment variable (if not set, vi is the Unix default and notepad the
2941 environment variable (if not set, vi is the Unix default and notepad the
2908 Windows one).
2942 Windows one).
2909 Since this editor is invoked on the fly by IPython and is meant for editing
2943 Since this editor is invoked on the fly by IPython and is meant for editing
2910 small code snippets, you may want to use a small, lightweight editor here
2944 small code snippets, you may want to use a small, lightweight editor here
2911 (in case your default
2945 (in case your default
2912 \family typewriter
2946 \family typewriter
2913 EDITOR
2947 EDITOR
2914 \family default
2948 \family default
2915 is something like Emacs).
2949 is something like Emacs).
2916 \layout List
2950 \layout List
2917 \labelwidthstring 00.00.0000
2951 \labelwidthstring 00.00.0000
2918
2952
2919
2953
2920 \family typewriter
2954 \family typewriter
2921 \series bold
2955 \series bold
2922 -ipythondir\SpecialChar ~
2956 -ipythondir\SpecialChar ~
2923 <name>
2957 <name>
2924 \series default
2958 \series default
2925 :
2959 :
2926 \family default
2960 \family default
2927 name of your IPython configuration directory
2961 name of your IPython configuration directory
2928 \family typewriter
2962 \family typewriter
2929 IPYTHONDIR
2963 IPYTHONDIR
2930 \family default
2964 \family default
2931 .
2965 .
2932 This can also be specified through the environment variable
2966 This can also be specified through the environment variable
2933 \family typewriter
2967 \family typewriter
2934 IPYTHONDIR
2968 IPYTHONDIR
2935 \family default
2969 \family default
2936 .
2970 .
2937 \layout List
2971 \layout List
2938 \labelwidthstring 00.00.0000
2972 \labelwidthstring 00.00.0000
2939
2973
2940
2974
2941 \family typewriter
2975 \family typewriter
2942 \series bold
2976 \series bold
2943 -log|l
2977 -log|l
2944 \family default
2978 \family default
2945 \series default
2979 \series default
2946 : generate a log file of all input.
2980 : generate a log file of all input.
2947 Defaults to
2981 Defaults to
2948 \family typewriter
2982 \family typewriter
2949 $IPYTHONDIR/log
2983 $IPYTHONDIR/log
2950 \family default
2984 \family default
2951 .
2985 .
2952 You can use this to later restore a session by loading your logfile as
2986 You can use this to later restore a session by loading your logfile as
2953 a file to be executed with option
2987 a file to be executed with option
2954 \family typewriter
2988 \family typewriter
2955 -logplay
2989 -logplay
2956 \family default
2990 \family default
2957 (see below).
2991 (see below).
2958 \layout List
2992 \layout List
2959 \labelwidthstring 00.00.0000
2993 \labelwidthstring 00.00.0000
2960
2994
2961
2995
2962 \family typewriter
2996 \family typewriter
2963 \series bold
2997 \series bold
2964 -logfile|lf\SpecialChar ~
2998 -logfile|lf\SpecialChar ~
2965 <name>
2999 <name>
2966 \series default
3000 \series default
2967 :
3001 :
2968 \family default
3002 \family default
2969 specify the name of your logfile.
3003 specify the name of your logfile.
2970 \layout List
3004 \layout List
2971 \labelwidthstring 00.00.0000
3005 \labelwidthstring 00.00.0000
2972
3006
2973
3007
2974 \family typewriter
3008 \family typewriter
2975 \series bold
3009 \series bold
2976 -logplay|lp\SpecialChar ~
3010 -logplay|lp\SpecialChar ~
2977 <name>
3011 <name>
2978 \series default
3012 \series default
2979 :
3013 :
2980 \family default
3014 \family default
2981 you can replay a previous log.
3015 you can replay a previous log.
2982 For restoring a session as close as possible to the state you left it in,
3016 For restoring a session as close as possible to the state you left it in,
2983 use this option (don't just run the logfile).
3017 use this option (don't just run the logfile).
2984 With
3018 With
2985 \family typewriter
3019 \family typewriter
2986 -logplay
3020 -logplay
2987 \family default
3021 \family default
2988 , IPython will try to reconstruct the previous working environment in full,
3022 , IPython will try to reconstruct the previous working environment in full,
2989 not just execute the commands in the logfile.
3023 not just execute the commands in the logfile.
2990 \layout List
3024 \layout List
2991 \labelwidthstring 00.00.0000
3025 \labelwidthstring 00.00.0000
2992
3026
2993 \SpecialChar ~
3027 \SpecialChar ~
2994 When a session is restored, logging is automatically turned on again with
3028 When a session is restored, logging is automatically turned on again with
2995 the name of the logfile it was invoked with (it is read from the log header).
3029 the name of the logfile it was invoked with (it is read from the log header).
2996 So once you've turned logging on for a session, you can quit IPython and
3030 So once you've turned logging on for a session, you can quit IPython and
2997 reload it as many times as you want and it will continue to log its history
3031 reload it as many times as you want and it will continue to log its history
2998 and restore from the beginning every time.
3032 and restore from the beginning every time.
2999 \layout List
3033 \layout List
3000 \labelwidthstring 00.00.0000
3034 \labelwidthstring 00.00.0000
3001
3035
3002 \SpecialChar ~
3036 \SpecialChar ~
3003 Caveats: there are limitations in this option.
3037 Caveats: there are limitations in this option.
3004 The history variables
3038 The history variables
3005 \family typewriter
3039 \family typewriter
3006 _i*
3040 _i*
3007 \family default
3041 \family default
3008 ,
3042 ,
3009 \family typewriter
3043 \family typewriter
3010 _*
3044 _*
3011 \family default
3045 \family default
3012 and
3046 and
3013 \family typewriter
3047 \family typewriter
3014 _dh
3048 _dh
3015 \family default
3049 \family default
3016 don't get restored properly.
3050 don't get restored properly.
3017 In the future we will try to implement full session saving by writing and
3051 In the future we will try to implement full session saving by writing and
3018 retrieving a 'snapshot' of the memory state of IPython.
3052 retrieving a 'snapshot' of the memory state of IPython.
3019 But our first attempts failed because of inherent limitations of Python's
3053 But our first attempts failed because of inherent limitations of Python's
3020 Pickle module, so this may have to wait.
3054 Pickle module, so this may have to wait.
3021 \layout List
3055 \layout List
3022 \labelwidthstring 00.00.0000
3056 \labelwidthstring 00.00.0000
3023
3057
3024
3058
3025 \family typewriter
3059 \family typewriter
3026 \series bold
3060 \series bold
3027 -[no]messages
3061 -[no]messages
3028 \series default
3062 \series default
3029 :
3063 :
3030 \family default
3064 \family default
3031 Print messages which IPython collects about its startup process (default
3065 Print messages which IPython collects about its startup process (default
3032 on).
3066 on).
3033 \layout List
3067 \layout List
3034 \labelwidthstring 00.00.0000
3068 \labelwidthstring 00.00.0000
3035
3069
3036
3070
3037 \family typewriter
3071 \family typewriter
3038 \series bold
3072 \series bold
3039 -[no]pdb
3073 -[no]pdb
3040 \family default
3074 \family default
3041 \series default
3075 \series default
3042 : Automatically call the pdb debugger after every uncaught exception.
3076 : Automatically call the pdb debugger after every uncaught exception.
3043 If you are used to debugging using pdb, this puts you automatically inside
3077 If you are used to debugging using pdb, this puts you automatically inside
3044 of it after any call (either in IPython or in code called by it) which
3078 of it after any call (either in IPython or in code called by it) which
3045 triggers an exception which goes uncaught.
3079 triggers an exception which goes uncaught.
3046 \layout List
3080 \layout List
3047 \labelwidthstring 00.00.0000
3081 \labelwidthstring 00.00.0000
3048
3082
3049
3083
3050 \family typewriter
3084 \family typewriter
3051 \series bold
3085 \series bold
3052 -[no]pprint
3086 -[no]pprint
3053 \series default
3087 \series default
3054 :
3088 :
3055 \family default
3089 \family default
3056 ipython can optionally use the pprint (pretty printer) module for displaying
3090 ipython can optionally use the pprint (pretty printer) module for displaying
3057 results.
3091 results.
3058 pprint tends to give a nicer display of nested data structures.
3092 pprint tends to give a nicer display of nested data structures.
3059 If you like it, you can turn it on permanently in your config file (default
3093 If you like it, you can turn it on permanently in your config file (default
3060 off).
3094 off).
3061 \layout List
3095 \layout List
3062 \labelwidthstring 00.00.0000
3096 \labelwidthstring 00.00.0000
3063
3097
3064
3098
3065 \family typewriter
3099 \family typewriter
3066 \series bold
3100 \series bold
3067 -profile|p <name>
3101 -profile|p <name>
3068 \series default
3102 \series default
3069 :
3103 :
3070 \family default
3104 \family default
3071 assume that your config file is
3105 assume that your config file is
3072 \family typewriter
3106 \family typewriter
3073 ipythonrc-<name>
3107 ipythonrc-<name>
3074 \family default
3108 \family default
3075 (looks in current dir first, then in
3109 (looks in current dir first, then in
3076 \family typewriter
3110 \family typewriter
3077 IPYTHONDIR
3111 IPYTHONDIR
3078 \family default
3112 \family default
3079 ).
3113 ).
3080 This is a quick way to keep and load multiple config files for different
3114 This is a quick way to keep and load multiple config files for different
3081 tasks, especially if you use the include option of config files.
3115 tasks, especially if you use the include option of config files.
3082 You can keep a basic
3116 You can keep a basic
3083 \family typewriter
3117 \family typewriter
3084 IPYTHONDIR/ipythonrc
3118 IPYTHONDIR/ipythonrc
3085 \family default
3119 \family default
3086 file and then have other 'profiles' which include this one and load extra
3120 file and then have other 'profiles' which include this one and load extra
3087 things for particular tasks.
3121 things for particular tasks.
3088 For example:
3122 For example:
3089 \layout List
3123 \layout List
3090 \labelwidthstring 00.00.0000
3124 \labelwidthstring 00.00.0000
3091
3125
3092
3126
3093 \family typewriter
3127 \family typewriter
3094 \SpecialChar ~
3128 \SpecialChar ~
3095
3129
3096 \family default
3130 \family default
3097 1.
3131 1.
3098
3132
3099 \family typewriter
3133 \family typewriter
3100 $HOME/.ipython/ipythonrc
3134 $HOME/.ipython/ipythonrc
3101 \family default
3135 \family default
3102 : load basic things you always want.
3136 : load basic things you always want.
3103 \layout List
3137 \layout List
3104 \labelwidthstring 00.00.0000
3138 \labelwidthstring 00.00.0000
3105
3139
3106
3140
3107 \family typewriter
3141 \family typewriter
3108 \SpecialChar ~
3142 \SpecialChar ~
3109
3143
3110 \family default
3144 \family default
3111 2.
3145 2.
3112
3146
3113 \family typewriter
3147 \family typewriter
3114 $HOME/.ipython/ipythonrc-math
3148 $HOME/.ipython/ipythonrc-math
3115 \family default
3149 \family default
3116 : load (1) and basic math-related modules.
3150 : load (1) and basic math-related modules.
3117
3151
3118 \layout List
3152 \layout List
3119 \labelwidthstring 00.00.0000
3153 \labelwidthstring 00.00.0000
3120
3154
3121
3155
3122 \family typewriter
3156 \family typewriter
3123 \SpecialChar ~
3157 \SpecialChar ~
3124
3158
3125 \family default
3159 \family default
3126 3.
3160 3.
3127
3161
3128 \family typewriter
3162 \family typewriter
3129 $HOME/.ipython/ipythonrc-numeric
3163 $HOME/.ipython/ipythonrc-numeric
3130 \family default
3164 \family default
3131 : load (1) and Numeric and plotting modules.
3165 : load (1) and Numeric and plotting modules.
3132 \layout List
3166 \layout List
3133 \labelwidthstring 00.00.0000
3167 \labelwidthstring 00.00.0000
3134
3168
3135 \SpecialChar ~
3169 \SpecialChar ~
3136 Since it is possible to create an endless loop by having circular file
3170 Since it is possible to create an endless loop by having circular file
3137 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3171 inclusions, IPython will stop if it reaches 15 recursive inclusions.
3138 \layout List
3172 \layout List
3139 \labelwidthstring 00.00.0000
3173 \labelwidthstring 00.00.0000
3140
3174
3141
3175
3142 \family typewriter
3176 \family typewriter
3143 \series bold
3177 \series bold
3144 -prompt_in1|pi1\SpecialChar ~
3178 -prompt_in1|pi1\SpecialChar ~
3145 <string>:
3179 <string>:
3146 \family default
3180 \family default
3147 \series default
3181 \series default
3148 Specify the string used for input prompts.
3182 Specify the string used for input prompts.
3149 Note that if you are using numbered prompts, the number is represented
3183 Note that if you are using numbered prompts, the number is represented
3150 with a '
3184 with a '
3151 \backslash
3185 \backslash
3152 #' in the string.
3186 #' in the string.
3153 Don't forget to quote strings with spaces embedded in them.
3187 Don't forget to quote strings with spaces embedded in them.
3154 Default: '
3188 Default: '
3155 \family typewriter
3189 \family typewriter
3156 In\SpecialChar ~
3190 In\SpecialChar ~
3157 [
3191 [
3158 \backslash
3192 \backslash
3159 #]:
3193 #]:
3160 \family default
3194 \family default
3161 '.
3195 '.
3162 Sec.\SpecialChar ~
3196 Sec.\SpecialChar ~
3163
3197
3164 \begin_inset LatexCommand \ref{sec:prompts}
3198 \begin_inset LatexCommand \ref{sec:prompts}
3165
3199
3166 \end_inset
3200 \end_inset
3167
3201
3168 discusses in detail all the available escapes to customize your prompts.
3202 discusses in detail all the available escapes to customize your prompts.
3169 \layout List
3203 \layout List
3170 \labelwidthstring 00.00.0000
3204 \labelwidthstring 00.00.0000
3171
3205
3172
3206
3173 \family typewriter
3207 \family typewriter
3174 \series bold
3208 \series bold
3175 -prompt_in2|pi2\SpecialChar ~
3209 -prompt_in2|pi2\SpecialChar ~
3176 <string>:
3210 <string>:
3177 \family default
3211 \family default
3178 \series default
3212 \series default
3179 Similar to the previous option, but used for the continuation prompts.
3213 Similar to the previous option, but used for the continuation prompts.
3180 The special sequence '
3214 The special sequence '
3181 \family typewriter
3215 \family typewriter
3182
3216
3183 \backslash
3217 \backslash
3184 D
3218 D
3185 \family default
3219 \family default
3186 ' is similar to '
3220 ' is similar to '
3187 \family typewriter
3221 \family typewriter
3188
3222
3189 \backslash
3223 \backslash
3190 #
3224 #
3191 \family default
3225 \family default
3192 ', but with all digits replaced dots (so you can have your continuation
3226 ', but with all digits replaced dots (so you can have your continuation
3193 prompt aligned with your input prompt).
3227 prompt aligned with your input prompt).
3194 Default: '
3228 Default: '
3195 \family typewriter
3229 \family typewriter
3196 \SpecialChar ~
3230 \SpecialChar ~
3197 \SpecialChar ~
3231 \SpecialChar ~
3198 \SpecialChar ~
3232 \SpecialChar ~
3199 .
3233 .
3200 \backslash
3234 \backslash
3201 D.:
3235 D.:
3202 \family default
3236 \family default
3203 ' (note three spaces at the start for alignment with '
3237 ' (note three spaces at the start for alignment with '
3204 \family typewriter
3238 \family typewriter
3205 In\SpecialChar ~
3239 In\SpecialChar ~
3206 [
3240 [
3207 \backslash
3241 \backslash
3208 #]
3242 #]
3209 \family default
3243 \family default
3210 ').
3244 ').
3211 \layout List
3245 \layout List
3212 \labelwidthstring 00.00.0000
3246 \labelwidthstring 00.00.0000
3213
3247
3214
3248
3215 \family typewriter
3249 \family typewriter
3216 \series bold
3250 \series bold
3217 -prompt_out|po\SpecialChar ~
3251 -prompt_out|po\SpecialChar ~
3218 <string>:
3252 <string>:
3219 \family default
3253 \family default
3220 \series default
3254 \series default
3221 String used for output prompts, also uses numbers like
3255 String used for output prompts, also uses numbers like
3222 \family typewriter
3256 \family typewriter
3223 prompt_in1
3257 prompt_in1
3224 \family default
3258 \family default
3225 .
3259 .
3226 Default: '
3260 Default: '
3227 \family typewriter
3261 \family typewriter
3228 Out[
3262 Out[
3229 \backslash
3263 \backslash
3230 #]:
3264 #]:
3231 \family default
3265 \family default
3232 '
3266 '
3233 \layout List
3267 \layout List
3234 \labelwidthstring 00.00.0000
3268 \labelwidthstring 00.00.0000
3235
3269
3236
3270
3237 \family typewriter
3271 \family typewriter
3238 \series bold
3272 \series bold
3239 -quick
3273 -quick
3240 \family default
3274 \family default
3241 \series default
3275 \series default
3242 : start in bare bones mode (no config file loaded).
3276 : start in bare bones mode (no config file loaded).
3243 \layout List
3277 \layout List
3244 \labelwidthstring 00.00.0000
3278 \labelwidthstring 00.00.0000
3245
3279
3246
3280
3247 \family typewriter
3281 \family typewriter
3248 \series bold
3282 \series bold
3249 -rcfile\SpecialChar ~
3283 -rcfile\SpecialChar ~
3250 <name>
3284 <name>
3251 \series default
3285 \series default
3252 :
3286 :
3253 \family default
3287 \family default
3254 name of your IPython resource configuration file.
3288 name of your IPython resource configuration file.
3255 Normally IPython loads ipythonrc (from current directory) or
3289 Normally IPython loads ipythonrc (from current directory) or
3256 \family typewriter
3290 \family typewriter
3257 IPYTHONDIR/ipythonrc
3291 IPYTHONDIR/ipythonrc
3258 \family default
3292 \family default
3259 .
3293 .
3260 \layout List
3294 \layout List
3261 \labelwidthstring 00.00.0000
3295 \labelwidthstring 00.00.0000
3262
3296
3263 \SpecialChar ~
3297 \SpecialChar ~
3264 If the loading of your config file fails, IPython starts with a bare bones
3298 If the loading of your config file fails, IPython starts with a bare bones
3265 configuration (no modules loaded at all).
3299 configuration (no modules loaded at all).
3266 \layout List
3300 \layout List
3267 \labelwidthstring 00.00.0000
3301 \labelwidthstring 00.00.0000
3268
3302
3269
3303
3270 \family typewriter
3304 \family typewriter
3271 \series bold
3305 \series bold
3272 -[no]readline
3306 -[no]readline
3273 \family default
3307 \family default
3274 \series default
3308 \series default
3275 : use the readline library, which is needed to support name completion and
3309 : use the readline library, which is needed to support name completion and
3276 command history, among other things.
3310 command history, among other things.
3277 It is enabled by default, but may cause problems for users of X/Emacs in
3311 It is enabled by default, but may cause problems for users of X/Emacs in
3278 Python comint or shell buffers.
3312 Python comint or shell buffers.
3279 \layout List
3313 \layout List
3280 \labelwidthstring 00.00.0000
3314 \labelwidthstring 00.00.0000
3281
3315
3282 \SpecialChar ~
3316 \SpecialChar ~
3283 Note that X/Emacs 'eterm' buffers (opened with
3317 Note that X/Emacs 'eterm' buffers (opened with
3284 \family typewriter
3318 \family typewriter
3285 M-x\SpecialChar ~
3319 M-x\SpecialChar ~
3286 term
3320 term
3287 \family default
3321 \family default
3288 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3322 ) support IPython's readline and syntax coloring fine, only 'emacs' (
3289 \family typewriter
3323 \family typewriter
3290 M-x\SpecialChar ~
3324 M-x\SpecialChar ~
3291 shell
3325 shell
3292 \family default
3326 \family default
3293 and
3327 and
3294 \family typewriter
3328 \family typewriter
3295 C-c\SpecialChar ~
3329 C-c\SpecialChar ~
3296 !
3330 !
3297 \family default
3331 \family default
3298 ) buffers do not.
3332 ) buffers do not.
3299 \layout List
3333 \layout List
3300 \labelwidthstring 00.00.0000
3334 \labelwidthstring 00.00.0000
3301
3335
3302
3336
3303 \family typewriter
3337 \family typewriter
3304 \series bold
3338 \series bold
3305 -screen_length|sl\SpecialChar ~
3339 -screen_length|sl\SpecialChar ~
3306 <n>
3340 <n>
3307 \series default
3341 \series default
3308 :
3342 :
3309 \family default
3343 \family default
3310 number of lines of your screen.
3344 number of lines of your screen.
3311 This is used to control printing of very long strings.
3345 This is used to control printing of very long strings.
3312 Strings longer than this number of lines will be sent through a pager instead
3346 Strings longer than this number of lines will be sent through a pager instead
3313 of directly printed.
3347 of directly printed.
3314 \layout List
3348 \layout List
3315 \labelwidthstring 00.00.0000
3349 \labelwidthstring 00.00.0000
3316
3350
3317 \SpecialChar ~
3351 \SpecialChar ~
3318 The default value for this is 0, which means IPython will auto-detect your
3352 The default value for this is 0, which means IPython will auto-detect your
3319 screen size every time it needs to print certain potentially long strings
3353 screen size every time it needs to print certain potentially long strings
3320 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3354 (this doesn't change the behavior of the 'print' keyword, it's only triggered
3321 internally).
3355 internally).
3322 If for some reason this isn't working well (it needs curses support), specify
3356 If for some reason this isn't working well (it needs curses support), specify
3323 it yourself.
3357 it yourself.
3324 Otherwise don't change the default.
3358 Otherwise don't change the default.
3325 \layout List
3359 \layout List
3326 \labelwidthstring 00.00.0000
3360 \labelwidthstring 00.00.0000
3327
3361
3328
3362
3329 \family typewriter
3363 \family typewriter
3330 \series bold
3364 \series bold
3331 -separate_in|si\SpecialChar ~
3365 -separate_in|si\SpecialChar ~
3332 <string>
3366 <string>
3333 \series default
3367 \series default
3334 :
3368 :
3335 \family default
3369 \family default
3336 separator before input prompts.
3370 separator before input prompts.
3337 Default: '
3371 Default: '
3338 \family typewriter
3372 \family typewriter
3339
3373
3340 \backslash
3374 \backslash
3341 n
3375 n
3342 \family default
3376 \family default
3343 '
3377 '
3344 \layout List
3378 \layout List
3345 \labelwidthstring 00.00.0000
3379 \labelwidthstring 00.00.0000
3346
3380
3347
3381
3348 \family typewriter
3382 \family typewriter
3349 \series bold
3383 \series bold
3350 -separate_out|so\SpecialChar ~
3384 -separate_out|so\SpecialChar ~
3351 <string>
3385 <string>
3352 \family default
3386 \family default
3353 \series default
3387 \series default
3354 : separator before output prompts.
3388 : separator before output prompts.
3355 Default: nothing.
3389 Default: nothing.
3356 \layout List
3390 \layout List
3357 \labelwidthstring 00.00.0000
3391 \labelwidthstring 00.00.0000
3358
3392
3359
3393
3360 \family typewriter
3394 \family typewriter
3361 \series bold
3395 \series bold
3362 -separate_out2|so2\SpecialChar ~
3396 -separate_out2|so2\SpecialChar ~
3363 <string>
3397 <string>
3364 \series default
3398 \series default
3365 :
3399 :
3366 \family default
3400 \family default
3367 separator after output prompts.
3401 separator after output prompts.
3368 Default: nothing.
3402 Default: nothing.
3369 \layout List
3403 \layout List
3370 \labelwidthstring 00.00.0000
3404 \labelwidthstring 00.00.0000
3371
3405
3372 \SpecialChar ~
3406 \SpecialChar ~
3373 For these three options, use the value 0 to specify no separator.
3407 For these three options, use the value 0 to specify no separator.
3374 \layout List
3408 \layout List
3375 \labelwidthstring 00.00.0000
3409 \labelwidthstring 00.00.0000
3376
3410
3377
3411
3378 \family typewriter
3412 \family typewriter
3379 \series bold
3413 \series bold
3380 -nosep
3414 -nosep
3381 \series default
3415 \series default
3382 :
3416 :
3383 \family default
3417 \family default
3384 shorthand for
3418 shorthand for
3385 \family typewriter
3419 \family typewriter
3386 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3420 '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'
3387 \family default
3421 \family default
3388 .
3422 .
3389 Simply removes all input/output separators.
3423 Simply removes all input/output separators.
3390 \layout List
3424 \layout List
3391 \labelwidthstring 00.00.0000
3425 \labelwidthstring 00.00.0000
3392
3426
3393
3427
3394 \family typewriter
3428 \family typewriter
3395 \series bold
3429 \series bold
3396 -upgrade
3430 -upgrade
3397 \family default
3431 \family default
3398 \series default
3432 \series default
3399 : allows you to upgrade your
3433 : allows you to upgrade your
3400 \family typewriter
3434 \family typewriter
3401 IPYTHONDIR
3435 IPYTHONDIR
3402 \family default
3436 \family default
3403 configuration when you install a new version of IPython.
3437 configuration when you install a new version of IPython.
3404 Since new versions may include new command line options or example files,
3438 Since new versions may include new command line options or example files,
3405 this copies updated ipythonrc-type files.
3439 this copies updated ipythonrc-type files.
3406 However, it backs up (with a
3440 However, it backs up (with a
3407 \family typewriter
3441 \family typewriter
3408 .old
3442 .old
3409 \family default
3443 \family default
3410 extension) all files which it overwrites so that you can merge back any
3444 extension) all files which it overwrites so that you can merge back any
3411 customizations you might have in your personal files.
3445 customizations you might have in your personal files.
3412 \layout List
3446 \layout List
3413 \labelwidthstring 00.00.0000
3447 \labelwidthstring 00.00.0000
3414
3448
3415
3449
3416 \family typewriter
3450 \family typewriter
3417 \series bold
3451 \series bold
3418 -Version
3452 -Version
3419 \series default
3453 \series default
3420 :
3454 :
3421 \family default
3455 \family default
3422 print version information and exit.
3456 print version information and exit.
3423 \layout List
3457 \layout List
3424 \labelwidthstring 00.00.0000
3458 \labelwidthstring 00.00.0000
3425
3459
3426
3460
3427 \family typewriter
3461 \family typewriter
3428 \series bold
3462 \series bold
3429 -xmode <modename>
3463 -xmode <modename>
3430 \series default
3464 \series default
3431 :
3465 :
3432 \family default
3466 \family default
3433 Mode for exception reporting.
3467 Mode for exception reporting.
3434 \layout List
3468 \layout List
3435 \labelwidthstring 00.00.0000
3469 \labelwidthstring 00.00.0000
3436
3470
3437 \SpecialChar ~
3471 \SpecialChar ~
3438 Valid modes: Plain, Context and Verbose.
3472 Valid modes: Plain, Context and Verbose.
3439 \layout List
3473 \layout List
3440 \labelwidthstring 00.00.0000
3474 \labelwidthstring 00.00.0000
3441
3475
3442 \SpecialChar ~
3476 \SpecialChar ~
3443 Plain: similar to python's normal traceback printing.
3477 Plain: similar to python's normal traceback printing.
3444 \layout List
3478 \layout List
3445 \labelwidthstring 00.00.0000
3479 \labelwidthstring 00.00.0000
3446
3480
3447 \SpecialChar ~
3481 \SpecialChar ~
3448 Context: prints 5 lines of context source code around each line in the
3482 Context: prints 5 lines of context source code around each line in the
3449 traceback.
3483 traceback.
3450 \layout List
3484 \layout List
3451 \labelwidthstring 00.00.0000
3485 \labelwidthstring 00.00.0000
3452
3486
3453 \SpecialChar ~
3487 \SpecialChar ~
3454 Verbose: similar to Context, but additionally prints the variables currently
3488 Verbose: similar to Context, but additionally prints the variables currently
3455 visible where the exception happened (shortening their strings if too long).
3489 visible where the exception happened (shortening their strings if too long).
3456 This can potentially be very slow, if you happen to have a huge data structure
3490 This can potentially be very slow, if you happen to have a huge data structure
3457 whose string representation is complex to compute.
3491 whose string representation is complex to compute.
3458 Your computer may appear to freeze for a while with cpu usage at 100%.
3492 Your computer may appear to freeze for a while with cpu usage at 100%.
3459 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3493 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
3460 it more than once).
3494 it more than once).
3461 \layout Section
3495 \layout Section
3462
3496
3463 Interactive use
3497 Interactive use
3464 \layout Standard
3498 \layout Standard
3465
3499
3466
3500
3467 \series bold
3501 \series bold
3468 Warning
3502 Warning
3469 \series default
3503 \series default
3470 : IPython relies on the existence of a global variable called
3504 : IPython relies on the existence of a global variable called
3471 \family typewriter
3505 \family typewriter
3472 __IP
3506 __IP
3473 \family default
3507 \family default
3474 which controls the shell itself.
3508 which controls the shell itself.
3475 If you redefine
3509 If you redefine
3476 \family typewriter
3510 \family typewriter
3477 __IP
3511 __IP
3478 \family default
3512 \family default
3479 to anything, bizarre behavior will quickly occur.
3513 to anything, bizarre behavior will quickly occur.
3480 \layout Standard
3514 \layout Standard
3481
3515
3482 Other than the above warning, IPython is meant to work as a drop-in replacement
3516 Other than the above warning, IPython is meant to work as a drop-in replacement
3483 for the standard interactive interpreter.
3517 for the standard interactive interpreter.
3484 As such, any code which is valid python should execute normally under IPython
3518 As such, any code which is valid python should execute normally under IPython
3485 (cases where this is not true should be reported as bugs).
3519 (cases where this is not true should be reported as bugs).
3486 It does, however, offer many features which are not available at a standard
3520 It does, however, offer many features which are not available at a standard
3487 python prompt.
3521 python prompt.
3488 What follows is a list of these.
3522 What follows is a list of these.
3489 \layout Subsection
3523 \layout Subsection
3490
3524
3491 Caution for Windows users
3525 Caution for Windows users
3492 \layout Standard
3526 \layout Standard
3493
3527
3494 Windows, unfortunately, uses the `
3528 Windows, unfortunately, uses the `
3495 \family typewriter
3529 \family typewriter
3496
3530
3497 \backslash
3531 \backslash
3498
3532
3499 \family default
3533 \family default
3500 ' character as a path separator.
3534 ' character as a path separator.
3501 This is a terrible choice, because `
3535 This is a terrible choice, because `
3502 \family typewriter
3536 \family typewriter
3503
3537
3504 \backslash
3538 \backslash
3505
3539
3506 \family default
3540 \family default
3507 ' also represents the escape character in most modern programming languages,
3541 ' also represents the escape character in most modern programming languages,
3508 including Python.
3542 including Python.
3509 For this reason, issuing many of the commands discussed below (especially
3543 For this reason, issuing many of the commands discussed below (especially
3510 magics which affect the filesystem) with `
3544 magics which affect the filesystem) with `
3511 \family typewriter
3545 \family typewriter
3512
3546
3513 \backslash
3547 \backslash
3514
3548
3515 \family default
3549 \family default
3516 ' in them will cause strange errors.
3550 ' in them will cause strange errors.
3517 \layout Standard
3551 \layout Standard
3518
3552
3519 A partial solution is to use instead the `
3553 A partial solution is to use instead the `
3520 \family typewriter
3554 \family typewriter
3521 /
3555 /
3522 \family default
3556 \family default
3523 ' character as a path separator, which Windows recognizes in
3557 ' character as a path separator, which Windows recognizes in
3524 \emph on
3558 \emph on
3525 most
3559 most
3526 \emph default
3560 \emph default
3527 situations.
3561 situations.
3528 However, in Windows commands `
3562 However, in Windows commands `
3529 \family typewriter
3563 \family typewriter
3530 /
3564 /
3531 \family default
3565 \family default
3532 ' flags options, so you can not use it for the root directory.
3566 ' flags options, so you can not use it for the root directory.
3533 This means that paths beginning at the root must be typed in a contrived
3567 This means that paths beginning at the root must be typed in a contrived
3534 manner like:
3568 manner like:
3535 \newline
3569 \newline
3536
3570
3537 \family typewriter
3571 \family typewriter
3538 %copy
3572 %copy
3539 \backslash
3573 \backslash
3540 opt/foo/bar.txt
3574 opt/foo/bar.txt
3541 \backslash
3575 \backslash
3542 tmp
3576 tmp
3543 \layout Standard
3577 \layout Standard
3544
3578
3545 There is no sensible thing IPython can do to truly work around this flaw
3579 There is no sensible thing IPython can do to truly work around this flaw
3546 in Windows
3580 in Windows
3547 \begin_inset Foot
3581 \begin_inset Foot
3548 collapsed true
3582 collapsed true
3549
3583
3550 \layout Standard
3584 \layout Standard
3551
3585
3552 If anyone comes up with a
3586 If anyone comes up with a
3553 \emph on
3587 \emph on
3554 clean
3588 clean
3555 \emph default
3589 \emph default
3556 solution which works consistently and does not negatively impact other
3590 solution which works consistently and does not negatively impact other
3557 platforms at all, I'll gladly accept a patch.
3591 platforms at all, I'll gladly accept a patch.
3558 \end_inset
3592 \end_inset
3559
3593
3560 .
3594 .
3561 \layout Subsection
3595 \layout Subsection
3562
3596
3563
3597
3564 \begin_inset LatexCommand \label{sec:magic}
3598 \begin_inset LatexCommand \label{sec:magic}
3565
3599
3566 \end_inset
3600 \end_inset
3567
3601
3568 Magic command system
3602 Magic command system
3569 \layout Standard
3603 \layout Standard
3570
3604
3571 IPython will treat any line whose first character is a
3605 IPython will treat any line whose first character is a
3572 \family typewriter
3606 \family typewriter
3573 %
3607 %
3574 \family default
3608 \family default
3575 as a special call to a 'magic' function.
3609 as a special call to a 'magic' function.
3576 These allow you to control the behavior of IPython itself, plus a lot of
3610 These allow you to control the behavior of IPython itself, plus a lot of
3577 system-type features.
3611 system-type features.
3578 They are all prefixed with a
3612 They are all prefixed with a
3579 \family typewriter
3613 \family typewriter
3580 %
3614 %
3581 \family default
3615 \family default
3582 character, but parameters are given without parentheses or quotes.
3616 character, but parameters are given without parentheses or quotes.
3583 \layout Standard
3617 \layout Standard
3584
3618
3585 Example: typing
3619 Example: typing
3586 \family typewriter
3620 \family typewriter
3587 '%cd mydir'
3621 '%cd mydir'
3588 \family default
3622 \family default
3589 (without the quotes) changes you working directory to
3623 (without the quotes) changes you working directory to
3590 \family typewriter
3624 \family typewriter
3591 'mydir'
3625 'mydir'
3592 \family default
3626 \family default
3593 , if it exists.
3627 , if it exists.
3594 \layout Standard
3628 \layout Standard
3595
3629
3596 If you have 'automagic' enabled (in your
3630 If you have 'automagic' enabled (in your
3597 \family typewriter
3631 \family typewriter
3598 ipythonrc
3632 ipythonrc
3599 \family default
3633 \family default
3600 file, via the command line option
3634 file, via the command line option
3601 \family typewriter
3635 \family typewriter
3602 -automagic
3636 -automagic
3603 \family default
3637 \family default
3604 or with the
3638 or with the
3605 \family typewriter
3639 \family typewriter
3606 %automagic
3640 %automagic
3607 \family default
3641 \family default
3608 function), you don't need to type in the
3642 function), you don't need to type in the
3609 \family typewriter
3643 \family typewriter
3610 %
3644 %
3611 \family default
3645 \family default
3612 explicitly.
3646 explicitly.
3613 IPython will scan its internal list of magic functions and call one if
3647 IPython will scan its internal list of magic functions and call one if
3614 it exists.
3648 it exists.
3615 With automagic on you can then just type '
3649 With automagic on you can then just type '
3616 \family typewriter
3650 \family typewriter
3617 cd mydir
3651 cd mydir
3618 \family default
3652 \family default
3619 ' to go to directory '
3653 ' to go to directory '
3620 \family typewriter
3654 \family typewriter
3621 mydir
3655 mydir
3622 \family default
3656 \family default
3623 '.
3657 '.
3624 The automagic system has the lowest possible precedence in name searches,
3658 The automagic system has the lowest possible precedence in name searches,
3625 so defining an identifier with the same name as an existing magic function
3659 so defining an identifier with the same name as an existing magic function
3626 will shadow it for automagic use.
3660 will shadow it for automagic use.
3627 You can still access the shadowed magic function by explicitly using the
3661 You can still access the shadowed magic function by explicitly using the
3628
3662
3629 \family typewriter
3663 \family typewriter
3630 %
3664 %
3631 \family default
3665 \family default
3632 character at the beginning of the line.
3666 character at the beginning of the line.
3633 \layout Standard
3667 \layout Standard
3634
3668
3635 An example (with automagic on) should clarify all this:
3669 An example (with automagic on) should clarify all this:
3636 \layout LyX-Code
3670 \layout LyX-Code
3637
3671
3638 In [1]: cd ipython # %cd is called by automagic
3672 In [1]: cd ipython # %cd is called by automagic
3639 \layout LyX-Code
3673 \layout LyX-Code
3640
3674
3641 /home/fperez/ipython
3675 /home/fperez/ipython
3642 \layout LyX-Code
3676 \layout LyX-Code
3643
3677
3644 In [2]: cd=1 # now cd is just a variable
3678 In [2]: cd=1 # now cd is just a variable
3645 \layout LyX-Code
3679 \layout LyX-Code
3646
3680
3647 In [3]: cd ..
3681 In [3]: cd ..
3648 # and doesn't work as a function anymore
3682 # and doesn't work as a function anymore
3649 \layout LyX-Code
3683 \layout LyX-Code
3650
3684
3651 ------------------------------------------------------------
3685 ------------------------------------------------------------
3652 \layout LyX-Code
3686 \layout LyX-Code
3653
3687
3654 File "<console>", line 1
3688 File "<console>", line 1
3655 \layout LyX-Code
3689 \layout LyX-Code
3656
3690
3657 cd ..
3691 cd ..
3658 \layout LyX-Code
3692 \layout LyX-Code
3659
3693
3660 ^
3694 ^
3661 \layout LyX-Code
3695 \layout LyX-Code
3662
3696
3663 SyntaxError: invalid syntax
3697 SyntaxError: invalid syntax
3664 \layout LyX-Code
3698 \layout LyX-Code
3665
3699
3666 \layout LyX-Code
3700 \layout LyX-Code
3667
3701
3668 In [4]: %cd ..
3702 In [4]: %cd ..
3669 # but %cd always works
3703 # but %cd always works
3670 \layout LyX-Code
3704 \layout LyX-Code
3671
3705
3672 /home/fperez
3706 /home/fperez
3673 \layout LyX-Code
3707 \layout LyX-Code
3674
3708
3675 In [5]: del cd # if you remove the cd variable
3709 In [5]: del cd # if you remove the cd variable
3676 \layout LyX-Code
3710 \layout LyX-Code
3677
3711
3678 In [6]: cd ipython # automagic can work again
3712 In [6]: cd ipython # automagic can work again
3679 \layout LyX-Code
3713 \layout LyX-Code
3680
3714
3681 /home/fperez/ipython
3715 /home/fperez/ipython
3682 \layout Standard
3716 \layout Standard
3683
3717
3684 You can define your own magic functions to extend the system.
3718 You can define your own magic functions to extend the system.
3685 The following is a snippet of code which shows how to do it.
3719 The following is a snippet of code which shows how to do it.
3686 It is provided as file
3720 It is provided as file
3687 \family typewriter
3721 \family typewriter
3688 example-magic.py
3722 example-magic.py
3689 \family default
3723 \family default
3690 in the examples directory:
3724 in the examples directory:
3691 \layout Standard
3725 \layout Standard
3692
3726
3693
3727
3694 \begin_inset ERT
3728 \begin_inset ERT
3695 status Open
3729 status Open
3696
3730
3697 \layout Standard
3731 \layout Standard
3698
3732
3699 \backslash
3733 \backslash
3700 codelist{examples/example-magic.py}
3734 codelist{examples/example-magic.py}
3701 \end_inset
3735 \end_inset
3702
3736
3703
3737
3704 \layout Standard
3738 \layout Standard
3705
3739
3706 You can also define your own aliased names for magic functions.
3740 You can also define your own aliased names for magic functions.
3707 In your
3741 In your
3708 \family typewriter
3742 \family typewriter
3709 ipythonrc
3743 ipythonrc
3710 \family default
3744 \family default
3711 file, placing a line like:
3745 file, placing a line like:
3712 \layout Standard
3746 \layout Standard
3713
3747
3714
3748
3715 \family typewriter
3749 \family typewriter
3716 execute __IP.magic_cl = __IP.magic_clear
3750 execute __IP.magic_cl = __IP.magic_clear
3717 \layout Standard
3751 \layout Standard
3718
3752
3719 will define
3753 will define
3720 \family typewriter
3754 \family typewriter
3721 %cl
3755 %cl
3722 \family default
3756 \family default
3723 as a new name for
3757 as a new name for
3724 \family typewriter
3758 \family typewriter
3725 %clear
3759 %clear
3726 \family default
3760 \family default
3727 .
3761 .
3728 \layout Standard
3762 \layout Standard
3729
3763
3730 Type
3764 Type
3731 \family typewriter
3765 \family typewriter
3732 %magic
3766 %magic
3733 \family default
3767 \family default
3734 for more information, including a list of all available magic functions
3768 for more information, including a list of all available magic functions
3735 at any time and their docstrings.
3769 at any time and their docstrings.
3736 You can also type
3770 You can also type
3737 \family typewriter
3771 \family typewriter
3738 %magic_function_name?
3772 %magic_function_name?
3739 \family default
3773 \family default
3740 (see sec.
3774 (see sec.
3741
3775
3742 \begin_inset LatexCommand \ref{sec:dyn-object-info}
3776 \begin_inset LatexCommand \ref{sec:dyn-object-info}
3743
3777
3744 \end_inset
3778 \end_inset
3745
3779
3746 for information on the
3780 for information on the
3747 \family typewriter
3781 \family typewriter
3748 '?'
3782 '?'
3749 \family default
3783 \family default
3750 system) to get information about any particular magic function you are
3784 system) to get information about any particular magic function you are
3751 interested in.
3785 interested in.
3752 \layout Subsubsection
3786 \layout Subsubsection
3753
3787
3754 Magic commands
3788 Magic commands
3755 \layout Standard
3789 \layout Standard
3756
3790
3757 The rest of this section is automatically generated for each release from
3791 The rest of this section is automatically generated for each release from
3758 the docstrings in the IPython code.
3792 the docstrings in the IPython code.
3759 Therefore the formatting is somewhat minimal, but this method has the advantage
3793 Therefore the formatting is somewhat minimal, but this method has the advantage
3760 of having information always in sync with the code.
3794 of having information always in sync with the code.
3761 \layout Standard
3795 \layout Standard
3762
3796
3763 A list of all the magic commands available in IPython's
3797 A list of all the magic commands available in IPython's
3764 \emph on
3798 \emph on
3765 default
3799 default
3766 \emph default
3800 \emph default
3767 installation follows.
3801 installation follows.
3768 This is similar to what you'll see by simply typing
3802 This is similar to what you'll see by simply typing
3769 \family typewriter
3803 \family typewriter
3770 %magic
3804 %magic
3771 \family default
3805 \family default
3772 at the prompt, but that will also give you information about magic commands
3806 at the prompt, but that will also give you information about magic commands
3773 you may have added as part of your personal customizations.
3807 you may have added as part of your personal customizations.
3774 \layout Standard
3808 \layout Standard
3775
3809
3776
3810
3777 \begin_inset Include \input{magic.tex}
3811 \begin_inset Include \input{magic.tex}
3778 preview false
3812 preview false
3779
3813
3780 \end_inset
3814 \end_inset
3781
3815
3782
3816
3783 \layout Subsection
3817 \layout Subsection
3784
3818
3785 Access to the standard Python help
3819 Access to the standard Python help
3786 \layout Standard
3820 \layout Standard
3787
3821
3788 As of Python 2.1, a help system is available with access to object docstrings
3822 As of Python 2.1, a help system is available with access to object docstrings
3789 and the Python manuals.
3823 and the Python manuals.
3790 Simply type
3824 Simply type
3791 \family typewriter
3825 \family typewriter
3792 'help'
3826 'help'
3793 \family default
3827 \family default
3794 (no quotes) to access it.
3828 (no quotes) to access it.
3795 You can also type
3829 You can also type
3796 \family typewriter
3830 \family typewriter
3797 help(object)
3831 help(object)
3798 \family default
3832 \family default
3799 to obtain information about a given object, and
3833 to obtain information about a given object, and
3800 \family typewriter
3834 \family typewriter
3801 help('keyword')
3835 help('keyword')
3802 \family default
3836 \family default
3803 for information on a keyword.
3837 for information on a keyword.
3804 As noted in sec.
3838 As noted in sec.
3805
3839
3806 \begin_inset LatexCommand \ref{sec:help-access}
3840 \begin_inset LatexCommand \ref{sec:help-access}
3807
3841
3808 \end_inset
3842 \end_inset
3809
3843
3810 , you need to properly configure your environment variable
3844 , you need to properly configure your environment variable
3811 \family typewriter
3845 \family typewriter
3812 PYTHONDOCS
3846 PYTHONDOCS
3813 \family default
3847 \family default
3814 for this feature to work correctly.
3848 for this feature to work correctly.
3815 \layout Subsection
3849 \layout Subsection
3816
3850
3817
3851
3818 \begin_inset LatexCommand \label{sec:dyn-object-info}
3852 \begin_inset LatexCommand \label{sec:dyn-object-info}
3819
3853
3820 \end_inset
3854 \end_inset
3821
3855
3822 Dynamic object information
3856 Dynamic object information
3823 \layout Standard
3857 \layout Standard
3824
3858
3825 Typing
3859 Typing
3826 \family typewriter
3860 \family typewriter
3827 ?word
3861 ?word
3828 \family default
3862 \family default
3829 or
3863 or
3830 \family typewriter
3864 \family typewriter
3831 word?
3865 word?
3832 \family default
3866 \family default
3833 prints detailed information about an object.
3867 prints detailed information about an object.
3834 If certain strings in the object are too long (docstrings, code, etc.) they
3868 If certain strings in the object are too long (docstrings, code, etc.) they
3835 get snipped in the center for brevity.
3869 get snipped in the center for brevity.
3836 This system gives access variable types and values, full source code for
3870 This system gives access variable types and values, full source code for
3837 any object (if available), function prototypes and other useful information.
3871 any object (if available), function prototypes and other useful information.
3838 \layout Standard
3872 \layout Standard
3839
3873
3840 Typing
3874 Typing
3841 \family typewriter
3875 \family typewriter
3842 ??word
3876 ??word
3843 \family default
3877 \family default
3844 or
3878 or
3845 \family typewriter
3879 \family typewriter
3846 word??
3880 word??
3847 \family default
3881 \family default
3848 gives access to the full information without snipping long strings.
3882 gives access to the full information without snipping long strings.
3849 Long strings are sent to the screen through the
3883 Long strings are sent to the screen through the
3850 \family typewriter
3884 \family typewriter
3851 less
3885 less
3852 \family default
3886 \family default
3853 pager if longer than the screen and printed otherwise.
3887 pager if longer than the screen and printed otherwise.
3854 On systems lacking the
3888 On systems lacking the
3855 \family typewriter
3889 \family typewriter
3856 less
3890 less
3857 \family default
3891 \family default
3858 command, IPython uses a very basic internal pager.
3892 command, IPython uses a very basic internal pager.
3859 \layout Standard
3893 \layout Standard
3860
3894
3861 The following magic functions are particularly useful for gathering information
3895 The following magic functions are particularly useful for gathering information
3862 about your working environment.
3896 about your working environment.
3863 You can get more details by typing
3897 You can get more details by typing
3864 \family typewriter
3898 \family typewriter
3865 %magic
3899 %magic
3866 \family default
3900 \family default
3867 or querying them individually (use
3901 or querying them individually (use
3868 \family typewriter
3902 \family typewriter
3869 %function_name?
3903 %function_name?
3870 \family default
3904 \family default
3871 with or without the
3905 with or without the
3872 \family typewriter
3906 \family typewriter
3873 %
3907 %
3874 \family default
3908 \family default
3875 ), this is just a summary:
3909 ), this is just a summary:
3876 \layout List
3910 \layout List
3877 \labelwidthstring 00.00.0000
3911 \labelwidthstring 00.00.0000
3878
3912
3879
3913
3880 \family typewriter
3914 \family typewriter
3881 \series bold
3915 \series bold
3882 %pdoc\SpecialChar ~
3916 %pdoc\SpecialChar ~
3883 <object>
3917 <object>
3884 \family default
3918 \family default
3885 \series default
3919 \series default
3886 : Print (or run through a pager if too long) the docstring for an object.
3920 : Print (or run through a pager if too long) the docstring for an object.
3887 If the given object is a class, it will print both the class and the constructo
3921 If the given object is a class, it will print both the class and the constructo
3888 r docstrings.
3922 r docstrings.
3889 \layout List
3923 \layout List
3890 \labelwidthstring 00.00.0000
3924 \labelwidthstring 00.00.0000
3891
3925
3892
3926
3893 \family typewriter
3927 \family typewriter
3894 \series bold
3928 \series bold
3895 %pdef\SpecialChar ~
3929 %pdef\SpecialChar ~
3896 <object>
3930 <object>
3897 \family default
3931 \family default
3898 \series default
3932 \series default
3899 : Print the definition header for any callable object.
3933 : Print the definition header for any callable object.
3900 If the object is a class, print the constructor information.
3934 If the object is a class, print the constructor information.
3901 \layout List
3935 \layout List
3902 \labelwidthstring 00.00.0000
3936 \labelwidthstring 00.00.0000
3903
3937
3904
3938
3905 \family typewriter
3939 \family typewriter
3906 \series bold
3940 \series bold
3907 %psource\SpecialChar ~
3941 %psource\SpecialChar ~
3908 <object>
3942 <object>
3909 \family default
3943 \family default
3910 \series default
3944 \series default
3911 : Print (or run through a pager if too long) the source code for an object.
3945 : Print (or run through a pager if too long) the source code for an object.
3912 \layout List
3946 \layout List
3913 \labelwidthstring 00.00.0000
3947 \labelwidthstring 00.00.0000
3914
3948
3915
3949
3916 \family typewriter
3950 \family typewriter
3917 \series bold
3951 \series bold
3918 %pfile\SpecialChar ~
3952 %pfile\SpecialChar ~
3919 <object>
3953 <object>
3920 \family default
3954 \family default
3921 \series default
3955 \series default
3922 : Show the entire source file where an object was defined via a pager, opening
3956 : Show the entire source file where an object was defined via a pager, opening
3923 it at the line where the object definition begins.
3957 it at the line where the object definition begins.
3924 \layout List
3958 \layout List
3925 \labelwidthstring 00.00.0000
3959 \labelwidthstring 00.00.0000
3926
3960
3927
3961
3928 \family typewriter
3962 \family typewriter
3929 \series bold
3963 \series bold
3930 %who/%whos
3964 %who/%whos
3931 \family default
3965 \family default
3932 \series default
3966 \series default
3933 : These functions give information about identifiers you have defined interactiv
3967 : These functions give information about identifiers you have defined interactiv
3934 ely (not things you loaded or defined in your configuration files).
3968 ely (not things you loaded or defined in your configuration files).
3935
3969
3936 \family typewriter
3970 \family typewriter
3937 %who
3971 %who
3938 \family default
3972 \family default
3939 just prints a list of identifiers and
3973 just prints a list of identifiers and
3940 \family typewriter
3974 \family typewriter
3941 %whos
3975 %whos
3942 \family default
3976 \family default
3943 prints a table with some basic details about each identifier.
3977 prints a table with some basic details about each identifier.
3944 \layout Standard
3978 \layout Standard
3945
3979
3946 Note that the dynamic object information functions (
3980 Note that the dynamic object information functions (
3947 \family typewriter
3981 \family typewriter
3948 ?/??, %pdoc, %pfile, %pdef, %psource
3982 ?/??, %pdoc, %pfile, %pdef, %psource
3949 \family default
3983 \family default
3950 ) give you access to documentation even on things which are not really defined
3984 ) give you access to documentation even on things which are not really defined
3951 as separate identifiers.
3985 as separate identifiers.
3952 Try for example typing
3986 Try for example typing
3953 \family typewriter
3987 \family typewriter
3954 {}.get?
3988 {}.get?
3955 \family default
3989 \family default
3956 or after doing
3990 or after doing
3957 \family typewriter
3991 \family typewriter
3958 import os
3992 import os
3959 \family default
3993 \family default
3960 , type
3994 , type
3961 \family typewriter
3995 \family typewriter
3962 os.path.abspath??
3996 os.path.abspath??
3963 \family default
3997 \family default
3964 .
3998 .
3965 \layout Subsection
3999 \layout Subsection
3966
4000
3967
4001
3968 \begin_inset LatexCommand \label{sec:readline}
4002 \begin_inset LatexCommand \label{sec:readline}
3969
4003
3970 \end_inset
4004 \end_inset
3971
4005
3972 Readline-based features
4006 Readline-based features
3973 \layout Standard
4007 \layout Standard
3974
4008
3975 These features require the GNU readline library, so they won't work if your
4009 These features require the GNU readline library, so they won't work if your
3976 Python installation lacks readline support.
4010 Python installation lacks readline support.
3977 We will first describe the default behavior IPython uses, and then how
4011 We will first describe the default behavior IPython uses, and then how
3978 to change it to suit your preferences.
4012 to change it to suit your preferences.
3979 \layout Subsubsection
4013 \layout Subsubsection
3980
4014
3981 Command line completion
4015 Command line completion
3982 \layout Standard
4016 \layout Standard
3983
4017
3984 At any time, hitting TAB will complete any available python commands or
4018 At any time, hitting TAB will complete any available python commands or
3985 variable names, and show you a list of the possible completions if there's
4019 variable names, and show you a list of the possible completions if there's
3986 no unambiguous one.
4020 no unambiguous one.
3987 It will also complete filenames in the current directory if no python names
4021 It will also complete filenames in the current directory if no python names
3988 match what you've typed so far.
4022 match what you've typed so far.
3989 \layout Subsubsection
4023 \layout Subsubsection
3990
4024
3991 Search command history
4025 Search command history
3992 \layout Standard
4026 \layout Standard
3993
4027
3994 IPython provides two ways for searching through previous input and thus
4028 IPython provides two ways for searching through previous input and thus
3995 reduce the need for repetitive typing:
4029 reduce the need for repetitive typing:
3996 \layout Enumerate
4030 \layout Enumerate
3997
4031
3998 Start typing, and then use
4032 Start typing, and then use
3999 \family typewriter
4033 \family typewriter
4000 Ctrl-p
4034 Ctrl-p
4001 \family default
4035 \family default
4002 (previous,up) and
4036 (previous,up) and
4003 \family typewriter
4037 \family typewriter
4004 Ctrl-n
4038 Ctrl-n
4005 \family default
4039 \family default
4006 (next,down) to search through only the history items that match what you've
4040 (next,down) to search through only the history items that match what you've
4007 typed so far.
4041 typed so far.
4008 If you use
4042 If you use
4009 \family typewriter
4043 \family typewriter
4010 Ctrl-p/Ctrl-n
4044 Ctrl-p/Ctrl-n
4011 \family default
4045 \family default
4012 at a blank prompt, they just behave like normal arrow keys.
4046 at a blank prompt, they just behave like normal arrow keys.
4013 \layout Enumerate
4047 \layout Enumerate
4014
4048
4015 Hit
4049 Hit
4016 \family typewriter
4050 \family typewriter
4017 Ctrl-r
4051 Ctrl-r
4018 \family default
4052 \family default
4019 : opens a search prompt.
4053 : opens a search prompt.
4020 Begin typing and the system searches your history for lines that contain
4054 Begin typing and the system searches your history for lines that contain
4021 what you've typed so far, completing as much as it can.
4055 what you've typed so far, completing as much as it can.
4022 \layout Subsubsection
4056 \layout Subsubsection
4023
4057
4024 Persistent command history across sessions
4058 Persistent command history across sessions
4025 \layout Standard
4059 \layout Standard
4026
4060
4027 IPython will save your input history when it leaves and reload it next time
4061 IPython will save your input history when it leaves and reload it next time
4028 you restart it.
4062 you restart it.
4029 By default, the history file is named
4063 By default, the history file is named
4030 \family typewriter
4064 \family typewriter
4031 $IPYTHONDIR/history
4065 $IPYTHONDIR/history
4032 \family default
4066 \family default
4033 , but if you've loaded a named profile, '
4067 , but if you've loaded a named profile, '
4034 \family typewriter
4068 \family typewriter
4035 -PROFILE_NAME
4069 -PROFILE_NAME
4036 \family default
4070 \family default
4037 ' is appended to the name.
4071 ' is appended to the name.
4038 This allows you to keep separate histories related to various tasks: commands
4072 This allows you to keep separate histories related to various tasks: commands
4039 related to numerical work will not be clobbered by a system shell history,
4073 related to numerical work will not be clobbered by a system shell history,
4040 for example.
4074 for example.
4041 \layout Subsubsection
4075 \layout Subsubsection
4042
4076
4043 Autoindent
4077 Autoindent
4044 \layout Standard
4078 \layout Standard
4045
4079
4046 IPython can recognize lines ending in ':' and indent the next line, while
4080 IPython can recognize lines ending in ':' and indent the next line, while
4047 also un-indenting automatically after 'raise' or 'return'.
4081 also un-indenting automatically after 'raise' or 'return'.
4048
4082
4049 \layout Standard
4083 \layout Standard
4050
4084
4051 This feature uses the readline library, so it will honor your
4085 This feature uses the readline library, so it will honor your
4052 \family typewriter
4086 \family typewriter
4053 ~/.inputrc
4087 ~/.inputrc
4054 \family default
4088 \family default
4055 configuration (or whatever file your
4089 configuration (or whatever file your
4056 \family typewriter
4090 \family typewriter
4057 INPUTRC
4091 INPUTRC
4058 \family default
4092 \family default
4059 variable points to).
4093 variable points to).
4060 Adding the following lines to your
4094 Adding the following lines to your
4061 \family typewriter
4095 \family typewriter
4062 .inputrc
4096 .inputrc
4063 \family default
4097 \family default
4064 file can make indenting/unindenting more convenient (
4098 file can make indenting/unindenting more convenient (
4065 \family typewriter
4099 \family typewriter
4066 M-i
4100 M-i
4067 \family default
4101 \family default
4068 indents,
4102 indents,
4069 \family typewriter
4103 \family typewriter
4070 M-u
4104 M-u
4071 \family default
4105 \family default
4072 unindents):
4106 unindents):
4073 \layout Standard
4107 \layout Standard
4074
4108
4075
4109
4076 \family typewriter
4110 \family typewriter
4077 $if Python
4111 $if Python
4078 \newline
4112 \newline
4079 "
4113 "
4080 \backslash
4114 \backslash
4081 M-i": "\SpecialChar ~
4115 M-i": "\SpecialChar ~
4082 \SpecialChar ~
4116 \SpecialChar ~
4083 \SpecialChar ~
4117 \SpecialChar ~
4084 \SpecialChar ~
4118 \SpecialChar ~
4085 "
4119 "
4086 \newline
4120 \newline
4087 "
4121 "
4088 \backslash
4122 \backslash
4089 M-u": "
4123 M-u": "
4090 \backslash
4124 \backslash
4091 d
4125 d
4092 \backslash
4126 \backslash
4093 d
4127 d
4094 \backslash
4128 \backslash
4095 d
4129 d
4096 \backslash
4130 \backslash
4097 d"
4131 d"
4098 \newline
4132 \newline
4099 $endif
4133 $endif
4100 \layout Standard
4134 \layout Standard
4101
4135
4102 Note that there are 4 spaces between the quote marks after
4136 Note that there are 4 spaces between the quote marks after
4103 \family typewriter
4137 \family typewriter
4104 "M-i"
4138 "M-i"
4105 \family default
4139 \family default
4106 above.
4140 above.
4107 \layout Standard
4141 \layout Standard
4108
4142
4109
4143
4110 \series bold
4144 \series bold
4111 Warning:
4145 Warning:
4112 \series default
4146 \series default
4113 this feature is ON by default, but it can cause problems with the pasting
4147 this feature is ON by default, but it can cause problems with the pasting
4114 of multi-line indented code (the pasted code gets re-indented on each line).
4148 of multi-line indented code (the pasted code gets re-indented on each line).
4115 A magic function
4149 A magic function
4116 \family typewriter
4150 \family typewriter
4117 %autoindent
4151 %autoindent
4118 \family default
4152 \family default
4119 allows you to toggle it on/off at runtime.
4153 allows you to toggle it on/off at runtime.
4120 You can also disable it permanently on in your
4154 You can also disable it permanently on in your
4121 \family typewriter
4155 \family typewriter
4122 ipythonrc
4156 ipythonrc
4123 \family default
4157 \family default
4124 file (set
4158 file (set
4125 \family typewriter
4159 \family typewriter
4126 autoindent 0
4160 autoindent 0
4127 \family default
4161 \family default
4128 ).
4162 ).
4129 \layout Subsubsection
4163 \layout Subsubsection
4130
4164
4131 Customizing readline behavior
4165 Customizing readline behavior
4132 \layout Standard
4166 \layout Standard
4133
4167
4134 All these features are based on the GNU readline library, which has an extremely
4168 All these features are based on the GNU readline library, which has an extremely
4135 customizable interface.
4169 customizable interface.
4136 Normally, readline is configured via a file which defines the behavior
4170 Normally, readline is configured via a file which defines the behavior
4137 of the library; the details of the syntax for this can be found in the
4171 of the library; the details of the syntax for this can be found in the
4138 readline documentation available with your system or on the Internet.
4172 readline documentation available with your system or on the Internet.
4139 IPython doesn't read this file (if it exists) directly, but it does support
4173 IPython doesn't read this file (if it exists) directly, but it does support
4140 passing to readline valid options via a simple interface.
4174 passing to readline valid options via a simple interface.
4141 In brief, you can customize readline by setting the following options in
4175 In brief, you can customize readline by setting the following options in
4142 your
4176 your
4143 \family typewriter
4177 \family typewriter
4144 ipythonrc
4178 ipythonrc
4145 \family default
4179 \family default
4146 configuration file (note that these options can
4180 configuration file (note that these options can
4147 \emph on
4181 \emph on
4148 not
4182 not
4149 \emph default
4183 \emph default
4150 be specified at the command line):
4184 be specified at the command line):
4151 \layout List
4185 \layout List
4152 \labelwidthstring 00.00.0000
4186 \labelwidthstring 00.00.0000
4153
4187
4154
4188
4155 \family typewriter
4189 \family typewriter
4156 \series bold
4190 \series bold
4157 readline_parse_and_bind:
4191 readline_parse_and_bind:
4158 \family default
4192 \family default
4159 \series default
4193 \series default
4160 this option can appear as many times as you want, each time defining a
4194 this option can appear as many times as you want, each time defining a
4161 string to be executed via a
4195 string to be executed via a
4162 \family typewriter
4196 \family typewriter
4163 readline.parse_and_bind()
4197 readline.parse_and_bind()
4164 \family default
4198 \family default
4165 command.
4199 command.
4166 The syntax for valid commands of this kind can be found by reading the
4200 The syntax for valid commands of this kind can be found by reading the
4167 documentation for the GNU readline library, as these commands are of the
4201 documentation for the GNU readline library, as these commands are of the
4168 kind which readline accepts in its configuration file.
4202 kind which readline accepts in its configuration file.
4169 \layout List
4203 \layout List
4170 \labelwidthstring 00.00.0000
4204 \labelwidthstring 00.00.0000
4171
4205
4172
4206
4173 \family typewriter
4207 \family typewriter
4174 \series bold
4208 \series bold
4175 readline_remove_delims:
4209 readline_remove_delims:
4176 \family default
4210 \family default
4177 \series default
4211 \series default
4178 a string of characters to be removed from the default word-delimiters list
4212 a string of characters to be removed from the default word-delimiters list
4179 used by readline, so that completions may be performed on strings which
4213 used by readline, so that completions may be performed on strings which
4180 contain them.
4214 contain them.
4181 Do not change the default value unless you know what you're doing.
4215 Do not change the default value unless you know what you're doing.
4182 \layout List
4216 \layout List
4183 \labelwidthstring 00.00.0000
4217 \labelwidthstring 00.00.0000
4184
4218
4185
4219
4186 \family typewriter
4220 \family typewriter
4187 \series bold
4221 \series bold
4188 readline_omit__names
4222 readline_omit__names
4189 \family default
4223 \family default
4190 \series default
4224 \series default
4191 : when tab-completion is enabled, hitting
4225 : when tab-completion is enabled, hitting
4192 \family typewriter
4226 \family typewriter
4193 <tab>
4227 <tab>
4194 \family default
4228 \family default
4195 after a '
4229 after a '
4196 \family typewriter
4230 \family typewriter
4197 .
4231 .
4198 \family default
4232 \family default
4199 ' in a name will complete all attributes of an object, including all the
4233 ' in a name will complete all attributes of an object, including all the
4200 special methods whose names include double underscores (like
4234 special methods whose names include double underscores (like
4201 \family typewriter
4235 \family typewriter
4202 __getitem__
4236 __getitem__
4203 \family default
4237 \family default
4204 or
4238 or
4205 \family typewriter
4239 \family typewriter
4206 __class__
4240 __class__
4207 \family default
4241 \family default
4208 ).
4242 ).
4209 If you'd rather not see these names by default, you can set this option
4243 If you'd rather not see these names by default, you can set this option
4210 to 1.
4244 to 1.
4211 Note that even when this option is set, you can still see those names by
4245 Note that even when this option is set, you can still see those names by
4212 explicitly typing a
4246 explicitly typing a
4213 \family typewriter
4247 \family typewriter
4214 _
4248 _
4215 \family default
4249 \family default
4216 after the period and hitting
4250 after the period and hitting
4217 \family typewriter
4251 \family typewriter
4218 <tab>
4252 <tab>
4219 \family default
4253 \family default
4220 : '
4254 : '
4221 \family typewriter
4255 \family typewriter
4222 name._<tab>
4256 name._<tab>
4223 \family default
4257 \family default
4224 ' will always complete attribute names starting with '
4258 ' will always complete attribute names starting with '
4225 \family typewriter
4259 \family typewriter
4226 _
4260 _
4227 \family default
4261 \family default
4228 '.
4262 '.
4229 \layout List
4263 \layout List
4230 \labelwidthstring 00.00.0000
4264 \labelwidthstring 00.00.0000
4231
4265
4232 \SpecialChar ~
4266 \SpecialChar ~
4233 This option is off by default so that new users see all attributes of any
4267 This option is off by default so that new users see all attributes of any
4234 objects they are dealing with.
4268 objects they are dealing with.
4235 \layout Standard
4269 \layout Standard
4236
4270
4237 You will find the default values along with a corresponding detailed explanation
4271 You will find the default values along with a corresponding detailed explanation
4238 in your
4272 in your
4239 \family typewriter
4273 \family typewriter
4240 ipythonrc
4274 ipythonrc
4241 \family default
4275 \family default
4242 file.
4276 file.
4243 \layout Subsection
4277 \layout Subsection
4244
4278
4245 Session logging and restoring
4279 Session logging and restoring
4246 \layout Standard
4280 \layout Standard
4247
4281
4248 You can log all input from a session either by starting IPython with the
4282 You can log all input from a session either by starting IPython with the
4249 command line switches
4283 command line switches
4250 \family typewriter
4284 \family typewriter
4251 -log
4285 -log
4252 \family default
4286 \family default
4253 or
4287 or
4254 \family typewriter
4288 \family typewriter
4255 -logfile
4289 -logfile
4256 \family default
4290 \family default
4257 (see sec.
4291 (see sec.
4258
4292
4259 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4293 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
4260
4294
4261 \end_inset
4295 \end_inset
4262
4296
4263 )or by activating the logging at any moment with the magic function
4297 )or by activating the logging at any moment with the magic function
4264 \family typewriter
4298 \family typewriter
4265 %logstart
4299 %logstart
4266 \family default
4300 \family default
4267 .
4301 .
4268
4302
4269 \layout Standard
4303 \layout Standard
4270
4304
4271 Log files can later be reloaded with the
4305 Log files can later be reloaded with the
4272 \family typewriter
4306 \family typewriter
4273 -logplay
4307 -logplay
4274 \family default
4308 \family default
4275 option and IPython will attempt to 'replay' the log by executing all the
4309 option and IPython will attempt to 'replay' the log by executing all the
4276 lines in it, thus restoring the state of a previous session.
4310 lines in it, thus restoring the state of a previous session.
4277 This feature is not quite perfect, but can still be useful in many cases.
4311 This feature is not quite perfect, but can still be useful in many cases.
4278 \layout Standard
4312 \layout Standard
4279
4313
4280 The log files can also be used as a way to have a permanent record of any
4314 The log files can also be used as a way to have a permanent record of any
4281 code you wrote while experimenting.
4315 code you wrote while experimenting.
4282 Log files are regular text files which you can later open in your favorite
4316 Log files are regular text files which you can later open in your favorite
4283 text editor to extract code or to 'clean them up' before using them to
4317 text editor to extract code or to 'clean them up' before using them to
4284 replay a session.
4318 replay a session.
4285 \layout Standard
4319 \layout Standard
4286
4320
4287 The
4321 The
4288 \family typewriter
4322 \family typewriter
4289 %logstart
4323 %logstart
4290 \family default
4324 \family default
4291 function for activating logging in mid-session is used as follows:
4325 function for activating logging in mid-session is used as follows:
4292 \layout Standard
4326 \layout Standard
4293
4327
4294
4328
4295 \family typewriter
4329 \family typewriter
4296 %logstart [log_name [log_mode]]
4330 %logstart [log_name [log_mode]]
4297 \layout Standard
4331 \layout Standard
4298
4332
4299 If no name is given, it defaults to a file named
4333 If no name is given, it defaults to a file named
4300 \family typewriter
4334 \family typewriter
4301 'log'
4335 'log'
4302 \family default
4336 \family default
4303 in your IPYTHONDIR directory, in
4337 in your IPYTHONDIR directory, in
4304 \family typewriter
4338 \family typewriter
4305 'rotate'
4339 'rotate'
4306 \family default
4340 \family default
4307 mode (see below).
4341 mode (see below).
4308 \layout Standard
4342 \layout Standard
4309
4343
4310 '
4344 '
4311 \family typewriter
4345 \family typewriter
4312 %logstart name
4346 %logstart name
4313 \family default
4347 \family default
4314 ' saves to file
4348 ' saves to file
4315 \family typewriter
4349 \family typewriter
4316 'name'
4350 'name'
4317 \family default
4351 \family default
4318 in
4352 in
4319 \family typewriter
4353 \family typewriter
4320 'backup'
4354 'backup'
4321 \family default
4355 \family default
4322 mode.
4356 mode.
4323 It saves your history up to that point and then continues logging.
4357 It saves your history up to that point and then continues logging.
4324 \layout Standard
4358 \layout Standard
4325
4359
4326
4360
4327 \family typewriter
4361 \family typewriter
4328 %logstart
4362 %logstart
4329 \family default
4363 \family default
4330 takes a second optional parameter: logging mode.
4364 takes a second optional parameter: logging mode.
4331 This can be one of (note that the modes are given unquoted):
4365 This can be one of (note that the modes are given unquoted):
4332 \layout List
4366 \layout List
4333 \labelwidthstring 00.00.0000
4367 \labelwidthstring 00.00.0000
4334
4368
4335
4369
4336 \family typewriter
4370 \family typewriter
4337 over
4371 over
4338 \family default
4372 \family default
4339 : overwrite existing
4373 : overwrite existing
4340 \family typewriter
4374 \family typewriter
4341 log_name
4375 log_name
4342 \family default
4376 \family default
4343 .
4377 .
4344 \layout List
4378 \layout List
4345 \labelwidthstring 00.00.0000
4379 \labelwidthstring 00.00.0000
4346
4380
4347
4381
4348 \family typewriter
4382 \family typewriter
4349 backup
4383 backup
4350 \family default
4384 \family default
4351 : rename (if exists) to
4385 : rename (if exists) to
4352 \family typewriter
4386 \family typewriter
4353 log_name~
4387 log_name~
4354 \family default
4388 \family default
4355 and start
4389 and start
4356 \family typewriter
4390 \family typewriter
4357 log_name
4391 log_name
4358 \family default
4392 \family default
4359 .
4393 .
4360 \layout List
4394 \layout List
4361 \labelwidthstring 00.00.0000
4395 \labelwidthstring 00.00.0000
4362
4396
4363
4397
4364 \family typewriter
4398 \family typewriter
4365 append
4399 append
4366 \family default
4400 \family default
4367 : well, that says it.
4401 : well, that says it.
4368 \layout List
4402 \layout List
4369 \labelwidthstring 00.00.0000
4403 \labelwidthstring 00.00.0000
4370
4404
4371
4405
4372 \family typewriter
4406 \family typewriter
4373 rotate
4407 rotate
4374 \family default
4408 \family default
4375 : create rotating logs
4409 : create rotating logs
4376 \family typewriter
4410 \family typewriter
4377 log_name
4411 log_name
4378 \family default
4412 \family default
4379 .
4413 .
4380 \family typewriter
4414 \family typewriter
4381 1~
4415 1~
4382 \family default
4416 \family default
4383 ,
4417 ,
4384 \family typewriter
4418 \family typewriter
4385 log_name.2~
4419 log_name.2~
4386 \family default
4420 \family default
4387 , etc.
4421 , etc.
4388 \layout Standard
4422 \layout Standard
4389
4423
4390 The
4424 The
4391 \family typewriter
4425 \family typewriter
4392 %logoff
4426 %logoff
4393 \family default
4427 \family default
4394 and
4428 and
4395 \family typewriter
4429 \family typewriter
4396 %logon
4430 %logon
4397 \family default
4431 \family default
4398 functions allow you to temporarily stop and resume logging to a file which
4432 functions allow you to temporarily stop and resume logging to a file which
4399 had previously been started with
4433 had previously been started with
4400 \family typewriter
4434 \family typewriter
4401 %logstart
4435 %logstart
4402 \family default
4436 \family default
4403 .
4437 .
4404 They will fail (with an explanation) if you try to use them before logging
4438 They will fail (with an explanation) if you try to use them before logging
4405 has been started.
4439 has been started.
4406 \layout Subsection
4440 \layout Subsection
4407
4441
4408
4442
4409 \begin_inset LatexCommand \label{sub:System-shell-access}
4443 \begin_inset LatexCommand \label{sub:System-shell-access}
4410
4444
4411 \end_inset
4445 \end_inset
4412
4446
4413 System shell access
4447 System shell access
4414 \layout Standard
4448 \layout Standard
4415
4449
4416 Any input line beginning with a
4450 Any input line beginning with a
4417 \family typewriter
4451 \family typewriter
4418 !
4452 !
4419 \family default
4453 \family default
4420 character is passed verbatim (minus the
4454 character is passed verbatim (minus the
4421 \family typewriter
4455 \family typewriter
4422 !
4456 !
4423 \family default
4457 \family default
4424 , of course) to the underlying operating system.
4458 , of course) to the underlying operating system.
4425 For example, typing
4459 For example, typing
4426 \family typewriter
4460 \family typewriter
4427 !ls
4461 !ls
4428 \family default
4462 \family default
4429 will run
4463 will run
4430 \family typewriter
4464 \family typewriter
4431 'ls'
4465 'ls'
4432 \family default
4466 \family default
4433 in the current directory.
4467 in the current directory.
4434 \layout Subsubsection
4468 \layout Subsubsection
4435
4469
4436 Manual capture of command output
4470 Manual capture of command output
4437 \layout Standard
4471 \layout Standard
4438
4472
4439 If the input line begins with
4473 If the input line begins with
4440 \emph on
4474 \emph on
4441 two
4475 two
4442 \emph default
4476 \emph default
4443 exclamation marks,
4477 exclamation marks,
4444 \family typewriter
4478 \family typewriter
4445 !!
4479 !!
4446 \family default
4480 \family default
4447 , the command is executed but its output is captured and returned as a python
4481 , the command is executed but its output is captured and returned as a python
4448 list, split on newlines.
4482 list, split on newlines.
4449 Any output sent by the subprocess to standard error is printed separately,
4483 Any output sent by the subprocess to standard error is printed separately,
4450 so that the resulting list only captures standard output.
4484 so that the resulting list only captures standard output.
4451 The
4485 The
4452 \family typewriter
4486 \family typewriter
4453 !!
4487 !!
4454 \family default
4488 \family default
4455 syntax is a shorthand for the
4489 syntax is a shorthand for the
4456 \family typewriter
4490 \family typewriter
4457 %sx
4491 %sx
4458 \family default
4492 \family default
4459 magic command.
4493 magic command.
4460 \layout Standard
4494 \layout Standard
4461
4495
4462 Finally, the
4496 Finally, the
4463 \family typewriter
4497 \family typewriter
4464 %sc
4498 %sc
4465 \family default
4499 \family default
4466 magic (short for `shell capture') is similar to
4500 magic (short for `shell capture') is similar to
4467 \family typewriter
4501 \family typewriter
4468 %sx
4502 %sx
4469 \family default
4503 \family default
4470 , but allowing more fine-grained control of the capture details, and storing
4504 , but allowing more fine-grained control of the capture details, and storing
4471 the result directly into a named variable.
4505 the result directly into a named variable.
4472 \layout Standard
4506 \layout Standard
4473
4507
4474 See Sec.\SpecialChar ~
4508 See Sec.\SpecialChar ~
4475
4509
4476 \begin_inset LatexCommand \ref{sec:magic}
4510 \begin_inset LatexCommand \ref{sec:magic}
4477
4511
4478 \end_inset
4512 \end_inset
4479
4513
4480 for details on the magics
4514 for details on the magics
4481 \family typewriter
4515 \family typewriter
4482 %sc
4516 %sc
4483 \family default
4517 \family default
4484 and
4518 and
4485 \family typewriter
4519 \family typewriter
4486 %sx
4520 %sx
4487 \family default
4521 \family default
4488 , or use IPython's own help (
4522 , or use IPython's own help (
4489 \family typewriter
4523 \family typewriter
4490 sc?
4524 sc?
4491 \family default
4525 \family default
4492 and
4526 and
4493 \family typewriter
4527 \family typewriter
4494 sx?
4528 sx?
4495 \family default
4529 \family default
4496 ) for further details.
4530 ) for further details.
4497 \layout Standard
4531 \layout Standard
4498
4532
4499 IPython also allows you to expand the value of python variables when making
4533 IPython also allows you to expand the value of python variables when making
4500 system calls.
4534 system calls.
4501 Any python variable or expression which you prepend with
4535 Any python variable or expression which you prepend with
4502 \family typewriter
4536 \family typewriter
4503 $
4537 $
4504 \family default
4538 \family default
4505 will get expanded before the system call is made.
4539 will get expanded before the system call is made.
4506
4540
4507 \layout Standard
4541 \layout Standard
4508
4542
4509
4543
4510 \family typewriter
4544 \family typewriter
4511 In [1]: pyvar='Hello world'
4545 In [1]: pyvar='Hello world'
4512 \newline
4546 \newline
4513 In [2]: !echo "A python variable: $pyvar"
4547 In [2]: !echo "A python variable: $pyvar"
4514 \newline
4548 \newline
4515 A python variable: Hello world
4549 A python variable: Hello world
4516 \layout Standard
4550 \layout Standard
4517
4551
4518 If you want the shell to actually see a literal
4552 If you want the shell to actually see a literal
4519 \family typewriter
4553 \family typewriter
4520 $
4554 $
4521 \family default
4555 \family default
4522 , you need to type it twice:
4556 , you need to type it twice:
4523 \layout Standard
4557 \layout Standard
4524
4558
4525
4559
4526 \family typewriter
4560 \family typewriter
4527 In [3]: !echo "A system variable: $$HOME"
4561 In [3]: !echo "A system variable: $$HOME"
4528 \newline
4562 \newline
4529 A system variable: /home/fperez
4563 A system variable: /home/fperez
4530 \layout Standard
4564 \layout Standard
4531
4565
4532 You can pass arbitrary expressions, though you'll need to delimit them with
4566 You can pass arbitrary expressions, though you'll need to delimit them with
4533
4567
4534 \family typewriter
4568 \family typewriter
4535 {}
4569 {}
4536 \family default
4570 \family default
4537 if there is ambiguity as to the extent of the expression:
4571 if there is ambiguity as to the extent of the expression:
4538 \layout Standard
4572 \layout Standard
4539
4573
4540
4574
4541 \family typewriter
4575 \family typewriter
4542 In [5]: x=10
4576 In [5]: x=10
4543 \newline
4577 \newline
4544 In [6]: y=20
4578 In [6]: y=20
4545 \newline
4579 \newline
4546 In [13]: !echo $x+y
4580 In [13]: !echo $x+y
4547 \newline
4581 \newline
4548 10+y
4582 10+y
4549 \newline
4583 \newline
4550 In [7]: !echo ${x+y}
4584 In [7]: !echo ${x+y}
4551 \newline
4585 \newline
4552 30
4586 30
4553 \layout Standard
4587 \layout Standard
4554
4588
4555 Even object attributes can be expanded:
4589 Even object attributes can be expanded:
4556 \layout Standard
4590 \layout Standard
4557
4591
4558
4592
4559 \family typewriter
4593 \family typewriter
4560 In [12]: !echo $sys.argv
4594 In [12]: !echo $sys.argv
4561 \newline
4595 \newline
4562 [/home/fperez/usr/bin/ipython]
4596 [/home/fperez/usr/bin/ipython]
4563 \layout Subsection
4597 \layout Subsection
4564
4598
4565 System command aliases
4599 System command aliases
4566 \layout Standard
4600 \layout Standard
4567
4601
4568 The
4602 The
4569 \family typewriter
4603 \family typewriter
4570 %alias
4604 %alias
4571 \family default
4605 \family default
4572 magic function and the
4606 magic function and the
4573 \family typewriter
4607 \family typewriter
4574 alias
4608 alias
4575 \family default
4609 \family default
4576 option in the
4610 option in the
4577 \family typewriter
4611 \family typewriter
4578 ipythonrc
4612 ipythonrc
4579 \family default
4613 \family default
4580 configuration file allow you to define magic functions which are in fact
4614 configuration file allow you to define magic functions which are in fact
4581 system shell commands.
4615 system shell commands.
4582 These aliases can have parameters.
4616 These aliases can have parameters.
4583
4617
4584 \layout Standard
4618 \layout Standard
4585
4619
4586 '
4620 '
4587 \family typewriter
4621 \family typewriter
4588 %alias alias_name cmd
4622 %alias alias_name cmd
4589 \family default
4623 \family default
4590 ' defines '
4624 ' defines '
4591 \family typewriter
4625 \family typewriter
4592 alias_name
4626 alias_name
4593 \family default
4627 \family default
4594 ' as an alias for '
4628 ' as an alias for '
4595 \family typewriter
4629 \family typewriter
4596 cmd
4630 cmd
4597 \family default
4631 \family default
4598 '
4632 '
4599 \layout Standard
4633 \layout Standard
4600
4634
4601 Then, typing '
4635 Then, typing '
4602 \family typewriter
4636 \family typewriter
4603 %alias_name params
4637 %alias_name params
4604 \family default
4638 \family default
4605 ' will execute the system command '
4639 ' will execute the system command '
4606 \family typewriter
4640 \family typewriter
4607 cmd params
4641 cmd params
4608 \family default
4642 \family default
4609 ' (from your underlying operating system).
4643 ' (from your underlying operating system).
4610
4644
4611 \layout Standard
4645 \layout Standard
4612
4646
4613 You can also define aliases with parameters using
4647 You can also define aliases with parameters using
4614 \family typewriter
4648 \family typewriter
4615 %s
4649 %s
4616 \family default
4650 \family default
4617 specifiers (one per parameter).
4651 specifiers (one per parameter).
4618 The following example defines the
4652 The following example defines the
4619 \family typewriter
4653 \family typewriter
4620 %parts
4654 %parts
4621 \family default
4655 \family default
4622 function as an alias to the command '
4656 function as an alias to the command '
4623 \family typewriter
4657 \family typewriter
4624 echo first %s second %s
4658 echo first %s second %s
4625 \family default
4659 \family default
4626 ' where each
4660 ' where each
4627 \family typewriter
4661 \family typewriter
4628 %s
4662 %s
4629 \family default
4663 \family default
4630 will be replaced by a positional parameter to the call to
4664 will be replaced by a positional parameter to the call to
4631 \family typewriter
4665 \family typewriter
4632 %parts:
4666 %parts:
4633 \layout Standard
4667 \layout Standard
4634
4668
4635
4669
4636 \family typewriter
4670 \family typewriter
4637 In [1]: alias parts echo first %s second %s
4671 In [1]: alias parts echo first %s second %s
4638 \newline
4672 \newline
4639 In [2]: %parts A B
4673 In [2]: %parts A B
4640 \newline
4674 \newline
4641 first A second B
4675 first A second B
4642 \newline
4676 \newline
4643 In [3]: %parts A
4677 In [3]: %parts A
4644 \newline
4678 \newline
4645 Incorrect number of arguments: 2 expected.
4679 Incorrect number of arguments: 2 expected.
4646
4680
4647 \newline
4681 \newline
4648 parts is an alias to: 'echo first %s second %s'
4682 parts is an alias to: 'echo first %s second %s'
4649 \layout Standard
4683 \layout Standard
4650
4684
4651 If called with no parameters,
4685 If called with no parameters,
4652 \family typewriter
4686 \family typewriter
4653 %alias
4687 %alias
4654 \family default
4688 \family default
4655 prints the table of currently defined aliases.
4689 prints the table of currently defined aliases.
4656 \layout Standard
4690 \layout Standard
4657
4691
4658 The
4692 The
4659 \family typewriter
4693 \family typewriter
4660 %rehash/rehashx
4694 %rehash/rehashx
4661 \family default
4695 \family default
4662 magics allow you to load your entire
4696 magics allow you to load your entire
4663 \family typewriter
4697 \family typewriter
4664 $PATH
4698 $PATH
4665 \family default
4699 \family default
4666 as ipython aliases.
4700 as ipython aliases.
4667 See their respective docstrings (or sec.\SpecialChar ~
4701 See their respective docstrings (or sec.\SpecialChar ~
4668
4702
4669 \begin_inset LatexCommand \ref{sec:magic}
4703 \begin_inset LatexCommand \ref{sec:magic}
4670
4704
4671 \end_inset
4705 \end_inset
4672
4706
4673 for further details).
4707 for further details).
4674 \layout Subsection
4708 \layout Subsection
4675
4709
4676
4710
4677 \begin_inset LatexCommand \label{sec:dreload}
4711 \begin_inset LatexCommand \label{sec:dreload}
4678
4712
4679 \end_inset
4713 \end_inset
4680
4714
4681 Recursive reload
4715 Recursive reload
4682 \layout Standard
4716 \layout Standard
4683
4717
4684 The
4718 The
4685 \family typewriter
4719 \family typewriter
4686 %dreload
4720 %dreload
4687 \family default
4721 \family default
4688 command does a recursive reload of a module: changes made to the module
4722 command does a recursive reload of a module: changes made to the module
4689 since you imported will actually be available without having to exit.
4723 since you imported will actually be available without having to exit.
4690 \layout Subsection
4724 \layout Subsection
4691
4725
4692 Verbose and colored exception traceback printouts
4726 Verbose and colored exception traceback printouts
4693 \layout Standard
4727 \layout Standard
4694
4728
4695 IPython provides the option to see very detailed exception tracebacks, which
4729 IPython provides the option to see very detailed exception tracebacks, which
4696 can be especially useful when debugging large programs.
4730 can be especially useful when debugging large programs.
4697 You can run any Python file with the
4731 You can run any Python file with the
4698 \family typewriter
4732 \family typewriter
4699 %run
4733 %run
4700 \family default
4734 \family default
4701 function to benefit from these detailed tracebacks.
4735 function to benefit from these detailed tracebacks.
4702 Furthermore, both normal and verbose tracebacks can be colored (if your
4736 Furthermore, both normal and verbose tracebacks can be colored (if your
4703 terminal supports it) which makes them much easier to parse visually.
4737 terminal supports it) which makes them much easier to parse visually.
4704 \layout Standard
4738 \layout Standard
4705
4739
4706 See the magic
4740 See the magic
4707 \family typewriter
4741 \family typewriter
4708 xmode
4742 xmode
4709 \family default
4743 \family default
4710 and
4744 and
4711 \family typewriter
4745 \family typewriter
4712 colors
4746 colors
4713 \family default
4747 \family default
4714 functions for details (just type
4748 functions for details (just type
4715 \family typewriter
4749 \family typewriter
4716 %magic
4750 %magic
4717 \family default
4751 \family default
4718 ).
4752 ).
4719 \layout Standard
4753 \layout Standard
4720
4754
4721 These features are basically a terminal version of Ka-Ping Yee's
4755 These features are basically a terminal version of Ka-Ping Yee's
4722 \family typewriter
4756 \family typewriter
4723 cgitb
4757 cgitb
4724 \family default
4758 \family default
4725 module, now part of the standard Python library.
4759 module, now part of the standard Python library.
4726 \layout Subsection
4760 \layout Subsection
4727
4761
4728
4762
4729 \begin_inset LatexCommand \label{sec:cache_input}
4763 \begin_inset LatexCommand \label{sec:cache_input}
4730
4764
4731 \end_inset
4765 \end_inset
4732
4766
4733 Input caching system
4767 Input caching system
4734 \layout Standard
4768 \layout Standard
4735
4769
4736 IPython offers numbered prompts (In/Out) with input and output caching.
4770 IPython offers numbered prompts (In/Out) with input and output caching.
4737 All input is saved and can be retrieved as variables (besides the usual
4771 All input is saved and can be retrieved as variables (besides the usual
4738 arrow key recall).
4772 arrow key recall).
4739 \layout Standard
4773 \layout Standard
4740
4774
4741 The following GLOBAL variables always exist (so don't overwrite them!):
4775 The following GLOBAL variables always exist (so don't overwrite them!):
4742
4776
4743 \family typewriter
4777 \family typewriter
4744 _i
4778 _i
4745 \family default
4779 \family default
4746 : stores previous input.
4780 : stores previous input.
4747
4781
4748 \family typewriter
4782 \family typewriter
4749 _ii
4783 _ii
4750 \family default
4784 \family default
4751 : next previous.
4785 : next previous.
4752
4786
4753 \family typewriter
4787 \family typewriter
4754 _iii
4788 _iii
4755 \family default
4789 \family default
4756 : next-next previous.
4790 : next-next previous.
4757
4791
4758 \family typewriter
4792 \family typewriter
4759 _ih
4793 _ih
4760 \family default
4794 \family default
4761 : a list of all input
4795 : a list of all input
4762 \family typewriter
4796 \family typewriter
4763 _ih[n]
4797 _ih[n]
4764 \family default
4798 \family default
4765 is the input from line
4799 is the input from line
4766 \family typewriter
4800 \family typewriter
4767 n
4801 n
4768 \family default
4802 \family default
4769 and this list is aliased to the global variable
4803 and this list is aliased to the global variable
4770 \family typewriter
4804 \family typewriter
4771 In
4805 In
4772 \family default
4806 \family default
4773 .
4807 .
4774 If you overwrite
4808 If you overwrite
4775 \family typewriter
4809 \family typewriter
4776 In
4810 In
4777 \family default
4811 \family default
4778 with a variable of your own, you can remake the assignment to the internal
4812 with a variable of your own, you can remake the assignment to the internal
4779 list with a simple
4813 list with a simple
4780 \family typewriter
4814 \family typewriter
4781 'In=_ih'
4815 'In=_ih'
4782 \family default
4816 \family default
4783 .
4817 .
4784 \layout Standard
4818 \layout Standard
4785
4819
4786 Additionally, global variables named
4820 Additionally, global variables named
4787 \family typewriter
4821 \family typewriter
4788 _i<n>
4822 _i<n>
4789 \family default
4823 \family default
4790 are dynamically created (
4824 are dynamically created (
4791 \family typewriter
4825 \family typewriter
4792 <n>
4826 <n>
4793 \family default
4827 \family default
4794 being the prompt counter), such that
4828 being the prompt counter), such that
4795 \newline
4829 \newline
4796
4830
4797 \family typewriter
4831 \family typewriter
4798 _i<n> == _ih[<n>] == In[<n>].
4832 _i<n> == _ih[<n>] == In[<n>].
4799 \layout Standard
4833 \layout Standard
4800
4834
4801 For example, what you typed at prompt 14 is available as
4835 For example, what you typed at prompt 14 is available as
4802 \family typewriter
4836 \family typewriter
4803 _i14,
4837 _i14,
4804 \family default
4838 \family default
4805
4839
4806 \family typewriter
4840 \family typewriter
4807 _ih[14]
4841 _ih[14]
4808 \family default
4842 \family default
4809 and
4843 and
4810 \family typewriter
4844 \family typewriter
4811 In[14]
4845 In[14]
4812 \family default
4846 \family default
4813 .
4847 .
4814 \layout Standard
4848 \layout Standard
4815
4849
4816 This allows you to easily cut and paste multi line interactive prompts by
4850 This allows you to easily cut and paste multi line interactive prompts by
4817 printing them out: they print like a clean string, without prompt characters.
4851 printing them out: they print like a clean string, without prompt characters.
4818 You can also manipulate them like regular variables (they are strings),
4852 You can also manipulate them like regular variables (they are strings),
4819 modify or exec them (typing
4853 modify or exec them (typing
4820 \family typewriter
4854 \family typewriter
4821 'exec _i9'
4855 'exec _i9'
4822 \family default
4856 \family default
4823 will re-execute the contents of input prompt 9, '
4857 will re-execute the contents of input prompt 9, '
4824 \family typewriter
4858 \family typewriter
4825 exec In[9:14]+In[18]
4859 exec In[9:14]+In[18]
4826 \family default
4860 \family default
4827 ' will re-execute lines 9 through 13 and line 18).
4861 ' will re-execute lines 9 through 13 and line 18).
4828 \layout Standard
4862 \layout Standard
4829
4863
4830 You can also re-execute multiple lines of input easily by using the magic
4864 You can also re-execute multiple lines of input easily by using the magic
4831
4865
4832 \family typewriter
4866 \family typewriter
4833 %macro
4867 %macro
4834 \family default
4868 \family default
4835 function (which automates the process and allows re-execution without having
4869 function (which automates the process and allows re-execution without having
4836 to type '
4870 to type '
4837 \family typewriter
4871 \family typewriter
4838 exec
4872 exec
4839 \family default
4873 \family default
4840 ' every time).
4874 ' every time).
4841 The macro system also allows you to re-execute previous lines which include
4875 The macro system also allows you to re-execute previous lines which include
4842 magic function calls (which require special processing).
4876 magic function calls (which require special processing).
4843 Type
4877 Type
4844 \family typewriter
4878 \family typewriter
4845 %macro?
4879 %macro?
4846 \family default
4880 \family default
4847 or see sec.
4881 or see sec.
4848
4882
4849 \begin_inset LatexCommand \ref{sec:magic}
4883 \begin_inset LatexCommand \ref{sec:magic}
4850
4884
4851 \end_inset
4885 \end_inset
4852
4886
4853 for more details on the macro system.
4887 for more details on the macro system.
4854 \layout Standard
4888 \layout Standard
4855
4889
4856 A history function
4890 A history function
4857 \family typewriter
4891 \family typewriter
4858 %hist
4892 %hist
4859 \family default
4893 \family default
4860 allows you to see any part of your input history by printing a range of
4894 allows you to see any part of your input history by printing a range of
4861 the
4895 the
4862 \family typewriter
4896 \family typewriter
4863 _i
4897 _i
4864 \family default
4898 \family default
4865 variables.
4899 variables.
4866 \layout Subsection
4900 \layout Subsection
4867
4901
4868
4902
4869 \begin_inset LatexCommand \label{sec:cache_output}
4903 \begin_inset LatexCommand \label{sec:cache_output}
4870
4904
4871 \end_inset
4905 \end_inset
4872
4906
4873 Output caching system
4907 Output caching system
4874 \layout Standard
4908 \layout Standard
4875
4909
4876 For output that is returned from actions, a system similar to the input
4910 For output that is returned from actions, a system similar to the input
4877 cache exists but using
4911 cache exists but using
4878 \family typewriter
4912 \family typewriter
4879 _
4913 _
4880 \family default
4914 \family default
4881 instead of
4915 instead of
4882 \family typewriter
4916 \family typewriter
4883 _i
4917 _i
4884 \family default
4918 \family default
4885 .
4919 .
4886 Only actions that produce a result (NOT assignments, for example) are cached.
4920 Only actions that produce a result (NOT assignments, for example) are cached.
4887 If you are familiar with Mathematica, IPython's
4921 If you are familiar with Mathematica, IPython's
4888 \family typewriter
4922 \family typewriter
4889 _
4923 _
4890 \family default
4924 \family default
4891 variables behave exactly like Mathematica's
4925 variables behave exactly like Mathematica's
4892 \family typewriter
4926 \family typewriter
4893 %
4927 %
4894 \family default
4928 \family default
4895 variables.
4929 variables.
4896 \layout Standard
4930 \layout Standard
4897
4931
4898 The following GLOBAL variables always exist (so don't overwrite them!):
4932 The following GLOBAL variables always exist (so don't overwrite them!):
4899
4933
4900 \layout List
4934 \layout List
4901 \labelwidthstring 00.00.0000
4935 \labelwidthstring 00.00.0000
4902
4936
4903
4937
4904 \family typewriter
4938 \family typewriter
4905 \series bold
4939 \series bold
4906 _
4940 _
4907 \family default
4941 \family default
4908 \series default
4942 \series default
4909 (a
4943 (a
4910 \emph on
4944 \emph on
4911 single
4945 single
4912 \emph default
4946 \emph default
4913 underscore) : stores previous output, like Python's default interpreter.
4947 underscore) : stores previous output, like Python's default interpreter.
4914 \layout List
4948 \layout List
4915 \labelwidthstring 00.00.0000
4949 \labelwidthstring 00.00.0000
4916
4950
4917
4951
4918 \family typewriter
4952 \family typewriter
4919 \series bold
4953 \series bold
4920 __
4954 __
4921 \family default
4955 \family default
4922 \series default
4956 \series default
4923 (two underscores): next previous.
4957 (two underscores): next previous.
4924 \layout List
4958 \layout List
4925 \labelwidthstring 00.00.0000
4959 \labelwidthstring 00.00.0000
4926
4960
4927
4961
4928 \family typewriter
4962 \family typewriter
4929 \series bold
4963 \series bold
4930 ___
4964 ___
4931 \family default
4965 \family default
4932 \series default
4966 \series default
4933 (three underscores): next-next previous.
4967 (three underscores): next-next previous.
4934 \layout Standard
4968 \layout Standard
4935
4969
4936 Additionally, global variables named
4970 Additionally, global variables named
4937 \family typewriter
4971 \family typewriter
4938 _<n>
4972 _<n>
4939 \family default
4973 \family default
4940 are dynamically created (
4974 are dynamically created (
4941 \family typewriter
4975 \family typewriter
4942 <n>
4976 <n>
4943 \family default
4977 \family default
4944 being the prompt counter), such that the result of output
4978 being the prompt counter), such that the result of output
4945 \family typewriter
4979 \family typewriter
4946 <n>
4980 <n>
4947 \family default
4981 \family default
4948 is always available as
4982 is always available as
4949 \family typewriter
4983 \family typewriter
4950 _<n>
4984 _<n>
4951 \family default
4985 \family default
4952 (don't use the angle brackets, just the number, e.g.
4986 (don't use the angle brackets, just the number, e.g.
4953
4987
4954 \family typewriter
4988 \family typewriter
4955 _21
4989 _21
4956 \family default
4990 \family default
4957 ).
4991 ).
4958 \layout Standard
4992 \layout Standard
4959
4993
4960 These global variables are all stored in a global dictionary (not a list,
4994 These global variables are all stored in a global dictionary (not a list,
4961 since it only has entries for lines which returned a result) available
4995 since it only has entries for lines which returned a result) available
4962 under the names
4996 under the names
4963 \family typewriter
4997 \family typewriter
4964 _oh
4998 _oh
4965 \family default
4999 \family default
4966 and
5000 and
4967 \family typewriter
5001 \family typewriter
4968 Out
5002 Out
4969 \family default
5003 \family default
4970 (similar to
5004 (similar to
4971 \family typewriter
5005 \family typewriter
4972 _ih
5006 _ih
4973 \family default
5007 \family default
4974 and
5008 and
4975 \family typewriter
5009 \family typewriter
4976 In
5010 In
4977 \family default
5011 \family default
4978 ).
5012 ).
4979 So the output from line 12 can be obtained as
5013 So the output from line 12 can be obtained as
4980 \family typewriter
5014 \family typewriter
4981 _12
5015 _12
4982 \family default
5016 \family default
4983 ,
5017 ,
4984 \family typewriter
5018 \family typewriter
4985 Out[12]
5019 Out[12]
4986 \family default
5020 \family default
4987 or
5021 or
4988 \family typewriter
5022 \family typewriter
4989 _oh[12]
5023 _oh[12]
4990 \family default
5024 \family default
4991 .
5025 .
4992 If you accidentally overwrite the
5026 If you accidentally overwrite the
4993 \family typewriter
5027 \family typewriter
4994 Out
5028 Out
4995 \family default
5029 \family default
4996 variable you can recover it by typing
5030 variable you can recover it by typing
4997 \family typewriter
5031 \family typewriter
4998 'Out=_oh
5032 'Out=_oh
4999 \family default
5033 \family default
5000 ' at the prompt.
5034 ' at the prompt.
5001 \layout Standard
5035 \layout Standard
5002
5036
5003 This system obviously can potentially put heavy memory demands on your system,
5037 This system obviously can potentially put heavy memory demands on your system,
5004 since it prevents Python's garbage collector from removing any previously
5038 since it prevents Python's garbage collector from removing any previously
5005 computed results.
5039 computed results.
5006 You can control how many results are kept in memory with the option (at
5040 You can control how many results are kept in memory with the option (at
5007 the command line or in your
5041 the command line or in your
5008 \family typewriter
5042 \family typewriter
5009 ipythonrc
5043 ipythonrc
5010 \family default
5044 \family default
5011 file)
5045 file)
5012 \family typewriter
5046 \family typewriter
5013 cache_size
5047 cache_size
5014 \family default
5048 \family default
5015 .
5049 .
5016 If you set it to 0, the whole system is completely disabled and the prompts
5050 If you set it to 0, the whole system is completely disabled and the prompts
5017 revert to the classic
5051 revert to the classic
5018 \family typewriter
5052 \family typewriter
5019 '>>>'
5053 '>>>'
5020 \family default
5054 \family default
5021 of normal Python.
5055 of normal Python.
5022 \layout Subsection
5056 \layout Subsection
5023
5057
5024 Directory history
5058 Directory history
5025 \layout Standard
5059 \layout Standard
5026
5060
5027 Your history of visited directories is kept in the global list
5061 Your history of visited directories is kept in the global list
5028 \family typewriter
5062 \family typewriter
5029 _dh
5063 _dh
5030 \family default
5064 \family default
5031 , and the magic
5065 , and the magic
5032 \family typewriter
5066 \family typewriter
5033 %cd
5067 %cd
5034 \family default
5068 \family default
5035 command can be used to go to any entry in that list.
5069 command can be used to go to any entry in that list.
5036 The
5070 The
5037 \family typewriter
5071 \family typewriter
5038 %dhist
5072 %dhist
5039 \family default
5073 \family default
5040 command allows you to view this history.
5074 command allows you to view this history.
5041 \layout Subsection
5075 \layout Subsection
5042
5076
5043 Automatic parentheses and quotes
5077 Automatic parentheses and quotes
5044 \layout Standard
5078 \layout Standard
5045
5079
5046 These features were adapted from Nathan Gray's LazyPython.
5080 These features were adapted from Nathan Gray's LazyPython.
5047 They are meant to allow less typing for common situations.
5081 They are meant to allow less typing for common situations.
5048 \layout Subsubsection
5082 \layout Subsubsection
5049
5083
5050 Automatic parentheses
5084 Automatic parentheses
5051 \layout Standard
5085 \layout Standard
5052
5086
5053 Callable objects (i.e.
5087 Callable objects (i.e.
5054 functions, methods, etc) can be invoked like this (notice the commas between
5088 functions, methods, etc) can be invoked like this (notice the commas between
5055 the arguments):
5089 the arguments):
5056 \layout Standard
5090 \layout Standard
5057
5091
5058
5092
5059 \family typewriter
5093 \family typewriter
5060 >>> callable_ob arg1, arg2, arg3
5094 >>> callable_ob arg1, arg2, arg3
5061 \layout Standard
5095 \layout Standard
5062
5096
5063 and the input will be translated to this:
5097 and the input will be translated to this:
5064 \layout Standard
5098 \layout Standard
5065
5099
5066
5100
5067 \family typewriter
5101 \family typewriter
5068 --> callable_ob(arg1, arg2, arg3)
5102 --> callable_ob(arg1, arg2, arg3)
5069 \layout Standard
5103 \layout Standard
5070
5104
5071 You can force automatic parentheses by using '/' as the first character
5105 You can force automatic parentheses by using '/' as the first character
5072 of a line.
5106 of a line.
5073 For example:
5107 For example:
5074 \layout Standard
5108 \layout Standard
5075
5109
5076
5110
5077 \family typewriter
5111 \family typewriter
5078 >>> /globals # becomes 'globals()'
5112 >>> /globals # becomes 'globals()'
5079 \layout Standard
5113 \layout Standard
5080
5114
5081 Note that the '/' MUST be the first character on the line! This won't work:
5115 Note that the '/' MUST be the first character on the line! This won't work:
5082
5116
5083 \layout Standard
5117 \layout Standard
5084
5118
5085
5119
5086 \family typewriter
5120 \family typewriter
5087 >>> print /globals # syntax error
5121 >>> print /globals # syntax error
5088 \layout Standard
5122 \layout Standard
5089
5123
5090 In most cases the automatic algorithm should work, so you should rarely
5124 In most cases the automatic algorithm should work, so you should rarely
5091 need to explicitly invoke /.
5125 need to explicitly invoke /.
5092 One notable exception is if you are trying to call a function with a list
5126 One notable exception is if you are trying to call a function with a list
5093 of tuples as arguments (the parenthesis will confuse IPython):
5127 of tuples as arguments (the parenthesis will confuse IPython):
5094 \layout Standard
5128 \layout Standard
5095
5129
5096
5130
5097 \family typewriter
5131 \family typewriter
5098 In [1]: zip (1,2,3),(4,5,6) # won't work
5132 In [1]: zip (1,2,3),(4,5,6) # won't work
5099 \layout Standard
5133 \layout Standard
5100
5134
5101 but this will work:
5135 but this will work:
5102 \layout Standard
5136 \layout Standard
5103
5137
5104
5138
5105 \family typewriter
5139 \family typewriter
5106 In [2]: /zip (1,2,3),(4,5,6)
5140 In [2]: /zip (1,2,3),(4,5,6)
5107 \newline
5141 \newline
5108 ------> zip ((1,2,3),(4,5,6))
5142 ------> zip ((1,2,3),(4,5,6))
5109 \newline
5143 \newline
5110 Out[2]= [(1, 4), (2, 5), (3, 6)]
5144 Out[2]= [(1, 4), (2, 5), (3, 6)]
5111 \layout Standard
5145 \layout Standard
5112
5146
5113 IPython tells you that it has altered your command line by displaying the
5147 IPython tells you that it has altered your command line by displaying the
5114 new command line preceded by
5148 new command line preceded by
5115 \family typewriter
5149 \family typewriter
5116 -->
5150 -->
5117 \family default
5151 \family default
5118 .
5152 .
5119 e.g.:
5153 e.g.:
5120 \layout Standard
5154 \layout Standard
5121
5155
5122
5156
5123 \family typewriter
5157 \family typewriter
5124 In [18]: callable list
5158 In [18]: callable list
5125 \newline
5159 \newline
5126 -------> callable (list)
5160 -------> callable (list)
5127 \layout Subsubsection
5161 \layout Subsubsection
5128
5162
5129 Automatic quoting
5163 Automatic quoting
5130 \layout Standard
5164 \layout Standard
5131
5165
5132 You can force automatic quoting of a function's arguments by using
5166 You can force automatic quoting of a function's arguments by using
5133 \family typewriter
5167 \family typewriter
5134 `,'
5168 `,'
5135 \family default
5169 \family default
5136 or
5170 or
5137 \family typewriter
5171 \family typewriter
5138 `;'
5172 `;'
5139 \family default
5173 \family default
5140 as the first character of a line.
5174 as the first character of a line.
5141 For example:
5175 For example:
5142 \layout Standard
5176 \layout Standard
5143
5177
5144
5178
5145 \family typewriter
5179 \family typewriter
5146 >>> ,my_function /home/me # becomes my_function("/home/me")
5180 >>> ,my_function /home/me # becomes my_function("/home/me")
5147 \layout Standard
5181 \layout Standard
5148
5182
5149 If you use
5183 If you use
5150 \family typewriter
5184 \family typewriter
5151 `;'
5185 `;'
5152 \family default
5186 \family default
5153 instead, the whole argument is quoted as a single string (while
5187 instead, the whole argument is quoted as a single string (while
5154 \family typewriter
5188 \family typewriter
5155 `,'
5189 `,'
5156 \family default
5190 \family default
5157 splits on whitespace):
5191 splits on whitespace):
5158 \layout Standard
5192 \layout Standard
5159
5193
5160
5194
5161 \family typewriter
5195 \family typewriter
5162 >>> ,my_function a b c # becomes my_function("a","b","c")
5196 >>> ,my_function a b c # becomes my_function("a","b","c")
5163 \layout Standard
5197 \layout Standard
5164
5198
5165
5199
5166 \family typewriter
5200 \family typewriter
5167 >>> ;my_function a b c # becomes my_function("a b c")
5201 >>> ;my_function a b c # becomes my_function("a b c")
5168 \layout Standard
5202 \layout Standard
5169
5203
5170 Note that the `
5204 Note that the `
5171 \family typewriter
5205 \family typewriter
5172 ,
5206 ,
5173 \family default
5207 \family default
5174 ' or `
5208 ' or `
5175 \family typewriter
5209 \family typewriter
5176 ;
5210 ;
5177 \family default
5211 \family default
5178 ' MUST be the first character on the line! This won't work:
5212 ' MUST be the first character on the line! This won't work:
5179 \layout Standard
5213 \layout Standard
5180
5214
5181
5215
5182 \family typewriter
5216 \family typewriter
5183 >>> x = ,my_function /home/me # syntax error
5217 >>> x = ,my_function /home/me # syntax error
5184 \layout Section
5218 \layout Section
5185
5219
5186
5220
5187 \begin_inset LatexCommand \label{sec:customization}
5221 \begin_inset LatexCommand \label{sec:customization}
5188
5222
5189 \end_inset
5223 \end_inset
5190
5224
5191 Customization
5225 Customization
5192 \layout Standard
5226 \layout Standard
5193
5227
5194 As we've already mentioned, IPython reads a configuration file which can
5228 As we've already mentioned, IPython reads a configuration file which can
5195 be specified at the command line (
5229 be specified at the command line (
5196 \family typewriter
5230 \family typewriter
5197 -rcfile
5231 -rcfile
5198 \family default
5232 \family default
5199 ) or which by default is assumed to be called
5233 ) or which by default is assumed to be called
5200 \family typewriter
5234 \family typewriter
5201 ipythonrc
5235 ipythonrc
5202 \family default
5236 \family default
5203 .
5237 .
5204 Such a file is looked for in the current directory where IPython is started
5238 Such a file is looked for in the current directory where IPython is started
5205 and then in your
5239 and then in your
5206 \family typewriter
5240 \family typewriter
5207 IPYTHONDIR
5241 IPYTHONDIR
5208 \family default
5242 \family default
5209 , which allows you to have local configuration files for specific projects.
5243 , which allows you to have local configuration files for specific projects.
5210 In this section we will call these types of configuration files simply
5244 In this section we will call these types of configuration files simply
5211 rcfiles (short for resource configuration file).
5245 rcfiles (short for resource configuration file).
5212 \layout Standard
5246 \layout Standard
5213
5247
5214 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5248 The syntax of an rcfile is one of key-value pairs separated by whitespace,
5215 one per line.
5249 one per line.
5216 Lines beginning with a
5250 Lines beginning with a
5217 \family typewriter
5251 \family typewriter
5218 #
5252 #
5219 \family default
5253 \family default
5220 are ignored as comments, but comments can
5254 are ignored as comments, but comments can
5221 \series bold
5255 \series bold
5222 not
5256 not
5223 \series default
5257 \series default
5224 be put on lines with data (the parser is fairly primitive).
5258 be put on lines with data (the parser is fairly primitive).
5225 Note that these are not python files, and this is deliberate, because it
5259 Note that these are not python files, and this is deliberate, because it
5226 allows us to do some things which would be quite tricky to implement if
5260 allows us to do some things which would be quite tricky to implement if
5227 they were normal python files.
5261 they were normal python files.
5228 \layout Standard
5262 \layout Standard
5229
5263
5230 First, an rcfile can contain permanent default values for almost all command
5264 First, an rcfile can contain permanent default values for almost all command
5231 line options (except things like
5265 line options (except things like
5232 \family typewriter
5266 \family typewriter
5233 -help
5267 -help
5234 \family default
5268 \family default
5235 or
5269 or
5236 \family typewriter
5270 \family typewriter
5237 -Version
5271 -Version
5238 \family default
5272 \family default
5239 ).
5273 ).
5240 Sec\SpecialChar ~
5274 Sec\SpecialChar ~
5241
5275
5242 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5276 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5243
5277
5244 \end_inset
5278 \end_inset
5245
5279
5246 contains a description of all command-line options.
5280 contains a description of all command-line options.
5247 However, values you explicitly specify at the command line override the
5281 However, values you explicitly specify at the command line override the
5248 values defined in the rcfile.
5282 values defined in the rcfile.
5249 \layout Standard
5283 \layout Standard
5250
5284
5251 Besides command line option values, the rcfile can specify values for certain
5285 Besides command line option values, the rcfile can specify values for certain
5252 extra special options which are not available at the command line.
5286 extra special options which are not available at the command line.
5253 These options are briefly described below.
5287 These options are briefly described below.
5254
5288
5255 \layout Standard
5289 \layout Standard
5256
5290
5257 Each of these options may appear as many times as you need it in the file.
5291 Each of these options may appear as many times as you need it in the file.
5258 \layout List
5292 \layout List
5259 \labelwidthstring 00.00.0000
5293 \labelwidthstring 00.00.0000
5260
5294
5261
5295
5262 \family typewriter
5296 \family typewriter
5263 \series bold
5297 \series bold
5264 include\SpecialChar ~
5298 include\SpecialChar ~
5265 <file1>\SpecialChar ~
5299 <file1>\SpecialChar ~
5266 <file2>\SpecialChar ~
5300 <file2>\SpecialChar ~
5267 ...
5301 ...
5268 \family default
5302 \family default
5269 \series default
5303 \series default
5270 : you can name
5304 : you can name
5271 \emph on
5305 \emph on
5272 other
5306 other
5273 \emph default
5307 \emph default
5274 rcfiles you want to recursively load up to 15 levels (don't use the
5308 rcfiles you want to recursively load up to 15 levels (don't use the
5275 \family typewriter
5309 \family typewriter
5276 <>
5310 <>
5277 \family default
5311 \family default
5278 brackets in your names!).
5312 brackets in your names!).
5279 This feature allows you to define a 'base' rcfile with general options
5313 This feature allows you to define a 'base' rcfile with general options
5280 and special-purpose files which can be loaded only when needed with particular
5314 and special-purpose files which can be loaded only when needed with particular
5281 configuration options.
5315 configuration options.
5282 To make this more convenient, IPython accepts the
5316 To make this more convenient, IPython accepts the
5283 \family typewriter
5317 \family typewriter
5284 -profile <name>
5318 -profile <name>
5285 \family default
5319 \family default
5286 option (abbreviates to
5320 option (abbreviates to
5287 \family typewriter
5321 \family typewriter
5288 -p <name
5322 -p <name
5289 \family default
5323 \family default
5290 >)
5324 >)
5291 \family typewriter
5325 \family typewriter
5292 which
5326 which
5293 \family default
5327 \family default
5294 tells it to look for an rcfile named
5328 tells it to look for an rcfile named
5295 \family typewriter
5329 \family typewriter
5296 ipythonrc-<name>
5330 ipythonrc-<name>
5297 \family default
5331 \family default
5298 .
5332 .
5299
5333
5300 \layout List
5334 \layout List
5301 \labelwidthstring 00.00.0000
5335 \labelwidthstring 00.00.0000
5302
5336
5303
5337
5304 \family typewriter
5338 \family typewriter
5305 \series bold
5339 \series bold
5306 import_mod\SpecialChar ~
5340 import_mod\SpecialChar ~
5307 <mod1>\SpecialChar ~
5341 <mod1>\SpecialChar ~
5308 <mod2>\SpecialChar ~
5342 <mod2>\SpecialChar ~
5309 ...
5343 ...
5310 \family default
5344 \family default
5311 \series default
5345 \series default
5312 : import modules with '
5346 : import modules with '
5313 \family typewriter
5347 \family typewriter
5314 import
5348 import
5315 \family default
5349 \family default
5316
5350
5317 \family typewriter
5351 \family typewriter
5318 <mod1>,<mod2>,...
5352 <mod1>,<mod2>,...
5319 \family default
5353 \family default
5320 '
5354 '
5321 \layout List
5355 \layout List
5322 \labelwidthstring 00.00.0000
5356 \labelwidthstring 00.00.0000
5323
5357
5324
5358
5325 \family typewriter
5359 \family typewriter
5326 \series bold
5360 \series bold
5327 import_some\SpecialChar ~
5361 import_some\SpecialChar ~
5328 <mod>\SpecialChar ~
5362 <mod>\SpecialChar ~
5329 <f1>\SpecialChar ~
5363 <f1>\SpecialChar ~
5330 <f2>\SpecialChar ~
5364 <f2>\SpecialChar ~
5331 ...
5365 ...
5332 \family default
5366 \family default
5333 \series default
5367 \series default
5334 : import functions with '
5368 : import functions with '
5335 \family typewriter
5369 \family typewriter
5336 from <mod> import
5370 from <mod> import
5337 \family default
5371 \family default
5338
5372
5339 \family typewriter
5373 \family typewriter
5340 <f1>,<f2>,...
5374 <f1>,<f2>,...
5341 \family default
5375 \family default
5342 '
5376 '
5343 \layout List
5377 \layout List
5344 \labelwidthstring 00.00.0000
5378 \labelwidthstring 00.00.0000
5345
5379
5346
5380
5347 \family typewriter
5381 \family typewriter
5348 \series bold
5382 \series bold
5349 import_all\SpecialChar ~
5383 import_all\SpecialChar ~
5350 <mod1>\SpecialChar ~
5384 <mod1>\SpecialChar ~
5351 <mod2>\SpecialChar ~
5385 <mod2>\SpecialChar ~
5352 ...
5386 ...
5353 \family default
5387 \family default
5354 \series default
5388 \series default
5355 : for each module listed import functions with '
5389 : for each module listed import functions with '
5356 \family typewriter
5390 \family typewriter
5357 from <mod> import *
5391 from <mod> import *
5358 \family default
5392 \family default
5359 '
5393 '
5360 \layout List
5394 \layout List
5361 \labelwidthstring 00.00.0000
5395 \labelwidthstring 00.00.0000
5362
5396
5363
5397
5364 \family typewriter
5398 \family typewriter
5365 \series bold
5399 \series bold
5366 execute\SpecialChar ~
5400 execute\SpecialChar ~
5367 <python\SpecialChar ~
5401 <python\SpecialChar ~
5368 code>
5402 code>
5369 \family default
5403 \family default
5370 \series default
5404 \series default
5371 : give any single-line python code to be executed.
5405 : give any single-line python code to be executed.
5372 \layout List
5406 \layout List
5373 \labelwidthstring 00.00.0000
5407 \labelwidthstring 00.00.0000
5374
5408
5375
5409
5376 \family typewriter
5410 \family typewriter
5377 \series bold
5411 \series bold
5378 execfile\SpecialChar ~
5412 execfile\SpecialChar ~
5379 <filename>
5413 <filename>
5380 \family default
5414 \family default
5381 \series default
5415 \series default
5382 : execute the python file given with an '
5416 : execute the python file given with an '
5383 \family typewriter
5417 \family typewriter
5384 execfile(filename)
5418 execfile(filename)
5385 \family default
5419 \family default
5386 ' command.
5420 ' command.
5387 Username expansion is performed on the given names.
5421 Username expansion is performed on the given names.
5388 So if you need any amount of extra fancy customization that won't fit in
5422 So if you need any amount of extra fancy customization that won't fit in
5389 any of the above 'canned' options, you can just put it in a separate python
5423 any of the above 'canned' options, you can just put it in a separate python
5390 file and execute it.
5424 file and execute it.
5391 \layout List
5425 \layout List
5392 \labelwidthstring 00.00.0000
5426 \labelwidthstring 00.00.0000
5393
5427
5394
5428
5395 \family typewriter
5429 \family typewriter
5396 \series bold
5430 \series bold
5397 alias\SpecialChar ~
5431 alias\SpecialChar ~
5398 <alias_def>
5432 <alias_def>
5399 \family default
5433 \family default
5400 \series default
5434 \series default
5401 : this is equivalent to calling '
5435 : this is equivalent to calling '
5402 \family typewriter
5436 \family typewriter
5403 %alias\SpecialChar ~
5437 %alias\SpecialChar ~
5404 <alias_def>
5438 <alias_def>
5405 \family default
5439 \family default
5406 ' at the IPython command line.
5440 ' at the IPython command line.
5407 This way, from within IPython you can do common system tasks without having
5441 This way, from within IPython you can do common system tasks without having
5408 to exit it or use the
5442 to exit it or use the
5409 \family typewriter
5443 \family typewriter
5410 !
5444 !
5411 \family default
5445 \family default
5412 escape.
5446 escape.
5413 IPython isn't meant to be a shell replacement, but it is often very useful
5447 IPython isn't meant to be a shell replacement, but it is often very useful
5414 to be able to do things with files while testing code.
5448 to be able to do things with files while testing code.
5415 This gives you the flexibility to have within IPython any aliases you may
5449 This gives you the flexibility to have within IPython any aliases you may
5416 be used to under your normal system shell.
5450 be used to under your normal system shell.
5417 \layout Subsection
5451 \layout Subsection
5418
5452
5419
5453
5420 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5454 \begin_inset LatexCommand \label{sec:ipytonrc-sample}
5421
5455
5422 \end_inset
5456 \end_inset
5423
5457
5424 Sample
5458 Sample
5425 \family typewriter
5459 \family typewriter
5426 ipythonrc
5460 ipythonrc
5427 \family default
5461 \family default
5428 file
5462 file
5429 \layout Standard
5463 \layout Standard
5430
5464
5431 The default rcfile, called
5465 The default rcfile, called
5432 \family typewriter
5466 \family typewriter
5433 ipythonrc
5467 ipythonrc
5434 \family default
5468 \family default
5435 and supplied in your
5469 and supplied in your
5436 \family typewriter
5470 \family typewriter
5437 IPYTHONDIR
5471 IPYTHONDIR
5438 \family default
5472 \family default
5439 directory contains lots of comments on all of these options.
5473 directory contains lots of comments on all of these options.
5440 We reproduce it here for reference:
5474 We reproduce it here for reference:
5441 \layout Standard
5475 \layout Standard
5442
5476
5443
5477
5444 \begin_inset ERT
5478 \begin_inset ERT
5445 status Open
5479 status Open
5446
5480
5447 \layout Standard
5481 \layout Standard
5448
5482
5449 \backslash
5483 \backslash
5450 codelist{../IPython/UserConfig/ipythonrc}
5484 codelist{../IPython/UserConfig/ipythonrc}
5451 \end_inset
5485 \end_inset
5452
5486
5453
5487
5454 \layout Subsection
5488 \layout Subsection
5455
5489
5456
5490
5457 \begin_inset LatexCommand \label{sec:prompts}
5491 \begin_inset LatexCommand \label{sec:prompts}
5458
5492
5459 \end_inset
5493 \end_inset
5460
5494
5461 Fine-tuning your prompt
5495 Fine-tuning your prompt
5462 \layout Standard
5496 \layout Standard
5463
5497
5464 IPython's prompts can be customized using a syntax similar to that of the
5498 IPython's prompts can be customized using a syntax similar to that of the
5465
5499
5466 \family typewriter
5500 \family typewriter
5467 bash
5501 bash
5468 \family default
5502 \family default
5469 shell.
5503 shell.
5470 Many of
5504 Many of
5471 \family typewriter
5505 \family typewriter
5472 bash
5506 bash
5473 \family default
5507 \family default
5474 's escapes are supported, as well as a few additional ones.
5508 's escapes are supported, as well as a few additional ones.
5475 We list them below:
5509 We list them below:
5476 \layout Description
5510 \layout Description
5477
5511
5478
5512
5479 \backslash
5513 \backslash
5480 # the prompt/history count number
5514 # the prompt/history count number
5481 \layout Description
5515 \layout Description
5482
5516
5483
5517
5484 \backslash
5518 \backslash
5485 D the prompt/history count, with the actual digits replaced by dots.
5519 D the prompt/history count, with the actual digits replaced by dots.
5486 Used mainly in continuation prompts (prompt_in2)
5520 Used mainly in continuation prompts (prompt_in2)
5487 \layout Description
5521 \layout Description
5488
5522
5489
5523
5490 \backslash
5524 \backslash
5491 w the current working directory
5525 w the current working directory
5492 \layout Description
5526 \layout Description
5493
5527
5494
5528
5495 \backslash
5529 \backslash
5496 W the basename of current working directory
5530 W the basename of current working directory
5497 \layout Description
5531 \layout Description
5498
5532
5499
5533
5500 \backslash
5534 \backslash
5501 X
5535 X
5502 \emph on
5536 \emph on
5503 n
5537 n
5504 \emph default
5538 \emph default
5505 where
5539 where
5506 \begin_inset Formula $n=0\ldots5.$
5540 \begin_inset Formula $n=0\ldots5.$
5507 \end_inset
5541 \end_inset
5508
5542
5509 The current working directory, with
5543 The current working directory, with
5510 \family typewriter
5544 \family typewriter
5511 $HOME
5545 $HOME
5512 \family default
5546 \family default
5513 replaced by
5547 replaced by
5514 \family typewriter
5548 \family typewriter
5515 ~
5549 ~
5516 \family default
5550 \family default
5517 , and filtered out to contain only
5551 , and filtered out to contain only
5518 \begin_inset Formula $n$
5552 \begin_inset Formula $n$
5519 \end_inset
5553 \end_inset
5520
5554
5521 path elements
5555 path elements
5522 \layout Description
5556 \layout Description
5523
5557
5524
5558
5525 \backslash
5559 \backslash
5526 Y
5560 Y
5527 \emph on
5561 \emph on
5528 n
5562 n
5529 \emph default
5563 \emph default
5530 Similar to
5564 Similar to
5531 \backslash
5565 \backslash
5532 X
5566 X
5533 \emph on
5567 \emph on
5534 n
5568 n
5535 \emph default
5569 \emph default
5536 , but with the
5570 , but with the
5537 \begin_inset Formula $n+1$
5571 \begin_inset Formula $n+1$
5538 \end_inset
5572 \end_inset
5539
5573
5540 element included if it is
5574 element included if it is
5541 \family typewriter
5575 \family typewriter
5542 ~
5576 ~
5543 \family default
5577 \family default
5544 (this is similar to the behavior of the %c
5578 (this is similar to the behavior of the %c
5545 \emph on
5579 \emph on
5546 n
5580 n
5547 \emph default
5581 \emph default
5548 escapes in
5582 escapes in
5549 \family typewriter
5583 \family typewriter
5550 tcsh
5584 tcsh
5551 \family default
5585 \family default
5552 )
5586 )
5553 \layout Description
5587 \layout Description
5554
5588
5555
5589
5556 \backslash
5590 \backslash
5557 u the username of the current user
5591 u the username of the current user
5558 \layout Description
5592 \layout Description
5559
5593
5560
5594
5561 \backslash
5595 \backslash
5562 $ if the effective UID is 0, a #, otherwise a $
5596 $ if the effective UID is 0, a #, otherwise a $
5563 \layout Description
5597 \layout Description
5564
5598
5565
5599
5566 \backslash
5600 \backslash
5567 h the hostname up to the first `.'
5601 h the hostname up to the first `.'
5568 \layout Description
5602 \layout Description
5569
5603
5570
5604
5571 \backslash
5605 \backslash
5572 H the hostname
5606 H the hostname
5573 \layout Description
5607 \layout Description
5574
5608
5575
5609
5576 \backslash
5610 \backslash
5577 n a newline
5611 n a newline
5578 \layout Description
5612 \layout Description
5579
5613
5580
5614
5581 \backslash
5615 \backslash
5582 r a carriage return
5616 r a carriage return
5583 \layout Description
5617 \layout Description
5584
5618
5585
5619
5586 \backslash
5620 \backslash
5587 v IPython version string
5621 v IPython version string
5588 \layout Standard
5622 \layout Standard
5589
5623
5590 In addition to these, ANSI color escapes can be insterted into the prompts,
5624 In addition to these, ANSI color escapes can be insterted into the prompts,
5591 as
5625 as
5592 \family typewriter
5626 \family typewriter
5593
5627
5594 \backslash
5628 \backslash
5595 C_
5629 C_
5596 \emph on
5630 \emph on
5597 ColorName
5631 ColorName
5598 \family default
5632 \family default
5599 \emph default
5633 \emph default
5600 .
5634 .
5601 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5635 The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green,
5602 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5636 LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor,
5603 Normal, Purple, Red, White, Yellow.
5637 Normal, Purple, Red, White, Yellow.
5604 \layout Standard
5638 \layout Standard
5605
5639
5606 Finally, IPython supports the evaluation of arbitrary expressions in your
5640 Finally, IPython supports the evaluation of arbitrary expressions in your
5607 prompt string.
5641 prompt string.
5608 The prompt strings are evaluated through the syntax of PEP 215, but basically
5642 The prompt strings are evaluated through the syntax of PEP 215, but basically
5609 you can use
5643 you can use
5610 \family typewriter
5644 \family typewriter
5611 $x.y
5645 $x.y
5612 \family default
5646 \family default
5613 to expand the value of
5647 to expand the value of
5614 \family typewriter
5648 \family typewriter
5615 x.y
5649 x.y
5616 \family default
5650 \family default
5617 , and for more complicated expressions you can use braces:
5651 , and for more complicated expressions you can use braces:
5618 \family typewriter
5652 \family typewriter
5619 ${foo()+x}
5653 ${foo()+x}
5620 \family default
5654 \family default
5621 will call function
5655 will call function
5622 \family typewriter
5656 \family typewriter
5623 foo
5657 foo
5624 \family default
5658 \family default
5625 and add to it the value of
5659 and add to it the value of
5626 \family typewriter
5660 \family typewriter
5627 x
5661 x
5628 \family default
5662 \family default
5629 , before putting the result into your prompt.
5663 , before putting the result into your prompt.
5630 For example, using
5664 For example, using
5631 \newline
5665 \newline
5632
5666
5633 \family typewriter
5667 \family typewriter
5634 prompt_in1 '${commands.getoutput("uptime")}
5668 prompt_in1 '${commands.getoutput("uptime")}
5635 \backslash
5669 \backslash
5636 nIn [
5670 nIn [
5637 \backslash
5671 \backslash
5638 #]: '
5672 #]: '
5639 \newline
5673 \newline
5640
5674
5641 \family default
5675 \family default
5642 will print the result of the uptime command on each prompt (assuming the
5676 will print the result of the uptime command on each prompt (assuming the
5643
5677
5644 \family typewriter
5678 \family typewriter
5645 commands
5679 commands
5646 \family default
5680 \family default
5647 module has been imported in your
5681 module has been imported in your
5648 \family typewriter
5682 \family typewriter
5649 ipythonrc
5683 ipythonrc
5650 \family default
5684 \family default
5651 file).
5685 file).
5652 \layout Subsubsection
5686 \layout Subsubsection
5653
5687
5654 Prompt examples
5688 Prompt examples
5655 \layout Standard
5689 \layout Standard
5656
5690
5657 The following options in an ipythonrc file will give you IPython's default
5691 The following options in an ipythonrc file will give you IPython's default
5658 prompts:
5692 prompts:
5659 \layout Standard
5693 \layout Standard
5660
5694
5661
5695
5662 \family typewriter
5696 \family typewriter
5663 prompt_in1 'In [
5697 prompt_in1 'In [
5664 \backslash
5698 \backslash
5665 #]:'
5699 #]:'
5666 \newline
5700 \newline
5667 prompt_in2 '\SpecialChar ~
5701 prompt_in2 '\SpecialChar ~
5668 \SpecialChar ~
5702 \SpecialChar ~
5669 \SpecialChar ~
5703 \SpecialChar ~
5670 .
5704 .
5671 \backslash
5705 \backslash
5672 D.:'
5706 D.:'
5673 \newline
5707 \newline
5674 prompt_out 'Out[
5708 prompt_out 'Out[
5675 \backslash
5709 \backslash
5676 #]:'
5710 #]:'
5677 \layout Standard
5711 \layout Standard
5678
5712
5679 which look like this:
5713 which look like this:
5680 \layout Standard
5714 \layout Standard
5681
5715
5682
5716
5683 \family typewriter
5717 \family typewriter
5684 In [1]: 1+2
5718 In [1]: 1+2
5685 \newline
5719 \newline
5686 Out[1]: 3
5720 Out[1]: 3
5687 \layout Standard
5721 \layout Standard
5688
5722
5689
5723
5690 \family typewriter
5724 \family typewriter
5691 In [2]: for i in (1,2,3):
5725 In [2]: for i in (1,2,3):
5692 \newline
5726 \newline
5693
5727
5694 \begin_inset ERT
5728 \begin_inset ERT
5695 status Collapsed
5729 status Collapsed
5696
5730
5697 \layout Standard
5731 \layout Standard
5698
5732
5699 \backslash
5733 \backslash
5700 hspace*{0mm}
5734 hspace*{0mm}
5701 \end_inset
5735 \end_inset
5702
5736
5703 \SpecialChar ~
5737 \SpecialChar ~
5704 \SpecialChar ~
5738 \SpecialChar ~
5705 \SpecialChar ~
5739 \SpecialChar ~
5706 ...: \SpecialChar ~
5740 ...: \SpecialChar ~
5707 \SpecialChar ~
5741 \SpecialChar ~
5708 \SpecialChar ~
5742 \SpecialChar ~
5709 \SpecialChar ~
5743 \SpecialChar ~
5710 print i,
5744 print i,
5711 \newline
5745 \newline
5712
5746
5713 \begin_inset ERT
5747 \begin_inset ERT
5714 status Collapsed
5748 status Collapsed
5715
5749
5716 \layout Standard
5750 \layout Standard
5717
5751
5718 \backslash
5752 \backslash
5719 hspace*{0mm}
5753 hspace*{0mm}
5720 \end_inset
5754 \end_inset
5721
5755
5722 \SpecialChar ~
5756 \SpecialChar ~
5723 \SpecialChar ~
5757 \SpecialChar ~
5724 \SpecialChar ~
5758 \SpecialChar ~
5725 ...:
5759 ...:
5726 \newline
5760 \newline
5727 1 2 3
5761 1 2 3
5728 \layout Standard
5762 \layout Standard
5729
5763
5730 These will give you a very colorful prompt with path information:
5764 These will give you a very colorful prompt with path information:
5731 \layout Standard
5765 \layout Standard
5732
5766
5733
5767
5734 \family typewriter
5768 \family typewriter
5735 #prompt_in1 '
5769 #prompt_in1 '
5736 \backslash
5770 \backslash
5737 C_Red
5771 C_Red
5738 \backslash
5772 \backslash
5739 u
5773 u
5740 \backslash
5774 \backslash
5741 C_Blue[
5775 C_Blue[
5742 \backslash
5776 \backslash
5743 C_Cyan
5777 C_Cyan
5744 \backslash
5778 \backslash
5745 Y1
5779 Y1
5746 \backslash
5780 \backslash
5747 C_Blue]
5781 C_Blue]
5748 \backslash
5782 \backslash
5749 C_LightGreen
5783 C_LightGreen
5750 \backslash
5784 \backslash
5751 #>'
5785 #>'
5752 \newline
5786 \newline
5753 prompt_in2 ' ..
5787 prompt_in2 ' ..
5754 \backslash
5788 \backslash
5755 D>'
5789 D>'
5756 \newline
5790 \newline
5757 prompt_out '<
5791 prompt_out '<
5758 \backslash
5792 \backslash
5759 #>'
5793 #>'
5760 \layout Standard
5794 \layout Standard
5761
5795
5762 which look like this:
5796 which look like this:
5763 \layout Standard
5797 \layout Standard
5764
5798
5765
5799
5766 \family typewriter
5800 \family typewriter
5767 \color red
5801 \color red
5768 fperez
5802 fperez
5769 \color blue
5803 \color blue
5770 [
5804 [
5771 \color cyan
5805 \color cyan
5772 ~/ipython
5806 ~/ipython
5773 \color blue
5807 \color blue
5774 ]
5808 ]
5775 \color green
5809 \color green
5776 1>
5810 1>
5777 \color default
5811 \color default
5778 1+2
5812 1+2
5779 \newline
5813 \newline
5780
5814
5781 \begin_inset ERT
5815 \begin_inset ERT
5782 status Collapsed
5816 status Collapsed
5783
5817
5784 \layout Standard
5818 \layout Standard
5785
5819
5786 \backslash
5820 \backslash
5787 hspace*{0mm}
5821 hspace*{0mm}
5788 \end_inset
5822 \end_inset
5789
5823
5790 \SpecialChar ~
5824 \SpecialChar ~
5791 \SpecialChar ~
5825 \SpecialChar ~
5792 \SpecialChar ~
5826 \SpecialChar ~
5793 \SpecialChar ~
5827 \SpecialChar ~
5794 \SpecialChar ~
5828 \SpecialChar ~
5795 \SpecialChar ~
5829 \SpecialChar ~
5796 \SpecialChar ~
5830 \SpecialChar ~
5797 \SpecialChar ~
5831 \SpecialChar ~
5798 \SpecialChar ~
5832 \SpecialChar ~
5799 \SpecialChar ~
5833 \SpecialChar ~
5800 \SpecialChar ~
5834 \SpecialChar ~
5801 \SpecialChar ~
5835 \SpecialChar ~
5802 \SpecialChar ~
5836 \SpecialChar ~
5803 \SpecialChar ~
5837 \SpecialChar ~
5804 \SpecialChar ~
5838 \SpecialChar ~
5805 \SpecialChar ~
5839 \SpecialChar ~
5806
5840
5807 \color red
5841 \color red
5808 <1>
5842 <1>
5809 \color default
5843 \color default
5810 3
5844 3
5811 \newline
5845 \newline
5812
5846
5813 \color red
5847 \color red
5814 fperez
5848 fperez
5815 \color blue
5849 \color blue
5816 [
5850 [
5817 \color cyan
5851 \color cyan
5818 ~/ipython
5852 ~/ipython
5819 \color blue
5853 \color blue
5820 ]
5854 ]
5821 \color green
5855 \color green
5822 2>
5856 2>
5823 \color default
5857 \color default
5824 for i in (1,2,3):
5858 for i in (1,2,3):
5825 \newline
5859 \newline
5826
5860
5827 \begin_inset ERT
5861 \begin_inset ERT
5828 status Collapsed
5862 status Collapsed
5829
5863
5830 \layout Standard
5864 \layout Standard
5831
5865
5832 \backslash
5866 \backslash
5833 hspace*{0mm}
5867 hspace*{0mm}
5834 \end_inset
5868 \end_inset
5835
5869
5836 \SpecialChar ~
5870 \SpecialChar ~
5837 \SpecialChar ~
5871 \SpecialChar ~
5838 \SpecialChar ~
5872 \SpecialChar ~
5839 \SpecialChar ~
5873 \SpecialChar ~
5840 \SpecialChar ~
5874 \SpecialChar ~
5841 \SpecialChar ~
5875 \SpecialChar ~
5842 \SpecialChar ~
5876 \SpecialChar ~
5843 \SpecialChar ~
5877 \SpecialChar ~
5844 \SpecialChar ~
5878 \SpecialChar ~
5845 \SpecialChar ~
5879 \SpecialChar ~
5846 \SpecialChar ~
5880 \SpecialChar ~
5847 \SpecialChar ~
5881 \SpecialChar ~
5848 \SpecialChar ~
5882 \SpecialChar ~
5849 \SpecialChar ~
5883 \SpecialChar ~
5850 \SpecialChar ~
5884 \SpecialChar ~
5851
5885
5852 \color green
5886 \color green
5853 ...>
5887 ...>
5854 \color default
5888 \color default
5855 \SpecialChar ~
5889 \SpecialChar ~
5856 \SpecialChar ~
5890 \SpecialChar ~
5857 \SpecialChar ~
5891 \SpecialChar ~
5858 \SpecialChar ~
5892 \SpecialChar ~
5859 print i,
5893 print i,
5860 \newline
5894 \newline
5861
5895
5862 \begin_inset ERT
5896 \begin_inset ERT
5863 status Collapsed
5897 status Collapsed
5864
5898
5865 \layout Standard
5899 \layout Standard
5866
5900
5867 \backslash
5901 \backslash
5868 hspace*{0mm}
5902 hspace*{0mm}
5869 \end_inset
5903 \end_inset
5870
5904
5871 \SpecialChar ~
5905 \SpecialChar ~
5872 \SpecialChar ~
5906 \SpecialChar ~
5873 \SpecialChar ~
5907 \SpecialChar ~
5874 \SpecialChar ~
5908 \SpecialChar ~
5875 \SpecialChar ~
5909 \SpecialChar ~
5876 \SpecialChar ~
5910 \SpecialChar ~
5877 \SpecialChar ~
5911 \SpecialChar ~
5878 \SpecialChar ~
5912 \SpecialChar ~
5879 \SpecialChar ~
5913 \SpecialChar ~
5880 \SpecialChar ~
5914 \SpecialChar ~
5881 \SpecialChar ~
5915 \SpecialChar ~
5882 \SpecialChar ~
5916 \SpecialChar ~
5883 \SpecialChar ~
5917 \SpecialChar ~
5884 \SpecialChar ~
5918 \SpecialChar ~
5885 \SpecialChar ~
5919 \SpecialChar ~
5886
5920
5887 \color green
5921 \color green
5888 ...>
5922 ...>
5889 \color default
5923 \color default
5890
5924
5891 \newline
5925 \newline
5892 1 2 3
5926 1 2 3
5893 \layout Standard
5927 \layout Standard
5894
5928
5895 The following shows the usage of dynamic expression evaluation:
5929 The following shows the usage of dynamic expression evaluation:
5896 \layout Subsection
5930 \layout Subsection
5897
5931
5898
5932
5899 \begin_inset LatexCommand \label{sec:profiles}
5933 \begin_inset LatexCommand \label{sec:profiles}
5900
5934
5901 \end_inset
5935 \end_inset
5902
5936
5903 IPython profiles
5937 IPython profiles
5904 \layout Standard
5938 \layout Standard
5905
5939
5906 As we already mentioned, IPython supports the
5940 As we already mentioned, IPython supports the
5907 \family typewriter
5941 \family typewriter
5908 -profile
5942 -profile
5909 \family default
5943 \family default
5910 command-line option (see sec.
5944 command-line option (see sec.
5911
5945
5912 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5946 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
5913
5947
5914 \end_inset
5948 \end_inset
5915
5949
5916 ).
5950 ).
5917 A profile is nothing more than a particular configuration file like your
5951 A profile is nothing more than a particular configuration file like your
5918 basic
5952 basic
5919 \family typewriter
5953 \family typewriter
5920 ipythonrc
5954 ipythonrc
5921 \family default
5955 \family default
5922 one, but with particular customizations for a specific purpose.
5956 one, but with particular customizations for a specific purpose.
5923 When you start IPython with '
5957 When you start IPython with '
5924 \family typewriter
5958 \family typewriter
5925 ipython -profile <name>
5959 ipython -profile <name>
5926 \family default
5960 \family default
5927 ', it assumes that in your
5961 ', it assumes that in your
5928 \family typewriter
5962 \family typewriter
5929 IPYTHONDIR
5963 IPYTHONDIR
5930 \family default
5964 \family default
5931 there is a file called
5965 there is a file called
5932 \family typewriter
5966 \family typewriter
5933 ipythonrc-<name>
5967 ipythonrc-<name>
5934 \family default
5968 \family default
5935 , and loads it instead of the normal
5969 , and loads it instead of the normal
5936 \family typewriter
5970 \family typewriter
5937 ipythonrc
5971 ipythonrc
5938 \family default
5972 \family default
5939 .
5973 .
5940 \layout Standard
5974 \layout Standard
5941
5975
5942 This system allows you to maintain multiple configurations which load modules,
5976 This system allows you to maintain multiple configurations which load modules,
5943 set options, define functions, etc.
5977 set options, define functions, etc.
5944 suitable for different tasks and activate them in a very simple manner.
5978 suitable for different tasks and activate them in a very simple manner.
5945 In order to avoid having to repeat all of your basic options (common things
5979 In order to avoid having to repeat all of your basic options (common things
5946 that don't change such as your color preferences, for example), any profile
5980 that don't change such as your color preferences, for example), any profile
5947 can include another configuration file.
5981 can include another configuration file.
5948 The most common way to use profiles is then to have each one include your
5982 The most common way to use profiles is then to have each one include your
5949 basic
5983 basic
5950 \family typewriter
5984 \family typewriter
5951 ipythonrc
5985 ipythonrc
5952 \family default
5986 \family default
5953 file as a starting point, and then add further customizations.
5987 file as a starting point, and then add further customizations.
5954 \layout Standard
5988 \layout Standard
5955
5989
5956 In sections
5990 In sections
5957 \begin_inset LatexCommand \ref{sec:syntax-extensions}
5991 \begin_inset LatexCommand \ref{sec:syntax-extensions}
5958
5992
5959 \end_inset
5993 \end_inset
5960
5994
5961 and
5995 and
5962 \begin_inset LatexCommand \ref{sec:Gnuplot}
5996 \begin_inset LatexCommand \ref{sec:Gnuplot}
5963
5997
5964 \end_inset
5998 \end_inset
5965
5999
5966 we discuss some particular profiles which come as part of the standard
6000 we discuss some particular profiles which come as part of the standard
5967 IPython distribution.
6001 IPython distribution.
5968 You may also look in your
6002 You may also look in your
5969 \family typewriter
6003 \family typewriter
5970 IPYTHONDIR
6004 IPYTHONDIR
5971 \family default
6005 \family default
5972 directory, any file whose name begins with
6006 directory, any file whose name begins with
5973 \family typewriter
6007 \family typewriter
5974 ipythonrc-
6008 ipythonrc-
5975 \family default
6009 \family default
5976 is a profile.
6010 is a profile.
5977 You can use those as examples for further customizations to suit your own
6011 You can use those as examples for further customizations to suit your own
5978 needs.
6012 needs.
5979 \layout Section
6013 \layout Section
5980
6014
5981
6015
5982 \begin_inset OptArg
6016 \begin_inset OptArg
5983 collapsed false
6017 collapsed false
5984
6018
5985 \layout Standard
6019 \layout Standard
5986
6020
5987 IPython as default...
6021 IPython as default...
5988 \end_inset
6022 \end_inset
5989
6023
5990 IPython as your default Python environment
6024 IPython as your default Python environment
5991 \layout Standard
6025 \layout Standard
5992
6026
5993 Python honors the environment variable
6027 Python honors the environment variable
5994 \family typewriter
6028 \family typewriter
5995 PYTHONSTARTUP
6029 PYTHONSTARTUP
5996 \family default
6030 \family default
5997 and will execute at startup the file referenced by this variable.
6031 and will execute at startup the file referenced by this variable.
5998 If you put at the end of this file the following two lines of code:
6032 If you put at the end of this file the following two lines of code:
5999 \layout Standard
6033 \layout Standard
6000
6034
6001
6035
6002 \family typewriter
6036 \family typewriter
6003 import IPython
6037 import IPython
6004 \newline
6038 \newline
6005 IPython.Shell.IPShell().mainloop(sys_exit=1)
6039 IPython.Shell.IPShell().mainloop(sys_exit=1)
6006 \layout Standard
6040 \layout Standard
6007
6041
6008 then IPython will be your working environment anytime you start Python.
6042 then IPython will be your working environment anytime you start Python.
6009 The
6043 The
6010 \family typewriter
6044 \family typewriter
6011 sys_exit=1
6045 sys_exit=1
6012 \family default
6046 \family default
6013 is needed to have IPython issue a call to
6047 is needed to have IPython issue a call to
6014 \family typewriter
6048 \family typewriter
6015 sys.exit()
6049 sys.exit()
6016 \family default
6050 \family default
6017 when it finishes, otherwise you'll be back at the normal Python '
6051 when it finishes, otherwise you'll be back at the normal Python '
6018 \family typewriter
6052 \family typewriter
6019 >>>
6053 >>>
6020 \family default
6054 \family default
6021 ' prompt
6055 ' prompt
6022 \begin_inset Foot
6056 \begin_inset Foot
6023 collapsed true
6057 collapsed true
6024
6058
6025 \layout Standard
6059 \layout Standard
6026
6060
6027 Based on an idea by Holger Krekel.
6061 Based on an idea by Holger Krekel.
6028 \end_inset
6062 \end_inset
6029
6063
6030 .
6064 .
6031 \layout Standard
6065 \layout Standard
6032
6066
6033 This is probably useful to developers who manage multiple Python versions
6067 This is probably useful to developers who manage multiple Python versions
6034 and don't want to have correspondingly multiple IPython versions.
6068 and don't want to have correspondingly multiple IPython versions.
6035 Note that in this mode, there is no way to pass IPython any command-line
6069 Note that in this mode, there is no way to pass IPython any command-line
6036 options, as those are trapped first by Python itself.
6070 options, as those are trapped first by Python itself.
6037 \layout Section
6071 \layout Section
6038
6072
6039
6073
6040 \begin_inset LatexCommand \label{sec:embed}
6074 \begin_inset LatexCommand \label{sec:embed}
6041
6075
6042 \end_inset
6076 \end_inset
6043
6077
6044 Embedding IPython
6078 Embedding IPython
6045 \layout Standard
6079 \layout Standard
6046
6080
6047 It is possible to start an IPython instance
6081 It is possible to start an IPython instance
6048 \emph on
6082 \emph on
6049 inside
6083 inside
6050 \emph default
6084 \emph default
6051 your own Python programs.
6085 your own Python programs.
6052 This allows you to evaluate dynamically the state of your code, operate
6086 This allows you to evaluate dynamically the state of your code, operate
6053 with your variables, analyze them, etc.
6087 with your variables, analyze them, etc.
6054 Note however that any changes you make to values while in the shell do
6088 Note however that any changes you make to values while in the shell do
6055
6089
6056 \emph on
6090 \emph on
6057 not
6091 not
6058 \emph default
6092 \emph default
6059 propagate back to the running code, so it is safe to modify your values
6093 propagate back to the running code, so it is safe to modify your values
6060 because you won't break your code in bizarre ways by doing so.
6094 because you won't break your code in bizarre ways by doing so.
6061 \layout Standard
6095 \layout Standard
6062
6096
6063 This feature allows you to easily have a fully functional python environment
6097 This feature allows you to easily have a fully functional python environment
6064 for doing object introspection anywhere in your code with a simple function
6098 for doing object introspection anywhere in your code with a simple function
6065 call.
6099 call.
6066 In some cases a simple print statement is enough, but if you need to do
6100 In some cases a simple print statement is enough, but if you need to do
6067 more detailed analysis of a code fragment this feature can be very valuable.
6101 more detailed analysis of a code fragment this feature can be very valuable.
6068 \layout Standard
6102 \layout Standard
6069
6103
6070 It can also be useful in scientific computing situations where it is common
6104 It can also be useful in scientific computing situations where it is common
6071 to need to do some automatic, computationally intensive part and then stop
6105 to need to do some automatic, computationally intensive part and then stop
6072 to look at data, plots, etc
6106 to look at data, plots, etc
6073 \begin_inset Foot
6107 \begin_inset Foot
6074 collapsed true
6108 collapsed true
6075
6109
6076 \layout Standard
6110 \layout Standard
6077
6111
6078 This functionality was inspired by IDL's combination of the
6112 This functionality was inspired by IDL's combination of the
6079 \family typewriter
6113 \family typewriter
6080 stop
6114 stop
6081 \family default
6115 \family default
6082 keyword and the
6116 keyword and the
6083 \family typewriter
6117 \family typewriter
6084 .continue
6118 .continue
6085 \family default
6119 \family default
6086 executive command, which I have found very useful in the past, and by a
6120 executive command, which I have found very useful in the past, and by a
6087 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6121 posting on comp.lang.python by cmkl <cmkleffner-AT-gmx.de> on Dec.
6088 06/01 concerning similar uses of pyrepl.
6122 06/01 concerning similar uses of pyrepl.
6089 \end_inset
6123 \end_inset
6090
6124
6091 .
6125 .
6092 Opening an IPython instance will give you full access to your data and
6126 Opening an IPython instance will give you full access to your data and
6093 functions, and you can resume program execution once you are done with
6127 functions, and you can resume program execution once you are done with
6094 the interactive part (perhaps to stop again later, as many times as needed).
6128 the interactive part (perhaps to stop again later, as many times as needed).
6095 \layout Standard
6129 \layout Standard
6096
6130
6097 The following code snippet is the bare minimum you need to include in your
6131 The following code snippet is the bare minimum you need to include in your
6098 Python programs for this to work (detailed examples follow later):
6132 Python programs for this to work (detailed examples follow later):
6099 \layout LyX-Code
6133 \layout LyX-Code
6100
6134
6101 from IPython.Shell import IPShellEmbed
6135 from IPython.Shell import IPShellEmbed
6102 \layout LyX-Code
6136 \layout LyX-Code
6103
6137
6104 ipshell = IPShellEmbed()
6138 ipshell = IPShellEmbed()
6105 \layout LyX-Code
6139 \layout LyX-Code
6106
6140
6107 ipshell() # this call anywhere in your program will start IPython
6141 ipshell() # this call anywhere in your program will start IPython
6108 \layout Standard
6142 \layout Standard
6109
6143
6110 You can run embedded instances even in code which is itself being run at
6144 You can run embedded instances even in code which is itself being run at
6111 the IPython interactive prompt with '
6145 the IPython interactive prompt with '
6112 \family typewriter
6146 \family typewriter
6113 %run\SpecialChar ~
6147 %run\SpecialChar ~
6114 <filename>
6148 <filename>
6115 \family default
6149 \family default
6116 '.
6150 '.
6117 Since it's easy to get lost as to where you are (in your top-level IPython
6151 Since it's easy to get lost as to where you are (in your top-level IPython
6118 or in your embedded one), it's a good idea in such cases to set the in/out
6152 or in your embedded one), it's a good idea in such cases to set the in/out
6119 prompts to something different for the embedded instances.
6153 prompts to something different for the embedded instances.
6120 The code examples below illustrate this.
6154 The code examples below illustrate this.
6121 \layout Standard
6155 \layout Standard
6122
6156
6123 You can also have multiple IPython instances in your program and open them
6157 You can also have multiple IPython instances in your program and open them
6124 separately, for example with different options for data presentation.
6158 separately, for example with different options for data presentation.
6125 If you close and open the same instance multiple times, its prompt counters
6159 If you close and open the same instance multiple times, its prompt counters
6126 simply continue from each execution to the next.
6160 simply continue from each execution to the next.
6127 \layout Standard
6161 \layout Standard
6128
6162
6129 Please look at the docstrings in the
6163 Please look at the docstrings in the
6130 \family typewriter
6164 \family typewriter
6131 Shell.py
6165 Shell.py
6132 \family default
6166 \family default
6133 module for more details on the use of this system.
6167 module for more details on the use of this system.
6134 \layout Standard
6168 \layout Standard
6135
6169
6136 The following sample file illustrating how to use the embedding functionality
6170 The following sample file illustrating how to use the embedding functionality
6137 is provided in the examples directory as
6171 is provided in the examples directory as
6138 \family typewriter
6172 \family typewriter
6139 example-embed.py
6173 example-embed.py
6140 \family default
6174 \family default
6141 .
6175 .
6142 It should be fairly self-explanatory:
6176 It should be fairly self-explanatory:
6143 \layout Standard
6177 \layout Standard
6144
6178
6145
6179
6146 \begin_inset ERT
6180 \begin_inset ERT
6147 status Open
6181 status Open
6148
6182
6149 \layout Standard
6183 \layout Standard
6150
6184
6151 \backslash
6185 \backslash
6152 codelist{examples/example-embed.py}
6186 codelist{examples/example-embed.py}
6153 \end_inset
6187 \end_inset
6154
6188
6155
6189
6156 \layout Standard
6190 \layout Standard
6157
6191
6158 Once you understand how the system functions, you can use the following
6192 Once you understand how the system functions, you can use the following
6159 code fragments in your programs which are ready for cut and paste:
6193 code fragments in your programs which are ready for cut and paste:
6160 \layout Standard
6194 \layout Standard
6161
6195
6162
6196
6163 \begin_inset ERT
6197 \begin_inset ERT
6164 status Open
6198 status Open
6165
6199
6166 \layout Standard
6200 \layout Standard
6167
6201
6168 \backslash
6202 \backslash
6169 codelist{examples/example-embed-short.py}
6203 codelist{examples/example-embed-short.py}
6170 \end_inset
6204 \end_inset
6171
6205
6172
6206
6173 \layout Section
6207 \layout Section
6174
6208
6175
6209
6176 \begin_inset LatexCommand \label{sec:using-pdb}
6210 \begin_inset LatexCommand \label{sec:using-pdb}
6177
6211
6178 \end_inset
6212 \end_inset
6179
6213
6180 Using the Python debugger (
6214 Using the Python debugger (
6181 \family typewriter
6215 \family typewriter
6182 pdb
6216 pdb
6183 \family default
6217 \family default
6184 )
6218 )
6185 \layout Subsection
6219 \layout Subsection
6186
6220
6187 Running entire programs via
6221 Running entire programs via
6188 \family typewriter
6222 \family typewriter
6189 pdb
6223 pdb
6190 \layout Standard
6224 \layout Standard
6191
6225
6192
6226
6193 \family typewriter
6227 \family typewriter
6194 pdb
6228 pdb
6195 \family default
6229 \family default
6196 , the Python debugger, is a powerful interactive debugger which allows you
6230 , the Python debugger, is a powerful interactive debugger which allows you
6197 to step through code, set breakpoints, watch variables, etc.
6231 to step through code, set breakpoints, watch variables, etc.
6198 IPython makes it very easy to start any script under the control of
6232 IPython makes it very easy to start any script under the control of
6199 \family typewriter
6233 \family typewriter
6200 pdb
6234 pdb
6201 \family default
6235 \family default
6202 , regardless of whether you have wrapped it into a
6236 , regardless of whether you have wrapped it into a
6203 \family typewriter
6237 \family typewriter
6204 `main()'
6238 `main()'
6205 \family default
6239 \family default
6206 function or not.
6240 function or not.
6207 For this, simply type
6241 For this, simply type
6208 \family typewriter
6242 \family typewriter
6209 `%run -d myscript'
6243 `%run -d myscript'
6210 \family default
6244 \family default
6211 at an IPython prompt.
6245 at an IPython prompt.
6212 See the
6246 See the
6213 \family typewriter
6247 \family typewriter
6214 %run
6248 %run
6215 \family default
6249 \family default
6216 command's documentation (via
6250 command's documentation (via
6217 \family typewriter
6251 \family typewriter
6218 `%run?'
6252 `%run?'
6219 \family default
6253 \family default
6220 or in Sec.\SpecialChar ~
6254 or in Sec.\SpecialChar ~
6221
6255
6222 \begin_inset LatexCommand \ref{sec:magic}
6256 \begin_inset LatexCommand \ref{sec:magic}
6223
6257
6224 \end_inset
6258 \end_inset
6225
6259
6226 ) for more details, including how to control where
6260 ) for more details, including how to control where
6227 \family typewriter
6261 \family typewriter
6228 pdb
6262 pdb
6229 \family default
6263 \family default
6230 will stop execution first.
6264 will stop execution first.
6231 \layout Standard
6265 \layout Standard
6232
6266
6233 For more information on the use of the
6267 For more information on the use of the
6234 \family typewriter
6268 \family typewriter
6235 pdb
6269 pdb
6236 \family default
6270 \family default
6237 debugger, read the included
6271 debugger, read the included
6238 \family typewriter
6272 \family typewriter
6239 pdb.doc
6273 pdb.doc
6240 \family default
6274 \family default
6241 file (part of the standard Python distribution).
6275 file (part of the standard Python distribution).
6242 On a stock Linux system it is located at
6276 On a stock Linux system it is located at
6243 \family typewriter
6277 \family typewriter
6244 /usr/lib/python2.3/pdb.doc
6278 /usr/lib/python2.3/pdb.doc
6245 \family default
6279 \family default
6246 , but the easiest way to read it is by using the
6280 , but the easiest way to read it is by using the
6247 \family typewriter
6281 \family typewriter
6248 help()
6282 help()
6249 \family default
6283 \family default
6250 function of the
6284 function of the
6251 \family typewriter
6285 \family typewriter
6252 pdb
6286 pdb
6253 \family default
6287 \family default
6254 module as follows (in an IPython prompt):
6288 module as follows (in an IPython prompt):
6255 \layout Standard
6289 \layout Standard
6256
6290
6257
6291
6258 \family typewriter
6292 \family typewriter
6259 In [1]: import pdb
6293 In [1]: import pdb
6260 \newline
6294 \newline
6261 In [2]: pdb.help()
6295 In [2]: pdb.help()
6262 \layout Standard
6296 \layout Standard
6263
6297
6264 This will load the
6298 This will load the
6265 \family typewriter
6299 \family typewriter
6266 pdb.doc
6300 pdb.doc
6267 \family default
6301 \family default
6268 document in a file viewer for you automatically.
6302 document in a file viewer for you automatically.
6269 \layout Subsection
6303 \layout Subsection
6270
6304
6271 Automatic invocation of
6305 Automatic invocation of
6272 \family typewriter
6306 \family typewriter
6273 pdb
6307 pdb
6274 \family default
6308 \family default
6275 on exceptions
6309 on exceptions
6276 \layout Standard
6310 \layout Standard
6277
6311
6278 IPython, if started with the
6312 IPython, if started with the
6279 \family typewriter
6313 \family typewriter
6280 -pdb
6314 -pdb
6281 \family default
6315 \family default
6282 option (or if the option is set in your rc file) can call the Python
6316 option (or if the option is set in your rc file) can call the Python
6283 \family typewriter
6317 \family typewriter
6284 pdb
6318 pdb
6285 \family default
6319 \family default
6286 debugger every time your code triggers an uncaught exception
6320 debugger every time your code triggers an uncaught exception
6287 \begin_inset Foot
6321 \begin_inset Foot
6288 collapsed true
6322 collapsed true
6289
6323
6290 \layout Standard
6324 \layout Standard
6291
6325
6292 Many thanks to Christopher Hart for the request which prompted adding this
6326 Many thanks to Christopher Hart for the request which prompted adding this
6293 feature to IPython.
6327 feature to IPython.
6294 \end_inset
6328 \end_inset
6295
6329
6296 .
6330 .
6297 This feature can also be toggled at any time with the
6331 This feature can also be toggled at any time with the
6298 \family typewriter
6332 \family typewriter
6299 %pdb
6333 %pdb
6300 \family default
6334 \family default
6301 magic command.
6335 magic command.
6302 This can be extremely useful in order to find the origin of subtle bugs,
6336 This can be extremely useful in order to find the origin of subtle bugs,
6303 because
6337 because
6304 \family typewriter
6338 \family typewriter
6305 pdb
6339 pdb
6306 \family default
6340 \family default
6307 opens up at the point in your code which triggered the exception, and while
6341 opens up at the point in your code which triggered the exception, and while
6308 your program is at this point `dead', all the data is still available and
6342 your program is at this point `dead', all the data is still available and
6309 you can walk up and down the stack frame and understand the origin of the
6343 you can walk up and down the stack frame and understand the origin of the
6310 problem.
6344 problem.
6311 \layout Standard
6345 \layout Standard
6312
6346
6313 Furthermore, you can use these debugging facilities both with the embedded
6347 Furthermore, you can use these debugging facilities both with the embedded
6314 IPython mode and without IPython at all.
6348 IPython mode and without IPython at all.
6315 For an embedded shell (see sec.
6349 For an embedded shell (see sec.
6316
6350
6317 \begin_inset LatexCommand \ref{sec:embed}
6351 \begin_inset LatexCommand \ref{sec:embed}
6318
6352
6319 \end_inset
6353 \end_inset
6320
6354
6321 ), simply call the constructor with
6355 ), simply call the constructor with
6322 \family typewriter
6356 \family typewriter
6323 `-pdb'
6357 `-pdb'
6324 \family default
6358 \family default
6325 in the argument string and automatically
6359 in the argument string and automatically
6326 \family typewriter
6360 \family typewriter
6327 pdb
6361 pdb
6328 \family default
6362 \family default
6329 will be called if an uncaught exception is triggered by your code.
6363 will be called if an uncaught exception is triggered by your code.
6330
6364
6331 \layout Standard
6365 \layout Standard
6332
6366
6333 For stand-alone use of the feature in your programs which do not use IPython
6367 For stand-alone use of the feature in your programs which do not use IPython
6334 at all, put the following lines toward the top of your `main' routine:
6368 at all, put the following lines toward the top of your `main' routine:
6335 \layout Standard
6369 \layout Standard
6336 \align left
6370 \align left
6337
6371
6338 \family typewriter
6372 \family typewriter
6339 import sys,IPython.ultraTB
6373 import sys,IPython.ultraTB
6340 \newline
6374 \newline
6341 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6375 sys.excepthook = IPython.ultraTB.FormattedTB(mode=`Verbose', color_scheme=`Linux',
6342 call_pdb=1)
6376 call_pdb=1)
6343 \layout Standard
6377 \layout Standard
6344
6378
6345 The
6379 The
6346 \family typewriter
6380 \family typewriter
6347 mode
6381 mode
6348 \family default
6382 \family default
6349 keyword can be either
6383 keyword can be either
6350 \family typewriter
6384 \family typewriter
6351 `Verbose'
6385 `Verbose'
6352 \family default
6386 \family default
6353 or
6387 or
6354 \family typewriter
6388 \family typewriter
6355 `Plain'
6389 `Plain'
6356 \family default
6390 \family default
6357 , giving either very detailed or normal tracebacks respectively.
6391 , giving either very detailed or normal tracebacks respectively.
6358 The
6392 The
6359 \family typewriter
6393 \family typewriter
6360 color_scheme
6394 color_scheme
6361 \family default
6395 \family default
6362 keyword can be one of
6396 keyword can be one of
6363 \family typewriter
6397 \family typewriter
6364 `NoColor'
6398 `NoColor'
6365 \family default
6399 \family default
6366 ,
6400 ,
6367 \family typewriter
6401 \family typewriter
6368 `Linux'
6402 `Linux'
6369 \family default
6403 \family default
6370 (default) or
6404 (default) or
6371 \family typewriter
6405 \family typewriter
6372 `LightBG'
6406 `LightBG'
6373 \family default
6407 \family default
6374 .
6408 .
6375 These are the same options which can be set in IPython with
6409 These are the same options which can be set in IPython with
6376 \family typewriter
6410 \family typewriter
6377 -colors
6411 -colors
6378 \family default
6412 \family default
6379 and
6413 and
6380 \family typewriter
6414 \family typewriter
6381 -xmode
6415 -xmode
6382 \family default
6416 \family default
6383 .
6417 .
6384 \layout Standard
6418 \layout Standard
6385
6419
6386 This will give any of your programs detailed, colored tracebacks with automatic
6420 This will give any of your programs detailed, colored tracebacks with automatic
6387 invocation of
6421 invocation of
6388 \family typewriter
6422 \family typewriter
6389 pdb
6423 pdb
6390 \family default
6424 \family default
6391 .
6425 .
6392 \layout Section
6426 \layout Section
6393
6427
6394
6428
6395 \begin_inset LatexCommand \label{sec:syntax-extensions}
6429 \begin_inset LatexCommand \label{sec:syntax-extensions}
6396
6430
6397 \end_inset
6431 \end_inset
6398
6432
6399 Extensions for syntax processing
6433 Extensions for syntax processing
6400 \layout Standard
6434 \layout Standard
6401
6435
6402 This isn't for the faint of heart, because the potential for breaking things
6436 This isn't for the faint of heart, because the potential for breaking things
6403 is quite high.
6437 is quite high.
6404 But it can be a very powerful and useful feature.
6438 But it can be a very powerful and useful feature.
6405 In a nutshell, you can redefine the way IPython processes the user input
6439 In a nutshell, you can redefine the way IPython processes the user input
6406 line to accept new, special extensions to the syntax without needing to
6440 line to accept new, special extensions to the syntax without needing to
6407 change any of IPython's own code.
6441 change any of IPython's own code.
6408 \layout Standard
6442 \layout Standard
6409
6443
6410 In the
6444 In the
6411 \family typewriter
6445 \family typewriter
6412 IPython/Extensions
6446 IPython/Extensions
6413 \family default
6447 \family default
6414 directory you will find some examples supplied, which we will briefly describe
6448 directory you will find some examples supplied, which we will briefly describe
6415 now.
6449 now.
6416 These can be used `as is' (and both provide very useful functionality),
6450 These can be used `as is' (and both provide very useful functionality),
6417 or you can use them as a starting point for writing your own extensions.
6451 or you can use them as a starting point for writing your own extensions.
6418 \layout Subsection
6452 \layout Subsection
6419
6453
6420 Pasting of code starting with
6454 Pasting of code starting with
6421 \family typewriter
6455 \family typewriter
6422 `>>>
6456 `>>>
6423 \family default
6457 \family default
6424 ' or
6458 ' or
6425 \family typewriter
6459 \family typewriter
6426 `...
6460 `...
6427
6461
6428 \family default
6462 \family default
6429 '
6463 '
6430 \layout Standard
6464 \layout Standard
6431
6465
6432 In the python tutorial it is common to find code examples which have been
6466 In the python tutorial it is common to find code examples which have been
6433 taken from real python sessions.
6467 taken from real python sessions.
6434 The problem with those is that all the lines begin with either
6468 The problem with those is that all the lines begin with either
6435 \family typewriter
6469 \family typewriter
6436 `>>>
6470 `>>>
6437 \family default
6471 \family default
6438 ' or
6472 ' or
6439 \family typewriter
6473 \family typewriter
6440 `...
6474 `...
6441
6475
6442 \family default
6476 \family default
6443 ', which makes it impossible to paste them all at once.
6477 ', which makes it impossible to paste them all at once.
6444 One must instead do a line by line manual copying, carefully removing the
6478 One must instead do a line by line manual copying, carefully removing the
6445 leading extraneous characters.
6479 leading extraneous characters.
6446 \layout Standard
6480 \layout Standard
6447
6481
6448 This extension identifies those starting characters and removes them from
6482 This extension identifies those starting characters and removes them from
6449 the input automatically, so that one can paste multi-line examples directly
6483 the input automatically, so that one can paste multi-line examples directly
6450 into IPython, saving a lot of time.
6484 into IPython, saving a lot of time.
6451 Please look at the file
6485 Please look at the file
6452 \family typewriter
6486 \family typewriter
6453 InterpreterPasteInput.py
6487 InterpreterPasteInput.py
6454 \family default
6488 \family default
6455 in the
6489 in the
6456 \family typewriter
6490 \family typewriter
6457 IPython/Extensions
6491 IPython/Extensions
6458 \family default
6492 \family default
6459 directory for details on how this is done.
6493 directory for details on how this is done.
6460 \layout Standard
6494 \layout Standard
6461
6495
6462 IPython comes with a special profile enabling this feature, called
6496 IPython comes with a special profile enabling this feature, called
6463 \family typewriter
6497 \family typewriter
6464 tutorial
6498 tutorial
6465 \family default
6499 \family default
6466 \emph on
6500 \emph on
6467 .
6501 .
6468
6502
6469 \emph default
6503 \emph default
6470 Simply start IPython via
6504 Simply start IPython via
6471 \family typewriter
6505 \family typewriter
6472 `ipython\SpecialChar ~
6506 `ipython\SpecialChar ~
6473 -p\SpecialChar ~
6507 -p\SpecialChar ~
6474 tutorial'
6508 tutorial'
6475 \family default
6509 \family default
6476 and the feature will be available.
6510 and the feature will be available.
6477 In a normal IPython session you can activate the feature by importing the
6511 In a normal IPython session you can activate the feature by importing the
6478 corresponding module with:
6512 corresponding module with:
6479 \newline
6513 \newline
6480
6514
6481 \family typewriter
6515 \family typewriter
6482 In [1]: import IPython.Extensions.InterpreterPasteInput
6516 In [1]: import IPython.Extensions.InterpreterPasteInput
6483 \layout Standard
6517 \layout Standard
6484
6518
6485 The following is a 'screenshot' of how things work when this extension is
6519 The following is a 'screenshot' of how things work when this extension is
6486 on, copying an example from the standard tutorial:
6520 on, copying an example from the standard tutorial:
6487 \layout Standard
6521 \layout Standard
6488
6522
6489
6523
6490 \family typewriter
6524 \family typewriter
6491 IPython profile: tutorial
6525 IPython profile: tutorial
6492 \newline
6526 \newline
6493 \SpecialChar ~
6527 \SpecialChar ~
6494
6528
6495 \newline
6529 \newline
6496 *** Pasting of code with ">>>" or "..." has been enabled.
6530 *** Pasting of code with ">>>" or "..." has been enabled.
6497 \newline
6531 \newline
6498 \SpecialChar ~
6532 \SpecialChar ~
6499
6533
6500 \newline
6534 \newline
6501 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6535 In [1]: >>> def fib2(n): # return Fibonacci series up to n
6502 \newline
6536 \newline
6503
6537
6504 \begin_inset ERT
6538 \begin_inset ERT
6505 status Collapsed
6539 status Collapsed
6506
6540
6507 \layout Standard
6541 \layout Standard
6508
6542
6509 \backslash
6543 \backslash
6510 hspace*{0mm}
6544 hspace*{0mm}
6511 \end_inset
6545 \end_inset
6512
6546
6513 \SpecialChar ~
6547 \SpecialChar ~
6514 \SpecialChar ~
6548 \SpecialChar ~
6515 ...: ...\SpecialChar ~
6549 ...: ...\SpecialChar ~
6516 \SpecialChar ~
6550 \SpecialChar ~
6517 \SpecialChar ~
6551 \SpecialChar ~
6518 \SpecialChar ~
6552 \SpecialChar ~
6519 """Return a list containing the Fibonacci series up to n."""
6553 """Return a list containing the Fibonacci series up to n."""
6520 \newline
6554 \newline
6521
6555
6522 \begin_inset ERT
6556 \begin_inset ERT
6523 status Collapsed
6557 status Collapsed
6524
6558
6525 \layout Standard
6559 \layout Standard
6526
6560
6527 \backslash
6561 \backslash
6528 hspace*{0mm}
6562 hspace*{0mm}
6529 \end_inset
6563 \end_inset
6530
6564
6531 \SpecialChar ~
6565 \SpecialChar ~
6532 \SpecialChar ~
6566 \SpecialChar ~
6533 ...: ...\SpecialChar ~
6567 ...: ...\SpecialChar ~
6534 \SpecialChar ~
6568 \SpecialChar ~
6535 \SpecialChar ~
6569 \SpecialChar ~
6536 \SpecialChar ~
6570 \SpecialChar ~
6537 result = []
6571 result = []
6538 \newline
6572 \newline
6539
6573
6540 \begin_inset ERT
6574 \begin_inset ERT
6541 status Collapsed
6575 status Collapsed
6542
6576
6543 \layout Standard
6577 \layout Standard
6544
6578
6545 \backslash
6579 \backslash
6546 hspace*{0mm}
6580 hspace*{0mm}
6547 \end_inset
6581 \end_inset
6548
6582
6549 \SpecialChar ~
6583 \SpecialChar ~
6550 \SpecialChar ~
6584 \SpecialChar ~
6551 ...: ...\SpecialChar ~
6585 ...: ...\SpecialChar ~
6552 \SpecialChar ~
6586 \SpecialChar ~
6553 \SpecialChar ~
6587 \SpecialChar ~
6554 \SpecialChar ~
6588 \SpecialChar ~
6555 a, b = 0, 1
6589 a, b = 0, 1
6556 \newline
6590 \newline
6557
6591
6558 \begin_inset ERT
6592 \begin_inset ERT
6559 status Collapsed
6593 status Collapsed
6560
6594
6561 \layout Standard
6595 \layout Standard
6562
6596
6563 \backslash
6597 \backslash
6564 hspace*{0mm}
6598 hspace*{0mm}
6565 \end_inset
6599 \end_inset
6566
6600
6567 \SpecialChar ~
6601 \SpecialChar ~
6568 \SpecialChar ~
6602 \SpecialChar ~
6569 ...: ...\SpecialChar ~
6603 ...: ...\SpecialChar ~
6570 \SpecialChar ~
6604 \SpecialChar ~
6571 \SpecialChar ~
6605 \SpecialChar ~
6572 \SpecialChar ~
6606 \SpecialChar ~
6573 while b < n:
6607 while b < n:
6574 \newline
6608 \newline
6575
6609
6576 \begin_inset ERT
6610 \begin_inset ERT
6577 status Collapsed
6611 status Collapsed
6578
6612
6579 \layout Standard
6613 \layout Standard
6580
6614
6581 \backslash
6615 \backslash
6582 hspace*{0mm}
6616 hspace*{0mm}
6583 \end_inset
6617 \end_inset
6584
6618
6585 \SpecialChar ~
6619 \SpecialChar ~
6586 \SpecialChar ~
6620 \SpecialChar ~
6587 ...: ...\SpecialChar ~
6621 ...: ...\SpecialChar ~
6588 \SpecialChar ~
6622 \SpecialChar ~
6589 \SpecialChar ~
6623 \SpecialChar ~
6590 \SpecialChar ~
6624 \SpecialChar ~
6591 \SpecialChar ~
6625 \SpecialChar ~
6592 \SpecialChar ~
6626 \SpecialChar ~
6593 \SpecialChar ~
6627 \SpecialChar ~
6594 \SpecialChar ~
6628 \SpecialChar ~
6595 result.append(b)\SpecialChar ~
6629 result.append(b)\SpecialChar ~
6596 \SpecialChar ~
6630 \SpecialChar ~
6597 \SpecialChar ~
6631 \SpecialChar ~
6598 # see below
6632 # see below
6599 \newline
6633 \newline
6600
6634
6601 \begin_inset ERT
6635 \begin_inset ERT
6602 status Collapsed
6636 status Collapsed
6603
6637
6604 \layout Standard
6638 \layout Standard
6605
6639
6606 \backslash
6640 \backslash
6607 hspace*{0mm}
6641 hspace*{0mm}
6608 \end_inset
6642 \end_inset
6609
6643
6610 \SpecialChar ~
6644 \SpecialChar ~
6611 \SpecialChar ~
6645 \SpecialChar ~
6612 ...: ...\SpecialChar ~
6646 ...: ...\SpecialChar ~
6613 \SpecialChar ~
6647 \SpecialChar ~
6614 \SpecialChar ~
6648 \SpecialChar ~
6615 \SpecialChar ~
6649 \SpecialChar ~
6616 \SpecialChar ~
6650 \SpecialChar ~
6617 \SpecialChar ~
6651 \SpecialChar ~
6618 \SpecialChar ~
6652 \SpecialChar ~
6619 \SpecialChar ~
6653 \SpecialChar ~
6620 a, b = b, a+b
6654 a, b = b, a+b
6621 \newline
6655 \newline
6622
6656
6623 \begin_inset ERT
6657 \begin_inset ERT
6624 status Collapsed
6658 status Collapsed
6625
6659
6626 \layout Standard
6660 \layout Standard
6627
6661
6628 \backslash
6662 \backslash
6629 hspace*{0mm}
6663 hspace*{0mm}
6630 \end_inset
6664 \end_inset
6631
6665
6632 \SpecialChar ~
6666 \SpecialChar ~
6633 \SpecialChar ~
6667 \SpecialChar ~
6634 ...: ...\SpecialChar ~
6668 ...: ...\SpecialChar ~
6635 \SpecialChar ~
6669 \SpecialChar ~
6636 \SpecialChar ~
6670 \SpecialChar ~
6637 \SpecialChar ~
6671 \SpecialChar ~
6638 return result
6672 return result
6639 \newline
6673 \newline
6640
6674
6641 \begin_inset ERT
6675 \begin_inset ERT
6642 status Collapsed
6676 status Collapsed
6643
6677
6644 \layout Standard
6678 \layout Standard
6645
6679
6646 \backslash
6680 \backslash
6647 hspace*{0mm}
6681 hspace*{0mm}
6648 \end_inset
6682 \end_inset
6649
6683
6650 \SpecialChar ~
6684 \SpecialChar ~
6651 \SpecialChar ~
6685 \SpecialChar ~
6652 ...:
6686 ...:
6653 \newline
6687 \newline
6654 \SpecialChar ~
6688 \SpecialChar ~
6655
6689
6656 \newline
6690 \newline
6657 In [2]: fib2(10)
6691 In [2]: fib2(10)
6658 \newline
6692 \newline
6659 Out[2]: [1, 1, 2, 3, 5, 8]
6693 Out[2]: [1, 1, 2, 3, 5, 8]
6660 \layout Standard
6694 \layout Standard
6661
6695
6662 Note that as currently written, this extension does
6696 Note that as currently written, this extension does
6663 \emph on
6697 \emph on
6664 not
6698 not
6665 \emph default
6699 \emph default
6666 recognize IPython's prompts for pasting.
6700 recognize IPython's prompts for pasting.
6667 Those are more complicated, since the user can change them very easily,
6701 Those are more complicated, since the user can change them very easily,
6668 they involve numbers and can vary in length.
6702 they involve numbers and can vary in length.
6669 One could however extract all the relevant information from the IPython
6703 One could however extract all the relevant information from the IPython
6670 instance and build an appropriate regular expression.
6704 instance and build an appropriate regular expression.
6671 This is left as an exercise for the reader.
6705 This is left as an exercise for the reader.
6672 \layout Subsection
6706 \layout Subsection
6673
6707
6674 Input of physical quantities with units
6708 Input of physical quantities with units
6675 \layout Standard
6709 \layout Standard
6676
6710
6677 The module
6711 The module
6678 \family typewriter
6712 \family typewriter
6679 PhysicalQInput
6713 PhysicalQInput
6680 \family default
6714 \family default
6681 allows a simplified form of input for physical quantities with units.
6715 allows a simplified form of input for physical quantities with units.
6682 This file is meant to be used in conjunction with the
6716 This file is meant to be used in conjunction with the
6683 \family typewriter
6717 \family typewriter
6684 PhysicalQInteractive
6718 PhysicalQInteractive
6685 \family default
6719 \family default
6686 module (in the same directory) and
6720 module (in the same directory) and
6687 \family typewriter
6721 \family typewriter
6688 Physics.PhysicalQuantities
6722 Physics.PhysicalQuantities
6689 \family default
6723 \family default
6690 from Konrad Hinsen's ScientificPython (
6724 from Konrad Hinsen's ScientificPython (
6691 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
6725 \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/hinsen/scientific.html}
6692
6726
6693 \end_inset
6727 \end_inset
6694
6728
6695 ).
6729 ).
6696 \layout Standard
6730 \layout Standard
6697
6731
6698 The
6732 The
6699 \family typewriter
6733 \family typewriter
6700 Physics.PhysicalQuantities
6734 Physics.PhysicalQuantities
6701 \family default
6735 \family default
6702 module defines
6736 module defines
6703 \family typewriter
6737 \family typewriter
6704 PhysicalQuantity
6738 PhysicalQuantity
6705 \family default
6739 \family default
6706 objects, but these must be declared as instances of a class.
6740 objects, but these must be declared as instances of a class.
6707 For example, to define
6741 For example, to define
6708 \family typewriter
6742 \family typewriter
6709 v
6743 v
6710 \family default
6744 \family default
6711 as a velocity of 3\SpecialChar ~
6745 as a velocity of 3\SpecialChar ~
6712 m/s, normally you would write:
6746 m/s, normally you would write:
6713 \family typewriter
6747 \family typewriter
6714
6748
6715 \newline
6749 \newline
6716 In [1]: v = PhysicalQuantity(3,'m/s')
6750 In [1]: v = PhysicalQuantity(3,'m/s')
6717 \layout Standard
6751 \layout Standard
6718
6752
6719 Using the
6753 Using the
6720 \family typewriter
6754 \family typewriter
6721 PhysicalQ_Input
6755 PhysicalQ_Input
6722 \family default
6756 \family default
6723 extension this can be input instead as:
6757 extension this can be input instead as:
6724 \family typewriter
6758 \family typewriter
6725
6759
6726 \newline
6760 \newline
6727 In [1]: v = 3 m/s
6761 In [1]: v = 3 m/s
6728 \family default
6762 \family default
6729
6763
6730 \newline
6764 \newline
6731 which is much more convenient for interactive use (even though it is blatantly
6765 which is much more convenient for interactive use (even though it is blatantly
6732 invalid Python syntax).
6766 invalid Python syntax).
6733 \layout Standard
6767 \layout Standard
6734
6768
6735 The
6769 The
6736 \family typewriter
6770 \family typewriter
6737 physics
6771 physics
6738 \family default
6772 \family default
6739 profile supplied with IPython (enabled via
6773 profile supplied with IPython (enabled via
6740 \family typewriter
6774 \family typewriter
6741 'ipython -p physics'
6775 'ipython -p physics'
6742 \family default
6776 \family default
6743 ) uses these extensions, which you can also activate with:
6777 ) uses these extensions, which you can also activate with:
6744 \layout Standard
6778 \layout Standard
6745
6779
6746
6780
6747 \family typewriter
6781 \family typewriter
6748 from math import * # math MUST be imported BEFORE PhysicalQInteractive
6782 from math import * # math MUST be imported BEFORE PhysicalQInteractive
6749 \newline
6783 \newline
6750 from IPython.Extensions.PhysicalQInteractive import *
6784 from IPython.Extensions.PhysicalQInteractive import *
6751 \newline
6785 \newline
6752 import IPython.Extensions.PhysicalQInput
6786 import IPython.Extensions.PhysicalQInput
6753 \layout Section
6787 \layout Section
6754
6788
6755 IPython as a system shell
6789 IPython as a system shell
6756 \layout Standard
6790 \layout Standard
6757
6791
6758 IPython ships with a special profile called
6792 IPython ships with a special profile called
6759 \family typewriter
6793 \family typewriter
6760 pysh
6794 pysh
6761 \family default
6795 \family default
6762 , which you can activate at the command line as
6796 , which you can activate at the command line as
6763 \family typewriter
6797 \family typewriter
6764 `ipython -p pysh'
6798 `ipython -p pysh'
6765 \family default
6799 \family default
6766 .
6800 .
6767 This loads
6801 This loads
6768 \family typewriter
6802 \family typewriter
6769 InterpreterExec
6803 InterpreterExec
6770 \family default
6804 \family default
6771 , along with some additional facilities and a prompt customized for filesystem
6805 , along with some additional facilities and a prompt customized for filesystem
6772 navigation.
6806 navigation.
6773 \layout Standard
6807 \layout Standard
6774
6808
6775 Note that this does
6809 Note that this does
6776 \emph on
6810 \emph on
6777 not
6811 not
6778 \emph default
6812 \emph default
6779 make IPython a full-fledged system shell.
6813 make IPython a full-fledged system shell.
6780 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
6814 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
6781 you'll suspend pysh itself, not the process you just started.
6815 you'll suspend pysh itself, not the process you just started.
6782
6816
6783 \layout Standard
6817 \layout Standard
6784
6818
6785 What the shell profile allows you to do is to use the convenient and powerful
6819 What the shell profile allows you to do is to use the convenient and powerful
6786 syntax of Python to do quick scripting at the command line.
6820 syntax of Python to do quick scripting at the command line.
6787 Below we describe some of its features.
6821 Below we describe some of its features.
6788 \layout Subsection
6822 \layout Subsection
6789
6823
6790 Aliases
6824 Aliases
6791 \layout Standard
6825 \layout Standard
6792
6826
6793 All of your
6827 All of your
6794 \family typewriter
6828 \family typewriter
6795 $PATH
6829 $PATH
6796 \family default
6830 \family default
6797 has been loaded as IPython aliases, so you should be able to type any normal
6831 has been loaded as IPython aliases, so you should be able to type any normal
6798 system command and have it executed.
6832 system command and have it executed.
6799 See
6833 See
6800 \family typewriter
6834 \family typewriter
6801 %alias?
6835 %alias?
6802 \family default
6836 \family default
6803 and
6837 and
6804 \family typewriter
6838 \family typewriter
6805 %unalias?
6839 %unalias?
6806 \family default
6840 \family default
6807 for details on the alias facilities.
6841 for details on the alias facilities.
6808 See also
6842 See also
6809 \family typewriter
6843 \family typewriter
6810 %rehash?
6844 %rehash?
6811 \family default
6845 \family default
6812 and
6846 and
6813 \family typewriter
6847 \family typewriter
6814 %rehashx?
6848 %rehashx?
6815 \family default
6849 \family default
6816 for details on the mechanism used to load
6850 for details on the mechanism used to load
6817 \family typewriter
6851 \family typewriter
6818 $PATH
6852 $PATH
6819 \family default
6853 \family default
6820 .
6854 .
6821 \layout Subsection
6855 \layout Subsection
6822
6856
6823 Special syntax
6857 Special syntax
6824 \layout Standard
6858 \layout Standard
6825
6859
6826 Any lines which begin with
6860 Any lines which begin with
6827 \family typewriter
6861 \family typewriter
6828 `~'
6862 `~'
6829 \family default
6863 \family default
6830 ,
6864 ,
6831 \family typewriter
6865 \family typewriter
6832 `/'
6866 `/'
6833 \family default
6867 \family default
6834 and
6868 and
6835 \family typewriter
6869 \family typewriter
6836 `.'
6870 `.'
6837 \family default
6871 \family default
6838 will be executed as shell commands instead of as Python code.
6872 will be executed as shell commands instead of as Python code.
6839 The special escapes below are also recognized.
6873 The special escapes below are also recognized.
6840
6874
6841 \family typewriter
6875 \family typewriter
6842 !cmd
6876 !cmd
6843 \family default
6877 \family default
6844 is valid in single or multi-line input, all others are only valid in single-lin
6878 is valid in single or multi-line input, all others are only valid in single-lin
6845 e input:
6879 e input:
6846 \layout Description
6880 \layout Description
6847
6881
6848
6882
6849 \family typewriter
6883 \family typewriter
6850 !cmd
6884 !cmd
6851 \family default
6885 \family default
6852 pass `cmd' directly to the shell
6886 pass `cmd' directly to the shell
6853 \layout Description
6887 \layout Description
6854
6888
6855
6889
6856 \family typewriter
6890 \family typewriter
6857 !!cmd
6891 !!cmd
6858 \family default
6892 \family default
6859 execute `cmd' and return output as a list (split on `
6893 execute `cmd' and return output as a list (split on `
6860 \backslash
6894 \backslash
6861 n')
6895 n')
6862 \layout Description
6896 \layout Description
6863
6897
6864
6898
6865 \family typewriter
6899 \family typewriter
6866 $var=cmd
6900 $var=cmd
6867 \family default
6901 \family default
6868 capture output of cmd into var, as a string
6902 capture output of cmd into var, as a string
6869 \layout Description
6903 \layout Description
6870
6904
6871
6905
6872 \family typewriter
6906 \family typewriter
6873 $$var=cmd
6907 $$var=cmd
6874 \family default
6908 \family default
6875 capture output of cmd into var, as a list (split on `
6909 capture output of cmd into var, as a list (split on `
6876 \backslash
6910 \backslash
6877 n')
6911 n')
6878 \layout Standard
6912 \layout Standard
6879
6913
6880 The
6914 The
6881 \family typewriter
6915 \family typewriter
6882 $
6916 $
6883 \family default
6917 \family default
6884 /
6918 /
6885 \family typewriter
6919 \family typewriter
6886 $$
6920 $$
6887 \family default
6921 \family default
6888 syntaxes make Python variables from system output, which you can later
6922 syntaxes make Python variables from system output, which you can later
6889 use for further scripting.
6923 use for further scripting.
6890 The converse is also possible: when executing an alias or calling to the
6924 The converse is also possible: when executing an alias or calling to the
6891 system via
6925 system via
6892 \family typewriter
6926 \family typewriter
6893 !
6927 !
6894 \family default
6928 \family default
6895 /
6929 /
6896 \family typewriter
6930 \family typewriter
6897 !!
6931 !!
6898 \family default
6932 \family default
6899 , you can expand any python variable or expression by prepending it with
6933 , you can expand any python variable or expression by prepending it with
6900
6934
6901 \family typewriter
6935 \family typewriter
6902 $
6936 $
6903 \family default
6937 \family default
6904 .
6938 .
6905 Full details of the allowed syntax can be found in Python's PEP 215.
6939 Full details of the allowed syntax can be found in Python's PEP 215.
6906 \layout Standard
6940 \layout Standard
6907
6941
6908 A few brief examples will illustrate these (note that the indentation below
6942 A few brief examples will illustrate these (note that the indentation below
6909 may be incorrectly displayed):
6943 may be incorrectly displayed):
6910 \layout Standard
6944 \layout Standard
6911
6945
6912
6946
6913 \family typewriter
6947 \family typewriter
6914 fperez[~/test]|3> !ls *s.py
6948 fperez[~/test]|3> !ls *s.py
6915 \newline
6949 \newline
6916 scopes.py strings.py
6950 scopes.py strings.py
6917 \layout Standard
6951 \layout Standard
6918
6952
6919 ls is an internal alias, so there's no need to use
6953 ls is an internal alias, so there's no need to use
6920 \family typewriter
6954 \family typewriter
6921 !
6955 !
6922 \family default
6956 \family default
6923 :
6957 :
6924 \layout Standard
6958 \layout Standard
6925
6959
6926
6960
6927 \family typewriter
6961 \family typewriter
6928 fperez[~/test]|4> ls *s.py
6962 fperez[~/test]|4> ls *s.py
6929 \newline
6963 \newline
6930 scopes.py* strings.py
6964 scopes.py* strings.py
6931 \layout Standard
6965 \layout Standard
6932
6966
6933 !!ls will return the output into a Python variable:
6967 !!ls will return the output into a Python variable:
6934 \layout Standard
6968 \layout Standard
6935
6969
6936
6970
6937 \family typewriter
6971 \family typewriter
6938 fperez[~/test]|5> !!ls *s.py
6972 fperez[~/test]|5> !!ls *s.py
6939 \newline
6973 \newline
6940
6974
6941 \begin_inset ERT
6975 \begin_inset ERT
6942 status Collapsed
6976 status Collapsed
6943
6977
6944 \layout Standard
6978 \layout Standard
6945
6979
6946 \backslash
6980 \backslash
6947 hspace*{0mm}
6981 hspace*{0mm}
6948 \end_inset
6982 \end_inset
6949
6983
6950 \SpecialChar ~
6984 \SpecialChar ~
6951 \SpecialChar ~
6985 \SpecialChar ~
6952 \SpecialChar ~
6986 \SpecialChar ~
6953 \SpecialChar ~
6987 \SpecialChar ~
6954 \SpecialChar ~
6988 \SpecialChar ~
6955 \SpecialChar ~
6989 \SpecialChar ~
6956 \SpecialChar ~
6990 \SpecialChar ~
6957 \SpecialChar ~
6991 \SpecialChar ~
6958 \SpecialChar ~
6992 \SpecialChar ~
6959 \SpecialChar ~
6993 \SpecialChar ~
6960 \SpecialChar ~
6994 \SpecialChar ~
6961 \SpecialChar ~
6995 \SpecialChar ~
6962 \SpecialChar ~
6996 \SpecialChar ~
6963 \SpecialChar ~
6997 \SpecialChar ~
6964 <5> ['scopes.py', 'strings.py']
6998 <5> ['scopes.py', 'strings.py']
6965 \newline
6999 \newline
6966 fperez[~/test]|6> print _5
7000 fperez[~/test]|6> print _5
6967 \newline
7001 \newline
6968 ['scopes.py', 'strings.py']
7002 ['scopes.py', 'strings.py']
6969 \layout Standard
7003 \layout Standard
6970
7004
6971
7005
6972 \family typewriter
7006 \family typewriter
6973 $
7007 $
6974 \family default
7008 \family default
6975 and
7009 and
6976 \family typewriter
7010 \family typewriter
6977 $$
7011 $$
6978 \family default
7012 \family default
6979 allow direct capture to named variables:
7013 allow direct capture to named variables:
6980 \layout Standard
7014 \layout Standard
6981
7015
6982
7016
6983 \family typewriter
7017 \family typewriter
6984 fperez[~/test]|7> $astr = ls *s.py
7018 fperez[~/test]|7> $astr = ls *s.py
6985 \newline
7019 \newline
6986 fperez[~/test]|8> astr
7020 fperez[~/test]|8> astr
6987 \newline
7021 \newline
6988
7022
6989 \begin_inset ERT
7023 \begin_inset ERT
6990 status Collapsed
7024 status Collapsed
6991
7025
6992 \layout Standard
7026 \layout Standard
6993
7027
6994 \backslash
7028 \backslash
6995 hspace*{0mm}
7029 hspace*{0mm}
6996 \end_inset
7030 \end_inset
6997
7031
6998 \SpecialChar ~
7032 \SpecialChar ~
6999 \SpecialChar ~
7033 \SpecialChar ~
7000 \SpecialChar ~
7034 \SpecialChar ~
7001 \SpecialChar ~
7035 \SpecialChar ~
7002 \SpecialChar ~
7036 \SpecialChar ~
7003 \SpecialChar ~
7037 \SpecialChar ~
7004 \SpecialChar ~
7038 \SpecialChar ~
7005 \SpecialChar ~
7039 \SpecialChar ~
7006 \SpecialChar ~
7040 \SpecialChar ~
7007 \SpecialChar ~
7041 \SpecialChar ~
7008 \SpecialChar ~
7042 \SpecialChar ~
7009 \SpecialChar ~
7043 \SpecialChar ~
7010 \SpecialChar ~
7044 \SpecialChar ~
7011 \SpecialChar ~
7045 \SpecialChar ~
7012 <8> 'scopes.py
7046 <8> 'scopes.py
7013 \backslash
7047 \backslash
7014 nstrings.py'
7048 nstrings.py'
7015 \layout Standard
7049 \layout Standard
7016
7050
7017
7051
7018 \family typewriter
7052 \family typewriter
7019 fperez[~/test]|9> $$alist = ls *s.py
7053 fperez[~/test]|9> $$alist = ls *s.py
7020 \newline
7054 \newline
7021 fperez[~/test]|10> alist
7055 fperez[~/test]|10> alist
7022 \newline
7056 \newline
7023
7057
7024 \begin_inset ERT
7058 \begin_inset ERT
7025 status Collapsed
7059 status Collapsed
7026
7060
7027 \layout Standard
7061 \layout Standard
7028
7062
7029 \backslash
7063 \backslash
7030 hspace*{0mm}
7064 hspace*{0mm}
7031 \end_inset
7065 \end_inset
7032
7066
7033 \SpecialChar ~
7067 \SpecialChar ~
7034 \SpecialChar ~
7068 \SpecialChar ~
7035 \SpecialChar ~
7069 \SpecialChar ~
7036 \SpecialChar ~
7070 \SpecialChar ~
7037 \SpecialChar ~
7071 \SpecialChar ~
7038 \SpecialChar ~
7072 \SpecialChar ~
7039 \SpecialChar ~
7073 \SpecialChar ~
7040 \SpecialChar ~
7074 \SpecialChar ~
7041 \SpecialChar ~
7075 \SpecialChar ~
7042 \SpecialChar ~
7076 \SpecialChar ~
7043 \SpecialChar ~
7077 \SpecialChar ~
7044 \SpecialChar ~
7078 \SpecialChar ~
7045 \SpecialChar ~
7079 \SpecialChar ~
7046 \SpecialChar ~
7080 \SpecialChar ~
7047 <10> ['scopes.py', 'strings.py']
7081 <10> ['scopes.py', 'strings.py']
7048 \layout Standard
7082 \layout Standard
7049
7083
7050 alist is now a normal python list you can loop over.
7084 alist is now a normal python list you can loop over.
7051 Using
7085 Using
7052 \family typewriter
7086 \family typewriter
7053 $
7087 $
7054 \family default
7088 \family default
7055 will expand back the python values when alias calls are made:
7089 will expand back the python values when alias calls are made:
7056 \layout Standard
7090 \layout Standard
7057
7091
7058
7092
7059 \family typewriter
7093 \family typewriter
7060 fperez[~/test]|11> for f in alist:
7094 fperez[~/test]|11> for f in alist:
7061 \newline
7095 \newline
7062
7096
7063 \begin_inset ERT
7097 \begin_inset ERT
7064 status Collapsed
7098 status Collapsed
7065
7099
7066 \layout Standard
7100 \layout Standard
7067
7101
7068 \backslash
7102 \backslash
7069 hspace*{0mm}
7103 hspace*{0mm}
7070 \end_inset
7104 \end_inset
7071
7105
7072 \SpecialChar ~
7106 \SpecialChar ~
7073 \SpecialChar ~
7107 \SpecialChar ~
7074 \SpecialChar ~
7108 \SpecialChar ~
7075 \SpecialChar ~
7109 \SpecialChar ~
7076 \SpecialChar ~
7110 \SpecialChar ~
7077 \SpecialChar ~
7111 \SpecialChar ~
7078 \SpecialChar ~
7112 \SpecialChar ~
7079 \SpecialChar ~
7113 \SpecialChar ~
7080 \SpecialChar ~
7114 \SpecialChar ~
7081 \SpecialChar ~
7115 \SpecialChar ~
7082 \SpecialChar ~
7116 \SpecialChar ~
7083 \SpecialChar ~
7117 \SpecialChar ~
7084 \SpecialChar ~
7118 \SpecialChar ~
7085 \SpecialChar ~
7119 \SpecialChar ~
7086 |..> \SpecialChar ~
7120 |..> \SpecialChar ~
7087 \SpecialChar ~
7121 \SpecialChar ~
7088 \SpecialChar ~
7122 \SpecialChar ~
7089 \SpecialChar ~
7123 \SpecialChar ~
7090 print 'file',f,
7124 print 'file',f,
7091 \newline
7125 \newline
7092
7126
7093 \begin_inset ERT
7127 \begin_inset ERT
7094 status Collapsed
7128 status Collapsed
7095
7129
7096 \layout Standard
7130 \layout Standard
7097
7131
7098 \backslash
7132 \backslash
7099 hspace*{0mm}
7133 hspace*{0mm}
7100 \end_inset
7134 \end_inset
7101
7135
7102 \SpecialChar ~
7136 \SpecialChar ~
7103 \SpecialChar ~
7137 \SpecialChar ~
7104 \SpecialChar ~
7138 \SpecialChar ~
7105 \SpecialChar ~
7139 \SpecialChar ~
7106 \SpecialChar ~
7140 \SpecialChar ~
7107 \SpecialChar ~
7141 \SpecialChar ~
7108 \SpecialChar ~
7142 \SpecialChar ~
7109 \SpecialChar ~
7143 \SpecialChar ~
7110 \SpecialChar ~
7144 \SpecialChar ~
7111 \SpecialChar ~
7145 \SpecialChar ~
7112 \SpecialChar ~
7146 \SpecialChar ~
7113 \SpecialChar ~
7147 \SpecialChar ~
7114 \SpecialChar ~
7148 \SpecialChar ~
7115 \SpecialChar ~
7149 \SpecialChar ~
7116 |..> \SpecialChar ~
7150 |..> \SpecialChar ~
7117 \SpecialChar ~
7151 \SpecialChar ~
7118 \SpecialChar ~
7152 \SpecialChar ~
7119 \SpecialChar ~
7153 \SpecialChar ~
7120 wc -l $f
7154 wc -l $f
7121 \newline
7155 \newline
7122
7156
7123 \begin_inset ERT
7157 \begin_inset ERT
7124 status Collapsed
7158 status Collapsed
7125
7159
7126 \layout Standard
7160 \layout Standard
7127
7161
7128 \backslash
7162 \backslash
7129 hspace*{0mm}
7163 hspace*{0mm}
7130 \end_inset
7164 \end_inset
7131
7165
7132 \SpecialChar ~
7166 \SpecialChar ~
7133 \SpecialChar ~
7167 \SpecialChar ~
7134 \SpecialChar ~
7168 \SpecialChar ~
7135 \SpecialChar ~
7169 \SpecialChar ~
7136 \SpecialChar ~
7170 \SpecialChar ~
7137 \SpecialChar ~
7171 \SpecialChar ~
7138 \SpecialChar ~
7172 \SpecialChar ~
7139 \SpecialChar ~
7173 \SpecialChar ~
7140 \SpecialChar ~
7174 \SpecialChar ~
7141 \SpecialChar ~
7175 \SpecialChar ~
7142 \SpecialChar ~
7176 \SpecialChar ~
7143 \SpecialChar ~
7177 \SpecialChar ~
7144 \SpecialChar ~
7178 \SpecialChar ~
7145 \SpecialChar ~
7179 \SpecialChar ~
7146 |..>
7180 |..>
7147 \newline
7181 \newline
7148 file scopes.py 13 scopes.py
7182 file scopes.py 13 scopes.py
7149 \newline
7183 \newline
7150 file strings.py 4 strings.py
7184 file strings.py 4 strings.py
7151 \layout Standard
7185 \layout Standard
7152
7186
7153 Note that you may need to protect your variables with braces if you want
7187 Note that you may need to protect your variables with braces if you want
7154 to append strings to their names.
7188 to append strings to their names.
7155 To copy all files in alist to
7189 To copy all files in alist to
7156 \family typewriter
7190 \family typewriter
7157 .bak
7191 .bak
7158 \family default
7192 \family default
7159 extensions, you must use:
7193 extensions, you must use:
7160 \layout Standard
7194 \layout Standard
7161
7195
7162
7196
7163 \family typewriter
7197 \family typewriter
7164 fperez[~/test]|12> for f in alist:
7198 fperez[~/test]|12> for f in alist:
7165 \newline
7199 \newline
7166
7200
7167 \begin_inset ERT
7201 \begin_inset ERT
7168 status Collapsed
7202 status Collapsed
7169
7203
7170 \layout Standard
7204 \layout Standard
7171
7205
7172 \backslash
7206 \backslash
7173 hspace*{0mm}
7207 hspace*{0mm}
7174 \end_inset
7208 \end_inset
7175
7209
7176 \SpecialChar ~
7210 \SpecialChar ~
7177 \SpecialChar ~
7211 \SpecialChar ~
7178 \SpecialChar ~
7212 \SpecialChar ~
7179 \SpecialChar ~
7213 \SpecialChar ~
7180 \SpecialChar ~
7214 \SpecialChar ~
7181 \SpecialChar ~
7215 \SpecialChar ~
7182 \SpecialChar ~
7216 \SpecialChar ~
7183 \SpecialChar ~
7217 \SpecialChar ~
7184 \SpecialChar ~
7218 \SpecialChar ~
7185 \SpecialChar ~
7219 \SpecialChar ~
7186 \SpecialChar ~
7220 \SpecialChar ~
7187 \SpecialChar ~
7221 \SpecialChar ~
7188 \SpecialChar ~
7222 \SpecialChar ~
7189 \SpecialChar ~
7223 \SpecialChar ~
7190 |..> \SpecialChar ~
7224 |..> \SpecialChar ~
7191 \SpecialChar ~
7225 \SpecialChar ~
7192 \SpecialChar ~
7226 \SpecialChar ~
7193 \SpecialChar ~
7227 \SpecialChar ~
7194 cp $f ${f}.bak
7228 cp $f ${f}.bak
7195 \layout Standard
7229 \layout Standard
7196
7230
7197 If you try using
7231 If you try using
7198 \family typewriter
7232 \family typewriter
7199 $f.bak
7233 $f.bak
7200 \family default
7234 \family default
7201 , you'll get an AttributeError exception saying that your string object
7235 , you'll get an AttributeError exception saying that your string object
7202 doesn't have a
7236 doesn't have a
7203 \family typewriter
7237 \family typewriter
7204 .bak
7238 .bak
7205 \family default
7239 \family default
7206 attribute.
7240 attribute.
7207 This is because the
7241 This is because the
7208 \family typewriter
7242 \family typewriter
7209 $
7243 $
7210 \family default
7244 \family default
7211 expansion mechanism allows you to expand full Python expressions:
7245 expansion mechanism allows you to expand full Python expressions:
7212 \layout Standard
7246 \layout Standard
7213
7247
7214
7248
7215 \family typewriter
7249 \family typewriter
7216 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7250 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
7217 \newline
7251 \newline
7218 sys.platform is: linux2
7252 sys.platform is: linux2
7219 \layout Standard
7253 \layout Standard
7220
7254
7221 IPython's input history handling is still active, which allows you to rerun
7255 IPython's input history handling is still active, which allows you to rerun
7222 a single block of multi-line input by simply using exec:
7256 a single block of multi-line input by simply using exec:
7223 \newline
7257 \newline
7224
7258
7225 \family typewriter
7259 \family typewriter
7226 fperez[~/test]|14> $$alist = ls *.eps
7260 fperez[~/test]|14> $$alist = ls *.eps
7227 \newline
7261 \newline
7228 fperez[~/test]|15> exec _i11
7262 fperez[~/test]|15> exec _i11
7229 \newline
7263 \newline
7230 file image2.eps 921 image2.eps
7264 file image2.eps 921 image2.eps
7231 \newline
7265 \newline
7232 file image.eps 921 image.eps
7266 file image.eps 921 image.eps
7233 \layout Standard
7267 \layout Standard
7234
7268
7235 While these are new special-case syntaxes, they are designed to allow very
7269 While these are new special-case syntaxes, they are designed to allow very
7236 efficient use of the shell with minimal typing.
7270 efficient use of the shell with minimal typing.
7237 At an interactive shell prompt, conciseness of expression wins over readability.
7271 At an interactive shell prompt, conciseness of expression wins over readability.
7238 \layout Subsection
7272 \layout Subsection
7239
7273
7240 Useful functions and modules
7274 Useful functions and modules
7241 \layout Standard
7275 \layout Standard
7242
7276
7243 The os, sys and shutil modules from the Python standard library are automaticall
7277 The os, sys and shutil modules from the Python standard library are automaticall
7244 y loaded.
7278 y loaded.
7245 Some additional functions, useful for shell usage, are listed below.
7279 Some additional functions, useful for shell usage, are listed below.
7246 You can request more help about them with `
7280 You can request more help about them with `
7247 \family typewriter
7281 \family typewriter
7248 ?
7282 ?
7249 \family default
7283 \family default
7250 '.
7284 '.
7251 \layout Description
7285 \layout Description
7252
7286
7253
7287
7254 \family typewriter
7288 \family typewriter
7255 shell
7289 shell
7256 \family default
7290 \family default
7257 - execute a command in the underlying system shell
7291 - execute a command in the underlying system shell
7258 \layout Description
7292 \layout Description
7259
7293
7260
7294
7261 \family typewriter
7295 \family typewriter
7262 system
7296 system
7263 \family default
7297 \family default
7264 - like
7298 - like
7265 \family typewriter
7299 \family typewriter
7266 shell()
7300 shell()
7267 \family default
7301 \family default
7268 , but return the exit status of the command
7302 , but return the exit status of the command
7269 \layout Description
7303 \layout Description
7270
7304
7271
7305
7272 \family typewriter
7306 \family typewriter
7273 sout
7307 sout
7274 \family default
7308 \family default
7275 - capture the output of a command as a string
7309 - capture the output of a command as a string
7276 \layout Description
7310 \layout Description
7277
7311
7278
7312
7279 \family typewriter
7313 \family typewriter
7280 lout
7314 lout
7281 \family default
7315 \family default
7282 - capture the output of a command as a list (split on `
7316 - capture the output of a command as a list (split on `
7283 \backslash
7317 \backslash
7284 n')
7318 n')
7285 \layout Description
7319 \layout Description
7286
7320
7287
7321
7288 \family typewriter
7322 \family typewriter
7289 getoutputerror
7323 getoutputerror
7290 \family default
7324 \family default
7291 - capture (output,error) of a shell commandss
7325 - capture (output,error) of a shell commandss
7292 \layout Standard
7326 \layout Standard
7293
7327
7294
7328
7295 \family typewriter
7329 \family typewriter
7296 sout
7330 sout
7297 \family default
7331 \family default
7298 /
7332 /
7299 \family typewriter
7333 \family typewriter
7300 lout
7334 lout
7301 \family default
7335 \family default
7302 are the functional equivalents of
7336 are the functional equivalents of
7303 \family typewriter
7337 \family typewriter
7304 $
7338 $
7305 \family default
7339 \family default
7306 /
7340 /
7307 \family typewriter
7341 \family typewriter
7308 $$
7342 $$
7309 \family default
7343 \family default
7310 .
7344 .
7311 They are provided to allow you to capture system output in the middle of
7345 They are provided to allow you to capture system output in the middle of
7312 true python code, function definitions, etc (where
7346 true python code, function definitions, etc (where
7313 \family typewriter
7347 \family typewriter
7314 $
7348 $
7315 \family default
7349 \family default
7316 and
7350 and
7317 \family typewriter
7351 \family typewriter
7318 $$
7352 $$
7319 \family default
7353 \family default
7320 are invalid).
7354 are invalid).
7321 \layout Subsection
7355 \layout Subsection
7322
7356
7323 Directory management
7357 Directory management
7324 \layout Standard
7358 \layout Standard
7325
7359
7326 Since each command passed by pysh to the underlying system is executed in
7360 Since each command passed by pysh to the underlying system is executed in
7327 a subshell which exits immediately, you can NOT use !cd to navigate the
7361 a subshell which exits immediately, you can NOT use !cd to navigate the
7328 filesystem.
7362 filesystem.
7329 \layout Standard
7363 \layout Standard
7330
7364
7331 Pysh provides its own builtin
7365 Pysh provides its own builtin
7332 \family typewriter
7366 \family typewriter
7333 `%cd
7367 `%cd
7334 \family default
7368 \family default
7335 ' magic command to move in the filesystem (the
7369 ' magic command to move in the filesystem (the
7336 \family typewriter
7370 \family typewriter
7337 %
7371 %
7338 \family default
7372 \family default
7339 is not required with automagic on).
7373 is not required with automagic on).
7340 It also maintains a list of visited directories (use
7374 It also maintains a list of visited directories (use
7341 \family typewriter
7375 \family typewriter
7342 %dhist
7376 %dhist
7343 \family default
7377 \family default
7344 to see it) and allows direct switching to any of them.
7378 to see it) and allows direct switching to any of them.
7345 Type
7379 Type
7346 \family typewriter
7380 \family typewriter
7347 `cd?
7381 `cd?
7348 \family default
7382 \family default
7349 ' for more details.
7383 ' for more details.
7350 \layout Standard
7384 \layout Standard
7351
7385
7352
7386
7353 \family typewriter
7387 \family typewriter
7354 %pushd
7388 %pushd
7355 \family default
7389 \family default
7356 ,
7390 ,
7357 \family typewriter
7391 \family typewriter
7358 %popd
7392 %popd
7359 \family default
7393 \family default
7360 and
7394 and
7361 \family typewriter
7395 \family typewriter
7362 %dirs
7396 %dirs
7363 \family default
7397 \family default
7364 are provided for directory stack handling.
7398 are provided for directory stack handling.
7365 \layout Subsection
7399 \layout Subsection
7366
7400
7367 Prompt customization
7401 Prompt customization
7368 \layout Standard
7402 \layout Standard
7369
7403
7370 The supplied
7404 The supplied
7371 \family typewriter
7405 \family typewriter
7372 ipythonrc-pysh
7406 ipythonrc-pysh
7373 \family default
7407 \family default
7374 profile comes with an example of a very colored and detailed prompt, mainly
7408 profile comes with an example of a very colored and detailed prompt, mainly
7375 to serve as an illustration.
7409 to serve as an illustration.
7376 The valid escape sequences, besides color names, are:
7410 The valid escape sequences, besides color names, are:
7377 \layout Description
7411 \layout Description
7378
7412
7379
7413
7380 \backslash
7414 \backslash
7381 # - Prompt number.
7415 # - Prompt number.
7382 \layout Description
7416 \layout Description
7383
7417
7384
7418
7385 \backslash
7419 \backslash
7386 D - Dots, as many as there are digits in
7420 D - Dots, as many as there are digits in
7387 \backslash
7421 \backslash
7388 # (so they align).
7422 # (so they align).
7389 \layout Description
7423 \layout Description
7390
7424
7391
7425
7392 \backslash
7426 \backslash
7393 w - Current working directory (cwd).
7427 w - Current working directory (cwd).
7394 \layout Description
7428 \layout Description
7395
7429
7396
7430
7397 \backslash
7431 \backslash
7398 W - Basename of current working directory.
7432 W - Basename of current working directory.
7399 \layout Description
7433 \layout Description
7400
7434
7401
7435
7402 \backslash
7436 \backslash
7403 X
7437 X
7404 \emph on
7438 \emph on
7405 N
7439 N
7406 \emph default
7440 \emph default
7407 - Where
7441 - Where
7408 \emph on
7442 \emph on
7409 N
7443 N
7410 \emph default
7444 \emph default
7411 =0..5.
7445 =0..5.
7412 N terms of the cwd, with $HOME written as ~.
7446 N terms of the cwd, with $HOME written as ~.
7413 \layout Description
7447 \layout Description
7414
7448
7415
7449
7416 \backslash
7450 \backslash
7417 Y
7451 Y
7418 \emph on
7452 \emph on
7419 N
7453 N
7420 \emph default
7454 \emph default
7421 - Where
7455 - Where
7422 \emph on
7456 \emph on
7423 N
7457 N
7424 \emph default
7458 \emph default
7425 =0..5.
7459 =0..5.
7426 Like X
7460 Like X
7427 \emph on
7461 \emph on
7428 N
7462 N
7429 \emph default
7463 \emph default
7430 , but if ~ is term
7464 , but if ~ is term
7431 \emph on
7465 \emph on
7432 N
7466 N
7433 \emph default
7467 \emph default
7434 +1 it's also shown.
7468 +1 it's also shown.
7435 \layout Description
7469 \layout Description
7436
7470
7437
7471
7438 \backslash
7472 \backslash
7439 u - Username.
7473 u - Username.
7440 \layout Description
7474 \layout Description
7441
7475
7442
7476
7443 \backslash
7477 \backslash
7444 H - Full hostname.
7478 H - Full hostname.
7445 \layout Description
7479 \layout Description
7446
7480
7447
7481
7448 \backslash
7482 \backslash
7449 h - Hostname up to first '.'
7483 h - Hostname up to first '.'
7450 \layout Description
7484 \layout Description
7451
7485
7452
7486
7453 \backslash
7487 \backslash
7454 $ - Root symbol ($ or #).
7488 $ - Root symbol ($ or #).
7455
7489
7456 \layout Description
7490 \layout Description
7457
7491
7458
7492
7459 \backslash
7493 \backslash
7460 t - Current time, in H:M:S format.
7494 t - Current time, in H:M:S format.
7461 \layout Description
7495 \layout Description
7462
7496
7463
7497
7464 \backslash
7498 \backslash
7465 v - IPython release version.
7499 v - IPython release version.
7466
7500
7467 \layout Description
7501 \layout Description
7468
7502
7469
7503
7470 \backslash
7504 \backslash
7471 n - Newline.
7505 n - Newline.
7472
7506
7473 \layout Description
7507 \layout Description
7474
7508
7475
7509
7476 \backslash
7510 \backslash
7477 r - Carriage return.
7511 r - Carriage return.
7478
7512
7479 \layout Description
7513 \layout Description
7480
7514
7481
7515
7482 \backslash
7516 \backslash
7483
7517
7484 \backslash
7518 \backslash
7485 - An explicitly escaped '
7519 - An explicitly escaped '
7486 \backslash
7520 \backslash
7487 '.
7521 '.
7488 \layout Standard
7522 \layout Standard
7489
7523
7490 You can configure your prompt colors using any ANSI color escape.
7524 You can configure your prompt colors using any ANSI color escape.
7491 Each color escape sets the color for any subsequent text, until another
7525 Each color escape sets the color for any subsequent text, until another
7492 escape comes in and changes things.
7526 escape comes in and changes things.
7493 The valid color escapes are:
7527 The valid color escapes are:
7494 \layout Description
7528 \layout Description
7495
7529
7496
7530
7497 \backslash
7531 \backslash
7498 C_Black
7532 C_Black
7499 \layout Description
7533 \layout Description
7500
7534
7501
7535
7502 \backslash
7536 \backslash
7503 C_Blue
7537 C_Blue
7504 \layout Description
7538 \layout Description
7505
7539
7506
7540
7507 \backslash
7541 \backslash
7508 C_Brown
7542 C_Brown
7509 \layout Description
7543 \layout Description
7510
7544
7511
7545
7512 \backslash
7546 \backslash
7513 C_Cyan
7547 C_Cyan
7514 \layout Description
7548 \layout Description
7515
7549
7516
7550
7517 \backslash
7551 \backslash
7518 C_DarkGray
7552 C_DarkGray
7519 \layout Description
7553 \layout Description
7520
7554
7521
7555
7522 \backslash
7556 \backslash
7523 C_Green
7557 C_Green
7524 \layout Description
7558 \layout Description
7525
7559
7526
7560
7527 \backslash
7561 \backslash
7528 C_LightBlue
7562 C_LightBlue
7529 \layout Description
7563 \layout Description
7530
7564
7531
7565
7532 \backslash
7566 \backslash
7533 C_LightCyan
7567 C_LightCyan
7534 \layout Description
7568 \layout Description
7535
7569
7536
7570
7537 \backslash
7571 \backslash
7538 C_LightGray
7572 C_LightGray
7539 \layout Description
7573 \layout Description
7540
7574
7541
7575
7542 \backslash
7576 \backslash
7543 C_LightGreen
7577 C_LightGreen
7544 \layout Description
7578 \layout Description
7545
7579
7546
7580
7547 \backslash
7581 \backslash
7548 C_LightPurple
7582 C_LightPurple
7549 \layout Description
7583 \layout Description
7550
7584
7551
7585
7552 \backslash
7586 \backslash
7553 C_LightRed
7587 C_LightRed
7554 \layout Description
7588 \layout Description
7555
7589
7556
7590
7557 \backslash
7591 \backslash
7558 C_Purple
7592 C_Purple
7559 \layout Description
7593 \layout Description
7560
7594
7561
7595
7562 \backslash
7596 \backslash
7563 C_Red
7597 C_Red
7564 \layout Description
7598 \layout Description
7565
7599
7566
7600
7567 \backslash
7601 \backslash
7568 C_White
7602 C_White
7569 \layout Description
7603 \layout Description
7570
7604
7571
7605
7572 \backslash
7606 \backslash
7573 C_Yellow
7607 C_Yellow
7574 \layout Description
7608 \layout Description
7575
7609
7576
7610
7577 \backslash
7611 \backslash
7578 C_Normal Stop coloring, defaults to your terminal settings.
7612 C_Normal Stop coloring, defaults to your terminal settings.
7579 \layout Section
7613 \layout Section
7580
7614
7581
7615
7582 \begin_inset LatexCommand \label{sec:Threading-support}
7616 \begin_inset LatexCommand \label{sec:Threading-support}
7583
7617
7584 \end_inset
7618 \end_inset
7585
7619
7586 Threading support
7620 Threading support
7587 \layout Standard
7621 \layout Standard
7588
7622
7589
7623
7590 \series bold
7624 \series bold
7591 WARNING:
7625 WARNING:
7592 \series default
7626 \series default
7593 The threading support is still somewhat experimental, and it has only seen
7627 The threading support is still somewhat experimental, and it has only seen
7594 reasonable testing under Linux.
7628 reasonable testing under Linux.
7595 Threaded code is particularly tricky to debug, and it tends to show extremely
7629 Threaded code is particularly tricky to debug, and it tends to show extremely
7596 platform-dependent behavior.
7630 platform-dependent behavior.
7597 Since I only have access to Linux machines, I will have to rely on user's
7631 Since I only have access to Linux machines, I will have to rely on user's
7598 experiences and assistance for this area of IPython to improve under other
7632 experiences and assistance for this area of IPython to improve under other
7599 platforms.
7633 platforms.
7600 \layout Standard
7634 \layout Standard
7601
7635
7602 IPython, via the
7636 IPython, via the
7603 \family typewriter
7637 \family typewriter
7604 -gthread
7638 -gthread
7605 \family default
7639 \family default
7606 ,
7640 ,
7607 \family typewriter
7641 \family typewriter
7608 -qthread
7642 -qthread
7609 \family default
7643 \family default
7610 and
7644 and
7611 \family typewriter
7645 \family typewriter
7612 -wthread
7646 -wthread
7613 \family default
7647 \family default
7614 options (described in Sec.\SpecialChar ~
7648 options (described in Sec.\SpecialChar ~
7615
7649
7616 \begin_inset LatexCommand \ref{sec:threading-opts}
7650 \begin_inset LatexCommand \ref{sec:threading-opts}
7617
7651
7618 \end_inset
7652 \end_inset
7619
7653
7620 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7654 ), can run in multithreaded mode to support pyGTK, Qt and WXPython applications
7621 respectively.
7655 respectively.
7622 These GUI toolkits need to control the python main loop of execution, so
7656 These GUI toolkits need to control the python main loop of execution, so
7623 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7657 under a normal Python interpreter, starting a pyGTK, Qt or WXPython application
7624 will immediately freeze the shell.
7658 will immediately freeze the shell.
7625
7659
7626 \layout Standard
7660 \layout Standard
7627
7661
7628 IPython, with one of these options (you can only use one at a time), separates
7662 IPython, with one of these options (you can only use one at a time), separates
7629 the graphical loop and IPython's code execution run into different threads.
7663 the graphical loop and IPython's code execution run into different threads.
7630 This allows you to test interactively (with
7664 This allows you to test interactively (with
7631 \family typewriter
7665 \family typewriter
7632 %run
7666 %run
7633 \family default
7667 \family default
7634 , for example) your GUI code without blocking.
7668 , for example) your GUI code without blocking.
7635 \layout Standard
7669 \layout Standard
7636
7670
7637 A nice mini-tutorial on using IPython along with the Qt Designer application
7671 A nice mini-tutorial on using IPython along with the Qt Designer application
7638 is available at the SciPy wiki:
7672 is available at the SciPy wiki:
7639 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7673 \begin_inset LatexCommand \htmlurl{http://www.scipy.org/wikis/topical_software/QtWithIPythonAndDesigner}
7640
7674
7641 \end_inset
7675 \end_inset
7642
7676
7643 .
7677 .
7644 \layout Subsection
7678 \layout Subsection
7645
7679
7646 Tk issues
7680 Tk issues
7647 \layout Standard
7681 \layout Standard
7648
7682
7649 As indicated in Sec.\SpecialChar ~
7683 As indicated in Sec.\SpecialChar ~
7650
7684
7651 \begin_inset LatexCommand \ref{sec:threading-opts}
7685 \begin_inset LatexCommand \ref{sec:threading-opts}
7652
7686
7653 \end_inset
7687 \end_inset
7654
7688
7655 , a special
7689 , a special
7656 \family typewriter
7690 \family typewriter
7657 -tk
7691 -tk
7658 \family default
7692 \family default
7659 option is provided to try and allow Tk graphical applications to coexist
7693 option is provided to try and allow Tk graphical applications to coexist
7660 interactively with WX, Qt or GTK ones.
7694 interactively with WX, Qt or GTK ones.
7661 Whether this works at all, however, is very platform and configuration
7695 Whether this works at all, however, is very platform and configuration
7662 dependent.
7696 dependent.
7663 Please experiment with simple test cases before committing to using this
7697 Please experiment with simple test cases before committing to using this
7664 combination of Tk and GTK/Qt/WX threading in a production environment.
7698 combination of Tk and GTK/Qt/WX threading in a production environment.
7665 \layout Subsection
7699 \layout Subsection
7666
7700
7667 Signals and Threads
7701 Signals and Threads
7668 \layout Standard
7702 \layout Standard
7669
7703
7670 When any of the thread systems (GTK, Qt or WX) are active, either directly
7704 When any of the thread systems (GTK, Qt or WX) are active, either directly
7671 or via
7705 or via
7672 \family typewriter
7706 \family typewriter
7673 -pylab
7707 -pylab
7674 \family default
7708 \family default
7675 with a threaded backend, it is impossible to interrupt long-running Python
7709 with a threaded backend, it is impossible to interrupt long-running Python
7676 code via
7710 code via
7677 \family typewriter
7711 \family typewriter
7678 Ctrl-C
7712 Ctrl-C
7679 \family default
7713 \family default
7680 .
7714 .
7681 IPython can not pass the KeyboardInterrupt exception (or the underlying
7715 IPython can not pass the KeyboardInterrupt exception (or the underlying
7682
7716
7683 \family typewriter
7717 \family typewriter
7684 SIGINT
7718 SIGINT
7685 \family default
7719 \family default
7686 ) across threads, so any long-running process started from IPython will
7720 ) across threads, so any long-running process started from IPython will
7687 run to completion, or will have to be killed via an external (OS-based)
7721 run to completion, or will have to be killed via an external (OS-based)
7688 mechanism.
7722 mechanism.
7689 \layout Standard
7723 \layout Standard
7690
7724
7691 To the best of my knowledge, this limitation is imposed by the Python interprete
7725 To the best of my knowledge, this limitation is imposed by the Python interprete
7692 r itself, and it comes from the difficulty of writing portable signal/threaded
7726 r itself, and it comes from the difficulty of writing portable signal/threaded
7693 code.
7727 code.
7694 If any user is an expert on this topic and can suggest a better solution,
7728 If any user is an expert on this topic and can suggest a better solution,
7695 I would love to hear about it.
7729 I would love to hear about it.
7696 In the IPython sources, look at the
7730 In the IPython sources, look at the
7697 \family typewriter
7731 \family typewriter
7698 Shell.py
7732 Shell.py
7699 \family default
7733 \family default
7700 module, and in particular at the
7734 module, and in particular at the
7701 \family typewriter
7735 \family typewriter
7702 runcode()
7736 runcode()
7703 \family default
7737 \family default
7704 method.
7738 method.
7705
7739
7706 \layout Subsection
7740 \layout Subsection
7707
7741
7708 I/O pitfalls
7742 I/O pitfalls
7709 \layout Standard
7743 \layout Standard
7710
7744
7711 Be mindful that the Python interpreter switches between threads every
7745 Be mindful that the Python interpreter switches between threads every
7712 \begin_inset Formula $N$
7746 \begin_inset Formula $N$
7713 \end_inset
7747 \end_inset
7714
7748
7715 bytecodes, where the default value as of Python\SpecialChar ~
7749 bytecodes, where the default value as of Python\SpecialChar ~
7716 2.3 is
7750 2.3 is
7717 \begin_inset Formula $N=100.$
7751 \begin_inset Formula $N=100.$
7718 \end_inset
7752 \end_inset
7719
7753
7720 This value can be read by using the
7754 This value can be read by using the
7721 \family typewriter
7755 \family typewriter
7722 sys.getcheckinterval()
7756 sys.getcheckinterval()
7723 \family default
7757 \family default
7724 function, and it can be reset via
7758 function, and it can be reset via
7725 \family typewriter
7759 \family typewriter
7726 sys.setcheckinterval(
7760 sys.setcheckinterval(
7727 \emph on
7761 \emph on
7728 N
7762 N
7729 \emph default
7763 \emph default
7730 )
7764 )
7731 \family default
7765 \family default
7732 .
7766 .
7733 This switching of threads can cause subtly confusing effects if one of
7767 This switching of threads can cause subtly confusing effects if one of
7734 your threads is doing file I/O.
7768 your threads is doing file I/O.
7735 In text mode, most systems only flush file buffers when they encounter
7769 In text mode, most systems only flush file buffers when they encounter
7736 a
7770 a
7737 \family typewriter
7771 \family typewriter
7738 `
7772 `
7739 \backslash
7773 \backslash
7740 n'
7774 n'
7741 \family default
7775 \family default
7742 .
7776 .
7743 An instruction as simple as
7777 An instruction as simple as
7744 \family typewriter
7778 \family typewriter
7745
7779
7746 \newline
7780 \newline
7747 \SpecialChar ~
7781 \SpecialChar ~
7748 \SpecialChar ~
7782 \SpecialChar ~
7749 print >> filehandle,
7783 print >> filehandle,
7750 \begin_inset Quotes eld
7784 \begin_inset Quotes eld
7751 \end_inset
7785 \end_inset
7752
7786
7753 hello world
7787 hello world
7754 \begin_inset Quotes erd
7788 \begin_inset Quotes erd
7755 \end_inset
7789 \end_inset
7756
7790
7757
7791
7758 \family default
7792 \family default
7759
7793
7760 \newline
7794 \newline
7761 actually consists of several bytecodes, so it is possible that the newline
7795 actually consists of several bytecodes, so it is possible that the newline
7762 does not reach your file before the next thread switch.
7796 does not reach your file before the next thread switch.
7763 Similarly, if you are writing to a file in binary mode, the file won't
7797 Similarly, if you are writing to a file in binary mode, the file won't
7764 be flushed until the buffer fills, and your other thread may see apparently
7798 be flushed until the buffer fills, and your other thread may see apparently
7765 truncated files.
7799 truncated files.
7766
7800
7767 \layout Standard
7801 \layout Standard
7768
7802
7769 For this reason, if you are using IPython's thread support and have (for
7803 For this reason, if you are using IPython's thread support and have (for
7770 example) a GUI application which will read data generated by files written
7804 example) a GUI application which will read data generated by files written
7771 to from the IPython thread, the safest approach is to open all of your
7805 to from the IPython thread, the safest approach is to open all of your
7772 files in unbuffered mode (the third argument to the
7806 files in unbuffered mode (the third argument to the
7773 \family typewriter
7807 \family typewriter
7774 file/open
7808 file/open
7775 \family default
7809 \family default
7776 function is the buffering value):
7810 function is the buffering value):
7777 \newline
7811 \newline
7778
7812
7779 \family typewriter
7813 \family typewriter
7780 \SpecialChar ~
7814 \SpecialChar ~
7781 \SpecialChar ~
7815 \SpecialChar ~
7782 filehandle = open(filename,mode,0)
7816 filehandle = open(filename,mode,0)
7783 \layout Standard
7817 \layout Standard
7784
7818
7785 This is obviously a brute force way of avoiding race conditions with the
7819 This is obviously a brute force way of avoiding race conditions with the
7786 file buffering.
7820 file buffering.
7787 If you want to do it cleanly, and you have a resource which is being shared
7821 If you want to do it cleanly, and you have a resource which is being shared
7788 by the interactive IPython loop and your GUI thread, you should really
7822 by the interactive IPython loop and your GUI thread, you should really
7789 handle it with thread locking and syncrhonization properties.
7823 handle it with thread locking and syncrhonization properties.
7790 The Python documentation discusses these.
7824 The Python documentation discusses these.
7791 \layout Section
7825 \layout Section
7792
7826
7793
7827
7794 \begin_inset LatexCommand \label{sec:interactive-demos}
7828 \begin_inset LatexCommand \label{sec:interactive-demos}
7795
7829
7796 \end_inset
7830 \end_inset
7797
7831
7798 Interactive demos with IPython
7832 Interactive demos with IPython
7799 \layout Standard
7833 \layout Standard
7800
7834
7801 IPython ships with a basic system for running scripts interactively in sections,
7835 IPython ships with a basic system for running scripts interactively in sections,
7802 useful when presenting code to audiences.
7836 useful when presenting code to audiences.
7803 A few tags embedded in comments (so that the script remains valid Python
7837 A few tags embedded in comments (so that the script remains valid Python
7804 code) divide a file into separate blocks, and the demo can be run one block
7838 code) divide a file into separate blocks, and the demo can be run one block
7805 at a time, with IPython printing (with syntax highlighting) the block before
7839 at a time, with IPython printing (with syntax highlighting) the block before
7806 executing it, and returning to the interactive prompt after each block.
7840 executing it, and returning to the interactive prompt after each block.
7807 The interactive namespace is updated after each block is run with the contents
7841 The interactive namespace is updated after each block is run with the contents
7808 of the demo's namespace.
7842 of the demo's namespace.
7809 \layout Standard
7843 \layout Standard
7810
7844
7811 This allows you to show a piece of code, run it and then execute interactively
7845 This allows you to show a piece of code, run it and then execute interactively
7812 commands based on the variables just created.
7846 commands based on the variables just created.
7813 Once you want to continue, you simply execute the next block of the demo.
7847 Once you want to continue, you simply execute the next block of the demo.
7814 The following listing shows the markup necessary for dividing a script
7848 The following listing shows the markup necessary for dividing a script
7815 into sections for execution as a demo.
7849 into sections for execution as a demo.
7816 \layout Standard
7850 \layout Standard
7817
7851
7818
7852
7819 \begin_inset ERT
7853 \begin_inset ERT
7820 status Open
7854 status Open
7821
7855
7822 \layout Standard
7856 \layout Standard
7823
7857
7824 \backslash
7858 \backslash
7825 codelist{examples/example-demo.py}
7859 codelist{examples/example-demo.py}
7826 \end_inset
7860 \end_inset
7827
7861
7828
7862
7829 \layout Standard
7863 \layout Standard
7830
7864
7831 In order to run a file as a demo, you must first make a
7865 In order to run a file as a demo, you must first make a
7832 \family typewriter
7866 \family typewriter
7833 Demo
7867 Demo
7834 \family default
7868 \family default
7835 object out of it.
7869 object out of it.
7836 If the file is named
7870 If the file is named
7837 \family typewriter
7871 \family typewriter
7838 myscript.py
7872 myscript.py
7839 \family default
7873 \family default
7840 , the following code will make a demo:
7874 , the following code will make a demo:
7841 \layout LyX-Code
7875 \layout LyX-Code
7842
7876
7843 from IPython.demo import Demo
7877 from IPython.demo import Demo
7844 \layout LyX-Code
7878 \layout LyX-Code
7845
7879
7846 mydemo = Demo('myscript.py')
7880 mydemo = Demo('myscript.py')
7847 \layout Standard
7881 \layout Standard
7848
7882
7849 This creates the
7883 This creates the
7850 \family typewriter
7884 \family typewriter
7851 mydemo
7885 mydemo
7852 \family default
7886 \family default
7853 object, whose blocks you run one at a time by simply calling the object
7887 object, whose blocks you run one at a time by simply calling the object
7854 with no arguments.
7888 with no arguments.
7855 If you have autocall active in IPython (the default), all you need to do
7889 If you have autocall active in IPython (the default), all you need to do
7856 is type
7890 is type
7857 \layout LyX-Code
7891 \layout LyX-Code
7858
7892
7859 mydemo
7893 mydemo
7860 \layout Standard
7894 \layout Standard
7861
7895
7862 and IPython will call it, executing each block.
7896 and IPython will call it, executing each block.
7863 Demo objects can be restarted, you can move forward or back skipping blocks,
7897 Demo objects can be restarted, you can move forward or back skipping blocks,
7864 re-execute the last block, etc.
7898 re-execute the last block, etc.
7865 Simply use the Tab key on a demo object to see its methods, and call
7899 Simply use the Tab key on a demo object to see its methods, and call
7866 \family typewriter
7900 \family typewriter
7867 `?'
7901 `?'
7868 \family default
7902 \family default
7869 on them to see their docstrings for more usage details.
7903 on them to see their docstrings for more usage details.
7870 In addition, the
7904 In addition, the
7871 \family typewriter
7905 \family typewriter
7872 demo
7906 demo
7873 \family default
7907 \family default
7874 module itself contains a comprehensive docstring, which you can access
7908 module itself contains a comprehensive docstring, which you can access
7875 via
7909 via
7876 \layout LyX-Code
7910 \layout LyX-Code
7877
7911
7878 from IPython import demo
7912 from IPython import demo
7879 \layout LyX-Code
7913 \layout LyX-Code
7880
7914
7881 demo?
7915 demo?
7882 \layout Standard
7916 \layout Standard
7883
7917
7884
7918
7885 \series bold
7919 \series bold
7886 Limitations:
7920 Limitations:
7887 \series default
7921 \series default
7888 It is important to note that these demos are limited to fairly simple uses.
7922 It is important to note that these demos are limited to fairly simple uses.
7889 In particular, you can
7923 In particular, you can
7890 \emph on
7924 \emph on
7891 not
7925 not
7892 \emph default
7926 \emph default
7893 put division marks in indented code (loops, if statements, function definitions
7927 put division marks in indented code (loops, if statements, function definitions
7894 , etc.) Supporting something like this would basically require tracking the
7928 , etc.) Supporting something like this would basically require tracking the
7895 internal execution state of the Python interpreter, so only top-level divisions
7929 internal execution state of the Python interpreter, so only top-level divisions
7896 are allowed.
7930 are allowed.
7897 If you want to be able to open an IPython instance at an arbitrary point
7931 If you want to be able to open an IPython instance at an arbitrary point
7898 in a program, you can use IPython's embedding facilities, described in
7932 in a program, you can use IPython's embedding facilities, described in
7899 detail in Sec\SpecialChar \@.
7933 detail in Sec\SpecialChar \@.
7900 \SpecialChar ~
7934 \SpecialChar ~
7901
7935
7902 \begin_inset LatexCommand \ref{sec:embed}
7936 \begin_inset LatexCommand \ref{sec:embed}
7903
7937
7904 \end_inset
7938 \end_inset
7905
7939
7906 .
7940 .
7907 \layout Section
7941 \layout Section
7908
7942
7909
7943
7910 \begin_inset LatexCommand \label{sec:matplotlib-support}
7944 \begin_inset LatexCommand \label{sec:matplotlib-support}
7911
7945
7912 \end_inset
7946 \end_inset
7913
7947
7914 Plotting with
7948 Plotting with
7915 \family typewriter
7949 \family typewriter
7916 matplotlib
7950 matplotlib
7917 \family default
7951 \family default
7918
7952
7919 \layout Standard
7953 \layout Standard
7920
7954
7921 The matplotlib library (
7955 The matplotlib library (
7922 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
7956 \begin_inset LatexCommand \htmlurl[http://matplotlib.sourceforge.net]{http://matplotlib.sourceforge.net}
7923
7957
7924 \end_inset
7958 \end_inset
7925
7959
7926 ) provides high quality 2D plotting for Python.
7960 ) provides high quality 2D plotting for Python.
7927 Matplotlib can produce plots on screen using a variety of GUI toolkits,
7961 Matplotlib can produce plots on screen using a variety of GUI toolkits,
7928 including Tk, GTK and WXPython.
7962 including Tk, GTK and WXPython.
7929 It also provides a number of commands useful for scientific computing,
7963 It also provides a number of commands useful for scientific computing,
7930 all with a syntax compatible with that of the popular Matlab program.
7964 all with a syntax compatible with that of the popular Matlab program.
7931 \layout Standard
7965 \layout Standard
7932
7966
7933 IPython accepts the special option
7967 IPython accepts the special option
7934 \family typewriter
7968 \family typewriter
7935 -pylab
7969 -pylab
7936 \family default
7970 \family default
7937 (Sec.\SpecialChar ~
7971 (Sec.\SpecialChar ~
7938
7972
7939 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
7973 \begin_inset LatexCommand \ref{sec:cmd-line-opts}
7940
7974
7941 \end_inset
7975 \end_inset
7942
7976
7943 ).
7977 ).
7944 This configures it to support matplotlib, honoring the settings in the
7978 This configures it to support matplotlib, honoring the settings in the
7945
7979
7946 \family typewriter
7980 \family typewriter
7947 .matplotlibrc
7981 .matplotlibrc
7948 \family default
7982 \family default
7949 file.
7983 file.
7950 IPython will detect the user's choice of matplotlib GUI backend, and automatica
7984 IPython will detect the user's choice of matplotlib GUI backend, and automatica
7951 lly select the proper threading model to prevent blocking.
7985 lly select the proper threading model to prevent blocking.
7952 It also sets matplotlib in interactive mode and modifies
7986 It also sets matplotlib in interactive mode and modifies
7953 \family typewriter
7987 \family typewriter
7954 %run
7988 %run
7955 \family default
7989 \family default
7956 slightly, so that any matplotlib-based script can be executed using
7990 slightly, so that any matplotlib-based script can be executed using
7957 \family typewriter
7991 \family typewriter
7958 %run
7992 %run
7959 \family default
7993 \family default
7960 and the final
7994 and the final
7961 \family typewriter
7995 \family typewriter
7962 show()
7996 show()
7963 \family default
7997 \family default
7964 command does not block the interactive shell.
7998 command does not block the interactive shell.
7965 \layout Standard
7999 \layout Standard
7966
8000
7967 The
8001 The
7968 \family typewriter
8002 \family typewriter
7969 -pylab
8003 -pylab
7970 \family default
8004 \family default
7971 option must be given first in order for IPython to configure its threading
8005 option must be given first in order for IPython to configure its threading
7972 mode.
8006 mode.
7973 However, you can still issue other options afterwards.
8007 However, you can still issue other options afterwards.
7974 This allows you to have a matplotlib-based environment customized with
8008 This allows you to have a matplotlib-based environment customized with
7975 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
8009 additional modules using the standard IPython profile mechanism (Sec.\SpecialChar ~
7976
8010
7977 \begin_inset LatexCommand \ref{sec:profiles}
8011 \begin_inset LatexCommand \ref{sec:profiles}
7978
8012
7979 \end_inset
8013 \end_inset
7980
8014
7981 ): ``
8015 ): ``
7982 \family typewriter
8016 \family typewriter
7983 ipython -pylab -p myprofile
8017 ipython -pylab -p myprofile
7984 \family default
8018 \family default
7985 '' will load the profile defined in
8019 '' will load the profile defined in
7986 \family typewriter
8020 \family typewriter
7987 ipythonrc-myprofile
8021 ipythonrc-myprofile
7988 \family default
8022 \family default
7989 after configuring matplotlib.
8023 after configuring matplotlib.
7990 \layout Section
8024 \layout Section
7991
8025
7992
8026
7993 \begin_inset LatexCommand \label{sec:Gnuplot}
8027 \begin_inset LatexCommand \label{sec:Gnuplot}
7994
8028
7995 \end_inset
8029 \end_inset
7996
8030
7997 Plotting with
8031 Plotting with
7998 \family typewriter
8032 \family typewriter
7999 Gnuplot
8033 Gnuplot
8000 \layout Standard
8034 \layout Standard
8001
8035
8002 Through the magic extension system described in sec.
8036 Through the magic extension system described in sec.
8003
8037
8004 \begin_inset LatexCommand \ref{sec:magic}
8038 \begin_inset LatexCommand \ref{sec:magic}
8005
8039
8006 \end_inset
8040 \end_inset
8007
8041
8008 , IPython incorporates a mechanism for conveniently interfacing with the
8042 , IPython incorporates a mechanism for conveniently interfacing with the
8009 Gnuplot system (
8043 Gnuplot system (
8010 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8044 \begin_inset LatexCommand \htmlurl{http://www.gnuplot.info}
8011
8045
8012 \end_inset
8046 \end_inset
8013
8047
8014 ).
8048 ).
8015 Gnuplot is a very complete 2D and 3D plotting package available for many
8049 Gnuplot is a very complete 2D and 3D plotting package available for many
8016 operating systems and commonly included in modern Linux distributions.
8050 operating systems and commonly included in modern Linux distributions.
8017
8051
8018 \layout Standard
8052 \layout Standard
8019
8053
8020 Besides having Gnuplot installed, this functionality requires the
8054 Besides having Gnuplot installed, this functionality requires the
8021 \family typewriter
8055 \family typewriter
8022 Gnuplot.py
8056 Gnuplot.py
8023 \family default
8057 \family default
8024 module for interfacing python with Gnuplot.
8058 module for interfacing python with Gnuplot.
8025 It can be downloaded from:
8059 It can be downloaded from:
8026 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8060 \begin_inset LatexCommand \htmlurl{http://gnuplot-py.sourceforge.net}
8027
8061
8028 \end_inset
8062 \end_inset
8029
8063
8030 .
8064 .
8031 \layout Subsection
8065 \layout Subsection
8032
8066
8033 Proper Gnuplot configuration
8067 Proper Gnuplot configuration
8034 \layout Standard
8068 \layout Standard
8035
8069
8036 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8070 As of version 4.0, Gnuplot has excellent mouse and interactive keyboard support.
8037 However, as of
8071 However, as of
8038 \family typewriter
8072 \family typewriter
8039 Gnuplot.py
8073 Gnuplot.py
8040 \family default
8074 \family default
8041 version 1.7, a new option was added to communicate between Python and Gnuplot
8075 version 1.7, a new option was added to communicate between Python and Gnuplot
8042 via FIFOs (pipes).
8076 via FIFOs (pipes).
8043 This mechanism, while fast, also breaks the mouse system.
8077 This mechanism, while fast, also breaks the mouse system.
8044 You must therefore set the variable
8078 You must therefore set the variable
8045 \family typewriter
8079 \family typewriter
8046 prefer_fifo_data
8080 prefer_fifo_data
8047 \family default
8081 \family default
8048 to
8082 to
8049 \family typewriter
8083 \family typewriter
8050 0
8084 0
8051 \family default
8085 \family default
8052 in file
8086 in file
8053 \family typewriter
8087 \family typewriter
8054 gp_unix.py
8088 gp_unix.py
8055 \family default
8089 \family default
8056 if you wish to keep the interactive mouse and keyboard features working
8090 if you wish to keep the interactive mouse and keyboard features working
8057 properly (
8091 properly (
8058 \family typewriter
8092 \family typewriter
8059 prefer_inline_data
8093 prefer_inline_data
8060 \family default
8094 \family default
8061 also must be
8095 also must be
8062 \family typewriter
8096 \family typewriter
8063 0
8097 0
8064 \family default
8098 \family default
8065 , but this is the default so unless you've changed it manually you should
8099 , but this is the default so unless you've changed it manually you should
8066 be fine).
8100 be fine).
8067 \layout Standard
8101 \layout Standard
8068
8102
8069 'Out of the box', Gnuplot is configured with a rather poor set of size,
8103 'Out of the box', Gnuplot is configured with a rather poor set of size,
8070 color and linewidth choices which make the graphs fairly hard to read on
8104 color and linewidth choices which make the graphs fairly hard to read on
8071 modern high-resolution displays (although they work fine on old 640x480
8105 modern high-resolution displays (although they work fine on old 640x480
8072 ones).
8106 ones).
8073 Below is a section of my
8107 Below is a section of my
8074 \family typewriter
8108 \family typewriter
8075 .Xdefaults
8109 .Xdefaults
8076 \family default
8110 \family default
8077 file which I use for having a more convenient Gnuplot setup.
8111 file which I use for having a more convenient Gnuplot setup.
8078 Remember to load it by running
8112 Remember to load it by running
8079 \family typewriter
8113 \family typewriter
8080 `xrdb .Xdefaults`
8114 `xrdb .Xdefaults`
8081 \family default
8115 \family default
8082 :
8116 :
8083 \layout Standard
8117 \layout Standard
8084
8118
8085
8119
8086 \family typewriter
8120 \family typewriter
8087 !******************************************************************
8121 !******************************************************************
8088 \newline
8122 \newline
8089 ! gnuplot options
8123 ! gnuplot options
8090 \newline
8124 \newline
8091 ! modify this for a convenient window size
8125 ! modify this for a convenient window size
8092 \newline
8126 \newline
8093 gnuplot*geometry: 780x580
8127 gnuplot*geometry: 780x580
8094 \layout Standard
8128 \layout Standard
8095
8129
8096
8130
8097 \family typewriter
8131 \family typewriter
8098 ! on-screen font (not for PostScript)
8132 ! on-screen font (not for PostScript)
8099 \newline
8133 \newline
8100 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8134 gnuplot*font: -misc-fixed-bold-r-normal--15-120-100-100-c-90-iso8859-1
8101 \layout Standard
8135 \layout Standard
8102
8136
8103
8137
8104 \family typewriter
8138 \family typewriter
8105 ! color options
8139 ! color options
8106 \newline
8140 \newline
8107 gnuplot*background: black
8141 gnuplot*background: black
8108 \newline
8142 \newline
8109 gnuplot*textColor: white
8143 gnuplot*textColor: white
8110 \newline
8144 \newline
8111 gnuplot*borderColor: white
8145 gnuplot*borderColor: white
8112 \newline
8146 \newline
8113 gnuplot*axisColor: white
8147 gnuplot*axisColor: white
8114 \newline
8148 \newline
8115 gnuplot*line1Color: red
8149 gnuplot*line1Color: red
8116 \newline
8150 \newline
8117 gnuplot*line2Color: green
8151 gnuplot*line2Color: green
8118 \newline
8152 \newline
8119 gnuplot*line3Color: blue
8153 gnuplot*line3Color: blue
8120 \newline
8154 \newline
8121 gnuplot*line4Color: magenta
8155 gnuplot*line4Color: magenta
8122 \newline
8156 \newline
8123 gnuplot*line5Color: cyan
8157 gnuplot*line5Color: cyan
8124 \newline
8158 \newline
8125 gnuplot*line6Color: sienna
8159 gnuplot*line6Color: sienna
8126 \newline
8160 \newline
8127 gnuplot*line7Color: orange
8161 gnuplot*line7Color: orange
8128 \newline
8162 \newline
8129 gnuplot*line8Color: coral
8163 gnuplot*line8Color: coral
8130 \layout Standard
8164 \layout Standard
8131
8165
8132
8166
8133 \family typewriter
8167 \family typewriter
8134 ! multiplicative factor for point styles
8168 ! multiplicative factor for point styles
8135 \newline
8169 \newline
8136 gnuplot*pointsize: 2
8170 gnuplot*pointsize: 2
8137 \layout Standard
8171 \layout Standard
8138
8172
8139
8173
8140 \family typewriter
8174 \family typewriter
8141 ! line width options (in pixels)
8175 ! line width options (in pixels)
8142 \newline
8176 \newline
8143 gnuplot*borderWidth: 2
8177 gnuplot*borderWidth: 2
8144 \newline
8178 \newline
8145 gnuplot*axisWidth: 2
8179 gnuplot*axisWidth: 2
8146 \newline
8180 \newline
8147 gnuplot*line1Width: 2
8181 gnuplot*line1Width: 2
8148 \newline
8182 \newline
8149 gnuplot*line2Width: 2
8183 gnuplot*line2Width: 2
8150 \newline
8184 \newline
8151 gnuplot*line3Width: 2
8185 gnuplot*line3Width: 2
8152 \newline
8186 \newline
8153 gnuplot*line4Width: 2
8187 gnuplot*line4Width: 2
8154 \newline
8188 \newline
8155 gnuplot*line5Width: 2
8189 gnuplot*line5Width: 2
8156 \newline
8190 \newline
8157 gnuplot*line6Width: 2
8191 gnuplot*line6Width: 2
8158 \newline
8192 \newline
8159 gnuplot*line7Width: 2
8193 gnuplot*line7Width: 2
8160 \newline
8194 \newline
8161 gnuplot*line8Width: 2
8195 gnuplot*line8Width: 2
8162 \layout Subsection
8196 \layout Subsection
8163
8197
8164 The
8198 The
8165 \family typewriter
8199 \family typewriter
8166 IPython.GnuplotRuntime
8200 IPython.GnuplotRuntime
8167 \family default
8201 \family default
8168 module
8202 module
8169 \layout Standard
8203 \layout Standard
8170
8204
8171 IPython includes a module called
8205 IPython includes a module called
8172 \family typewriter
8206 \family typewriter
8173 Gnuplot2.py
8207 Gnuplot2.py
8174 \family default
8208 \family default
8175 which extends and improves the default
8209 which extends and improves the default
8176 \family typewriter
8210 \family typewriter
8177 Gnuplot
8211 Gnuplot
8178 \family default
8212 \family default
8179 .
8213 .
8180 \family typewriter
8214 \family typewriter
8181 py
8215 py
8182 \family default
8216 \family default
8183 (which it still relies upon).
8217 (which it still relies upon).
8184 For example, the new
8218 For example, the new
8185 \family typewriter
8219 \family typewriter
8186 plot
8220 plot
8187 \family default
8221 \family default
8188 function adds several improvements to the original making it more convenient
8222 function adds several improvements to the original making it more convenient
8189 for interactive use, and
8223 for interactive use, and
8190 \family typewriter
8224 \family typewriter
8191 hardcopy
8225 hardcopy
8192 \family default
8226 \family default
8193 fixes a bug in the original which under some circumstances blocks the creation
8227 fixes a bug in the original which under some circumstances blocks the creation
8194 of PostScript output.
8228 of PostScript output.
8195 \layout Standard
8229 \layout Standard
8196
8230
8197 For scripting use,
8231 For scripting use,
8198 \family typewriter
8232 \family typewriter
8199 GnuplotRuntime.py
8233 GnuplotRuntime.py
8200 \family default
8234 \family default
8201 is provided, which wraps
8235 is provided, which wraps
8202 \family typewriter
8236 \family typewriter
8203 Gnuplot2.py
8237 Gnuplot2.py
8204 \family default
8238 \family default
8205 and creates a series of global aliases.
8239 and creates a series of global aliases.
8206 These make it easy to control Gnuplot plotting jobs through the Python
8240 These make it easy to control Gnuplot plotting jobs through the Python
8207 language.
8241 language.
8208 \layout Standard
8242 \layout Standard
8209
8243
8210 Below is some example code which illustrates how to configure Gnuplot inside
8244 Below is some example code which illustrates how to configure Gnuplot inside
8211 your own programs but have it available for further interactive use through
8245 your own programs but have it available for further interactive use through
8212 an embedded IPython instance.
8246 an embedded IPython instance.
8213 Simply run this file at a system prompt.
8247 Simply run this file at a system prompt.
8214 This file is provided as
8248 This file is provided as
8215 \family typewriter
8249 \family typewriter
8216 example-gnuplot.py
8250 example-gnuplot.py
8217 \family default
8251 \family default
8218 in the examples directory:
8252 in the examples directory:
8219 \layout Standard
8253 \layout Standard
8220
8254
8221
8255
8222 \begin_inset ERT
8256 \begin_inset ERT
8223 status Open
8257 status Open
8224
8258
8225 \layout Standard
8259 \layout Standard
8226
8260
8227 \backslash
8261 \backslash
8228 codelist{examples/example-gnuplot.py}
8262 codelist{examples/example-gnuplot.py}
8229 \end_inset
8263 \end_inset
8230
8264
8231
8265
8232 \layout Subsection
8266 \layout Subsection
8233
8267
8234 The
8268 The
8235 \family typewriter
8269 \family typewriter
8236 numeric
8270 numeric
8237 \family default
8271 \family default
8238 profile: a scientific computing environment
8272 profile: a scientific computing environment
8239 \layout Standard
8273 \layout Standard
8240
8274
8241 The
8275 The
8242 \family typewriter
8276 \family typewriter
8243 numeric
8277 numeric
8244 \family default
8278 \family default
8245 IPython profile, which you can activate with
8279 IPython profile, which you can activate with
8246 \family typewriter
8280 \family typewriter
8247 `ipython -p numeric
8281 `ipython -p numeric
8248 \family default
8282 \family default
8249 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8283 ' will automatically load the IPython Gnuplot extensions (plus Numeric and
8250 other useful things for numerical computing), contained in the
8284 other useful things for numerical computing), contained in the
8251 \family typewriter
8285 \family typewriter
8252 IPython.GnuplotInteractive
8286 IPython.GnuplotInteractive
8253 \family default
8287 \family default
8254 module.
8288 module.
8255 This will create the globals
8289 This will create the globals
8256 \family typewriter
8290 \family typewriter
8257 Gnuplot
8291 Gnuplot
8258 \family default
8292 \family default
8259 (an alias to the improved Gnuplot2 module),
8293 (an alias to the improved Gnuplot2 module),
8260 \family typewriter
8294 \family typewriter
8261 gp
8295 gp
8262 \family default
8296 \family default
8263 (a Gnuplot active instance), the new magic commands
8297 (a Gnuplot active instance), the new magic commands
8264 \family typewriter
8298 \family typewriter
8265 %gpc
8299 %gpc
8266 \family default
8300 \family default
8267 and
8301 and
8268 \family typewriter
8302 \family typewriter
8269 %gp_set_instance
8303 %gp_set_instance
8270 \family default
8304 \family default
8271 and several other convenient globals.
8305 and several other convenient globals.
8272 Type
8306 Type
8273 \family typewriter
8307 \family typewriter
8274 gphelp()
8308 gphelp()
8275 \family default
8309 \family default
8276 for further details.
8310 for further details.
8277 \layout Standard
8311 \layout Standard
8278
8312
8279 This should turn IPython into a convenient environment for numerical computing,
8313 This should turn IPython into a convenient environment for numerical computing,
8280 with all the functions in the NumPy library and the Gnuplot facilities
8314 with all the functions in the NumPy library and the Gnuplot facilities
8281 for plotting.
8315 for plotting.
8282 Further improvements can be obtained by loading the SciPy libraries for
8316 Further improvements can be obtained by loading the SciPy libraries for
8283 scientific computing, available at
8317 scientific computing, available at
8284 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8318 \begin_inset LatexCommand \htmlurl{http://scipy.org}
8285
8319
8286 \end_inset
8320 \end_inset
8287
8321
8288 .
8322 .
8289 \layout Standard
8323 \layout Standard
8290
8324
8291 If you are in the middle of a working session with numerical objects and
8325 If you are in the middle of a working session with numerical objects and
8292 need to plot them but you didn't start the
8326 need to plot them but you didn't start the
8293 \family typewriter
8327 \family typewriter
8294 numeric
8328 numeric
8295 \family default
8329 \family default
8296 profile, you can load these extensions at any time by typing
8330 profile, you can load these extensions at any time by typing
8297 \newline
8331 \newline
8298
8332
8299 \family typewriter
8333 \family typewriter
8300 from IPython.GnuplotInteractive import *
8334 from IPython.GnuplotInteractive import *
8301 \newline
8335 \newline
8302
8336
8303 \family default
8337 \family default
8304 at the IPython prompt.
8338 at the IPython prompt.
8305 This will allow you to keep your objects intact and start using Gnuplot
8339 This will allow you to keep your objects intact and start using Gnuplot
8306 to view them.
8340 to view them.
8307 \layout Section
8341 \layout Section
8308
8342
8309 Reporting bugs
8343 Reporting bugs
8310 \layout Subsection*
8344 \layout Subsection*
8311
8345
8312 Automatic crash reports
8346 Automatic crash reports
8313 \layout Standard
8347 \layout Standard
8314
8348
8315 Ideally, IPython itself shouldn't crash.
8349 Ideally, IPython itself shouldn't crash.
8316 It will catch exceptions produced by you, but bugs in its internals will
8350 It will catch exceptions produced by you, but bugs in its internals will
8317 still crash it.
8351 still crash it.
8318 \layout Standard
8352 \layout Standard
8319
8353
8320 In such a situation, IPython will leave a file named
8354 In such a situation, IPython will leave a file named
8321 \family typewriter
8355 \family typewriter
8322 IPython_crash_report.txt
8356 IPython_crash_report.txt
8323 \family default
8357 \family default
8324 in your IPYTHONDIR directory (that way if crashes happen several times
8358 in your IPYTHONDIR directory (that way if crashes happen several times
8325 it won't litter many directories, the post-mortem file is always located
8359 it won't litter many directories, the post-mortem file is always located
8326 in the same place and new occurrences just overwrite the previous one).
8360 in the same place and new occurrences just overwrite the previous one).
8327 If you can mail this file to the developers (see sec.
8361 If you can mail this file to the developers (see sec.
8328
8362
8329 \begin_inset LatexCommand \ref{sec:credits}
8363 \begin_inset LatexCommand \ref{sec:credits}
8330
8364
8331 \end_inset
8365 \end_inset
8332
8366
8333 for names and addresses), it will help us
8367 for names and addresses), it will help us
8334 \emph on
8368 \emph on
8335 a lot
8369 a lot
8336 \emph default
8370 \emph default
8337 in understanding the cause of the problem and fixing it sooner.
8371 in understanding the cause of the problem and fixing it sooner.
8338 \layout Subsection*
8372 \layout Subsection*
8339
8373
8340 The bug tracker
8374 The bug tracker
8341 \layout Standard
8375 \layout Standard
8342
8376
8343 IPython also has an online bug-tracker, located at
8377 IPython also has an online bug-tracker, located at
8344 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8378 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython}
8345
8379
8346 \end_inset
8380 \end_inset
8347
8381
8348 .
8382 .
8349 In addition to mailing the developers, it would be a good idea to file
8383 In addition to mailing the developers, it would be a good idea to file
8350 a bug report here.
8384 a bug report here.
8351 This will ensure that the issue is properly followed to conclusion.
8385 This will ensure that the issue is properly followed to conclusion.
8352 \layout Standard
8386 \layout Standard
8353
8387
8354 You can also use this bug tracker to file feature requests.
8388 You can also use this bug tracker to file feature requests.
8355 \layout Section
8389 \layout Section
8356
8390
8357 Brief history
8391 Brief history
8358 \layout Subsection
8392 \layout Subsection
8359
8393
8360 Origins
8394 Origins
8361 \layout Standard
8395 \layout Standard
8362
8396
8363 The current IPython system grew out of the following three projects:
8397 The current IPython system grew out of the following three projects:
8364 \layout List
8398 \layout List
8365 \labelwidthstring 00.00.0000
8399 \labelwidthstring 00.00.0000
8366
8400
8367 ipython by Fernando Pérez.
8401 ipython by Fernando Pérez.
8368 I was working on adding Mathematica-type prompts and a flexible configuration
8402 I was working on adding Mathematica-type prompts and a flexible configuration
8369 system (something better than
8403 system (something better than
8370 \family typewriter
8404 \family typewriter
8371 $PYTHONSTARTUP
8405 $PYTHONSTARTUP
8372 \family default
8406 \family default
8373 ) to the standard Python interactive interpreter.
8407 ) to the standard Python interactive interpreter.
8374 \layout List
8408 \layout List
8375 \labelwidthstring 00.00.0000
8409 \labelwidthstring 00.00.0000
8376
8410
8377 IPP by Janko Hauser.
8411 IPP by Janko Hauser.
8378 Very well organized, great usability.
8412 Very well organized, great usability.
8379 Had an old help system.
8413 Had an old help system.
8380 IPP was used as the `container' code into which I added the functionality
8414 IPP was used as the `container' code into which I added the functionality
8381 from ipython and LazyPython.
8415 from ipython and LazyPython.
8382 \layout List
8416 \layout List
8383 \labelwidthstring 00.00.0000
8417 \labelwidthstring 00.00.0000
8384
8418
8385 LazyPython by Nathan Gray.
8419 LazyPython by Nathan Gray.
8386 Simple but
8420 Simple but
8387 \emph on
8421 \emph on
8388 very
8422 very
8389 \emph default
8423 \emph default
8390 powerful.
8424 powerful.
8391 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8425 The quick syntax (auto parens, auto quotes) and verbose/colored tracebacks
8392 were all taken from here.
8426 were all taken from here.
8393 \layout Standard
8427 \layout Standard
8394
8428
8395 When I found out (see sec.
8429 When I found out (see sec.
8396
8430
8397 \begin_inset LatexCommand \ref{figgins}
8431 \begin_inset LatexCommand \ref{figgins}
8398
8432
8399 \end_inset
8433 \end_inset
8400
8434
8401 ) about IPP and LazyPython I tried to join all three into a unified system.
8435 ) about IPP and LazyPython I tried to join all three into a unified system.
8402 I thought this could provide a very nice working environment, both for
8436 I thought this could provide a very nice working environment, both for
8403 regular programming and scientific computing: shell-like features, IDL/Matlab
8437 regular programming and scientific computing: shell-like features, IDL/Matlab
8404 numerics, Mathematica-type prompt history and great object introspection
8438 numerics, Mathematica-type prompt history and great object introspection
8405 and help facilities.
8439 and help facilities.
8406 I think it worked reasonably well, though it was a lot more work than I
8440 I think it worked reasonably well, though it was a lot more work than I
8407 had initially planned.
8441 had initially planned.
8408 \layout Subsection
8442 \layout Subsection
8409
8443
8410 Current status
8444 Current status
8411 \layout Standard
8445 \layout Standard
8412
8446
8413 The above listed features work, and quite well for the most part.
8447 The above listed features work, and quite well for the most part.
8414 But until a major internal restructuring is done (see below), only bug
8448 But until a major internal restructuring is done (see below), only bug
8415 fixing will be done, no other features will be added (unless very minor
8449 fixing will be done, no other features will be added (unless very minor
8416 and well localized in the cleaner parts of the code).
8450 and well localized in the cleaner parts of the code).
8417 \layout Standard
8451 \layout Standard
8418
8452
8419 IPython consists of some 12000 lines of pure python code, of which roughly
8453 IPython consists of some 12000 lines of pure python code, of which roughly
8420 50% are fairly clean.
8454 50% are fairly clean.
8421 The other 50% are fragile, messy code which needs a massive restructuring
8455 The other 50% are fragile, messy code which needs a massive restructuring
8422 before any further major work is done.
8456 before any further major work is done.
8423 Even the messy code is fairly well documented though, and most of the problems
8457 Even the messy code is fairly well documented though, and most of the problems
8424 in the (non-existent) class design are well pointed to by a PyChecker run.
8458 in the (non-existent) class design are well pointed to by a PyChecker run.
8425 So the rewriting work isn't that bad, it will just be time-consuming.
8459 So the rewriting work isn't that bad, it will just be time-consuming.
8426 \layout Subsection
8460 \layout Subsection
8427
8461
8428 Future
8462 Future
8429 \layout Standard
8463 \layout Standard
8430
8464
8431 See the separate
8465 See the separate
8432 \family typewriter
8466 \family typewriter
8433 new_design
8467 new_design
8434 \family default
8468 \family default
8435 document for details.
8469 document for details.
8436 Ultimately, I would like to see IPython become part of the standard Python
8470 Ultimately, I would like to see IPython become part of the standard Python
8437 distribution as a `big brother with batteries' to the standard Python interacti
8471 distribution as a `big brother with batteries' to the standard Python interacti
8438 ve interpreter.
8472 ve interpreter.
8439 But that will never happen with the current state of the code, so all contribut
8473 But that will never happen with the current state of the code, so all contribut
8440 ions are welcome.
8474 ions are welcome.
8441 \layout Section
8475 \layout Section
8442
8476
8443 License
8477 License
8444 \layout Standard
8478 \layout Standard
8445
8479
8446 IPython is released under the terms of the BSD license, whose general form
8480 IPython is released under the terms of the BSD license, whose general form
8447 can be found at:
8481 can be found at:
8448 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8482 \begin_inset LatexCommand \htmlurl{http://www.opensource.org/licenses/bsd-license.php}
8449
8483
8450 \end_inset
8484 \end_inset
8451
8485
8452 .
8486 .
8453 The full text of the IPython license is reproduced below:
8487 The full text of the IPython license is reproduced below:
8454 \layout Quote
8488 \layout Quote
8455
8489
8456
8490
8457 \family typewriter
8491 \family typewriter
8458 \size small
8492 \size small
8459 IPython is released under a BSD-type license.
8493 IPython is released under a BSD-type license.
8460 \layout Quote
8494 \layout Quote
8461
8495
8462
8496
8463 \family typewriter
8497 \family typewriter
8464 \size small
8498 \size small
8465 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8499 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez <fperez@colorado.edu>.
8466 \layout Quote
8500 \layout Quote
8467
8501
8468
8502
8469 \family typewriter
8503 \family typewriter
8470 \size small
8504 \size small
8471 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8505 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
8472 \newline
8506 \newline
8473 Nathaniel Gray <n8gray@caltech.edu>.
8507 Nathaniel Gray <n8gray@caltech.edu>.
8474 \layout Quote
8508 \layout Quote
8475
8509
8476
8510
8477 \family typewriter
8511 \family typewriter
8478 \size small
8512 \size small
8479 All rights reserved.
8513 All rights reserved.
8480 \layout Quote
8514 \layout Quote
8481
8515
8482
8516
8483 \family typewriter
8517 \family typewriter
8484 \size small
8518 \size small
8485 Redistribution and use in source and binary forms, with or without modification,
8519 Redistribution and use in source and binary forms, with or without modification,
8486 are permitted provided that the following conditions are met:
8520 are permitted provided that the following conditions are met:
8487 \layout Quote
8521 \layout Quote
8488
8522
8489
8523
8490 \family typewriter
8524 \family typewriter
8491 \size small
8525 \size small
8492 a.
8526 a.
8493 Redistributions of source code must retain the above copyright notice,
8527 Redistributions of source code must retain the above copyright notice,
8494 this list of conditions and the following disclaimer.
8528 this list of conditions and the following disclaimer.
8495 \layout Quote
8529 \layout Quote
8496
8530
8497
8531
8498 \family typewriter
8532 \family typewriter
8499 \size small
8533 \size small
8500 b.
8534 b.
8501 Redistributions in binary form must reproduce the above copyright notice,
8535 Redistributions in binary form must reproduce the above copyright notice,
8502 this list of conditions and the following disclaimer in the documentation
8536 this list of conditions and the following disclaimer in the documentation
8503 and/or other materials provided with the distribution.
8537 and/or other materials provided with the distribution.
8504 \layout Quote
8538 \layout Quote
8505
8539
8506
8540
8507 \family typewriter
8541 \family typewriter
8508 \size small
8542 \size small
8509 c.
8543 c.
8510 Neither the name of the copyright holders nor the names of any contributors
8544 Neither the name of the copyright holders nor the names of any contributors
8511 to this software may be used to endorse or promote products derived from
8545 to this software may be used to endorse or promote products derived from
8512 this software without specific prior written permission.
8546 this software without specific prior written permission.
8513 \layout Quote
8547 \layout Quote
8514
8548
8515
8549
8516 \family typewriter
8550 \family typewriter
8517 \size small
8551 \size small
8518 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8552 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8519 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8553 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
8520 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8554 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
8521 PURPOSE ARE DISCLAIMED.
8555 PURPOSE ARE DISCLAIMED.
8522 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8556 IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
8523 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8557 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
8524 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8558 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
8525 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8559 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
8526 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8560 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8527 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8561 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8528 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8562 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8529
8563
8530 \layout Standard
8564 \layout Standard
8531
8565
8532 Individual authors are the holders of the copyright for their code and are
8566 Individual authors are the holders of the copyright for their code and are
8533 listed in each file.
8567 listed in each file.
8534 \layout Standard
8568 \layout Standard
8535
8569
8536 Some files (
8570 Some files (
8537 \family typewriter
8571 \family typewriter
8538 DPyGetOpt.py
8572 DPyGetOpt.py
8539 \family default
8573 \family default
8540 , for example) may be licensed under different conditions.
8574 , for example) may be licensed under different conditions.
8541 Ultimately each file indicates clearly the conditions under which its author/au
8575 Ultimately each file indicates clearly the conditions under which its author/au
8542 thors have decided to publish the code.
8576 thors have decided to publish the code.
8543 \layout Standard
8577 \layout Standard
8544
8578
8545 Versions of IPython up to and including 0.6.3 were released under the GNU
8579 Versions of IPython up to and including 0.6.3 were released under the GNU
8546 Lesser General Public License (LGPL), available at
8580 Lesser General Public License (LGPL), available at
8547 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8581 \begin_inset LatexCommand \htmlurl{http://www.gnu.org/copyleft/lesser.html}
8548
8582
8549 \end_inset
8583 \end_inset
8550
8584
8551 .
8585 .
8552 \layout Section
8586 \layout Section
8553
8587
8554
8588
8555 \begin_inset LatexCommand \label{sec:credits}
8589 \begin_inset LatexCommand \label{sec:credits}
8556
8590
8557 \end_inset
8591 \end_inset
8558
8592
8559 Credits
8593 Credits
8560 \layout Standard
8594 \layout Standard
8561
8595
8562 IPython is mainly developed by Fernando Pérez
8596 IPython is mainly developed by Fernando Pérez
8563 \family typewriter
8597 \family typewriter
8564 <fperez@colorado.edu>
8598 <fperez@colorado.edu>
8565 \family default
8599 \family default
8566 , but the project was born from mixing in Fernando's code with the IPP project
8600 , but the project was born from mixing in Fernando's code with the IPP project
8567 by Janko Hauser
8601 by Janko Hauser
8568 \family typewriter
8602 \family typewriter
8569 <jhauser-AT-zscout.de>
8603 <jhauser-AT-zscout.de>
8570 \family default
8604 \family default
8571 and LazyPython by Nathan Gray
8605 and LazyPython by Nathan Gray
8572 \family typewriter
8606 \family typewriter
8573 <n8gray-AT-caltech.edu>
8607 <n8gray-AT-caltech.edu>
8574 \family default
8608 \family default
8575 .
8609 .
8576 For all IPython-related requests, please contact Fernando.
8610 For all IPython-related requests, please contact Fernando.
8577
8611
8578 \layout Standard
8612 \layout Standard
8579
8613
8580 As of late 2005, the following developers have joined the core team:
8614 As of late 2005, the following developers have joined the core team:
8581 \layout List
8615 \layout List
8582 \labelwidthstring 00.00.0000
8616 \labelwidthstring 00.00.0000
8583
8617
8584 Robert\SpecialChar ~
8618 Robert\SpecialChar ~
8585 Kern
8619 Kern
8586 \family typewriter
8620 \family typewriter
8587 <rkern-AT-enthought.com>
8621 <rkern-AT-enthought.com>
8588 \family default
8622 \family default
8589 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8623 : co-mentored the 2005 Google Summer of Code project to develop python interacti
8590 ve notebooks (XML documents) and graphical interface.
8624 ve notebooks (XML documents) and graphical interface.
8591 This project was awarded to the students Tzanko Matev
8625 This project was awarded to the students Tzanko Matev
8592 \family typewriter
8626 \family typewriter
8593 <tsanko-AT-gmail.com>
8627 <tsanko-AT-gmail.com>
8594 \family default
8628 \family default
8595 and Toni Alatalo
8629 and Toni Alatalo
8596 \family typewriter
8630 \family typewriter
8597 <antont-AT-an.org>
8631 <antont-AT-an.org>
8598 \layout List
8632 \layout List
8599 \labelwidthstring 00.00.0000
8633 \labelwidthstring 00.00.0000
8600
8634
8601 Brian\SpecialChar ~
8635 Brian\SpecialChar ~
8602 Granger
8636 Granger
8603 \family typewriter
8637 \family typewriter
8604 <bgranger-AT-scu.edu>
8638 <bgranger-AT-scu.edu>
8605 \family default
8639 \family default
8606 : extending IPython to allow support for interactive parallel computing.
8640 : extending IPython to allow support for interactive parallel computing.
8607 \layout Standard
8641 \layout Standard
8608
8642
8609 User or development help should be requested via the IPython mailing lists:
8643 User or development help should be requested via the IPython mailing lists:
8610 \layout Description
8644 \layout Description
8611
8645
8612 User\SpecialChar ~
8646 User\SpecialChar ~
8613 list:
8647 list:
8614 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8648 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-user}
8615
8649
8616 \end_inset
8650 \end_inset
8617
8651
8618
8652
8619 \layout Description
8653 \layout Description
8620
8654
8621 Developer's\SpecialChar ~
8655 Developer's\SpecialChar ~
8622 list:
8656 list:
8623 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8657 \begin_inset LatexCommand \htmlurl{http://scipy.net/mailman/listinfo/ipython-dev}
8624
8658
8625 \end_inset
8659 \end_inset
8626
8660
8627
8661
8628 \layout Standard
8662 \layout Standard
8629
8663
8630 The IPython project is also very grateful to
8664 The IPython project is also very grateful to
8631 \begin_inset Foot
8665 \begin_inset Foot
8632 collapsed true
8666 collapsed true
8633
8667
8634 \layout Standard
8668 \layout Standard
8635
8669
8636 I've mangled email addresses to reduce spam, since the IPython manuals can
8670 I've mangled email addresses to reduce spam, since the IPython manuals can
8637 be accessed online.
8671 be accessed online.
8638 \end_inset
8672 \end_inset
8639
8673
8640 :
8674 :
8641 \layout Standard
8675 \layout Standard
8642
8676
8643 Bill Bumgarner
8677 Bill Bumgarner
8644 \family typewriter
8678 \family typewriter
8645 <bbum-AT-friday.com>
8679 <bbum-AT-friday.com>
8646 \family default
8680 \family default
8647 : for providing the DPyGetOpt module which gives very powerful and convenient
8681 : for providing the DPyGetOpt module which gives very powerful and convenient
8648 handling of command-line options (light years ahead of what Python 2.1.1's
8682 handling of command-line options (light years ahead of what Python 2.1.1's
8649 getopt module does).
8683 getopt module does).
8650 \layout Standard
8684 \layout Standard
8651
8685
8652 Ka-Ping Yee
8686 Ka-Ping Yee
8653 \family typewriter
8687 \family typewriter
8654 <ping-AT-lfw.org>
8688 <ping-AT-lfw.org>
8655 \family default
8689 \family default
8656 : for providing the Itpl module for convenient and powerful string interpolation
8690 : for providing the Itpl module for convenient and powerful string interpolation
8657 with a much nicer syntax than formatting through the '%' operator.
8691 with a much nicer syntax than formatting through the '%' operator.
8658 \layout Standard
8692 \layout Standard
8659
8693
8660 Arnd Bäcker
8694 Arnd Bäcker
8661 \family typewriter
8695 \family typewriter
8662 <baecker-AT-physik.tu-dresden.de>
8696 <baecker-AT-physik.tu-dresden.de>
8663 \family default
8697 \family default
8664 : for his many very useful suggestions and comments, and lots of help with
8698 : for his many very useful suggestions and comments, and lots of help with
8665 testing and documentation checking.
8699 testing and documentation checking.
8666 Many of IPython's newer features are a result of discussions with him (bugs
8700 Many of IPython's newer features are a result of discussions with him (bugs
8667 are still my fault, not his).
8701 are still my fault, not his).
8668 \layout Standard
8702 \layout Standard
8669
8703
8670 Obviously Guido van\SpecialChar ~
8704 Obviously Guido van\SpecialChar ~
8671 Rossum and the whole Python development team, that goes
8705 Rossum and the whole Python development team, that goes
8672 without saying.
8706 without saying.
8673 \layout Standard
8707 \layout Standard
8674
8708
8675 IPython's website is generously hosted at
8709 IPython's website is generously hosted at
8676 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
8710 \begin_inset LatexCommand \htmlurl{http://ipython.scipy.org}
8677
8711
8678 \end_inset
8712 \end_inset
8679
8713
8680 by Enthought (
8714 by Enthought (
8681 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
8715 \begin_inset LatexCommand \htmlurl{http://www.enthought.com}
8682
8716
8683 \end_inset
8717 \end_inset
8684
8718
8685 ).
8719 ).
8686 I am very grateful to them and all of the SciPy team for their contribution.
8720 I am very grateful to them and all of the SciPy team for their contribution.
8687 \layout Standard
8721 \layout Standard
8688
8722
8689
8723
8690 \begin_inset LatexCommand \label{figgins}
8724 \begin_inset LatexCommand \label{figgins}
8691
8725
8692 \end_inset
8726 \end_inset
8693
8727
8694 Fernando would also like to thank Stephen Figgins
8728 Fernando would also like to thank Stephen Figgins
8695 \family typewriter
8729 \family typewriter
8696 <fig-AT-monitor.net>
8730 <fig-AT-monitor.net>
8697 \family default
8731 \family default
8698 , an O'Reilly Python editor.
8732 , an O'Reilly Python editor.
8699 His Oct/11/2001 article about IPP and LazyPython, was what got this project
8733 His Oct/11/2001 article about IPP and LazyPython, was what got this project
8700 started.
8734 started.
8701 You can read it at:
8735 You can read it at:
8702 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
8736 \begin_inset LatexCommand \htmlurl{http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html}
8703
8737
8704 \end_inset
8738 \end_inset
8705
8739
8706 .
8740 .
8707 \layout Standard
8741 \layout Standard
8708
8742
8709 And last but not least, all the kind IPython users who have emailed new
8743 And last but not least, all the kind IPython users who have emailed new
8710 code, bug reports, fixes, comments and ideas.
8744 code, bug reports, fixes, comments and ideas.
8711 A brief list follows, please let me know if I have ommitted your name by
8745 A brief list follows, please let me know if I have ommitted your name by
8712 accident:
8746 accident:
8713 \layout List
8747 \layout List
8714 \labelwidthstring 00.00.0000
8748 \labelwidthstring 00.00.0000
8715
8749
8716 Jack\SpecialChar ~
8750 Jack\SpecialChar ~
8717 Moffit
8751 Moffit
8718 \family typewriter
8752 \family typewriter
8719 <jack-AT-xiph.org>
8753 <jack-AT-xiph.org>
8720 \family default
8754 \family default
8721 Bug fixes, including the infamous color problem.
8755 Bug fixes, including the infamous color problem.
8722 This bug alone caused many lost hours and frustration, many thanks to him
8756 This bug alone caused many lost hours and frustration, many thanks to him
8723 for the fix.
8757 for the fix.
8724 I've always been a fan of Ogg & friends, now I have one more reason to
8758 I've always been a fan of Ogg & friends, now I have one more reason to
8725 like these folks.
8759 like these folks.
8726 \newline
8760 \newline
8727 Jack is also contributing with Debian packaging and many other things.
8761 Jack is also contributing with Debian packaging and many other things.
8728 \layout List
8762 \layout List
8729 \labelwidthstring 00.00.0000
8763 \labelwidthstring 00.00.0000
8730
8764
8731 Alexander\SpecialChar ~
8765 Alexander\SpecialChar ~
8732 Schmolck
8766 Schmolck
8733 \family typewriter
8767 \family typewriter
8734 <a.schmolck-AT-gmx.net>
8768 <a.schmolck-AT-gmx.net>
8735 \family default
8769 \family default
8736 Emacs work, bug reports, bug fixes, ideas, lots more.
8770 Emacs work, bug reports, bug fixes, ideas, lots more.
8737 The ipython.el mode for (X)Emacs is Alex's code, providing full support
8771 The ipython.el mode for (X)Emacs is Alex's code, providing full support
8738 for IPython under (X)Emacs.
8772 for IPython under (X)Emacs.
8739 \layout List
8773 \layout List
8740 \labelwidthstring 00.00.0000
8774 \labelwidthstring 00.00.0000
8741
8775
8742 Andrea\SpecialChar ~
8776 Andrea\SpecialChar ~
8743 Riciputi
8777 Riciputi
8744 \family typewriter
8778 \family typewriter
8745 <andrea.riciputi-AT-libero.it>
8779 <andrea.riciputi-AT-libero.it>
8746 \family default
8780 \family default
8747 Mac OSX information, Fink package management.
8781 Mac OSX information, Fink package management.
8748 \layout List
8782 \layout List
8749 \labelwidthstring 00.00.0000
8783 \labelwidthstring 00.00.0000
8750
8784
8751 Gary\SpecialChar ~
8785 Gary\SpecialChar ~
8752 Bishop
8786 Bishop
8753 \family typewriter
8787 \family typewriter
8754 <gb-AT-cs.unc.edu>
8788 <gb-AT-cs.unc.edu>
8755 \family default
8789 \family default
8756 Bug reports, and patches to work around the exception handling idiosyncracies
8790 Bug reports, and patches to work around the exception handling idiosyncracies
8757 of WxPython.
8791 of WxPython.
8758 Readline and color support for Windows.
8792 Readline and color support for Windows.
8759 \layout List
8793 \layout List
8760 \labelwidthstring 00.00.0000
8794 \labelwidthstring 00.00.0000
8761
8795
8762 Jeffrey\SpecialChar ~
8796 Jeffrey\SpecialChar ~
8763 Collins
8797 Collins
8764 \family typewriter
8798 \family typewriter
8765 <Jeff.Collins-AT-vexcel.com>
8799 <Jeff.Collins-AT-vexcel.com>
8766 \family default
8800 \family default
8767 Bug reports.
8801 Bug reports.
8768 Much improved readline support, including fixes for Python 2.3.
8802 Much improved readline support, including fixes for Python 2.3.
8769 \layout List
8803 \layout List
8770 \labelwidthstring 00.00.0000
8804 \labelwidthstring 00.00.0000
8771
8805
8772 Dryice\SpecialChar ~
8806 Dryice\SpecialChar ~
8773 Liu
8807 Liu
8774 \family typewriter
8808 \family typewriter
8775 <dryice-AT-liu.com.cn>
8809 <dryice-AT-liu.com.cn>
8776 \family default
8810 \family default
8777 FreeBSD port.
8811 FreeBSD port.
8778 \layout List
8812 \layout List
8779 \labelwidthstring 00.00.0000
8813 \labelwidthstring 00.00.0000
8780
8814
8781 Mike\SpecialChar ~
8815 Mike\SpecialChar ~
8782 Heeter
8816 Heeter
8783 \family typewriter
8817 \family typewriter
8784 <korora-AT-SDF.LONESTAR.ORG>
8818 <korora-AT-SDF.LONESTAR.ORG>
8785 \layout List
8819 \layout List
8786 \labelwidthstring 00.00.0000
8820 \labelwidthstring 00.00.0000
8787
8821
8788 Christopher\SpecialChar ~
8822 Christopher\SpecialChar ~
8789 Hart
8823 Hart
8790 \family typewriter
8824 \family typewriter
8791 <hart-AT-caltech.edu>
8825 <hart-AT-caltech.edu>
8792 \family default
8826 \family default
8793 PDB integration.
8827 PDB integration.
8794 \layout List
8828 \layout List
8795 \labelwidthstring 00.00.0000
8829 \labelwidthstring 00.00.0000
8796
8830
8797 Milan\SpecialChar ~
8831 Milan\SpecialChar ~
8798 Zamazal
8832 Zamazal
8799 \family typewriter
8833 \family typewriter
8800 <pdm-AT-zamazal.org>
8834 <pdm-AT-zamazal.org>
8801 \family default
8835 \family default
8802 Emacs info.
8836 Emacs info.
8803 \layout List
8837 \layout List
8804 \labelwidthstring 00.00.0000
8838 \labelwidthstring 00.00.0000
8805
8839
8806 Philip\SpecialChar ~
8840 Philip\SpecialChar ~
8807 Hisley
8841 Hisley
8808 \family typewriter
8842 \family typewriter
8809 <compsys-AT-starpower.net>
8843 <compsys-AT-starpower.net>
8810 \layout List
8844 \layout List
8811 \labelwidthstring 00.00.0000
8845 \labelwidthstring 00.00.0000
8812
8846
8813 Holger\SpecialChar ~
8847 Holger\SpecialChar ~
8814 Krekel
8848 Krekel
8815 \family typewriter
8849 \family typewriter
8816 <pyth-AT-devel.trillke.net>
8850 <pyth-AT-devel.trillke.net>
8817 \family default
8851 \family default
8818 Tab completion, lots more.
8852 Tab completion, lots more.
8819 \layout List
8853 \layout List
8820 \labelwidthstring 00.00.0000
8854 \labelwidthstring 00.00.0000
8821
8855
8822 Robin\SpecialChar ~
8856 Robin\SpecialChar ~
8823 Siebler
8857 Siebler
8824 \family typewriter
8858 \family typewriter
8825 <robinsiebler-AT-starband.net>
8859 <robinsiebler-AT-starband.net>
8826 \layout List
8860 \layout List
8827 \labelwidthstring 00.00.0000
8861 \labelwidthstring 00.00.0000
8828
8862
8829 Ralf\SpecialChar ~
8863 Ralf\SpecialChar ~
8830 Ahlbrink
8864 Ahlbrink
8831 \family typewriter
8865 \family typewriter
8832 <ralf_ahlbrink-AT-web.de>
8866 <ralf_ahlbrink-AT-web.de>
8833 \layout List
8867 \layout List
8834 \labelwidthstring 00.00.0000
8868 \labelwidthstring 00.00.0000
8835
8869
8836 Thorsten\SpecialChar ~
8870 Thorsten\SpecialChar ~
8837 Kampe
8871 Kampe
8838 \family typewriter
8872 \family typewriter
8839 <thorsten-AT-thorstenkampe.de>
8873 <thorsten-AT-thorstenkampe.de>
8840 \layout List
8874 \layout List
8841 \labelwidthstring 00.00.0000
8875 \labelwidthstring 00.00.0000
8842
8876
8843 Fredrik\SpecialChar ~
8877 Fredrik\SpecialChar ~
8844 Kant
8878 Kant
8845 \family typewriter
8879 \family typewriter
8846 <fredrik.kant-AT-front.com>
8880 <fredrik.kant-AT-front.com>
8847 \family default
8881 \family default
8848 Windows setup.
8882 Windows setup.
8849 \layout List
8883 \layout List
8850 \labelwidthstring 00.00.0000
8884 \labelwidthstring 00.00.0000
8851
8885
8852 Syver\SpecialChar ~
8886 Syver\SpecialChar ~
8853 Enstad
8887 Enstad
8854 \family typewriter
8888 \family typewriter
8855 <syver-en-AT-online.no>
8889 <syver-en-AT-online.no>
8856 \family default
8890 \family default
8857 Windows setup.
8891 Windows setup.
8858 \layout List
8892 \layout List
8859 \labelwidthstring 00.00.0000
8893 \labelwidthstring 00.00.0000
8860
8894
8861 Richard
8895 Richard
8862 \family typewriter
8896 \family typewriter
8863 <rxe-AT-renre-europe.com>
8897 <rxe-AT-renre-europe.com>
8864 \family default
8898 \family default
8865 Global embedding.
8899 Global embedding.
8866 \layout List
8900 \layout List
8867 \labelwidthstring 00.00.0000
8901 \labelwidthstring 00.00.0000
8868
8902
8869 Hayden\SpecialChar ~
8903 Hayden\SpecialChar ~
8870 Callow
8904 Callow
8871 \family typewriter
8905 \family typewriter
8872 <h.callow-AT-elec.canterbury.ac.nz>
8906 <h.callow-AT-elec.canterbury.ac.nz>
8873 \family default
8907 \family default
8874 Gnuplot.py 1.6 compatibility.
8908 Gnuplot.py 1.6 compatibility.
8875 \layout List
8909 \layout List
8876 \labelwidthstring 00.00.0000
8910 \labelwidthstring 00.00.0000
8877
8911
8878 Leonardo\SpecialChar ~
8912 Leonardo\SpecialChar ~
8879 Santagada
8913 Santagada
8880 \family typewriter
8914 \family typewriter
8881 <retype-AT-terra.com.br>
8915 <retype-AT-terra.com.br>
8882 \family default
8916 \family default
8883 Fixes for Windows installation.
8917 Fixes for Windows installation.
8884 \layout List
8918 \layout List
8885 \labelwidthstring 00.00.0000
8919 \labelwidthstring 00.00.0000
8886
8920
8887 Christopher\SpecialChar ~
8921 Christopher\SpecialChar ~
8888 Armstrong
8922 Armstrong
8889 \family typewriter
8923 \family typewriter
8890 <radix-AT-twistedmatrix.com>
8924 <radix-AT-twistedmatrix.com>
8891 \family default
8925 \family default
8892 Bugfixes.
8926 Bugfixes.
8893 \layout List
8927 \layout List
8894 \labelwidthstring 00.00.0000
8928 \labelwidthstring 00.00.0000
8895
8929
8896 Francois\SpecialChar ~
8930 Francois\SpecialChar ~
8897 Pinard
8931 Pinard
8898 \family typewriter
8932 \family typewriter
8899 <pinard-AT-iro.umontreal.ca>
8933 <pinard-AT-iro.umontreal.ca>
8900 \family default
8934 \family default
8901 Code and documentation fixes.
8935 Code and documentation fixes.
8902 \layout List
8936 \layout List
8903 \labelwidthstring 00.00.0000
8937 \labelwidthstring 00.00.0000
8904
8938
8905 Cory\SpecialChar ~
8939 Cory\SpecialChar ~
8906 Dodt
8940 Dodt
8907 \family typewriter
8941 \family typewriter
8908 <cdodt-AT-fcoe.k12.ca.us>
8942 <cdodt-AT-fcoe.k12.ca.us>
8909 \family default
8943 \family default
8910 Bug reports and Windows ideas.
8944 Bug reports and Windows ideas.
8911 Patches for Windows installer.
8945 Patches for Windows installer.
8912 \layout List
8946 \layout List
8913 \labelwidthstring 00.00.0000
8947 \labelwidthstring 00.00.0000
8914
8948
8915 Olivier\SpecialChar ~
8949 Olivier\SpecialChar ~
8916 Aubert
8950 Aubert
8917 \family typewriter
8951 \family typewriter
8918 <oaubert-AT-bat710.univ-lyon1.fr>
8952 <oaubert-AT-bat710.univ-lyon1.fr>
8919 \family default
8953 \family default
8920 New magics.
8954 New magics.
8921 \layout List
8955 \layout List
8922 \labelwidthstring 00.00.0000
8956 \labelwidthstring 00.00.0000
8923
8957
8924 King\SpecialChar ~
8958 King\SpecialChar ~
8925 C.\SpecialChar ~
8959 C.\SpecialChar ~
8926 Shu
8960 Shu
8927 \family typewriter
8961 \family typewriter
8928 <kingshu-AT-myrealbox.com>
8962 <kingshu-AT-myrealbox.com>
8929 \family default
8963 \family default
8930 Autoindent patch.
8964 Autoindent patch.
8931 \layout List
8965 \layout List
8932 \labelwidthstring 00.00.0000
8966 \labelwidthstring 00.00.0000
8933
8967
8934 Chris\SpecialChar ~
8968 Chris\SpecialChar ~
8935 Drexler
8969 Drexler
8936 \family typewriter
8970 \family typewriter
8937 <chris-AT-ac-drexler.de>
8971 <chris-AT-ac-drexler.de>
8938 \family default
8972 \family default
8939 Readline packages for Win32/CygWin.
8973 Readline packages for Win32/CygWin.
8940 \layout List
8974 \layout List
8941 \labelwidthstring 00.00.0000
8975 \labelwidthstring 00.00.0000
8942
8976
8943 Gustavo\SpecialChar ~
8977 Gustavo\SpecialChar ~
8944 Córdova\SpecialChar ~
8978 Córdova\SpecialChar ~
8945 Avila
8979 Avila
8946 \family typewriter
8980 \family typewriter
8947 <gcordova-AT-sismex.com>
8981 <gcordova-AT-sismex.com>
8948 \family default
8982 \family default
8949 EvalDict code for nice, lightweight string interpolation.
8983 EvalDict code for nice, lightweight string interpolation.
8950 \layout List
8984 \layout List
8951 \labelwidthstring 00.00.0000
8985 \labelwidthstring 00.00.0000
8952
8986
8953 Kasper\SpecialChar ~
8987 Kasper\SpecialChar ~
8954 Souren
8988 Souren
8955 \family typewriter
8989 \family typewriter
8956 <Kasper.Souren-AT-ircam.fr>
8990 <Kasper.Souren-AT-ircam.fr>
8957 \family default
8991 \family default
8958 Bug reports, ideas.
8992 Bug reports, ideas.
8959 \layout List
8993 \layout List
8960 \labelwidthstring 00.00.0000
8994 \labelwidthstring 00.00.0000
8961
8995
8962 Gever\SpecialChar ~
8996 Gever\SpecialChar ~
8963 Tulley
8997 Tulley
8964 \family typewriter
8998 \family typewriter
8965 <gever-AT-helium.com>
8999 <gever-AT-helium.com>
8966 \family default
9000 \family default
8967 Code contributions.
9001 Code contributions.
8968 \layout List
9002 \layout List
8969 \labelwidthstring 00.00.0000
9003 \labelwidthstring 00.00.0000
8970
9004
8971 Ralf\SpecialChar ~
9005 Ralf\SpecialChar ~
8972 Schmitt
9006 Schmitt
8973 \family typewriter
9007 \family typewriter
8974 <ralf-AT-brainbot.com>
9008 <ralf-AT-brainbot.com>
8975 \family default
9009 \family default
8976 Bug reports & fixes.
9010 Bug reports & fixes.
8977 \layout List
9011 \layout List
8978 \labelwidthstring 00.00.0000
9012 \labelwidthstring 00.00.0000
8979
9013
8980 Oliver\SpecialChar ~
9014 Oliver\SpecialChar ~
8981 Sander
9015 Sander
8982 \family typewriter
9016 \family typewriter
8983 <osander-AT-gmx.de>
9017 <osander-AT-gmx.de>
8984 \family default
9018 \family default
8985 Bug reports.
9019 Bug reports.
8986 \layout List
9020 \layout List
8987 \labelwidthstring 00.00.0000
9021 \labelwidthstring 00.00.0000
8988
9022
8989 Rod\SpecialChar ~
9023 Rod\SpecialChar ~
8990 Holland
9024 Holland
8991 \family typewriter
9025 \family typewriter
8992 <rhh-AT-structurelabs.com>
9026 <rhh-AT-structurelabs.com>
8993 \family default
9027 \family default
8994 Bug reports and fixes to logging module.
9028 Bug reports and fixes to logging module.
8995 \layout List
9029 \layout List
8996 \labelwidthstring 00.00.0000
9030 \labelwidthstring 00.00.0000
8997
9031
8998 Daniel\SpecialChar ~
9032 Daniel\SpecialChar ~
8999 'Dang'\SpecialChar ~
9033 'Dang'\SpecialChar ~
9000 Griffith
9034 Griffith
9001 \family typewriter
9035 \family typewriter
9002 <pythondev-dang-AT-lazytwinacres.net>
9036 <pythondev-dang-AT-lazytwinacres.net>
9003 \family default
9037 \family default
9004 Fixes, enhancement suggestions for system shell use.
9038 Fixes, enhancement suggestions for system shell use.
9005 \layout List
9039 \layout List
9006 \labelwidthstring 00.00.0000
9040 \labelwidthstring 00.00.0000
9007
9041
9008 Viktor\SpecialChar ~
9042 Viktor\SpecialChar ~
9009 Ransmayr
9043 Ransmayr
9010 \family typewriter
9044 \family typewriter
9011 <viktor.ransmayr-AT-t-online.de>
9045 <viktor.ransmayr-AT-t-online.de>
9012 \family default
9046 \family default
9013 Tests and reports on Windows installation issues.
9047 Tests and reports on Windows installation issues.
9014 Contributed a true Windows binary installer.
9048 Contributed a true Windows binary installer.
9015 \layout List
9049 \layout List
9016 \labelwidthstring 00.00.0000
9050 \labelwidthstring 00.00.0000
9017
9051
9018 Mike\SpecialChar ~
9052 Mike\SpecialChar ~
9019 Salib
9053 Salib
9020 \family typewriter
9054 \family typewriter
9021 <msalib-AT-mit.edu>
9055 <msalib-AT-mit.edu>
9022 \family default
9056 \family default
9023 Help fixing a subtle bug related to traceback printing.
9057 Help fixing a subtle bug related to traceback printing.
9024 \layout List
9058 \layout List
9025 \labelwidthstring 00.00.0000
9059 \labelwidthstring 00.00.0000
9026
9060
9027 W.J.\SpecialChar ~
9061 W.J.\SpecialChar ~
9028 van\SpecialChar ~
9062 van\SpecialChar ~
9029 der\SpecialChar ~
9063 der\SpecialChar ~
9030 Laan
9064 Laan
9031 \family typewriter
9065 \family typewriter
9032 <gnufnork-AT-hetdigitalegat.nl>
9066 <gnufnork-AT-hetdigitalegat.nl>
9033 \family default
9067 \family default
9034 Bash-like prompt specials.
9068 Bash-like prompt specials.
9035 \layout List
9069 \layout List
9036 \labelwidthstring 00.00.0000
9070 \labelwidthstring 00.00.0000
9037
9071
9038 Ville\SpecialChar ~
9072 Ville\SpecialChar ~
9039 Vainio
9073 Vainio
9040 \family typewriter
9074 \family typewriter
9041 <vivainio-AT-kolumbus.fi>
9075 <vivainio-AT-kolumbus.fi>
9042 \family default
9076 \family default
9043 Bugfixes and suggestions.
9077 Bugfixes and suggestions.
9044 Excellent patches for many new features.
9078 Excellent patches for many new features.
9045 \layout List
9079 \layout List
9046 \labelwidthstring 00.00.0000
9080 \labelwidthstring 00.00.0000
9047
9081
9048 Antoon\SpecialChar ~
9082 Antoon\SpecialChar ~
9049 Pardon
9083 Pardon
9050 \family typewriter
9084 \family typewriter
9051 <Antoon.Pardon-AT-rece.vub.ac.be>
9085 <Antoon.Pardon-AT-rece.vub.ac.be>
9052 \family default
9086 \family default
9053 Critical fix for the multithreaded IPython.
9087 Critical fix for the multithreaded IPython.
9054 \layout List
9088 \layout List
9055 \labelwidthstring 00.00.0000
9089 \labelwidthstring 00.00.0000
9056
9090
9057 John\SpecialChar ~
9091 John\SpecialChar ~
9058 Hunter
9092 Hunter
9059 \family typewriter
9093 \family typewriter
9060 <jdhunter-AT-nitace.bsd.uchicago.edu>
9094 <jdhunter-AT-nitace.bsd.uchicago.edu>
9061 \family default
9095 \family default
9062 Matplotlib author, helped with all the development of support for matplotlib
9096 Matplotlib author, helped with all the development of support for matplotlib
9063 in IPyhton, including making necessary changes to matplotlib itself.
9097 in IPyhton, including making necessary changes to matplotlib itself.
9064 \layout List
9098 \layout List
9065 \labelwidthstring 00.00.0000
9099 \labelwidthstring 00.00.0000
9066
9100
9067 Matthew\SpecialChar ~
9101 Matthew\SpecialChar ~
9068 Arnison
9102 Arnison
9069 \family typewriter
9103 \family typewriter
9070 <maffew-AT-cat.org.au>
9104 <maffew-AT-cat.org.au>
9071 \family default
9105 \family default
9072 Bug reports, `
9106 Bug reports, `
9073 \family typewriter
9107 \family typewriter
9074 %run -d
9108 %run -d
9075 \family default
9109 \family default
9076 ' idea.
9110 ' idea.
9077 \layout List
9111 \layout List
9078 \labelwidthstring 00.00.0000
9112 \labelwidthstring 00.00.0000
9079
9113
9080 Prabhu\SpecialChar ~
9114 Prabhu\SpecialChar ~
9081 Ramachandran
9115 Ramachandran
9082 \family typewriter
9116 \family typewriter
9083 <prabhu_r-AT-users.sourceforge.net>
9117 <prabhu_r-AT-users.sourceforge.net>
9084 \family default
9118 \family default
9085 Help with (X)Emacs support, threading patches, ideas...
9119 Help with (X)Emacs support, threading patches, ideas...
9086 \layout List
9120 \layout List
9087 \labelwidthstring 00.00.0000
9121 \labelwidthstring 00.00.0000
9088
9122
9089 Norbert\SpecialChar ~
9123 Norbert\SpecialChar ~
9090 Tretkowski
9124 Tretkowski
9091 \family typewriter
9125 \family typewriter
9092 <tretkowski-AT-inittab.de>
9126 <tretkowski-AT-inittab.de>
9093 \family default
9127 \family default
9094 help with Debian packaging and distribution.
9128 help with Debian packaging and distribution.
9095 \layout List
9129 \layout List
9096 \labelwidthstring 00.00.0000
9130 \labelwidthstring 00.00.0000
9097
9131
9098 George\SpecialChar ~
9132 George\SpecialChar ~
9099 Sakkis <
9133 Sakkis <
9100 \family typewriter
9134 \family typewriter
9101 gsakkis-AT-eden.rutgers.edu>
9135 gsakkis-AT-eden.rutgers.edu>
9102 \family default
9136 \family default
9103 New matcher for tab-completing named arguments of user-defined functions.
9137 New matcher for tab-completing named arguments of user-defined functions.
9104 \layout List
9138 \layout List
9105 \labelwidthstring 00.00.0000
9139 \labelwidthstring 00.00.0000
9106
9140
9107 J�rgen\SpecialChar ~
9141 J�rgen\SpecialChar ~
9108 Stenarson
9142 Stenarson
9109 \family typewriter
9143 \family typewriter
9110 <jorgen.stenarson-AT-bostream.nu>
9144 <jorgen.stenarson-AT-bostream.nu>
9111 \family default
9145 \family default
9112 Wildcard support implementation for searching namespaces.
9146 Wildcard support implementation for searching namespaces.
9113 \layout List
9147 \layout List
9114 \labelwidthstring 00.00.0000
9148 \labelwidthstring 00.00.0000
9115
9149
9116 Vivian\SpecialChar ~
9150 Vivian\SpecialChar ~
9117 De\SpecialChar ~
9151 De\SpecialChar ~
9118 Smedt
9152 Smedt
9119 \family typewriter
9153 \family typewriter
9120 <vivian-AT-vdesmedt.com>
9154 <vivian-AT-vdesmedt.com>
9121 \family default
9155 \family default
9122 Debugger enhancements, so that when pdb is activated from within IPython,
9156 Debugger enhancements, so that when pdb is activated from within IPython,
9123 coloring, tab completion and other features continue to work seamlessly.
9157 coloring, tab completion and other features continue to work seamlessly.
9158 \layout List
9159 \labelwidthstring 00.00.0000
9160
9161 Scott (email unknown) Support for automatic editor invocation on syntax
9162 errors (see
9163 \begin_inset LatexCommand \htmlurl{http://www.scipy.net/roundup/ipython/issue36}
9164
9165 \end_inset
9166
9167 ).
9124 \the_end
9168 \the_end
General Comments 0
You need to be logged in to leave comments. Login now